Protobuf serialisation
The smithy4s-protobuf
module provides protocol-buffers codecs that can read/write generated data-types from protobuf-encoded bytes.
sbt : "com.disneystreaming.smithy4s" %% "smithy4s-protobuf" % "0.18.33"
mill : "com.disneystreaming.smithy4s::smithy4s-protobuf:0.18.33"
The entrypoint for Protobuf parsing/writing is smithy4s.protobuf.Protobuf
. See below for example usage.
import smithy4s.example.hello.Person
import smithy4s.protobuf.Protobuf
val personCodec = Protobuf.codecs.fromSchema(Person.schema)
// personCodec: smithy4s.protobuf.ProtobufCodec[Person] = smithy4s.protobuf.ProtobufCodec$$anon$1@5b4ce80
val personBytes = personCodec.writeBlob(Person(name = "John Doe"))
// personBytes: smithy4s.Blob = ArraySliceBlob(..., 0, 10)
val maybePerson = personCodec.readBlob(personBytes)
// maybePerson: Either[smithy4s.protobuf.ProtobufReadError, Person] = Right(
// value = Person(name = "John Doe", town = None)
// )
By default, smithy4s-protobuf
abides by the semantics of :
- alloy protobuf traits. These semantics are the exact same semantics that smithy-translate uses to translate smithy to protobuf. This implies that the Smithy4s protobuf codecs are compatible with the codecs of other protobuf tools, generated from the .proto files resulting from running smithy through smithy-translate. In short, Smithy4s and ScalaPB can talk to each other : the ScalaPB codecs generated from protobuf after a translation from smithy are able to decode binary data produced by Smithy4s protobuf codecs (and vice versa).
┌────────────────────┐ ┌────────────────────┐
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ Smithy IDL ├────────────────────────► Protobuf IDL │
│ │ smithy-translate │ │
│ │ │ │
│ │ │ │
│ │ │ │
└─────────┬──────────┘ └─────────┬──────────┘
│ │
│ │
│ │
│ │
│ │
│ │
│ Smithy4s codegen │ ScalaPB codegen
│ │
│ │
│ │
│ │
│ │
┌─────────▼──────────┐ ┌─────────▼──────────┐
│ │ │ │
│ │ │ │
│ │ │ │
│ ◄────────────────────────┤ │
│ Smithy4s code │ Runtime communication │ ScalaPB code │
│ ├────────────────────────► │
│ │ │ │
│ │ │ │
│ │ │ │
└────────────────────┘ └────────────────────┘