diff --git a/Cargo.lock b/Cargo.lock index d9c1390..9852b62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "aliasable" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd" + [[package]] name = "alloca" version = "0.4.0" @@ -97,10 +103,50 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "apache-avro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99df1cb179dda2bed7b366b43b6a319349e4c0e920e287f09b285f852db6884e" +dependencies = [ + "apache-avro-derive", + "bigdecimal", + "bon", + "digest 0.11.3", + "log", + "miniz_oxide", + "num-bigint", + "ouroboros", + "quad-rand", + "rand 0.10.4", + "regex-lite", + "serde", + "serde_bytes", + "serde_json", + "strum", + "thiserror", + "uuid", +] + +[[package]] +name = "apache-avro-derive" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e965c4cafba0c52d33a5cfa423a105b724211763db30b68fd70dee2c3aa8bb3" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "rustversion", + "serde_json", + "syn 3.0.10", +] + [[package]] name = "apache-pulsar" version = "0.1.0" dependencies = [ + "apache-avro", "apache-pulsar-protocol", "apache-pulsar-testkit", "base64 0.22.1", @@ -115,6 +161,7 @@ dependencies = [ "rcgen", "ring", "rustls-native-certs", + "serde", "serde_json", "testcontainers", "thiserror", @@ -337,6 +384,20 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bigdecimal" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fa3f3d8cbf4dffcfe4991de61d012bef509a409ecbe9dd41049bfe32b4d4653" +dependencies = [ + "autocfg", + "libm", + "num-bigint", + "num-integer", + "num-traits", + "serde", +] + [[package]] name = "bit-vec" version = "0.9.1" @@ -444,6 +505,29 @@ dependencies = [ "time", ] +[[package]] +name = "bon" +version = "3.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05442cd7005532d0cfedec676b5b9333d2b4c7c3afabe2b1a9ce2742fbe2ee6" +dependencies = [ + "bon-macros", +] + +[[package]] +name = "bon-macros" +version = "3.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93833e97ac7c46ba97045afcf247238c27057538fcf2f06344662ddd5f567be6" +dependencies = [ + "darling", + "ident_case", + "prettyplease 0.3.0", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "bs58" version = "0.5.1" @@ -489,7 +573,7 @@ checksum = "bb4bea10ef85ea3d06a20412c67cb612527feb25f33367eab850139441fb5dd9" dependencies = [ "buffa", "buffa-descriptor", - "prettyplease", + "prettyplease 0.2.37", "proc-macro2", "quote", "syn 2.0.119", @@ -640,7 +724,7 @@ version = "4.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a" dependencies = [ - "heck", + "heck 0.5.0", "proc-macro2", "quote", "syn 3.0.10", @@ -1675,6 +1759,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + [[package]] name = "heck" version = "0.5.0" @@ -2180,6 +2270,12 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libtest-mimic" version = "0.8.2" @@ -2353,6 +2449,7 @@ checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" dependencies = [ "num-integer", "num-traits", + "serde", ] [[package]] @@ -2442,6 +2539,30 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" +[[package]] +name = "ouroboros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0f050db9c44b97a94723127e6be766ac5c340c48f2c4bb3ffa11713744be59" +dependencies = [ + "aliasable", + "ouroboros_macro", + "static_assertions", +] + +[[package]] +name = "ouroboros_macro" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c7028bdd3d43083f6d8d4d5187680d0d3560d54df4cc9d752005268b41e64d0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 2.0.119", +] + [[package]] name = "p256" version = "0.14.0" @@ -2661,6 +2782,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.10", +] + [[package]] name = "primefield" version = "0.14.0" @@ -2706,6 +2837,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "version_check", + "yansi", +] + [[package]] name = "prost" version = "0.14.6" @@ -2738,6 +2882,12 @@ dependencies = [ "prost", ] +[[package]] +name = "quad-rand" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a651516ddc9168ebd67b24afd085a718be02f8858fe406591b013d101ce2f40" + [[package]] name = "quinn-proto" version = "0.11.19" @@ -2893,6 +3043,12 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + [[package]] name = "regex-syntax" version = "0.8.12" @@ -3148,6 +3304,16 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -3397,6 +3563,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "strsim" version = "0.11.1" @@ -3426,6 +3598,27 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "subtle" version = "2.6.1" @@ -3935,6 +4128,17 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + [[package]] name = "valuable" version = "0.1.1" @@ -4340,6 +4544,12 @@ dependencies = [ "buffa-build", ] +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + [[package]] name = "yasna" version = "0.6.0" diff --git a/PLAN.md b/PLAN.md index a526442..2523e07 100644 --- a/PLAN.md +++ b/PLAN.md @@ -176,17 +176,18 @@ covered. The schemas land in five pull requests: the primitive types and C11's typed error; key/value; generic records, with each message decoded by the schema of its version; JSON and Avro; Protobuf. -Schemas so far: bytes, string, the primitive types, key/value and generic records, named and encoded as Java's, with a -public `SchemaInfo` and `SchemaType`. The simulated cluster keeps a schema history per topic, as the broker does, and -serves a schema by version. C11 holds there and against a 5.0.1 broker: a schema of another type than the topic's -fails with `IncompatibleSchema` for a Shared producer's sends, an exclusive producer's create, and each kind of -consumer's subscribe; the first consumer of a new topic registers its schema; and a topic with messages but no schema -refuses a schema. Java reads the values of each primitive type and key/value pairs that Rust sends, and Rust those -Java sends, typed and as generic records. A generic consumer fetches the schema of each version it meets, and decodes -each message with its own: against 5.0.1, with the primitive types and key/value, that is a message of a schema and -one without; schema evolution, with JSON and Avro, comes with their pull request. Key/value is Java's inline encoding; -its separated one, with the key in the message's key, comes later. Java V5's `autoProduceBytes()` and -`generic(SchemaInfo)`, which the spec's standard set doesn't name, aren't planned yet. +Schemas so far: bytes, string, the primitive types, key/value, generic records, JSON and Avro, named and encoded as +Java's, with a public `SchemaInfo` and `SchemaType`; JSON and Avro are features, on by default, through `serde` and +apache-avro. The simulated cluster keeps a schema history per topic, as the broker does, and serves a schema by +version. C11 holds there and against a 5.0.1 broker: a schema of another type than the topic's fails with +`IncompatibleSchema` for a Shared producer's sends, an exclusive producer's create, and each kind of consumer's +subscribe; the first consumer of a new topic registers its schema; and a topic with messages but no schema refuses a +schema. Java reads the values of each schema that Rust sends, and Rust those Java sends, typed and as generic records. +Generic and Avro consumers fetch the schema of each version they meet, and decode each message with its own: against +5.0.1, Java's V5 evolution test holds across the two clients, a second Avro version registering after a split and +both clients reading the first version's records with it. Key/value is Java's inline encoding; its separated one, +with the key in the message's key, comes later. Java V5's `autoProduceBytes()` and `generic(SchemaInfo)`, which the +spec's standard set doesn't name, aren't planned yet. The migration bridge's end-to-end tests run against 5.0.1, on partitioned and non-partitioned topics, with Java v4 clients running alongside (`tests/integration/bridge.rs`): diff --git a/crates/apache-pulsar/Cargo.toml b/crates/apache-pulsar/Cargo.toml index 7764e89..8dd40dd 100644 --- a/crates/apache-pulsar/Cargo.toml +++ b/crates/apache-pulsar/Cargo.toml @@ -28,6 +28,9 @@ homepage.workspace = true workspace = true [dependencies] +# The JSON and Avro schemas' definitions, which are Avro's, and Avro's encoding. Applications derive `AvroSchema` +# with apache-avro's `derive` feature. +apache-avro = { version = "0.23", optional = true } apache-pulsar-protocol.workspace = true buffa.workspace = true bytes.workspace = true @@ -38,28 +41,35 @@ futures-channel = "0.3" futures-executor = "0.3" futures-util = { version = "0.3", default-features = false, features = ["std", "io"] } rustls-native-certs = "0.8" +# The values of the JSON and Avro schemas. +serde = { version = "1", optional = true } # Key/value schemas record their key's and value's properties as JSON, as Java's do. serde_json = "1" thiserror.workspace = true tracing = "0.1" [dev-dependencies] +apache-avro = { version = "0.23", features = ["derive"] } apache-pulsar-testkit = { path = "../apache-pulsar-testkit" } base64 = "0.22" jsonwebtoken = { version = "12", default-features = false, features = ["rust_crypto"] } libtest-mimic = "0.8" rcgen = "0.14" ring = "0.17" +serde = { version = "1", features = ["derive"] } testcontainers = { version = "0.28", features = ["blocking", "watchdog"] } # The compression codecs, each behind a feature, all on by default (docs/3-protocol.md §6). ZSTD binds the C # `libzstd`, so building it needs a C compiler. [features] -default = ["lz4", "zlib", "snappy", "zstd"] +default = ["lz4", "zlib", "snappy", "zstd", "json", "avro"] lz4 = ["apache-pulsar-protocol/lz4"] zlib = ["apache-pulsar-protocol/zlib"] snappy = ["apache-pulsar-protocol/snappy"] zstd = ["apache-pulsar-protocol/zstd"] +# The JSON and Avro schemas, on by default (docs/7-api.md §8). Both describe their records in Avro, as Java's do. +json = ["dep:apache-avro", "dep:serde"] +avro = ["dep:apache-avro", "dep:serde"] # Against a broker and a proxy in Docker. Not run by `cargo test`: `cargo test -p apache-pulsar --test integration`. [[test]] diff --git a/crates/apache-pulsar/src/consumer/writers.rs b/crates/apache-pulsar/src/consumer/writers.rs index 526938a..975c942 100644 --- a/crates/apache-pulsar/src/consumer/writers.rs +++ b/crates/apache-pulsar/src/consumer/writers.rs @@ -16,8 +16,9 @@ // under the License. //! The schemas a consumer's messages were written with, which [`Schema::auto_consume`](crate::Schema::auto_consume) -//! decodes them with. The consumer fetches the schema of a version before it delivers the first message of it, by the -//! topic of the message's segment, as the standard schema commands go to a segment (*wire-protocol* §10). +//! and the Avro schemas decode them with. The consumer fetches the schema of a version before it delivers the first +//! message of it, by the topic of the message's segment, as the standard schema commands go to a segment +//! (*wire-protocol* §10). use std::collections::HashMap; use std::future::Future; @@ -61,9 +62,19 @@ pub(crate) struct Writers { } /// Whether a consumer of `options` decodes with the schemas its messages were written with: one that declares -/// [`Schema::auto_consume`](crate::Schema::auto_consume)'s type, the one schema that does. +/// [`Schema::auto_consume`](crate::Schema::auto_consume)'s type, or Avro's, alone or in a key/value schema, as Java's +/// Avro schema reads each message with its version's. A key/value schema nested in another counts: it may hold Avro. pub(crate) fn wanted(options: &ConsumerOptions) -> bool { - options.schema.as_ref().is_some_and(|schema| schema.r#type == Type::AutoConsume) + let fetching = |schema: &proto::Schema, part: &str| { + let key = format!("{part}.schema.type"); + let fetching = |kind: &str| matches!(kind, "AVRO" | "KEY_VALUE"); + schema.properties.iter().any(|property| property.key == key && fetching(&property.value)) + }; + options.schema.as_ref().is_some_and(|schema| match schema.r#type { + Type::AutoConsume | Type::Avro => true, + Type::KeyValue => fetching(schema, "key") || fetching(schema, "value"), + _ => false, + }) } impl Writers { @@ -115,3 +126,34 @@ impl Writers { true } } + +#[cfg(all(test, feature = "json", feature = "avro"))] +mod tests { + use super::*; + use crate::schema::Schema; + + #[derive(serde::Serialize, serde::Deserialize, apache_avro::AvroSchema)] + struct Pojo { + name: Option, + } + + fn fetches(schema: Schema) -> bool { + wanted(&ConsumerOptions { schema: schema.info().to_proto(), ..ConsumerOptions::default() }) + } + + /// The consumers that fetch their messages' schemas: generic records', and Avro's, alone or in a key/value + /// schema, nested ones included, as Java's Avro schema reads each message with its version's. + #[test] + fn the_consumers_that_fetch_their_messages_schemas() { + assert!(fetches(Schema::auto_consume())); + assert!(fetches(Schema::::avro())); + assert!(fetches(Schema::key_value(Schema::string(), Schema::::avro()))); + assert!(fetches(Schema::key_value(Schema::::avro(), Schema::string()))); + let nested = Schema::key_value(Schema::string(), Schema::::avro()); + assert!(fetches(Schema::key_value(nested, Schema::bool()))); + assert!(!fetches(Schema::key_value(Schema::string(), Schema::::json()))); + assert!(!fetches(Schema::::json())); + assert!(!fetches(Schema::string())); + assert!(!fetches(Schema::bytes())); + } +} diff --git a/crates/apache-pulsar/src/schema.rs b/crates/apache-pulsar/src/schema.rs index 4240850..7712efb 100644 --- a/crates/apache-pulsar/src/schema.rs +++ b/crates/apache-pulsar/src/schema.rs @@ -20,7 +20,13 @@ //! The schema is topic-level (*data-model* §6): the broker keeps one history of schemas for a scalable topic, which //! every segment shares, and checks a producer's or a consumer's schema against it as it registers on a segment. +#[cfg(feature = "avro")] +mod avro; mod generic; +#[cfg(feature = "json")] +mod json; +#[cfg(any(feature = "json", feature = "avro"))] +mod record; use std::collections::BTreeMap; use std::sync::Arc; @@ -30,11 +36,18 @@ use apache_pulsar_protocol::proto::schema::Type; use bytes::{BufMut, Bytes, BytesMut}; pub use self::generic::{GenericRecord, GenericValue}; +#[cfg(any(feature = "json", feature = "avro"))] +use self::record::Definitions; use crate::error::{Error, ErrorKind, Result}; +/// Without JSON and Avro, no definitions to parse. +#[cfg(not(any(feature = "json", feature = "avro")))] +#[derive(Default)] +struct Definitions {} + type Encode = Arc Result + Send + Sync>; -/// Decodes a payload. Only [`Schema::auto_consume`] reads the schema it was written with: `None` for a message -/// without one. +/// Decodes a payload, written with the schema given: `None` for a message without one. Only the schemas that fetch the +/// schemas of their messages read it: [`Schema::auto_consume`], the Avro schemas, and a key/value schema of them. type Decode = Arc) -> Result + Send + Sync>; /// How values of type `T` are encoded, and the schema the broker is told about. Cheap to clone. @@ -49,6 +62,8 @@ type Decode = Arc) -> Result + Send + Sy /// | `int8()` to `int64()` | `i8` to `i64` | big endian | /// | `float32()`, `float64()` | `f32`, `f64` | IEEE 754, big endian | /// | `key_value(key, value)` | [`KeyValue`] | the key's length, 4 bytes big endian, and bytes, then the value's | +/// | `json()` (feature `json`) | a record type of `serde` and apache-avro | JSON, described in Avro | +/// | `avro()` (feature `avro`) | a record type of `serde` and apache-avro | an Avro datum | /// | `auto_consume()` | [`GenericRecord`] | decoded with the schema each message was written with | pub struct Schema { info: SchemaInfo, @@ -167,6 +182,30 @@ impl SchemaInfo { Self { name: "KeyValue".to_string(), schema_type: SchemaType::KeyValue, definition, properties } } + /// The schemas of a key/value schema's key and value, as Java's `KeyValueSchemaInfo` reads them: their names, + /// types and properties from its properties, and their definitions from its. Without a type, a part is bytes, as + /// in Java. + fn parts(&self) -> Result<(SchemaInfo, SchemaInfo)> { + let (key, value) = split_inline(&self.definition)?; + Ok((self.part("key", key)?, self.part("value", value)?)) + } + + fn part(&self, side: &str, definition: Option<&[u8]>) -> Result { + let property = |name: &str| self.properties.get(&format!("{side}.schema.{name}")); + let properties = match property("properties").filter(|json| !json.is_empty()) { + Some(json) => serde_json::from_str(json).map_err(|e| { + Error::new(ErrorKind::Other, format!("the key/value schema's {side} properties aren't JSON: {e}")) + })?, + None => BTreeMap::new(), + }; + Ok(SchemaInfo { + name: property("name").cloned().unwrap_or_default(), + schema_type: property("type").map_or(SchemaType::Bytes, |name| SchemaType::from_java_name(name)), + definition: definition.unwrap_or_default().to_vec(), + properties, + }) + } + /// The name, as Java names its schema of the same type. pub fn name(&self) -> &str { &self.name @@ -346,11 +385,12 @@ impl Schema> { encode: Arc::new(move |pair: &KeyValue| { Ok(inline(&encode_key(&pair.key)?, &encode_value(&pair.value)?)) }), - decode: Arc::new(move |data: &[u8], _: Option<&SchemaInfo>| { + decode: Arc::new(move |data: &[u8], writer: Option<&SchemaInfo>| { let (key, value) = split_inline(data)?; + let (key_writer, value_writer) = part_writers(writer)?; Ok(KeyValue { - key: decode_key(not_null(key, "key")?, None)?, - value: decode_value(not_null(value, "value")?, None)?, + key: decode_key(not_null(key, "key")?, key_writer.as_ref())?, + value: decode_value(not_null(value, "value")?, value_writer.as_ref())?, }) }), generic, @@ -358,6 +398,17 @@ impl Schema> { } } +/// The schemas a key/value message's key and value were written with: the parts of the key/value schema it was +/// written with, which an Avro key or value reads with. +fn part_writers(writer: Option<&SchemaInfo>) -> Result<(Option, Option)> { + match writer { + Some(writer) if writer.schema_type == SchemaType::KeyValue => { + writer.parts().map(|(key, value)| (Some(key), Some(value))) + } + _ => Ok((None, None)), + } +} + /// An inline key/value payload, as Java writes it: the key's length, 4 bytes big endian, and its bytes, then the /// value's. fn inline(key: &[u8], value: &[u8]) -> Bytes { @@ -434,7 +485,7 @@ impl Schema { (self.encode)(value) } - /// Decodes a payload written with `writer`, which only [`Schema::auto_consume`] reads: `None` for a message + /// Decodes a payload written with `writer`, which the schemas that fetch their messages' read: `None` for a message /// without a schema. pub(crate) fn decode_with(&self, data: &[u8], writer: Option<&SchemaInfo>) -> Result { (self.decode)(data, writer) diff --git a/crates/apache-pulsar/src/schema/avro.rs b/crates/apache-pulsar/src/schema/avro.rs new file mode 100644 index 0000000..e8b4479 --- /dev/null +++ b/crates/apache-pulsar/src/schema/avro.rs @@ -0,0 +1,239 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Avro: Java's `Schema.avro`, records encoded as Avro datums, read with the schema each was written with. + +use std::sync::Arc; + +use apache_avro::AvroSchema; +use apache_avro::reader::datum::GenericDatumReader; +use apache_avro::types::Value; +use apache_avro::writer::datum::GenericDatumWriter; +use bytes::Bytes; +use serde::Serialize; +use serde::de::DeserializeOwned; + +use super::record::{Definitions, avro_error, info}; +use super::{Generic, Schema, SchemaInfo, SchemaType}; +use crate::error::{Error, Result}; + +impl Schema { + /// Records in Avro's binary encoding, as Java's `Schema.avro(Class)` encodes them: a datum, without a header. The + /// schema is the one `T` derives, with `#[derive(AvroSchema)]` of apache-avro's `derive` feature: an `Option` + /// field is nullable, with a default of null, as Java's reflection makes its nullable fields. + /// + /// Each message is read with the schema it was written with, which the consumer fetches from the broker once for + /// each version, as Java does: Avro's resolution then fills in what this schema adds, such as a field of a later + /// version, and the fields come in whichever order the writer's schema has them. A message without a version reads + /// with this schema. + pub fn avro() -> Self { + let avro = Arc::new(Avro::new(T::get_schema())); + let reader = avro.clone(); + Self { + info: info(SchemaType::Avro, &avro.schema), + encode: Arc::new(move |value: &T| avro.encode(value)), + decode: Arc::new(move |data: &[u8], writer: Option<&SchemaInfo>| reader.decode(data, writer)), + generic: Generic::No, + } + } +} + +/// An Avro schema, and the schemas of other versions it reads messages written with. +struct Avro { + schema: apache_avro::Schema, + /// The definition the broker is told about, which a message written with this schema has. + definition: Vec, + writers: Definitions, +} + +impl Avro { + fn new(schema: apache_avro::Schema) -> Self { + let definition = info(SchemaType::Avro, &schema).definition; + Self { schema, definition, writers: Definitions::default() } + } + + fn encode(&self, value: &T) -> Result { + let writer = GenericDatumWriter::builder(&self.schema).build(); + writer.and_then(|writer| writer.write_ser_to_vec(value)).map(Bytes::from).map_err(unencodable) + } + + /// Decodes a payload written with `writer`'s schema. + fn decode(&self, data: &[u8], writer: Option<&SchemaInfo>) -> Result { + match self.writer(writer)? { + None => { + GenericDatumReader::builder(&self.schema).build().and_then(|reader| reader.read_deser(&mut &data[..])) + } + Some(writer) => self.resolve(&writer, data).and_then(|value| apache_avro::from_value(&value)), + } + .map_err(undecodable) + } + + /// The schema a message was written with, if it isn't this one: an Avro schema's of another definition. + fn writer(&self, writer: Option<&SchemaInfo>) -> Result>> { + match writer { + Some(writer) if writer.schema_type == SchemaType::Avro && writer.definition != self.definition => { + self.writers.parse(&writer.definition).map(Some) + } + _ => Ok(None), + } + } + + /// A payload written with `writer`, read into this schema. + fn resolve(&self, writer: &apache_avro::Schema, data: &[u8]) -> std::result::Result { + let reader = GenericDatumReader::builder(writer).reader_schema(&self.schema).build(); + reader.and_then(|reader| reader.read_value(&mut &data[..])) + } +} + +fn unencodable(error: apache_avro::Error) -> Error { + avro_error("the value doesn't encode in Avro", error) +} + +/// A payload that doesn't decode in Avro, or doesn't resolve into the reader's schema. +pub(super) fn undecodable(error: apache_avro::Error) -> Error { + avro_error("the payload doesn't decode in Avro", error) +} + +#[cfg(test)] +mod tests { + use serde::Deserialize; + + use super::*; + use crate::schema::KeyValue; + use crate::schema::record::{Unencodable, properties}; + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, apache_avro::AvroSchema)] + struct Pojo { + name: Option, + age: i32, + } + + /// A record's first version, and its second, which adds a nullable field, as Java's V5 evolution test has them. + #[derive(Debug, PartialEq, Serialize, Deserialize, apache_avro::AvroSchema)] + struct V1 { + i: i32, + } + + #[derive(Debug, PartialEq, Serialize, Deserialize, apache_avro::AvroSchema)] + struct V2 { + i: i32, + j: Option, + } + + /// A second version that adds a field without a default, which a record of the first can't fill. + #[derive(Debug, PartialEq, Serialize, Deserialize, apache_avro::AvroSchema)] + struct Bad { + i: i32, + j: i32, + } + + /// A schema as the broker returns it, named after its topic. + fn written_with(definition: &[u8]) -> SchemaInfo { + SchemaInfo { + name: "acme/orders/events".to_string(), + schema_type: SchemaType::Avro, + definition: definition.to_vec(), + properties: properties(), + } + } + + #[test] + fn records_encode_as_avro_datums() { + let schema = Schema::::avro(); + let info = schema.info(); + assert_eq!((info.name(), info.schema_type(), info.properties()), ("", SchemaType::Avro, &properties())); + let definition: serde_json::Value = serde_json::from_slice(info.definition()).unwrap(); + let fields = [ + serde_json::json!({"name": "name", "type": ["null", "string"], "default": null}), + serde_json::json!({"name": "age", "type": "int"}), + ]; + assert_eq!(definition, serde_json::json!({"type": "record", "name": "Pojo", "fields": fields})); + let alice = Pojo { name: Some("alice".to_string()), age: 30 }; + // The name's union branch, 1, and its length, 5, then the age, 30, each a zig-zag varint. + let payload = schema.encode(&alice).unwrap(); + assert_eq!(&payload[..], [2, 10, b'a', b'l', b'i', b'c', b'e', 60]); + assert_eq!(schema.decode(&payload).unwrap(), alice); + assert_eq!(schema.decode_with(&payload, Some(info)).unwrap(), alice, "its own version"); + let nameless = Pojo { name: None, age: -1 }; + assert_eq!(schema.decode(&schema.encode(&nameless).unwrap()).unwrap(), nameless); + } + + /// A record reads with the schema it was written with: Java's reflection orders the fields of the same record + /// otherwise, and an older Java client names it in a namespace that ends in `$`; and a version that adds a + /// nullable field reads a record of the one before with it null, as Java's V5 evolution test does. + #[test] + fn records_read_with_the_schema_they_were_written_with() { + let java = br#"{"type":"record","name":"Pojo","namespace":"SchemaTool$","fields":[{"name":"age","type":"int"}, + {"name":"name","type":["null","string"],"default":null}]}"#; + let payload = [60, 2, 10, b'a', b'l', b'i', b'c', b'e']; + let read = Schema::::avro().decode_with(&payload, Some(&written_with(java))).unwrap(); + assert_eq!(read, Pojo { name: Some("alice".to_string()), age: 30 }); + + let (v1, v2) = (Schema::::avro(), Schema::::avro()); + let first = v1.encode(&V1 { i: 7 }).unwrap(); + let read = v2.decode_with(&first, Some(&written_with(v1.info().definition()))).unwrap(); + assert_eq!(read, V2 { i: 7, j: None }); + let second = v2.encode(&V2 { i: 8, j: Some(9) }).unwrap(); + assert_eq!( + v2.decode_with(&second, Some(&written_with(v2.info().definition()))).unwrap(), + V2 { i: 8, j: Some(9) } + ); + // Without a version, or with a schema of another type, a message reads with the consumer's own schema. + assert_eq!(v2.decode_with(&second, None).unwrap(), V2 { i: 8, j: Some(9) }); + assert_eq!(v2.decode_with(&second, Some(Schema::int32().info())).unwrap(), V2 { i: 8, j: Some(9) }); + } + + #[test] + fn records_that_dont_encode_or_decode() { + let error = Schema::::avro().encode(&Unencodable).unwrap_err().to_string(); + assert!(error.contains("the value doesn't encode in Avro"), "{error}"); + let schema = Schema::::avro(); + let error = schema.decode(&[0x80]).unwrap_err().to_string(); + assert!(error.contains("the payload doesn't decode in Avro"), "{error}"); + let error = schema.decode_with(&[], Some(&written_with(b"{"))).unwrap_err().to_string(); + assert!(error.contains("isn't JSON"), "{error}"); + let error = schema.decode_with(&[0x80], Some(&written_with(br#""int""#))).unwrap_err().to_string(); + assert!(error.contains("the payload doesn't decode in Avro"), "{error}"); + // A record of the first version doesn't have the field the bad one requires: Avro's resolution can't fill it. + let v1 = Schema::::avro(); + let first = v1.encode(&V1 { i: 7 }).unwrap(); + let error = Schema::::avro().decode_with(&first, Some(&written_with(v1.info().definition()))).unwrap_err(); + assert!(error.to_string().contains("the payload doesn't decode in Avro"), "{error}"); + } + + /// A key/value schema reads each part with its part of the schema the message was written with: a later + /// version's value reads the earlier one's record. + #[test] + fn key_values_read_each_part_with_its_writer() { + let first = Schema::key_value(Schema::string(), Schema::::avro()); + let second = Schema::key_value(Schema::string(), Schema::::avro()); + let payload = first.encode(&KeyValue { key: "k".to_string(), value: V1 { i: 7 } }).unwrap(); + let read = second.decode_with(&payload, Some(first.info())).unwrap(); + assert_eq!(read, KeyValue { key: "k".to_string(), value: V2 { i: 7, j: None } }); + // A key/value schema whose parts don't read fails the message. + let mut broken = first.info().clone(); + broken.definition.truncate(2); + let error = second.decode_with(&payload, Some(&broken)).unwrap_err().to_string(); + assert!(error.contains("ends in its key"), "{error}"); + // A key/value schema nested in another hands its Avro part its part too. + let (first, second) = (Schema::key_value(first, Schema::bool()), Schema::key_value(second, Schema::bool())); + let inner = KeyValue { key: "k".to_string(), value: V1 { i: 8 } }; + let payload = first.encode(&KeyValue { key: inner, value: true }).unwrap(); + let read = second.decode_with(&payload, Some(first.info())).unwrap(); + assert_eq!((read.key.value, read.value), (V2 { i: 8, j: None }, true)); + } +} diff --git a/crates/apache-pulsar/src/schema/generic.rs b/crates/apache-pulsar/src/schema/generic.rs index 21ae1fb..50aa48a 100644 --- a/crates/apache-pulsar/src/schema/generic.rs +++ b/crates/apache-pulsar/src/schema/generic.rs @@ -17,10 +17,14 @@ //! Generic records: values decoded with the schema each message was written with ([`Schema::auto_consume`]). -use std::collections::BTreeMap; use std::sync::Arc; -use super::{Generic, KeyValue, Schema, SchemaInfo, SchemaType, boolean, sized, split_inline, utf8}; +#[cfg(feature = "avro")] +use apache_avro::reader::datum::GenericDatumReader; + +#[cfg(feature = "avro")] +use super::avro::undecodable; +use super::{Definitions, Generic, KeyValue, Schema, SchemaInfo, SchemaType, boolean, sized, split_inline, utf8}; use crate::error::{Error, ErrorKind, Result}; /// A value decoded with the schema its message was written with: the values of [`Schema::auto_consume`], as Java @@ -29,6 +33,7 @@ use crate::error::{Error, ErrorKind, Result}; pub struct GenericRecord { schema_type: SchemaType, value: GenericValue, + fields: Vec, } impl GenericRecord { @@ -45,6 +50,36 @@ impl GenericRecord { pub fn into_value(self) -> GenericValue { self.value } + + /// The names of a record's fields, in the order of the schema it was written with, as Java V5's `fields()`: none + /// for a value that isn't a JSON or an Avro record. + pub fn fields(&self) -> &[String] { + &self.fields + } + + /// A field of a JSON or an Avro record, as Java V5's `field(name)`: its value, as Java's record holds it, an Avro + /// union's branch without the union, or `None` for a field it doesn't have, and for a value that isn't a record. + #[cfg_attr(not(any(feature = "json", feature = "avro")), expect(unused_variables))] + pub fn field(&self, name: &str) -> Option { + match &self.value { + #[cfg(feature = "json")] + GenericValue::Json(serde_json::Value::Object(fields)) => fields.get(name).cloned().map(GenericValue::Json), + #[cfg(feature = "avro")] + GenericValue::Avro(apache_avro::types::Value::Record(fields)) => { + fields.iter().find(|(field, _)| field == name).map(|(_, value)| GenericValue::Avro(branch(value))) + } + _ => None, + } + } +} + +/// An Avro value as Java's record holds it: a union's branch without the union. +#[cfg(feature = "avro")] +fn branch(value: &apache_avro::types::Value) -> apache_avro::types::Value { + match value { + apache_avro::types::Value::Union(_, branch) => (**branch).clone(), + value => value.clone(), + } } /// The value of a generic record, by the type of the schema it was written with. @@ -65,6 +100,13 @@ pub enum GenericValue { Double(f64), /// A key and a value, each by its own schema. KeyValue(Box>), + /// A value of a JSON schema, as `serde_json` reads it: an object for a record. + #[cfg(feature = "json")] + Json(serde_json::Value), + /// A value of an Avro schema, as apache-avro reads it with the schema it was written with: a record's fields come + /// in that schema's order. + #[cfg(feature = "avro")] + Avro(apache_avro::types::Value), } impl Schema { @@ -74,30 +116,33 @@ impl Schema { /// message's [`value`](crate::Message::value), and the next message of that version fetches again. /// /// The broker doesn't check this schema against the topic's, so it reads any topic, and registers none. It - /// decodes the primitive types and key/value; JSON, Avro and Protobuf values fail to decode, as this client - /// doesn't read them yet. Producers don't take it: they fail to create with [`ErrorKind::InvalidConfiguration`], as - /// Java v4's do. + /// decodes the primitive types, key/value, and with their features JSON and Avro; Protobuf values fail to decode, + /// as this client doesn't read them yet. Producers don't take it: they fail to create with + /// [`ErrorKind::InvalidConfiguration`], as Java v4's do. pub fn auto_consume() -> Self { + let definitions = Definitions::default(); Self { info: SchemaInfo::new("AutoConsume", SchemaType::AutoConsume), encode: Arc::new(|_: &GenericRecord| { Err(Error::new(ErrorKind::InvalidConfiguration, "auto_consume() only decodes")) }), - decode: Arc::new(decode), + decode: Arc::new(move |data: &[u8], writer: Option<&SchemaInfo>| decode(&definitions, data, writer)), generic: Generic::Whole, } } } /// Decodes a payload with the schema it was written with: as bytes without one. -fn decode(data: &[u8], writer: Option<&SchemaInfo>) -> Result { +fn decode(definitions: &Definitions, data: &[u8], writer: Option<&SchemaInfo>) -> Result { let bytes = SchemaInfo::new("Bytes", SchemaType::Bytes); let writer = writer.unwrap_or(&bytes); - Ok(GenericRecord { schema_type: writer.schema_type, value: decode_value(data, writer)? }) + let value = decode_value(definitions, data, writer)?; + let fields = fields(definitions, &value, writer); + Ok(GenericRecord { schema_type: writer.schema_type, value, fields }) } /// A payload's value, by the schema it was written with. -fn decode_value(data: &[u8], writer: &SchemaInfo) -> Result { +fn decode_value(definitions: &Definitions, data: &[u8], writer: &SchemaInfo) -> Result { let name = writer.schema_type.java_name(); Ok(match writer.schema_type { SchemaType::Bytes | SchemaType::None => GenericValue::Bytes(data.to_vec()), @@ -109,7 +154,9 @@ fn decode_value(data: &[u8], writer: &SchemaInfo) -> Result { SchemaType::Int64 => GenericValue::Int64(sized(name, data, i64::from_be_bytes)?), SchemaType::Float => GenericValue::Float(sized(name, data, f32::from_be_bytes)?), SchemaType::Double => GenericValue::Double(sized(name, data, f64::from_be_bytes)?), - SchemaType::KeyValue => key_value(data, writer)?, + SchemaType::KeyValue => key_value(definitions, data, writer)?, + SchemaType::Json => json(data)?, + SchemaType::Avro => avro(definitions, data, writer)?, _ => { return Err(Error::new( ErrorKind::Other, @@ -119,37 +166,62 @@ fn decode_value(data: &[u8], writer: &SchemaInfo) -> Result { }) } +/// The names of a record's fields, in the order of the schema it was written with: an Avro record's own, and a JSON +/// one's from the Avro schema that describes it, or its own if that doesn't describe a record. +#[cfg_attr(not(feature = "json"), expect(unused_variables))] +fn fields(definitions: &Definitions, value: &GenericValue, writer: &SchemaInfo) -> Vec { + match value { + #[cfg(feature = "json")] + GenericValue::Json(serde_json::Value::Object(fields)) => match definitions.parse(&writer.definition).as_deref() + { + Ok(apache_avro::Schema::Record(record)) => record.fields.iter().map(|field| field.name.clone()).collect(), + _ => fields.keys().cloned().collect(), + }, + #[cfg(feature = "avro")] + GenericValue::Avro(apache_avro::types::Value::Record(fields)) => { + fields.iter().map(|(name, _)| name.clone()).collect() + } + _ => Vec::new(), + } +} + +#[cfg(feature = "json")] +fn json(data: &[u8]) -> Result { + let value = serde_json::from_slice(data); + value.map(GenericValue::Json).map_err(|e| Error::new(ErrorKind::Other, format!("the payload isn't JSON: {e}"))) +} + +#[cfg(not(feature = "json"))] +fn json(_: &[u8]) -> Result { + Err(Error::new(ErrorKind::Other, "reading JSON records takes the `json` feature")) +} + +/// An Avro payload, read with the schema it was written with. +#[cfg(feature = "avro")] +fn avro(definitions: &Definitions, data: &[u8], writer: &SchemaInfo) -> Result { + let schema = definitions.parse(&writer.definition)?; + let value = GenericDatumReader::builder(&schema).build().and_then(|reader| reader.read_value(&mut &data[..])); + value.map(GenericValue::Avro).map_err(undecodable) +} + +#[cfg(not(feature = "avro"))] +fn avro(_: &Definitions, _: &[u8], _: &SchemaInfo) -> Result { + Err(Error::new(ErrorKind::Other, "reading Avro records takes the `avro` feature")) +} + /// A key/value payload, as Java's `KeyValueSchemaInfo` reads its schema: the key's and the value's schemas from its /// properties and definition. Only the inline encoding is read: Java's other one puts the key in the message's key. -fn key_value(data: &[u8], writer: &SchemaInfo) -> Result { +fn key_value(definitions: &Definitions, data: &[u8], writer: &SchemaInfo) -> Result { if writer.properties.get("kv.encoding.type").is_some_and(|encoding| encoding == "SEPARATED") { let message = "key/value messages with the key in the message's key aren't supported yet"; return Err(Error::new(ErrorKind::Other, message)); } - let (key_definition, value_definition) = split_inline(&writer.definition)?; - let (key_schema, value_schema) = (part(writer, "key", key_definition)?, part(writer, "value", value_definition)?); + let (key_schema, value_schema) = writer.parts()?; let (key, value) = split_inline(data)?; - let read = |data: Option<&[u8]>, schema| data.map_or(Ok(GenericValue::Null), |data| decode_value(data, schema)); - Ok(GenericValue::KeyValue(Box::new(KeyValue { key: read(key, &key_schema)?, value: read(value, &value_schema)? }))) -} - -/// The schema of a key/value schema's key or value, `side`: its name, type and properties, which the key/value -/// schema's properties record, and its part of the key/value schema's definition. Without a type, it is bytes, as in -/// Java. -fn part(writer: &SchemaInfo, side: &str, definition: Option<&[u8]>) -> Result { - let property = |name: &str| writer.properties.get(&format!("{side}.schema.{name}")); - let properties = match property("properties").filter(|json| !json.is_empty()) { - Some(json) => serde_json::from_str(json).map_err(|e| { - Error::new(ErrorKind::Other, format!("the key/value schema's {side} properties aren't JSON: {e}")) - })?, - None => BTreeMap::new(), + let read = |data: Option<&[u8]>, schema| { + data.map_or(Ok(GenericValue::Null), |data| decode_value(definitions, data, schema)) }; - Ok(SchemaInfo { - name: property("name").cloned().unwrap_or_default(), - schema_type: property("type").map_or(SchemaType::Bytes, |name| SchemaType::from_java_name(name)), - definition: definition.unwrap_or_default().to_vec(), - properties, - }) + Ok(GenericValue::KeyValue(Box::new(KeyValue { key: read(key, &key_schema)?, value: read(value, &value_schema)? }))) } #[cfg(test)] @@ -166,7 +238,7 @@ mod tests { } fn record(schema_type: SchemaType, value: GenericValue) -> GenericRecord { - GenericRecord { schema_type, value } + GenericRecord { schema_type, value, fields: Vec::new() } } fn pair(key: GenericValue, value: GenericValue) -> GenericValue { @@ -215,14 +287,21 @@ mod tests { let refused = |data: &[u8], writer: &SchemaInfo| auto.decode_with(data, Some(writer)).unwrap_err().to_string(); assert!(refused(&[0, 1], Schema::int32().info()).contains("a INT32 value takes 4 bytes")); assert!(refused(&[0xff], Schema::string().info()).contains("not UTF-8")); + #[cfg(feature = "json")] + assert!(refused(b"{", &writer(SchemaType::Json, &[], b"\"int\"")).contains("the payload isn't JSON")); + #[cfg(feature = "avro")] + { + assert!(refused(&[], &writer(SchemaType::Avro, &[], b"\"int\"")).contains("doesn't decode in Avro")); + assert!(refused(&[], &writer(SchemaType::Avro, &[], b"{")).contains("isn't JSON")); + } + // Without their features, JSON and Avro records fail to decode, naming the feature. + #[cfg(not(feature = "json"))] + assert!(refused(b"{}", &writer(SchemaType::Json, &[], &[])).contains("takes the `json` feature")); + #[cfg(not(feature = "avro"))] + assert!(refused(&[], &writer(SchemaType::Avro, &[], &[])).contains("takes the `avro` feature")); // The types this client doesn't decode yet fail, naming themselves. - let later = [ - (SchemaType::Json, "JSON"), - (SchemaType::Avro, "AVRO"), - (SchemaType::Protobuf, "PROTOBUF"), - (SchemaType::ProtobufNative, "PROTOBUF_NATIVE"), - ]; - for (schema_type, name) in later { + for (schema_type, name) in [(SchemaType::Protobuf, "PROTOBUF"), (SchemaType::ProtobufNative, "PROTOBUF_NATIVE")] + { let error = refused(b"{}", &writer(schema_type, &[], &[])); assert!(error.contains(&format!("generic records of {name} schemas")), "{error}"); } @@ -248,12 +327,77 @@ mod tests { /// A key/value schema with parts missing, as Java's `KeyValueSchemaInfo` reads it: a part without a type is bytes, /// one without a name or properties has none. + /// Java's definition of the record its tool writes: its reflection orders the fields otherwise than the record's + /// JSON. + #[cfg(any(feature = "json", feature = "avro"))] + const JAVA_POJO: &[u8] = br#"{"type":"record","name":"Pojo","namespace":"SchemaTool","fields":[ + {"name":"age","type":"int"},{"name":"name","type":["null","string"],"default":null}]}"#; + + #[cfg(feature = "json")] + #[test] + fn generic_json_records() { + use serde_json::json; + + let auto = Schema::auto_consume(); + let read = auto.decode_with(br#"{"name":"alice","age":30}"#, Some(&writer(SchemaType::Json, &[], JAVA_POJO))); + let read = read.unwrap(); + assert_eq!( + (read.schema_type(), read.value()), + (SchemaType::Json, &GenericValue::Json(json!({"name": "alice", "age": 30}))) + ); + assert_eq!(read.fields(), ["age", "name"], "in the definition's order"); + assert_eq!(read.field("name"), Some(GenericValue::Json(json!("alice")))); + assert_eq!(read.field("city"), None); + // A definition that doesn't describe a record: the object's fields, in serde_json's order. + let not_a_record = writer(SchemaType::Json, &[], br#""string""#); + assert_eq!(auto.decode_with(br#"{"b":1,"a":2}"#, Some(¬_a_record)).unwrap().fields(), ["a", "b"]); + // A value that isn't an object has no fields. + let read = auto.decode_with(b"7", Some(¬_a_record)).unwrap(); + assert!(read.fields().is_empty() && read.field("a").is_none()); + } + + #[cfg(feature = "avro")] + #[test] + fn generic_avro_records() { + use apache_avro::types::Value; + + let auto = Schema::auto_consume(); + let payload = [60, 2, 10, b'a', b'l', b'i', b'c', b'e']; + let read = auto.decode_with(&payload, Some(&writer(SchemaType::Avro, &[], JAVA_POJO))).unwrap(); + assert_eq!(read.schema_type(), SchemaType::Avro); + assert_eq!(read.fields(), ["age", "name"]); + assert_eq!(read.field("age"), Some(GenericValue::Avro(Value::Int(30)))); + assert_eq!(read.field("name"), Some(GenericValue::Avro(Value::String("alice".to_string())))); + assert_eq!(read.field("city"), None); + let nameless = auto.decode_with(&[60, 0], Some(&writer(SchemaType::Avro, &[], JAVA_POJO))).unwrap(); + assert_eq!(nameless.field("name"), Some(GenericValue::Avro(Value::Null)), "the union's null branch"); + // A value that isn't a record has no fields. + let read = auto.decode_with(&[60], Some(&writer(SchemaType::Avro, &[], br#""int""#))).unwrap(); + assert_eq!(read.value(), &GenericValue::Avro(Value::Int(30))); + assert!(read.fields().is_empty() && read.field("a").is_none()); + // A key/value of an Avro record: each part read with its own schema. + let schema = Schema::key_value(Schema::string(), Schema::::avro()); + let read = generic(&schema, &KeyValue { key: "k".to_string(), value: Pojo { name: None, age: 7 } }); + let record = Value::Record(vec![ + ("name".to_string(), Value::Union(0, Box::new(Value::Null))), + ("age".to_string(), Value::Int(7)), + ]); + assert_eq!(read.into_value(), pair(GenericValue::String("k".into()), GenericValue::Avro(record))); + } + + #[cfg(feature = "avro")] + #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize, apache_avro::AvroSchema)] + struct Pojo { + name: Option, + age: i32, + } + #[test] fn key_value_schemas_as_java_reads_them() { let bare = writer(SchemaType::KeyValue, &[("key.schema.properties", "")], &[0; 8]); let read = Schema::auto_consume().decode_with(&[0, 0, 0, 1, 7, 0, 0, 0, 0], Some(&bare)).unwrap(); assert_eq!(read.into_value(), pair(GenericValue::Bytes(vec![7]), GenericValue::Bytes(Vec::new()))); - let key = part(&bare, "key", None).unwrap(); + let key = bare.part("key", None).unwrap(); assert_eq!((key.name(), key.schema_type(), key.definition()), ("", SchemaType::Bytes, &[][..])); assert!(key.properties().is_empty()); } diff --git a/crates/apache-pulsar/src/schema/json.rs b/crates/apache-pulsar/src/schema/json.rs new file mode 100644 index 0000000..ce6d9fc --- /dev/null +++ b/crates/apache-pulsar/src/schema/json.rs @@ -0,0 +1,101 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! JSON: Java's `Schema.json`, records encoded as JSON objects and described in Avro. + +use std::sync::Arc; + +use apache_avro::AvroSchema; +use bytes::Bytes; +use serde::Serialize; +use serde::de::DeserializeOwned; + +use super::record::info; +use super::{Generic, Schema, SchemaInfo, SchemaType}; +use crate::error::{Error, ErrorKind, Result}; + +impl Schema { + /// Records as JSON objects, as Java's `Schema.json(Class)` encodes them, through `serde`. The broker is told the + /// Avro schema `T` derives, as Java describes its JSON records in Avro, with `#[derive(AvroSchema)]` of + /// apache-avro's `derive` feature: an `Option` field is nullable, as Java's reflection makes its nullable fields. + /// + /// Each message reads as `serde` reads JSON, whichever version wrote it, as in Java: a field `T` doesn't have is + /// left, and an `Option` one the message doesn't have is `None`. Java leaves its null fields out, where `serde` + /// writes them as `null` unless told otherwise: both read either. + pub fn json() -> Self { + Self { + info: info(SchemaType::Json, &T::get_schema()), + encode: Arc::new(|value: &T| encode(value)), + decode: Arc::new(|data: &[u8], _: Option<&SchemaInfo>| decode(data)), + generic: Generic::No, + } + } +} + +fn encode(value: &T) -> Result { + serde_json::to_vec(value).map(Bytes::from).map_err(unencodable) +} + +fn decode(data: &[u8]) -> Result { + serde_json::from_slice(data).map_err(undecodable) +} + +fn unencodable(error: serde_json::Error) -> Error { + Error::new(ErrorKind::Other, format!("the value doesn't encode in JSON: {error}")) +} + +fn undecodable(error: serde_json::Error) -> Error { + Error::new(ErrorKind::Other, format!("the payload doesn't decode from JSON: {error}")) +} + +#[cfg(test)] +mod tests { + use serde::Deserialize; + + use super::*; + use crate::schema::record::{Unencodable, properties}; + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, apache_avro::AvroSchema)] + struct Pojo { + name: Option, + age: i32, + } + + #[test] + fn records_encode_as_json_described_in_avro() { + let schema = Schema::::json(); + let info = schema.info(); + assert_eq!((info.name(), info.schema_type(), info.properties()), ("", SchemaType::Json, &properties())); + let described = serde_json::to_vec(&::get_schema()).unwrap(); + assert_eq!(info.definition(), described, "in Avro"); + let alice = Pojo { name: Some("alice".to_string()), age: 30 }; + let payload = schema.encode(&alice).unwrap(); + assert_eq!(&payload[..], br#"{"name":"alice","age":30}"#); + assert_eq!(schema.decode(&payload).unwrap(), alice); + // As Java writes it: without its null fields, the fields in its order, and those this record doesn't have. + let java = br#"{"age":7,"city":"Rome"}"#; + assert_eq!(schema.decode_with(java, Some(info)).unwrap(), Pojo { name: None, age: 7 }); + } + + #[test] + fn records_that_dont_encode_or_decode() { + let error = Schema::::json().encode(&Unencodable).unwrap_err().to_string(); + assert!(error.contains("the value doesn't encode in JSON"), "{error}"); + let error = Schema::::json().decode(br#"{"name":"bob"}"#).unwrap_err().to_string(); + assert!(error.contains("the payload doesn't decode from JSON"), "{error}"); + } +} diff --git a/crates/apache-pulsar/src/schema/record.rs b/crates/apache-pulsar/src/schema/record.rs new file mode 100644 index 0000000..068f80a --- /dev/null +++ b/crates/apache-pulsar/src/schema/record.rs @@ -0,0 +1,183 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! What the JSON and Avro schemas share: their records are described in Avro, as Java's are. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, PoisonError}; + +use serde_json::Value as Json; + +use super::{SchemaInfo, SchemaType}; +use crate::error::{Error, ErrorKind, Result}; + +/// The schema the broker is told about for records that `definition` describes, as Java's: no name, the definition +/// as JSON, and the properties Java records on how it derived it, here from a Rust type, whose `Option` fields are +/// its nullable ones. +pub(super) fn info(schema_type: SchemaType, definition: &apache_avro::Schema) -> SchemaInfo { + let properties = [("__alwaysAllowNull", "false"), ("__jsr310ConversionEnabled", "false")]; + SchemaInfo { + name: String::new(), + schema_type, + definition: serde_json::to_vec(definition).expect("an Avro schema is JSON"), + properties: properties.into_iter().map(|(key, value)| (key.to_string(), value.to_string())).collect(), + } +} + +/// An error of apache-avro's, as what failed. +pub(super) fn avro_error(what: &str, error: apache_avro::Error) -> Error { + Error::new(ErrorKind::Other, format!("{what}: {error}")) +} + +/// The Avro schemas of the definitions messages were written with, each parsed once. +#[derive(Default)] +pub(super) struct Definitions(Mutex, Arc>>); + +impl Definitions { + /// The schema `definition` describes. A definition that doesn't parse fails each time. + pub(super) fn parse(&self, definition: &[u8]) -> Result> { + let mut parsed = self.0.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(schema) = parsed.get(definition) { + return Ok(schema.clone()); + } + let schema = Arc::new(parse(definition)?); + parsed.insert(definition.to_vec(), schema.clone()); + Ok(schema) + } +} + +/// An Avro definition, parsed as Java's parser takes it: Java doesn't validate names, and older Java clients name a +/// nested class's record in a namespace that ends in `$`, which apache-avro refuses. Names and namespaces become valid +/// Avro ones, each other character an underscore: they serve to resolve the definition's references, which change +/// alike, and records are matched without their namespace. +fn parse(definition: &[u8]) -> Result { + let mut json: Json = serde_json::from_slice(definition) + .map_err(|e| Error::new(ErrorKind::Other, format!("the schema's definition isn't JSON: {e}")))?; + names(&mut json); + apache_avro::Schema::parse(json).map_err(|e| avro_error("the schema's definition isn't Avro", e)) +} + +/// Makes valid the names of a schema: of its named types, their aliases and namespaces, and the names that refer to +/// them. Fields keep theirs: they are the records' keys. +fn names(schema: &mut Json) { + match schema { + Json::String(name) => valid(name), + Json::Array(branches) => branches.iter_mut().for_each(names), + Json::Object(object) => { + for (key, value) in object.iter_mut() { + match (key.as_str(), value) { + ("name" | "namespace" | "aliases" | "type" | "items" | "values", value) => names(value), + ("fields", Json::Array(fields)) => { + fields.iter_mut().filter_map(|f| f.get_mut("type")).for_each(names) + } + _ => {} + } + } + } + _ => {} + } +} + +/// A name or a namespace, each character that Avro doesn't take in one an underscore. +fn valid(name: &mut String) { + let takes = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '.'; + if !name.chars().all(takes) { + *name = name.chars().map(|c| if takes(c) { c } else { '_' }).collect(); + } +} + +/// A value that refuses to serialize, whose schema is an int. +#[cfg(test)] +#[derive(Debug, PartialEq, serde::Deserialize)] +pub(super) struct Unencodable; + +#[cfg(test)] +impl serde::Serialize for Unencodable { + fn serialize(&self, _: S) -> std::result::Result { + Err(serde::ser::Error::custom("refused")) + } +} + +#[cfg(test)] +impl apache_avro::AvroSchemaComponent for Unencodable { + fn get_schema_in_ctxt( + _: &mut std::collections::HashSet, + _: apache_avro::schema::NamespaceRef, + ) -> apache_avro::Schema { + apache_avro::Schema::Int + } +} + +#[cfg(test)] +pub(super) fn properties() -> std::collections::BTreeMap { + std::collections::BTreeMap::from([ + ("__alwaysAllowNull".to_string(), "false".to_string()), + ("__jsr310ConversionEnabled".to_string(), "false".to_string()), + ]) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A definition as Java's reflection writes one for a static nested class: its namespace ends in `$`, in the + /// record's, in a nested record's and in a reference to it, with fields, an array, a map, a union and an alias. + const JAVA: &str = r#"{"type":"record","name":"Order","namespace":"com.acme.Shop$","aliases":["old.Shop$Order"], + "doc":"an order, in com.acme.Shop$", + "fields":[ + {"name":"line","type":{"type":"record","name":"Line","namespace":"com.acme.Shop$","fields":[ + {"name":"sku","type":"string"}]}}, + {"name":"lines","type":{"type":"array","items":"com.acme.Shop$.Line"}}, + {"name":"by","type":{"type":"map","values":"long"}}, + {"name":"note","type":["null","string"],"default":null}]}"#; + + #[test] + fn javas_nested_classes_parse() { + let definitions = Definitions::default(); + let schema = definitions.parse(JAVA.as_bytes()).unwrap(); + let json = serde_json::to_value(&*schema).unwrap(); + assert_eq!(json["namespace"], "com.acme.Shop_"); + assert_eq!(json["aliases"], serde_json::json!(["old.Shop_Order"])); + assert_eq!(json["doc"], "an order, in com.acme.Shop$", "not a name"); + assert_eq!(json["fields"][0]["type"]["namespace"], "com.acme.Shop_"); + assert_eq!(json["fields"][1]["type"]["items"], "com.acme.Shop_.Line"); + assert!(Arc::ptr_eq(&schema, &definitions.parse(JAVA.as_bytes()).unwrap()), "parsed once"); + } + + #[test] + fn definitions_that_dont_parse() { + let definitions = Definitions::default(); + let error = definitions.parse(b"{").unwrap_err().to_string(); + assert!(error.contains("isn't JSON"), "{error}"); + let error = definitions.parse(br#"{"type":"record"}"#).unwrap_err().to_string(); + assert!(error.contains("isn't Avro"), "{error}"); + let error = definitions.parse(b"7").unwrap_err().to_string(); + assert!(error.contains("isn't Avro"), "{error}"); + // A field keeps its name, which its records' values are found by: one that Avro doesn't take, as Java can + // write, fails to parse. + let field = br#"{"type":"record","name":"R","fields":[{"name":"a$b","type":"int"}]}"#; + let error = definitions.parse(field).unwrap_err().to_string(); + assert!(error.contains("a$b"), "{error}"); + } + + #[test] + fn the_info_is_javas() { + let info = info(SchemaType::Avro, &apache_avro::Schema::Int); + assert_eq!((info.name(), info.schema_type(), info.definition()), ("", SchemaType::Avro, &b"\"int\""[..])); + assert_eq!(info.properties(), &properties()); + } +} diff --git a/crates/apache-pulsar/src/schema_tests.rs b/crates/apache-pulsar/src/schema_tests.rs index 0974775..07e93de 100644 --- a/crates/apache-pulsar/src/schema_tests.rs +++ b/crates/apache-pulsar/src/schema_tests.rs @@ -394,3 +394,96 @@ fn generic_schemas_where_they_dont_serve() { client.close().await.unwrap(); }); } + +/// The record of Java's V5 schema tests. +#[cfg(all(feature = "json", feature = "avro"))] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, apache_avro::AvroSchema)] +struct Pojo { + name: Option, + age: i32, +} + +/// Java's V5 round-trip test, for JSON and Avro: a record reaches a consumer of its schema, which registered it. +#[cfg(all(feature = "json", feature = "avro"))] +#[test] +fn records_reach_a_consumer() { + run(async { + round_trip(Schema::::json(), Pojo { name: Some("alice".to_string()), age: 30 }).await; + round_trip(Schema::::avro(), Pojo { name: Some("bob".to_string()), age: 42 }).await; + round_trip(Schema::::avro(), Pojo { name: None, age: 7 }).await; + }); +} + +/// A generic consumer reads JSON and Avro records with the schema each was written with: JSON as `serde_json` reads +/// it, Avro as apache-avro does, the fields in the writer's order. +#[cfg(all(feature = "json", feature = "avro"))] +#[test] +fn generic_records_of_json_and_avro() { + use apache_avro::types::Value; + + run(async { + let alice = Pojo { name: Some("alice".to_string()), age: 30 }; + let json = GenericValue::Json(serde_json::json!({"name": "alice", "age": 30})); + generic_round_trip(Schema::::json(), alice.clone(), json).await; + let name = Value::Union(1, Box::new(Value::String("alice".to_string()))); + let avro = + GenericValue::Avro(Value::Record(vec![("name".to_string(), name), ("age".to_string(), Value::Int(30))])); + generic_round_trip(Schema::::avro(), alice, avro).await; + }); +} + +/// A record's first version, and its second, which adds a nullable field, as Java's V5 evolution test has them. +#[cfg(feature = "avro")] +#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize, apache_avro::AvroSchema)] +struct V1 { + i: i32, +} + +#[cfg(feature = "avro")] +#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize, apache_avro::AvroSchema)] +struct V2 { + i: i32, + j: Option, +} + +/// Java's V5 evolution test: the second version registers after a split, on the topic's one history, and a consumer +/// of it reads the first version's records with the new field null. Each kind of consumer fetches each version's +/// schema once, its own included. A Stream consumer reads the split's children once the parent's messages are +/// acknowledged. +#[cfg(feature = "avro")] +#[test] +fn avro_consumers_read_each_version_with_its_schema() { + run(async { + let server = WorldServer::start(world(1)).await; + let client = local_client(&server).await; + let first = client.new_producer(Schema::::avro()).topic(TOPIC).create().await.unwrap(); + first.send(V1 { i: 1 }).await.unwrap(); + first.send(V1 { i: 2 }).await.unwrap(); + server.with(|w| w.split(TOPIC, 0)); + let second = client.new_producer(Schema::::avro()).topic(TOPIC).create().await.unwrap(); + second.send(V2 { i: 3, j: Some(30) }).await.unwrap(); + assert_eq!(schema_types(&server), [Type::Avro, Type::Avro], "two versions of one history"); + + let expected = [V2 { i: 1, j: None }, V2 { i: 2, j: None }, V2 { i: 3, j: Some(30) }]; + let (mut queued, mut streamed, mut read) = (Vec::new(), Vec::new(), Vec::new()); + let queue = queue(&client, Schema::::avro(), "queue").await.unwrap(); + let stream = client.new_stream_consumer(Schema::::avro()).topic(TOPIC).subscription_name("stream"); + let stream = stream.subscription_initial_position(SubscriptionInitialPosition::Earliest).subscribe(); + let stream = stream.await.unwrap(); + let reader = client.new_checkpoint_consumer(Schema::::avro()).topic(TOPIC); + let reader = reader.start_position(Checkpoint::earliest()).create().await.unwrap(); + for _ in 0..3 { + queued.push(queue.receive().await.unwrap().value().unwrap()); + let message = stream.receive().await.unwrap(); + stream.acknowledge_cumulative(message.id()).await.unwrap(); + streamed.push(message.value().unwrap()); + read.push(reader.receive().await.unwrap().value().unwrap()); + } + for mut values in [queued, streamed, read] { + values.sort_by_key(|value| value.i); + assert_eq!(values, expected); + } + assert_eq!(schema_fetches(&server), 6, "each consumer fetches each version once"); + client.close().await.unwrap(); + }); +} diff --git a/crates/apache-pulsar/tests/integration/SchemaTool.java b/crates/apache-pulsar/tests/integration/SchemaTool.java index f38e11e..1bc4189 100644 --- a/crates/apache-pulsar/tests/integration/SchemaTool.java +++ b/crates/apache-pulsar/tests/integration/SchemaTool.java @@ -40,8 +40,10 @@ * The schemas are named as the V5 factories that make them: {@code string}, {@code bool}, {@code int8}, * {@code int16}, {@code int32}, {@code int64}, {@code float32} and {@code float64}. {@code kv} is a key/value of a * string and an int32, written {@code key=value}: the V5 factory has none, so it is v4's, through {@code V5Interop}. - * {@code auto} only consumes, with {@code Schema.autoConsume()}: it prints each generic record's schema type and - * value, a key/value as {@code key=value} and bytes as text. + * {@code json} and {@code avro} are records of a name and an age, written {@code name:age}; {@code avro-v1} and + * {@code avro-v2} the two versions of Java's V5 evolution test, written {@code i} and {@code i:j}. {@code auto} only + * consumes, with {@code Schema.autoConsume()}: it prints each generic record's schema type and value, a key/value as + * {@code key=value} and bytes as text. */ public final class SchemaTool { /** A schema, and how its values are read from the command line and printed. */ @@ -66,6 +68,10 @@ public static void main(String[] args) throws Exception { org.apache.pulsar.client.api.Schema.STRING, org.apache.pulsar.client.api.Schema.INT32)), text -> new KeyValue<>(text.split("=", 2)[0], Integer.parseInt(text.split("=", 2)[1])), pair -> pair.getKey() + "=" + pair.getValue()); + case "json" -> new Codec<>(Schema.json(Pojo.class), Pojo::parse); + case "avro" -> new Codec<>(Schema.avro(Pojo.class), Pojo::parse); + case "avro-v1" -> new Codec<>(Schema.avro(V1.class), V1::parse); + case "avro-v2" -> new Codec<>(Schema.avro(V2.class), V2::parse); case "auto" -> new Codec( Schema.autoConsume(), text -> { @@ -86,6 +92,84 @@ record -> record.schemaType() + " " + text(record.nativeObject())); } } + /** + * A record of the JSON and Avro schemas, written {@code name:age}, {@code null} for no name. A static nested class, + * as Java's V5 schema tests have, which Avro names in a namespace that ends in {@code $}. + */ + public static final class Pojo { + private String name; + private int age; + + public Pojo() { + } + + Pojo(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + static Pojo parse(String text) { + String[] parts = text.split(":", 2); + return new Pojo("null".equals(parts[0]) ? null : parts[0], Integer.parseInt(parts[1])); + } + + @Override + public String toString() { + return name + ":" + age; + } + } + + /** The first version of Java's V5 evolution test's record: an int. */ + public static final class V1 { + public int i; + + static V1 parse(String text) { + V1 record = new V1(); + record.i = Integer.parseInt(text); + return record; + } + + @Override + public String toString() { + return String.valueOf(i); + } + } + + /** The second version, which adds a nullable int, {@code null} in the first version's records. */ + public static final class V2 { + public int i; + public Integer j; + + static V2 parse(String text) { + String[] parts = text.split(":", 2); + V2 record = new V2(); + record.i = Integer.parseInt(parts[0]); + record.j = "null".equals(parts[1]) ? null : Integer.valueOf(parts[1]); + return record; + } + + @Override + public String toString() { + return i + ":" + j; + } + } + /** A generic record's value as text: a key/value as {@code key=value}, bytes as UTF-8. */ private static String text(Object value) { if (value instanceof org.apache.pulsar.client.api.v5.schema.KeyValue pair) { diff --git a/crates/apache-pulsar/tests/integration/schemas.rs b/crates/apache-pulsar/tests/integration/schemas.rs index 640d9fd..1a898b7 100644 --- a/crates/apache-pulsar/tests/integration/schemas.rs +++ b/crates/apache-pulsar/tests/integration/schemas.rs @@ -22,6 +22,7 @@ use std::fmt::Debug; use std::str::FromStr; use std::time::Duration; +use apache_avro::types::Value; use apache_pulsar::{ ErrorKind, GenericValue, KeyValue, ProducerAccessMode, Schema, SchemaType, SubscriptionInitialPosition, local, }; @@ -38,6 +39,8 @@ pub const TESTS: &[(&str, fn(&Env))] = &[ ), ("primitive_values_cross_between_java_and_rust", primitive_values_cross_between_java_and_rust), ("key_values_cross_between_java_and_rust", key_values_cross_between_java_and_rust), + ("records_cross_between_java_and_rust", records_cross_between_java_and_rust), + ("avro_records_evolve_across_a_split", avro_records_evolve_across_a_split), ("generic_records_cross_between_java_and_rust", generic_records_cross_between_java_and_rust), ("a_generic_consumer_decodes_each_message_by_its_version", a_generic_consumer_decodes_each_message_by_its_version), ]; @@ -158,6 +161,80 @@ fn key_values_cross_between_java_and_rust(env: &Env) { both_ways(env, "kv", schema, &["a=1", "b=-2", "=0"], pair); } +/// A record of the JSON and Avro schemas, as the Java tool's `Pojo`: Java's nullable `String` is an `Option`. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, apache_avro::AvroSchema)] +struct Pojo { + name: Option, + age: i32, +} + +/// A `Pojo` as the Java tool takes and prints it: `name:age`, `null` for no name. +fn pojo(text: &str) -> Pojo { + let (name, age) = text.split_once(':').unwrap(); + Pojo { name: (name != "null").then(|| name.to_string()), age: age.parse().unwrap() } +} + +/// Records of the JSON and the Avro schemas, both ways, Java's described by its reflection and Rust's by its derive: +/// the broker checks each against the other, and the fields come in another order. +fn records_cross_between_java_and_rust(env: &Env) { + let records = ["alice:30", "bob:42", "null:7"]; + both_ways(env, "json", Schema::::json(), &records, pojo); + both_ways(env, "avro", Schema::::avro(), &records, pojo); +} + +/// The second version of Java's V5 evolution test's record, which adds a nullable field. +#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize, apache_avro::AvroSchema)] +struct V2 { + i: i32, + j: Option, +} + +/// A second version that requires its new field, which a record of the first can't fill. +#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize, apache_avro::AvroSchema)] +struct Bad { + i: i32, + j: i32, +} + +/// Java's `V5SchemaEvolutionTest`, across the two clients: under BACKWARD, Java writes the first version, the segment +/// splits, and Rust registers the second on the topic's one history and writes it to the children; a consumer of the +/// second version, Rust's and Java's, reads each record with its version's schema, the first version's with the new +/// field null. A version that requires its new field is refused, and isn't registered. +fn avro_records_evolve_across_a_split(env: &Env) { + let namespace = format!("public/{}", unique("evolution")); + env.admin(&["namespaces", "create", &namespace]); + env.admin(&["namespaces", "set-schema-compatibility-strategy", &namespace, "--compatibility", "BACKWARD"]); + let path = format!("{namespace}/{}", unique("records")); + env.admin(&["scalable-topics", "create", "-s", "1", &path]); + let topic = format!("topic://{path}"); + env.java_produce("avro-v1", &topic, &["1", "2"]); + env.admin(&["scalable-topics", "split-segment", "-s", "0", &path]); + let expected = [V2 { i: 1, j: None }, V2 { i: 2, j: None }, V2 { i: 3, j: Some(30) }, V2 { i: 4, j: Some(40) }]; + run(async { + let client = client(env).await; + let producer = client.new_producer(Schema::::avro()).topic(&topic).create().await.unwrap(); + for (key, record) in [("a", V2 { i: 3, j: Some(30) }), ("b", V2 { i: 4, j: Some(40) })] { + producer.new_message().key(key).value(record).send().await.unwrap(); + } + let bad = client.new_producer(Schema::::avro()).topic(&topic).create().await.unwrap(); + assert_eq!(bad.send(Bad { i: 5, j: 50 }).await.unwrap_err().kind(), ErrorKind::IncompatibleSchema); + let consumer = queue(&client, Schema::::avro(), &topic, "rust").await.unwrap(); + let mut read = take(&consumer, 4).await; + read.sort_by_key(|record| record.i); + assert_eq!(read, expected); + client.close().await.unwrap(); + }); + let mut read = env.java_consume("avro-v2", &topic, 4); + read.sort(); + assert_eq!(read, ["1:null", "2:null", "3:30", "4:40"]); + let versions = env.admin(&["schemas", "get", "-a", &topic]); + assert_eq!( + versions.matches("\"type\" : \"AVRO\"").count(), + 2, + "Java's first version and Rust's second:\n{versions}" + ); +} + /// A value as Java prints it, parsed. fn parsed>(text: &str) -> T { text.parse().unwrap() @@ -213,6 +290,15 @@ fn generic_records_cross_between_java_and_rust(env: &Env) { let pair = KeyValue { key: "a".to_string(), value: 1 }; let generic = KeyValue { key: GenericValue::String("a".to_string()), value: GenericValue::Int32(1) }; generic_both_ways(env, "kv", schema, "a=1", pair, GenericValue::KeyValue(Box::new(generic)), "KEY_VALUE a=1"); + // Records, each read with its writer's schema: Java's orders the fields of the same record otherwise. + let alice = Pojo { name: Some("alice".to_string()), age: 30 }; + let json = GenericValue::Json(serde_json::json!({"age": 30, "name": "alice"})); + let java = r#"JSON {"name":"alice","age":30}"#; + generic_both_ways(env, "json", Schema::::json(), "alice:30", alice.clone(), json, java); + let name = Value::Union(1, Box::new(Value::String("alice".to_string()))); + let avro = GenericValue::Avro(Value::Record(vec![("age".to_string(), Value::Int(30)), ("name".to_string(), name)])); + let java = r#"AVRO {"name": "alice", "age": 30}"#; + generic_both_ways(env, "avro", Schema::::avro(), "alice:30", alice, avro, java); } /// Sends `value` with `schema` from Java, as the tool takes it (`text`), and reads it in Rust as a generic record, diff --git a/docs/7-api.md b/docs/7-api.md index 897b7f1..4f418e9 100644 --- a/docs/7-api.md +++ b/docs/7-api.md @@ -262,9 +262,22 @@ Built-in schemas come in this order: each decoded with the schema its message was written with. The consumer fetches the schema of each version from the broker, once, before it delivers the first message of it, and holds the messages after it meanwhile; a message without a version reads as bytes. A fetch the broker fails fails that message's `value()`, and the next message of - the version fetches again. The broker checks no generic consumer's schema, so it reads any topic; producers don't - take the schema. The data model requires generic records, so they are part of conformance; -4. JSON through `serde`, and Avro through `apache-avro`, each behind a feature; + the version fetches again. The Avro schemas fetch their messages' schemas the same way. The broker checks no + generic consumer's schema, so it reads any topic; producers don't take the schema. The data model requires generic + records, so they are part of conformance; +4. JSON and Avro: `Schema::json()` and `Schema::avro()`, Java V5's `Schema.json(Class)` and `Schema.avro(Class)`, + for a record type that `serde` serializes and apache-avro describes (`#[derive(AvroSchema)]`). Each is a feature, + `json` and `avro`, on by default; both describe their records in Avro, as Java does, so both take apache-avro. + - JSON values go through `serde_json`. A message reads whichever version wrote it, as in Java: a field the type + doesn't have is left, and an `Option` field the message doesn't have is `None`. + - Avro values are datums, without a header. A consumer fetches the schema of each version, as for generic + records, and reads each message with it: Avro's resolution fills in what a later version adds, and takes the + fields in whichever order the writer's schema has them, as Java's reflection orders them its own way. A + key/value schema reads an Avro key or value with its part of the writer's. + - Java's parser takes names that apache-avro refuses, such as the namespace that ends in `$` older Java clients + give a nested class's record: a definition's names become Avro's before it is parsed. + - Generic records of either are `serde_json`'s and apache-avro's values, with Java V5's `fields()` and + `field(name)`; 5. Protobuf, behind a feature: both of Pulsar's types, `PROTOBUF` (Java V5's `Schema.protobuf`) and `PROTOBUF_NATIVE`, for message types generated by prost or by buffa.