diff --git a/docs/codecs.md b/docs/codecs.md index 7a4170a6..74487dd0 100644 --- a/docs/codecs.md +++ b/docs/codecs.md @@ -6,7 +6,7 @@ import java.time.Instant import org.typelevel.vulcan.Codec -Codec[Option[Instant]] +val codec = Codec[Option[Instant]] ``` In some cases, it's not possible to generate Avro schemas. This is why @:api(org.typelevel.vulcan.Codec) `schema`s are wrapped in `Either` with error type @:api(org.typelevel.vulcan.AvroException). For example, Avro doesn't support nested unions, so what would happen when we try to ask for a @:api(org.typelevel.vulcan.Codec) for `Option[Option[Instant]]`? @@ -15,7 +15,33 @@ In some cases, it's not possible to generate Avro schemas. This is why @:api(org Codec[Option[Option[Instant]]] ``` -A @:api(org.typelevel.vulcan.Codec) compiles encoders for its schema, and decoders for the schema values were written with, called the writer schema. They are compiled when requested, so request them once and reuse them for any number of values. Encoding and decoding might also be unsuccessful, so results are wrapped in `Either` with error type @:api(org.typelevel.vulcan.AvroException). For example, what happens if we try to decode `Int`s written using a `Boolean` schema? +A @:api(org.typelevel.vulcan.Codec) compiles encoders for its schema, and decoders for the schema values were written with, called the writer schema. They are compiled when requested, so request them once and reuse them for any number of values. For example, we can use `binaryEncoder` to encode values as Avro binary, and `binaryDecoder` to decode them, here with the schema of the @:api(org.typelevel.vulcan.Codec) as the writer schema. + +```scala mdoc +for { + schema <- codec.schema + encoder <- codec.binaryEncoder + decoder <- codec.binaryDecoder(schema) + bytes <- encoder.encode(Some(Instant.EPOCH)) + instant <- decoder.decode(bytes) +} yield (bytes.toHex, instant) +``` + +Avro binary uses `ByteVector`s from scodec-bits, where `toArray` gives an `Array[Byte]`, and `ByteVector.view` wraps an `Array[Byte]` without copying. + +Similarly, we can use `jsonEncoder` and `jsonDecoder` for the [Avro JSON encoding](https://avro.apache.org/docs/1.12.0/specification/#json-encoding), using circe's `Json`. + +```scala mdoc +for { + schema <- codec.schema + encoder <- codec.jsonEncoder + decoder <- codec.jsonDecoder(schema) + json <- encoder.encode(Some(Instant.EPOCH)) + instant <- decoder.decode(json) +} yield (json.noSpaces, instant) +``` + +Values can also be encoded as, and decoded from, @:api(org.typelevel.vulcan.AvroValue)s using `encoder` and `decoder`. Encoding and decoding might also be unsuccessful, so results are wrapped in `Either` with error type @:api(org.typelevel.vulcan.AvroException). For example, what happens if we try to decode `Int`s written using a `Boolean` schema? ```scala mdoc import org.typelevel.vulcan.AvroValue @@ -27,7 +53,7 @@ for { } yield result ``` -@:api(org.typelevel.vulcan.Codec)s encode Scala types as `AvroValue`s, and decode `AvroValue`s using the schema they were written with. Encoded values are not checked against the schema until they are written as Avro binary or JSON, so tests should be used to ensure @:api(org.typelevel.vulcan.Codec)s work as intended. This becomes important when we define @:api(org.typelevel.vulcan.Codec)s from scratch. +Encoded `AvroValue`s are not checked against the schema until they are written as Avro binary or JSON, so tests should be used to ensure @:api(org.typelevel.vulcan.Codec)s work as intended. This becomes important when we define @:api(org.typelevel.vulcan.Codec)s from scratch. @:api(org.typelevel.vulcan.Codec)s form [invariant functors][invariant], which means you can easily use an existing @:api(org.typelevel.vulcan.Codec) to encode and decode a different type, by mapping back-and-forth between the @:api(org.typelevel.vulcan.Codec)'s existing type argument and the new type. This becomes useful when dealing with newtypes, like `InstallationTime` in the following example. @@ -252,4 +278,47 @@ Codec.union[FirstOrSecond] { alt => For generic derivation support, refer to the [generic module](derivation.md#unions). +## Schema Resolution + +Values are decoded using the schema they were written with, called the writer schema, which might be different from the schema of the @:api(org.typelevel.vulcan.Codec). For example, when using a schema registry, the writer schema is looked up in the registry with an identifier written together with the value. @:api(org.typelevel.vulcan.Schema)s can be parsed from JSON using `Schema.parse` or `Schema.fromJson`. Decoders are compiled for a writer schema, so keep one decoder per writer schema, rather than requesting a new decoder for every value. + +Decoders follow Avro's [schema resolution](https://avro.apache.org/docs/1.12.0/specification/#schema-resolution) to decode values written with a different schema. For example, record fields are matched by name or alias, fields missing in the writer schema are decoded using their default values, and numbers can be promoted, like `int`s to `double`s. Logical types have to match, so for example, a `long` without the `timestamp-millis` logical type can't be decoded as an `Instant`. In the following example, we decode a `Point` written with `int` coordinates, before the `z` field was added. + +```scala mdoc +final case class Point(x: Double, y: Double, z: Double) + +val pointCodec: Codec[Point] = + Codec.record[Point](name = "Point", namespace = "com.example") { field => + ( + field("x", _.x), + field("y", _.y), + field("z", _.z, default = Some(0.0)) + ).mapN(Point(_, _, _)) + } + +for { + writerSchema <- Schema.parse("""{ + "type": "record", + "name": "Point", + "namespace": "com.example", + "fields": [ + { "name": "x", "type": "int" }, + { "name": "y", "type": "int" } + ] + }""") + decoder <- pointCodec.binaryDecoder(writerSchema) + point <- decoder.decode(ByteVector.fromValidHex("0204")) +} yield point +``` + +Binary decoders decode `ByteVector`s, so values written after a header can be decoded without copying. For example, values in the Confluent wire format, which starts with a five byte header, can be decoded using `decoder.decode(ByteVector.view(bytes).drop(5))`. + +Values can also be encoded using a writer schema with `binaryEncoder(writerSchema)`, for example the latest schema in a registry. Values are then resolved into the writer schema, so fields missing in the @:api(org.typelevel.vulcan.Codec) use the defaults of the writer schema, and fields missing in the writer schema are left out. + +To identify schemas, `canonicalForm` and `fingerprint64` return the [Parsing Canonical Form](https://avro.apache.org/docs/1.12.0/specification/#parsing-canonical-form-for-schemas) of a @:api(org.typelevel.vulcan.Schema) and its 64-bit fingerprint. + +## Untrusted Input + +To protect against invalid input, decoding fails for values with records, arrays and maps nested more than 512 levels deep, for more than 1,000,000 array or map items encoded using zero bytes, and for maps and sets with more than 64 keys sharing a hash code. Similarly, parsing fails for schemas with JSON nested more than 256 levels deep. Make sure to also limit the size of values and schemas accepted, and to parse untrusted JSON with circe-jawn's `JawnParser(maxValueSize)`. + [invariant]: https://typelevel.org/cats/typeclasses/invariant.html diff --git a/docs/directory.conf b/docs/directory.conf index fc229b6f..83a5e180 100644 --- a/docs/directory.conf +++ b/docs/directory.conf @@ -2,6 +2,7 @@ laika.navigationOrder = [ overview.md, codecs.md, derivation.md, + migration.md, integrations ] diff --git a/docs/migration.md b/docs/migration.md new file mode 100644 index 00000000..7f9d65ee --- /dev/null +++ b/docs/migration.md @@ -0,0 +1,76 @@ +# Migration Guide + +Vulcan 2.x is a rewrite of the library in pure Scala, without the official Apache Avro Java library, published for Scala @SCALA_PUBLISH_VERSIONS@ on the JVM, [Scala.js](https://www.scala-js.org) and [Scala Native](https://scala-native.org). This page describes what has changed from 1.x, and what to use instead in 2.x. @:api(org.typelevel.vulcan.Codec) schemas remain the same as in 1.x, except in some [minor cases](#behaviour-changes). + +## Dependencies + +Vulcan 2.x is published under `@ORGANIZATION@` instead of `com.github.fd4s`, and uses the `org.typelevel.vulcan` package instead of `vulcan`. This means 1.x and 2.x can be used side by side. + +```scala +libraryDependencies += "@ORGANIZATION@" %% "@CORE_MODULE_NAME@" % "@VERSION@" +``` + +The `@GENERIC_MODULE_NAME@`, `@ENUMERATUM_MODULE_NAME@` and `@REFINED_MODULE_NAME@` modules keep their names. + +Scala 2.12 is no longer supported. + +## API Changes + +The following table shows what has changed from 1.x, and what to use instead in 2.x. + +| 1.x | 2.x | +| ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | +| `import vulcan._`, `vulcan.generic._`, `vulcan.refined._` | `import org.typelevel.vulcan._`, `org.typelevel.vulcan.generic._`, `org.typelevel.vulcan.refined._` | +| `enumeratum.VulcanEnum`, `enumeratum.values.IntVulcanEnum` and the other value enums | The same names in `org.typelevel.vulcan.enumeratum` and `org.typelevel.vulcan.enumeratum.values` | +| `Codec.Aux[Avro.Record, A]`, `Avro.*` | `Codec[A]` | +| `codec.AvroType`, `codec.Repr` | `AvroValue` | +| `codec.encode(a)`, `Codec.encode(a)` | `codec.encoder`, then `encoder.encode(a)` | +| `codec.decode(value, schema)` | `codec.decoder(schema)`, then `decoder.decode(value)` | +| `Codec.decode[A](value)` | `codec.schema.flatMap(codec.decoder)`, then `decoder.decode(value)` | +| `Codec.toBinary(a)` | `codec.binaryEncoder`, then `encoder.encode(a)`; `.toArray` gives an `Array[Byte]` | +| `Codec.fromBinary[A](bytes, schema)` | `codec.binaryDecoder(schema)`, then `decoder.decode(ByteVector.view(bytes))` | +| `Codec.toJson(a)` | `codec.jsonEncoder`, then `encoder.encode(a)`; returns circe `Json`, and `.noSpaces` gives a `String` | +| `Codec.fromJson[A](string, schema)` | `codec.jsonDecoder(schema)`, then `decoder.decode(json)`; parse `string` with `io.circe.jawn.parse` | +| `imapError(f)(g)` | `narrow(f)(g)` | +| `imapErrors(f)(g)` | `exmap(f)(g)` | +| `imapTry(f)(g)` | `narrow(a => f(a).toEither.left.map(e => AvroException(e.toString, e)))(g)` | +| `Codec.instance(schema, encode, decode)` | `Codec.custom(schema, encoder, writerSchema => decoder)` | +| `Codec.enum` | `Codec.enumeration` | +| `Codec.deriveEnum`, `Codec.deriveFixed`, `vulcan.AvroDoc`, `vulcan.AvroNamespace` | The same names in `org.typelevel.vulcan.generic` | +| `Codec.BooleanCodec`, `Codec.FloatCodec`, `Codec.LongCodec` | `Codec.boolean`, `Codec.float`, `Codec.long` | +| Shapeless coproduct codecs | `Codec.union`, or a derived `sealed trait` | +| `Alt#imap`, `Prism#imap` | Removed | +| `InstantMicros#toEpochMicro`, returning `Long` | `toEpochMicro`, returning `Either[Throwable, Long]`, with an error if the microseconds exceed a `Long` | +| `Codec[Array[Byte]]` | `Codec[ByteVector]`; for `Array[Byte]` fields, use `Codec[ByteVector].imap(_.toArray)(ByteVector.view(_))` | +| `Codec.fixed`, `deriveFixed` with `Array[Byte]` functions | The same, with `ByteVector` functions | +| `org.apache.avro.Schema` | `org.typelevel.vulcan.Schema`; for Java tooling, use `new org.apache.avro.Schema.Parser().parse(schema.toString)` | +| `new Schema.Parser().parse(string)` | `Schema.parse(string)`, or `Schema.fromJson(json)` for circe `Json` | +| `SchemaBuilder.builder().intType()` | `Schema.Int`; records are `Schema.Record(name, fields)`, with `withX` modifiers | +| `schema.getFields`, `schema.getLogicalType` | `case record: Schema.Record => record.fields`, `schema.logicalType` | +| `schema.toString(true)` | `schema.toJson.spaces2` | +| `order = Some(Schema.Field.Order.DESCENDING)` | `order = Schema.Field.Order.Descending` | +| `GenericRecord`, `Utf8`, `ByteBuffer`, decoded from `Any` | `AvroValue.Record`, `AvroValue.String`, `AvroValue.Bytes` | +| Untagged union values | `AvroValue.Union(index, value)` | +| `Props.one("a", 1).add("b", "c")` | `JsonObject("a" -> 1.asJson, "b" -> "c".asJson)`, with `io.circe.syntax._` | +| `@AvroProps(props)`, `.prop` | `@AvroProps(jsonObject)`, `.props` | +| `AvroError(message)` | `AvroException(message)` or `AvroException(message, cause)` | +| `AvroDecodingError` | `AvroException` | +| `error.throwable` | `error`, which is now the exception | +| `Eq[AvroError]` | No `Eq` instance; compare `error.message`, or define an `Eq` locally | + +## Behaviour Changes + +- Logical types are checked at every level, so decoding a field with a logical type, like an `Instant`, fails if the writer field doesn't have the same logical type. To decode values written without the logical type, use a codec without one, like `Codec[Long].imap(Instant.ofEpochMilli)(_.toEpochMilli)`. +- Unions also match writer types to reader types by promotion, so an `int` can be read as a union's `long`. +- Error messages have changed. Errors have a subclass per case, like `AvroException.MissingField`. +- To protect against invalid input, decoding and schema parsing have limits, see [untrusted input](codecs.md#untrusted-input). +- On Scala 3, `deriveEnum`, `deriveFixed` and enumeratum codecs for types nested in objects no longer have namespaces ending with `$`, like `com.example.Outer$`, which are invalid in Avro. The namespaces now match Scala 2 and derived records. +- Properties are `Json`, rather than values encoded with a @:api(org.typelevel.vulcan.Codec). To keep schemas the same, convert values to the same `Json` as before. For example, circe encodes `Instant`s and `LocalDate`s as strings, while 1.x encoded them as numbers since the epoch. + +## New Features + +- [Recursive types](codecs.md#recursive-types), where record codecs refer to themselves, and `Codec.recursive` for `def` codecs. +- Codecs for additional logical types: `Codec.decimalFixed`, `Codec.bigDecimal`, `Codec.uuidFixed` and `Codec.duration`, and `Codec.InstantNanos`, `Codec.LocalDateTimeMicros` and `Codec.LocalDateTimeNanos` for timestamps. +- `Codec#widen` for mappings where only encoding can fail, `withLogicalType` and `withTypeName` for custom codecs, and `Codec.fail`. +- `binaryEncoder(writerSchema)`, to encode values using a different writer schema, see [schema resolution](codecs.md#schema-resolution). +- `canonicalForm` and `fingerprint64` on @:api(org.typelevel.vulcan.Schema)s. diff --git a/docs/overview.md b/docs/overview.md index c44b8423..2854ca27 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -26,6 +26,8 @@ Published for Scala @SCALA_PUBLISH_VERSIONS@, [Scala.js](https://www.scala-js.or For changes between versions, please refer to the [release notes](https://github.com/typelevel/vulcan/releases). +To upgrade from 1.x, refer to the [migration guide](migration.md). + ### External Modules Following is an incomplete list of third-party integrations.