chamikaramj commented on code in PR #41484: URL: https://github.com/apache/beam/pull/41484#discussion_r4750679596
########## sdks/rust/beam/core/src/coders/traits.rs: ########## @@ -0,0 +1,254 @@ +/* + * 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. + */ + +//! Core traits and context definitions for Beam coders. + +use std::sync::Arc; +use thiserror::Error; + +/// Error encountered during element encoding or decoding. +#[derive(Error, Debug)] +pub enum CoderError { + #[error("IO error during encoding/decoding: {0}")] + Io(#[from] std::io::Error), + #[error("UTF-8 decoding error: {0}")] + Utf8(#[from] std::string::FromUtf8Error), + #[error("Schema error during encoding/decoding: {0}")] + Schema(#[from] crate::schema::SchemaError), + #[error("Decoding format error: {0}")] + Format(String), + /// Error from a runner state stream backing a state-backed iterable. + #[error("{0}")] + StateStream(String), +} + +/// Position of an element in the byte stream, which sets how it is delimited. In `Nested` +/// context (inside a tuple, a KV or a stream), a variable-length element must have a length +/// prefix. In `WholeStream` context, the element extends to the end of the stream. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Context { + WholeStream, + Nested, +} + +/// Maps each reader schema field to its position in a writer schema. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FieldMap { + /// The writer schema has the wire layout of the reader type. + Same, + /// For each reader field, the writer field index, or `None` for an absent nullable field. + /// The `Arc` lets a lazy iterable decoder share the map with no copy. + ByName(Arc<[Option<usize>]>), +} + +/// Keeps the [`FieldMap`] of one type for the last writer schema. A hit costs one pointer +/// compare, so call [`get`](Self::get) for each element. +#[derive(Clone, Debug, Default)] +pub struct FieldMapCache { + resolved: Option<(Arc<crate::schema::Schema>, Option<FieldMap>)>, +} + +impl FieldMapCache { + pub fn new() -> Self { + Self::default() + } + + /// Returns [`DefaultCoder::resolve_field_map`] of `T` for `schema`. Resolves again only + /// when `schema` is a different `Arc`. Returns `Ok(None)` when `schema` is `None` or `T` + /// has no field map. + pub fn get<T: DefaultCoder>( + &mut self, + schema: Option<&Arc<crate::schema::Schema>>, + ) -> Result<Option<&FieldMap>, crate::schema::SchemaError> { + let Some(schema) = schema else { + return Ok(None); + }; + let resolved = match self.resolved.take() { + Some((cached, map)) if Arc::ptr_eq(&cached, schema) => (cached, map), + Some(_) | None => (Arc::clone(schema), T::resolve_field_map(schema)?), + }; + Ok(self.resolved.insert(resolved).1.as_ref()) + } + + /// Decodes one element of `T` from `bytes` with the field map for `schema`. + pub fn decode<T: DefaultCoder>( + &mut self, + bytes: &[u8], + schema: Option<&Arc<crate::schema::Schema>>, + state_reader: Option<&Arc<dyn super::iterable::StateStreamReader>>, + ) -> Result<T, CoderError> { + let map = self.get::<T>(schema)?; + T::decode_with_context(bytes, schema, map, state_reader) + } +} + +/// Encodes and decodes values of type `T` in a Beam wire format. +pub trait Coder<T>: Send + Sync + 'static { + /// Returns the Runner API coder URN, standard or custom. + fn urn(&self) -> &'static str; + + fn encode(&self, value: &T, writer: &mut Vec<u8>, context: Context) -> Result<(), CoderError>; + + fn decode(&self, reader: &mut &[u8], context: Context) -> Result<T, CoderError>; +} + +/// Records coders in the Runner API pipeline components. +pub trait CoderRegistry { + fn register_coder(&self, urn: &str, component_coder_ids: Vec<String>) -> String; + + /// Registers a coder that carries a spec payload. `Pipeline` overrides this. The default + /// drops `payload` for URN-only test registries. + fn register_coder_with_payload( + &self, + urn: &str, + component_coder_ids: Vec<String>, + payload: Vec<u8>, + ) -> String { + let _ = payload; + self.register_coder(urn, component_coder_ids) + } +} + +impl<T: ?Sized + CoderRegistry> CoderRegistry for &T { + fn register_coder(&self, urn: &str, component_coder_ids: Vec<String>) -> String { + (**self).register_coder(urn, component_coder_ids) + } + + fn register_coder_with_payload( + &self, + urn: &str, + component_coder_ids: Vec<String>, + payload: Vec<u8>, + ) -> String { + (**self).register_coder_with_payload(urn, component_coder_ids, payload) + } +} + +/// Associates a pipeline type with its default coder and gives byte-level encode and decode. +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot cross a Beam pipeline because it does not implement `DefaultCoder`", + label = "`DefaultCoder` is not implemented for `{Self}`", + note = "derive `BeamRow` or `BeamEnum` on your type, or implement `DefaultCoder`" +)] +pub trait DefaultCoder: Send + Sync + Sized + 'static { + type Coder: Coder<Self>; + fn coder() -> Self::Coder; + + /// Encodes this value to element bytes. + fn encode(&self) -> Result<Vec<u8>, CoderError> { + let mut buf = Vec::new(); + self.encode_element(&mut buf)?; + Ok(buf) + } + + /// Decodes an element from bytes. + fn decode(mut bytes: &[u8]) -> Result<Self, CoderError> { + Self::decode_element(&mut bytes) + } + + /// True when equal values always encode to identical bytes in element context, without + /// schema or state context. + const CANONICAL_BYTES: bool = false; + + /// Encodes this value to a byte writer in the element context of the type. + fn encode_element(&self, writer: &mut Vec<u8>) -> Result<(), CoderError>; + + /// Decodes an element from a byte reader. + fn decode_element(reader: &mut &[u8]) -> Result<Self, CoderError>; + + /// Advances `reader` past one encoded value in element context without allocating when + /// possible. Callers that must check the bytes (such as UTF-8) decode on a cache miss. + fn skip_nested(reader: &mut &[u8]) -> Result<(), CoderError> { + Self::decode_element(reader).map(|_| ()) + } + + /// Decodes with an optional schema. The default calls [`Self::decode_element_with_context`] + /// with no field map and no state reader. + fn decode_element_with_schema( + reader: &mut &[u8], + schema: Option<&Arc<crate::schema::Schema>>, + ) -> Result<Self, CoderError> { + Self::decode_element_with_context(reader, schema, None, None) + } + + /// Decodes with an optional schema, field map and state stream reader. The default calls + /// [`Self::decode_element`]. Override it for a type that needs a schema, such as `Row`, or + /// reads state-backed iterables, such as `BeamIterable`, or wraps one. Pass all three on to + /// the components. + /// + /// `field_map` comes from [`Self::resolve_field_map`] for `schema`. `None` means that the + /// caller did not resolve one, so a row type must compare `schema` with its own layout. + fn decode_element_with_context( + reader: &mut &[u8], + _schema: Option<&Arc<crate::schema::Schema>>, + _field_map: Option<&FieldMap>, + _state_reader: Option<&Arc<dyn super::iterable::StateStreamReader>>, + ) -> Result<Self, CoderError> { + Self::decode_element(reader) + } + + /// Decodes an element in whole-stream context. + /// + /// The element extends to the end of `reader` ([`Context::WholeStream`]). The arguments are + /// those of [`Self::decode_element_with_context`]. A type with no schema or state context + /// decodes with `Self::coder().decode(reader, Context::WholeStream)`. + fn decode_whole_stream_with_context( Review Comment: Should we implement this for existing implementations ? For eample, https://github.com/apache/beam/edit/master/sdks/rust/beam/derive/src/row/delegates.rs ########## sdks/rust/beam/core/tests/coders/coder_encoding_test.rs: ########## @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file Review Comment: How/where is this test executed ? ########## sdks/rust/beam/core/src/coders/traits.rs: ########## @@ -0,0 +1,254 @@ +/* + * 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. + */ + +//! Core traits and context definitions for Beam coders. + +use std::sync::Arc; +use thiserror::Error; + +/// Error encountered during element encoding or decoding. +#[derive(Error, Debug)] +pub enum CoderError { + #[error("IO error during encoding/decoding: {0}")] + Io(#[from] std::io::Error), + #[error("UTF-8 decoding error: {0}")] + Utf8(#[from] std::string::FromUtf8Error), + #[error("Schema error during encoding/decoding: {0}")] + Schema(#[from] crate::schema::SchemaError), + #[error("Decoding format error: {0}")] + Format(String), + /// Error from a runner state stream backing a state-backed iterable. + #[error("{0}")] + StateStream(String), +} + +/// Position of an element in the byte stream, which sets how it is delimited. In `Nested` +/// context (inside a tuple, a KV or a stream), a variable-length element must have a length +/// prefix. In `WholeStream` context, the element extends to the end of the stream. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Context { + WholeStream, + Nested, +} + +/// Maps each reader schema field to its position in a writer schema. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FieldMap { + /// The writer schema has the wire layout of the reader type. + Same, + /// For each reader field, the writer field index, or `None` for an absent nullable field. + /// The `Arc` lets a lazy iterable decoder share the map with no copy. + ByName(Arc<[Option<usize>]>), +} + +/// Keeps the [`FieldMap`] of one type for the last writer schema. A hit costs one pointer +/// compare, so call [`get`](Self::get) for each element. +#[derive(Clone, Debug, Default)] +pub struct FieldMapCache { + resolved: Option<(Arc<crate::schema::Schema>, Option<FieldMap>)>, +} + +impl FieldMapCache { + pub fn new() -> Self { + Self::default() + } + + /// Returns [`DefaultCoder::resolve_field_map`] of `T` for `schema`. Resolves again only + /// when `schema` is a different `Arc`. Returns `Ok(None)` when `schema` is `None` or `T` + /// has no field map. + pub fn get<T: DefaultCoder>( + &mut self, + schema: Option<&Arc<crate::schema::Schema>>, + ) -> Result<Option<&FieldMap>, crate::schema::SchemaError> { + let Some(schema) = schema else { + return Ok(None); + }; + let resolved = match self.resolved.take() { + Some((cached, map)) if Arc::ptr_eq(&cached, schema) => (cached, map), + Some(_) | None => (Arc::clone(schema), T::resolve_field_map(schema)?), + }; + Ok(self.resolved.insert(resolved).1.as_ref()) + } + + /// Decodes one element of `T` from `bytes` with the field map for `schema`. + pub fn decode<T: DefaultCoder>( + &mut self, + bytes: &[u8], + schema: Option<&Arc<crate::schema::Schema>>, + state_reader: Option<&Arc<dyn super::iterable::StateStreamReader>>, + ) -> Result<T, CoderError> { + let map = self.get::<T>(schema)?; + T::decode_with_context(bytes, schema, map, state_reader) + } +} + +/// Encodes and decodes values of type `T` in a Beam wire format. +pub trait Coder<T>: Send + Sync + 'static { + /// Returns the Runner API coder URN, standard or custom. + fn urn(&self) -> &'static str; + + fn encode(&self, value: &T, writer: &mut Vec<u8>, context: Context) -> Result<(), CoderError>; + + fn decode(&self, reader: &mut &[u8], context: Context) -> Result<T, CoderError>; +} + +/// Records coders in the Runner API pipeline components. +pub trait CoderRegistry { + fn register_coder(&self, urn: &str, component_coder_ids: Vec<String>) -> String; + + /// Registers a coder that carries a spec payload. `Pipeline` overrides this. The default + /// drops `payload` for URN-only test registries. + fn register_coder_with_payload( + &self, + urn: &str, + component_coder_ids: Vec<String>, + payload: Vec<u8>, + ) -> String { + let _ = payload; + self.register_coder(urn, component_coder_ids) + } +} + +impl<T: ?Sized + CoderRegistry> CoderRegistry for &T { + fn register_coder(&self, urn: &str, component_coder_ids: Vec<String>) -> String { + (**self).register_coder(urn, component_coder_ids) + } + + fn register_coder_with_payload( + &self, + urn: &str, + component_coder_ids: Vec<String>, + payload: Vec<u8>, + ) -> String { + (**self).register_coder_with_payload(urn, component_coder_ids, payload) + } +} + +/// Associates a pipeline type with its default coder and gives byte-level encode and decode. +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot cross a Beam pipeline because it does not implement `DefaultCoder`", + label = "`DefaultCoder` is not implemented for `{Self}`", + note = "derive `BeamRow` or `BeamEnum` on your type, or implement `DefaultCoder`" +)] +pub trait DefaultCoder: Send + Sync + Sized + 'static { + type Coder: Coder<Self>; + fn coder() -> Self::Coder; + + /// Encodes this value to element bytes. + fn encode(&self) -> Result<Vec<u8>, CoderError> { + let mut buf = Vec::new(); + self.encode_element(&mut buf)?; + Ok(buf) + } + + /// Decodes an element from bytes. + fn decode(mut bytes: &[u8]) -> Result<Self, CoderError> { + Self::decode_element(&mut bytes) + } + + /// True when equal values always encode to identical bytes in element context, without + /// schema or state context. + const CANONICAL_BYTES: bool = false; + + /// Encodes this value to a byte writer in the element context of the type. + fn encode_element(&self, writer: &mut Vec<u8>) -> Result<(), CoderError>; + + /// Decodes an element from a byte reader. + fn decode_element(reader: &mut &[u8]) -> Result<Self, CoderError>; Review Comment: I think we should simplify this interface. Seems like this has a high API surface with many decode/encode entry-points which could result in incorrect usage and bugs. ########## sdks/rust/beam/core/src/coders/traits.rs: ########## @@ -0,0 +1,254 @@ +/* + * 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. + */ + +//! Core traits and context definitions for Beam coders. + +use std::sync::Arc; +use thiserror::Error; + +/// Error encountered during element encoding or decoding. +#[derive(Error, Debug)] +pub enum CoderError { + #[error("IO error during encoding/decoding: {0}")] + Io(#[from] std::io::Error), + #[error("UTF-8 decoding error: {0}")] + Utf8(#[from] std::string::FromUtf8Error), + #[error("Schema error during encoding/decoding: {0}")] + Schema(#[from] crate::schema::SchemaError), + #[error("Decoding format error: {0}")] + Format(String), + /// Error from a runner state stream backing a state-backed iterable. + #[error("{0}")] + StateStream(String), +} + +/// Position of an element in the byte stream, which sets how it is delimited. In `Nested` +/// context (inside a tuple, a KV or a stream), a variable-length element must have a length +/// prefix. In `WholeStream` context, the element extends to the end of the stream. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Context { + WholeStream, + Nested, +} + +/// Maps each reader schema field to its position in a writer schema. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FieldMap { + /// The writer schema has the wire layout of the reader type. + Same, + /// For each reader field, the writer field index, or `None` for an absent nullable field. + /// The `Arc` lets a lazy iterable decoder share the map with no copy. + ByName(Arc<[Option<usize>]>), +} + +/// Keeps the [`FieldMap`] of one type for the last writer schema. A hit costs one pointer +/// compare, so call [`get`](Self::get) for each element. +#[derive(Clone, Debug, Default)] +pub struct FieldMapCache { + resolved: Option<(Arc<crate::schema::Schema>, Option<FieldMap>)>, +} + +impl FieldMapCache { + pub fn new() -> Self { + Self::default() + } + + /// Returns [`DefaultCoder::resolve_field_map`] of `T` for `schema`. Resolves again only + /// when `schema` is a different `Arc`. Returns `Ok(None)` when `schema` is `None` or `T` + /// has no field map. + pub fn get<T: DefaultCoder>( Review Comment: Seems like the key of the cache above is `Arc::ptr_eq(schema)` but the get is for a generic ? Please address the descrepency. ########## sdks/rust/beam/core/tests/coders/coder_encoding_test.rs: ########## @@ -0,0 +1,119 @@ +/* + * 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 Review Comment: Please add schema validation tests across SDKs. For example, values encoded in Rust can be decoded in Java/Python and vice versa. ########## sdks/rust/Cargo.toml: ########## @@ -18,8 +18,10 @@ [workspace] resolver = "3" members = [ + "beam", Review Comment: Please make sure that we keep dependencies minimized for the build/container size as well as vulnerability reduction. We can always add dependencies later if needed. ########## sdks/rust/beam/core/tests/coders/instant_test.rs: ########## @@ -0,0 +1,136 @@ +/* + * 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 + * Review Comment: Could you add following tests if they are not available: * Malformed input: -an 11-byte varint - a 10th varint byte greater than 1 - a truncated varint - a negative or oversized length prefix - invalid UTF-8 * skip_nested for each type: encode two values back to back, skip the first, and decode the second. * register_coder URNs through a mock registry (f32 → double, () → bytes, Instant → varint). * Whole-stream context for bytes and unit, and decode_whole_stream_with_context. * Round trips for schema options and the logical-type argument. Start from a proto, because TypedValue can't be built yet. ########## sdks/rust/Cargo.toml: ########## @@ -75,10 +77,18 @@ prost-types = "0.14" tonic = { version = "0.14", features = ["tls-native-roots"] } tonic-prost = "0.14" tonic-prost-build = "0.14" +thiserror = "2" +chrono = { version = "0.4", default-features = false, features = ["std", "clock"] } Review Comment: Is chrono clock feature needed ? Does this add to the latency ? ########## sdks/rust/beam/core/src/schema/types.rs: ########## @@ -0,0 +1,377 @@ +/* + * 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. + */ + +use std::fmt; +use std::sync::Arc; + +use beam_model::pipeline as proto; +use prost::Message; + +use super::error::SchemaError; + +/// Primitive (atomic) types of a Beam schema. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum AtomicType { + Byte, + Int16, + Int32, + Int64, + Float, + Double, + String, + Boolean, + Bytes, +} + +impl fmt::Display for AtomicType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Byte => write!(f, "BYTE"), + Self::Int16 => write!(f, "INT16"), + Self::Int32 => write!(f, "INT32"), + Self::Int64 => write!(f, "INT64"), + Self::Float => write!(f, "FLOAT"), + Self::Double => write!(f, "DOUBLE"), + Self::String => write!(f, "STRING"), + Self::Boolean => write!(f, "BOOLEAN"), + Self::Bytes => write!(f, "BYTES"), + } + } +} + +/// Type information for a field in a Beam schema. +#[derive(Debug, Clone, PartialEq)] +pub enum TypeInfo { + Atomic(AtomicType), + Array(Box<FieldType>), + Iterable(Box<FieldType>), + Map(Box<FieldType>, Box<FieldType>), + /// A nested row. The schema is shared, so a decoder clones only the `Arc` for each row. + Row(Arc<Schema>), + Logical { + urn: String, + payload: Vec<u8>, + representation: Box<FieldType>, + /// The argument that parameterizes the logical type, if the type takes one. + argument: Option<Box<TypedValue>>, + }, +} + +impl fmt::Display for TypeInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Atomic(a) => write!(f, "{a}"), + Self::Array(elem) => write!(f, "ARRAY<{elem}>"), + Self::Iterable(elem) => write!(f, "ITERABLE<{elem}>"), + Self::Map(k, v) => write!(f, "MAP<{k}, {v}>"), + Self::Row(schema) => write!(f, "ROW<{schema:?}>"), + Self::Logical { urn, .. } => write!(f, "LOGICAL<{urn}>"), + } + } +} + +/// A complete field type specification, including nullability. +#[derive(Debug, Clone, PartialEq)] +pub struct FieldType { + pub nullable: bool, + pub type_info: TypeInfo, +} + +impl fmt::Display for FieldType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.nullable { + write!(f, "{}?", self.type_info) + } else { + write!(f, "{}", self.type_info) + } + } +} + +impl FieldType { + pub fn new(type_info: TypeInfo, nullable: bool) -> Self { + Self { + nullable, + type_info, + } + } + + pub fn atomic(atomic: AtomicType) -> Self { + Self::new(TypeInfo::Atomic(atomic), false) + } + + pub fn nullable_atomic(atomic: AtomicType) -> Self { + Self::new(TypeInfo::Atomic(atomic), true) + } + + pub fn boolean() -> Self { + Self::atomic(AtomicType::Boolean) + } + + pub fn byte() -> Self { + Self::atomic(AtomicType::Byte) + } + + pub fn int16() -> Self { + Self::atomic(AtomicType::Int16) + } + + pub fn int32() -> Self { + Self::atomic(AtomicType::Int32) + } + + pub fn int64() -> Self { + Self::atomic(AtomicType::Int64) + } + + pub fn float() -> Self { + Self::atomic(AtomicType::Float) + } + + pub fn double() -> Self { + Self::atomic(AtomicType::Double) + } + + pub fn string() -> Self { + Self::atomic(AtomicType::String) + } + + pub fn bytes() -> Self { + Self::atomic(AtomicType::Bytes) + } + + pub fn array(element_type: FieldType) -> Self { + Self::new(TypeInfo::Array(Box::new(element_type)), false) + } + + pub fn map(key_type: FieldType, val_type: FieldType) -> Self { + Self::new(TypeInfo::Map(Box::new(key_type), Box::new(val_type)), false) + } + + pub fn row(schema: impl Into<Arc<Schema>>) -> Self { + Self::new(TypeInfo::Row(schema.into()), false) + } + + /// Creates a logical type: a named interpretation of `representation` that an SDK which + /// recognizes `urn` decodes into a richer value. + pub fn logical(urn: impl Into<String>, payload: Vec<u8>, representation: Self) -> Self { + Self::new( + TypeInfo::Logical { + urn: urn.into(), + payload, + representation: Box::new(representation), + argument: None, + }, + false, + ) + } + + /// Creates a logical type with an argument, for example the precision of a fixed-size + /// decimal. + pub fn logical_with_argument( + urn: impl Into<String>, + payload: Vec<u8>, + representation: Self, + argument: TypedValue, + ) -> Self { + Self::new( + TypeInfo::Logical { + urn: urn.into(), + payload, + representation: Box::new(representation), + argument: Some(Box::new(argument)), + }, + false, + ) + } + + pub fn with_nullable(mut self, nullable: bool) -> Self { + self.nullable = nullable; + self + } +} + +/// A named field in a Beam schema. +#[derive(Debug, Clone, PartialEq)] +pub struct Field { + pub name: String, + pub description: Option<String>, + pub field_type: FieldType, + pub id: Option<i32>, + pub encoding_position: Option<i32>, + pub options: Vec<SchemaOption>, +} + +impl Field { + pub fn new(name: impl Into<String>, field_type: FieldType) -> Self { + Self { + name: name.into(), + description: None, + field_type, + id: None, + encoding_position: None, + options: Vec::new(), + } + } + + pub fn nullable(name: impl Into<String>, field_type: FieldType) -> Self { + Self::new(name, field_type.with_nullable(true)) + } + + pub fn with_description(mut self, description: impl Into<String>) -> Self { + self.description = Some(description.into()); + self + } + + pub fn with_encoding_position(mut self, pos: i32) -> Self { + self.encoding_position = Some(pos); + self + } + + pub fn with_option(mut self, option: SchemaOption) -> Self { + self.options.push(option); + self + } +} + +/// Schema that defines the layout and types of a `Row`. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Schema { + pub fields: Vec<Field>, + pub id: Option<String>, + pub encoding_positions_set: bool, + pub options: Vec<SchemaOption>, +} + +impl Schema { + /// Builds a schema with no id and no options. Sets `encoding_positions_set` when every + /// field has an encoding position. + pub fn new(fields: Vec<Field>) -> Self { + let encoding_positions_set = + !fields.is_empty() && fields.iter().all(|f| f.encoding_position.is_some()); + Self { + fields, + id: None, + encoding_positions_set, + options: Vec::new(), + } + } + + pub fn with_option(mut self, option: SchemaOption) -> Self { + self.options.push(option); + self + } + + pub fn builder() -> SchemaBuilder { + SchemaBuilder::default() + } + + pub fn field_index(&self, name: &str) -> Option<usize> { + self.fields.iter().position(|f| f.name == name) + } + + pub fn field(&self, name: &str) -> Option<&Field> { + self.fields.iter().find(|f| f.name == name) + } + + pub fn num_fields(&self) -> usize { + self.fields.len() + } + + /// Serializes this schema to `Schema` proto bytes. + pub fn to_proto_bytes(&self) -> Vec<u8> { + let proto = proto::Schema::from(self); + proto.encode_to_vec() + } + + /// Deserializes a schema from `Schema` proto bytes. + pub fn from_proto_bytes(bytes: &[u8]) -> Result<Self, SchemaError> { + let proto = proto::Schema::decode(bytes)?; + Self::try_from(proto) + } +} + +#[derive(Debug, Default)] +pub struct SchemaBuilder { + fields: Vec<Field>, + id: Option<String>, + options: Vec<SchemaOption>, +} + +impl SchemaBuilder { + pub fn field(mut self, name: impl Into<String>, field_type: FieldType) -> Self { + self.fields.push(Field::new(name, field_type)); + self + } + + pub fn nullable_field(mut self, name: impl Into<String>, field_type: FieldType) -> Self { + self.fields.push(Field::nullable(name, field_type)); + self + } + + pub fn id(mut self, id: impl Into<String>) -> Self { + self.id = Some(id.into()); + self + } + + pub fn option(mut self, option: SchemaOption) -> Self { + self.options.push(option); + self + } + + pub fn build(self) -> Schema { + Schema { + id: self.id, + options: self.options, + ..Schema::new(self.fields) + } + } +} + +/// A named value that annotates a [`Schema`] or a [`Field`]. Other SDKs and runners read +/// options by name, so the conversion to the `Schema` proto keeps them. +#[derive(Debug, Clone, PartialEq)] +pub struct SchemaOption { + pub name: String, + pub value: TypedValue, +} + +impl SchemaOption { + pub fn new(name: impl Into<String>, value: TypedValue) -> Self { + Self { + name: name.into(), + value, + } + } +} + +/// A value together with its schema type: the value of a [`SchemaOption`], or the argument +/// of a logical type. +#[derive(Debug, Clone, PartialEq)] +pub struct TypedValue { Review Comment: Does this and fields have to be public ? Please make sure that the public API surface is minimized here and elsewhere. Please make sure all public API is documented. ########## sdks/rust/beam/core/src/coders/standard.rs: ########## @@ -0,0 +1,595 @@ +/* + * 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. + */ + +//! Standard primitive Beam coders and the wire helpers that the other coders share. + +use std::io::Write; +use std::sync::Arc; + +use super::iterable::StateStreamReader; +use super::traits::{Coder, CoderError, CoderRegistry, Context, DefaultCoder, FieldMap}; +use super::{URN_BOOL, URN_BYTES, URN_DOUBLE, URN_STRING_UTF8, URN_VARINT}; + +fn unexpected_eof(wanted: usize, left: usize) -> std::io::Error { + std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + format!("expected {wanted} bytes, {left} left"), + ) +} + +/// Splits the next `len` bytes off `reader` and returns them, borrowed. +pub fn take_bytes<'a>(reader: &mut &'a [u8], len: usize) -> Result<&'a [u8], std::io::Error> { + if reader.len() < len { + return Err(unexpected_eof(len, reader.len())); + } + let (head, rest) = reader.split_at(len); + *reader = rest; + Ok(head) +} + +pub(super) fn read_array<const N: usize>(reader: &mut &[u8]) -> Result<[u8; N], std::io::Error> { + let bytes = take_bytes(reader, N)?; + let mut buf = [0u8; N]; + buf.copy_from_slice(bytes); + Ok(buf) +} + +/// Reads `len` bytes into a new buffer. The length is checked against the input first, so a +/// corrupt length cannot allocate more than the input holds. +pub(super) fn read_exact_vec(reader: &mut &[u8], len: usize) -> Result<Vec<u8>, std::io::Error> { + take_bytes(reader, len).map(<[u8]>::to_vec) +} + +/// Reads a varint length prefix. A negative length is an error, not a huge `usize`. +pub(super) fn read_varint_len(reader: &mut &[u8]) -> Result<usize, CoderError> { + let len = VarIntCoder::decode_varint(reader)?; + usize::try_from(len).map_err(|_| CoderError::Format(format!("Negative length: {len}"))) +} + +/// Writes a byte payload, with a varint length prefix in `Nested` context. +fn write_bytes(value: &[u8], writer: &mut Vec<u8>, context: Context) -> Result<(), CoderError> { + if context == Context::Nested { + VarIntCoder::encode_varint(value.len() as i64, writer)?; + } + writer.write_all(value)?; + Ok(()) +} + +/// Reads a byte payload: varint length-prefixed in `Nested` context, else the rest of the stream. +fn read_bytes(reader: &mut &[u8], context: Context) -> Result<Vec<u8>, CoderError> { + match context { + Context::Nested => { + let len = read_varint_len(reader)?; + Ok(read_exact_vec(reader, len)?) + } + Context::WholeStream => Ok(std::mem::take(reader).to_vec()), + } +} + +/// Coder for UTF-8 strings. +#[derive(Clone, Debug, Default)] +pub struct StringUtf8Coder; + +impl Coder<String> for StringUtf8Coder { + fn urn(&self) -> &'static str { + URN_STRING_UTF8 + } + + fn encode( + &self, + value: &String, + writer: &mut Vec<u8>, + context: Context, + ) -> Result<(), CoderError> { + write_bytes(value.as_bytes(), writer, context) + } + + fn decode(&self, reader: &mut &[u8], context: Context) -> Result<String, CoderError> { + let bytes = read_bytes(reader, context)?; + Ok(String::from_utf8(bytes)?) + } +} + +impl DefaultCoder for String { + type Coder = StringUtf8Coder; + const CANONICAL_BYTES: bool = true; + fn coder() -> Self::Coder { + StringUtf8Coder + } + + fn encode_element(&self, writer: &mut Vec<u8>) -> Result<(), CoderError> { + StringUtf8Coder.encode(self, writer, Context::Nested) + } + + fn decode_element(reader: &mut &[u8]) -> Result<Self, CoderError> { + StringUtf8Coder.decode(reader, Context::Nested) + } + + fn decode_whole_stream_with_context( + reader: &mut &[u8], + _schema: Option<&Arc<crate::schema::Schema>>, + _field_map: Option<&FieldMap>, + _state_reader: Option<&Arc<dyn StateStreamReader>>, + ) -> Result<Self, CoderError> { + Self::coder().decode(reader, Context::WholeStream) + } + + fn skip_nested(reader: &mut &[u8]) -> Result<(), CoderError> { + let len = read_varint_len(reader)?; + take_bytes(reader, len)?; + Ok(()) + } + + fn register_coder<R: CoderRegistry + ?Sized>(registry: &R) -> String { + registry.register_coder(URN_STRING_UTF8, Vec::new()) + } +} + +/// Coder for raw byte vectors. +#[derive(Clone, Debug, Default)] +pub struct BytesCoder; + +impl Coder<Vec<u8>> for BytesCoder { + fn urn(&self) -> &'static str { + URN_BYTES + } + + fn encode( + &self, + value: &Vec<u8>, + writer: &mut Vec<u8>, + context: Context, + ) -> Result<(), CoderError> { + write_bytes(value, writer, context) + } + + fn decode(&self, reader: &mut &[u8], context: Context) -> Result<Vec<u8>, CoderError> { + read_bytes(reader, context) + } +} + +impl DefaultCoder for Vec<u8> { + type Coder = BytesCoder; + const CANONICAL_BYTES: bool = true; + fn coder() -> Self::Coder { + BytesCoder + } + + fn encode_element(&self, writer: &mut Vec<u8>) -> Result<(), CoderError> { + BytesCoder.encode(self, writer, Context::Nested) + } + + fn decode_element(reader: &mut &[u8]) -> Result<Self, CoderError> { + BytesCoder.decode(reader, Context::Nested) + } + + fn decode_whole_stream_with_context( + reader: &mut &[u8], + _schema: Option<&Arc<crate::schema::Schema>>, + _field_map: Option<&FieldMap>, + _state_reader: Option<&Arc<dyn StateStreamReader>>, + ) -> Result<Self, CoderError> { + Self::coder().decode(reader, Context::WholeStream) + } + + fn skip_nested(reader: &mut &[u8]) -> Result<(), CoderError> { + let len = read_varint_len(reader)?; + take_bytes(reader, len)?; + Ok(()) + } + + fn register_coder<R: CoderRegistry + ?Sized>(registry: &R) -> String { + registry.register_coder(URN_BYTES, Vec::new()) + } +} + +/// Coder for booleans, as one byte: 0 is false and 1 is true. Other values are an error. +#[derive(Clone, Debug, Default)] +pub struct BoolCoder; + +impl Coder<bool> for BoolCoder { + fn urn(&self) -> &'static str { + URN_BOOL + } + + fn encode( + &self, + value: &bool, + writer: &mut Vec<u8>, + _context: Context, + ) -> Result<(), CoderError> { + writer.write_all(&[u8::from(*value)])?; + Ok(()) + } + + fn decode(&self, reader: &mut &[u8], _context: Context) -> Result<bool, CoderError> { + let [byte] = read_array(reader)?; + match byte { + 0 => Ok(false), + 1 => Ok(true), + other => Err(CoderError::Format(format!("Invalid boolean byte: {other}"))), + } + } +} + +impl DefaultCoder for bool { + type Coder = BoolCoder; + const CANONICAL_BYTES: bool = true; + fn coder() -> Self::Coder { + BoolCoder + } + + fn encode_element(&self, writer: &mut Vec<u8>) -> Result<(), CoderError> { + BoolCoder.encode(self, writer, Context::WholeStream) + } + + fn decode_element(reader: &mut &[u8]) -> Result<Self, CoderError> { + BoolCoder.decode(reader, Context::WholeStream) + } + + fn decode_whole_stream_with_context( + reader: &mut &[u8], + _schema: Option<&Arc<crate::schema::Schema>>, + _field_map: Option<&FieldMap>, + _state_reader: Option<&Arc<dyn StateStreamReader>>, + ) -> Result<Self, CoderError> { + Self::coder().decode(reader, Context::WholeStream) + } + + fn skip_nested(reader: &mut &[u8]) -> Result<(), CoderError> { + BoolCoder.decode(reader, Context::WholeStream).map(|_| ()) + } + + fn register_coder<R: CoderRegistry + ?Sized>(registry: &R) -> String { + registry.register_coder(URN_BOOL, Vec::new()) + } +} + +/// Coder for 64-bit IEEE 754 floating-point values, big-endian. +#[derive(Clone, Debug, Default)] +pub struct DoubleCoder; + +impl Coder<f64> for DoubleCoder { + fn urn(&self) -> &'static str { + URN_DOUBLE + } + + fn encode( + &self, + value: &f64, + writer: &mut Vec<u8>, + _context: Context, + ) -> Result<(), CoderError> { + writer.write_all(&value.to_be_bytes())?; + Ok(()) + } + + fn decode(&self, reader: &mut &[u8], _context: Context) -> Result<f64, CoderError> { + Ok(f64::from_be_bytes(read_array(reader)?)) + } +} + +impl DefaultCoder for f64 { + type Coder = DoubleCoder; + fn coder() -> Self::Coder { + DoubleCoder + } + + fn encode_element(&self, writer: &mut Vec<u8>) -> Result<(), CoderError> { + DoubleCoder.encode(self, writer, Context::WholeStream) + } + + fn decode_element(reader: &mut &[u8]) -> Result<Self, CoderError> { + DoubleCoder.decode(reader, Context::WholeStream) + } + + fn decode_whole_stream_with_context( + reader: &mut &[u8], + _schema: Option<&Arc<crate::schema::Schema>>, + _field_map: Option<&FieldMap>, + _state_reader: Option<&Arc<dyn StateStreamReader>>, + ) -> Result<Self, CoderError> { + Self::coder().decode(reader, Context::WholeStream) + } + + fn register_coder<R: CoderRegistry + ?Sized>(registry: &R) -> String { + registry.register_coder(URN_DOUBLE, Vec::new()) + } +} + +/// Coder for 32-bit floats, in the format of `beam:coder:double:v1`, so other SDKs read a +/// double. A double outside the `f32` range decodes as an infinity. +#[derive(Clone, Debug, Default)] +pub struct FloatCoder; + +impl Coder<f32> for FloatCoder { + fn urn(&self) -> &'static str { + URN_DOUBLE + } + + fn encode( + &self, + value: &f32, + writer: &mut Vec<u8>, + context: Context, + ) -> Result<(), CoderError> { + DoubleCoder.encode(&f64::from(*value), writer, context) + } + + fn decode(&self, reader: &mut &[u8], context: Context) -> Result<f32, CoderError> { + // The narrowing is the documented behavior: an `f32` written here comes back exactly. + DoubleCoder + .decode(reader, context) + .map(|value| value as f32) + } +} + +impl DefaultCoder for f32 { + type Coder = FloatCoder; + fn coder() -> Self::Coder { + FloatCoder + } + + fn encode_element(&self, writer: &mut Vec<u8>) -> Result<(), CoderError> { + FloatCoder.encode(self, writer, Context::WholeStream) + } + + fn decode_element(reader: &mut &[u8]) -> Result<Self, CoderError> { + FloatCoder.decode(reader, Context::WholeStream) + } + + fn decode_whole_stream_with_context( + reader: &mut &[u8], + _schema: Option<&Arc<crate::schema::Schema>>, + _field_map: Option<&FieldMap>, + _state_reader: Option<&Arc<dyn StateStreamReader>>, + ) -> Result<Self, CoderError> { + Self::coder().decode(reader, Context::WholeStream) + } + + fn register_coder<R: CoderRegistry + ?Sized>(registry: &R) -> String { + registry.register_coder(URN_DOUBLE, Vec::new()) + } +} + +/// Coder for 64-bit varints. A negative value encodes as its two's-complement `u64` (10 bytes). +#[derive(Clone, Debug, Default)] +pub struct VarIntCoder; + +impl VarIntCoder { + pub(crate) fn encode_varint_bytes(value: i64, buf: &mut [u8; 10]) -> usize { + let mut v = value as u64; + let mut len = 0; + loop { + if (v & !0x7F) == 0 { + buf[len] = v as u8; + return len + 1; + } + buf[len] = ((v & 0x7F) as u8) | 0x80; + len += 1; + v >>= 7; + } + } + + pub fn encode_varint(value: i64, writer: &mut impl Write) -> Result<(), std::io::Error> { + let mut buf = [0u8; 10]; + let len = Self::encode_varint_bytes(value, &mut buf); + writer.write_all(&buf[..len]) + } + + /// Appends the 64-bit varint encoding of `value` to `out`. + pub fn encode_varint_to_vec(value: i64, out: &mut Vec<u8>) { + let mut buf = [0u8; 10]; + let len = Self::encode_varint_bytes(value, &mut buf); + out.extend_from_slice(&buf[..len]); + } + + /// Returns an error if the varint is longer than 64 bits. + pub fn decode_varint(reader: &mut &[u8]) -> Result<i64, std::io::Error> { + let mut result: u64 = 0; + let mut shift = 0; + loop { + let (&byte, rest) = reader.split_first().ok_or_else(|| unexpected_eof(1, 0))?; + *reader = rest; + let bits = (byte & 0x7F) as u64; + if shift >= 64 || (shift == 63 && bits > 1) { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "varint too long or out of range", + )); + } + result |= bits << shift; + shift += 7; + if (byte & 0x80) == 0 { + break; + } + } + Ok(result as i64) + } +} + +impl Coder<i64> for VarIntCoder { + fn urn(&self) -> &'static str { + URN_VARINT + } + + fn encode( + &self, + value: &i64, + writer: &mut Vec<u8>, + _context: Context, + ) -> Result<(), CoderError> { + Self::encode_varint(*value, writer)?; + Ok(()) + } + + fn decode(&self, reader: &mut &[u8], _context: Context) -> Result<i64, CoderError> { + let v = Self::decode_varint(reader)?; + Ok(v) + } +} + +impl DefaultCoder for i64 { + type Coder = VarIntCoder; + const CANONICAL_BYTES: bool = true; + fn coder() -> Self::Coder { + VarIntCoder + } + + fn encode_element(&self, writer: &mut Vec<u8>) -> Result<(), CoderError> { + Coder::<i64>::encode(&VarIntCoder, self, writer, Context::WholeStream) + } + + fn decode_element(reader: &mut &[u8]) -> Result<Self, CoderError> { + Coder::<i64>::decode(&VarIntCoder, reader, Context::WholeStream) + } + + fn decode_whole_stream_with_context( + reader: &mut &[u8], + _schema: Option<&Arc<crate::schema::Schema>>, + _field_map: Option<&FieldMap>, + _state_reader: Option<&Arc<dyn StateStreamReader>>, + ) -> Result<Self, CoderError> { + Self::coder().decode(reader, Context::WholeStream) + } + + fn skip_nested(reader: &mut &[u8]) -> Result<(), CoderError> { + VarIntCoder::decode_varint(reader)?; + Ok(()) + } + + fn register_coder<R: CoderRegistry + ?Sized>(registry: &R) -> String { + registry.register_coder(URN_VARINT, Vec::new()) + } +} + +impl Coder<i32> for VarIntCoder { + fn urn(&self) -> &'static str { + URN_VARINT + } + + fn encode( + &self, + value: &i32, + writer: &mut Vec<u8>, + _context: Context, + ) -> Result<(), CoderError> { + Self::encode_varint(*value as i64, writer)?; + Ok(()) + } + + fn decode(&self, reader: &mut &[u8], _context: Context) -> Result<i32, CoderError> { + let v = Self::decode_varint(reader)?; + i32::try_from(v) + .map_err(|_| CoderError::Format(format!("varint {v} is outside the i32 range"))) + } +} + +impl DefaultCoder for i32 { + type Coder = VarIntCoder; Review Comment: Using i64 VarIntCoder is valid for for `beam:coder:varint:v1` but not compatible with INT32 in Java/Python Beam Rows which uses a zero-extended 32 bit variant. https://github.com/apache/beam/blob/c6f0078219c86c31f913b46533754a40957aaae1/sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaCoderHelpers.java#L62 https://github.com/apache/beam/blob/c6f0078219c86c31f913b46533754a40957aaae1/sdks/java/core/src/main/java/org/apache/beam/sdk/util/VarInt.java#L36 https://github.com/apache/beam/blob/c6f0078219c86c31f913b46533754a40957aaae1/sdks/python/apache_beam/coders/row_coder.py#L149 ########## sdks/rust/beam/core/src/schema/proto.rs: ########## @@ -0,0 +1,328 @@ +/* + * 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. + */ + +use std::sync::Arc; + +use beam_model::pipeline as proto; + +use super::error::SchemaError; +use super::types::{AtomicType, Field, FieldType, Schema, SchemaOption, TypeInfo, TypedValue}; + +impl From<AtomicType> for proto::AtomicType { + fn from(t: AtomicType) -> Self { + match t { + AtomicType::Byte => proto::AtomicType::Byte, + AtomicType::Int16 => proto::AtomicType::Int16, + AtomicType::Int32 => proto::AtomicType::Int32, + AtomicType::Int64 => proto::AtomicType::Int64, + AtomicType::Float => proto::AtomicType::Float, + AtomicType::Double => proto::AtomicType::Double, + AtomicType::String => proto::AtomicType::String, + AtomicType::Boolean => proto::AtomicType::Boolean, + AtomicType::Bytes => proto::AtomicType::Bytes, + } + } +} + +impl TryFrom<proto::AtomicType> for AtomicType { + type Error = SchemaError; + + fn try_from(t: proto::AtomicType) -> Result<Self, Self::Error> { + match t { + proto::AtomicType::Byte => Ok(Self::Byte), + proto::AtomicType::Int16 => Ok(Self::Int16), + proto::AtomicType::Int32 => Ok(Self::Int32), + proto::AtomicType::Int64 => Ok(Self::Int64), + proto::AtomicType::Float => Ok(Self::Float), + proto::AtomicType::Double => Ok(Self::Double), + proto::AtomicType::String => Ok(Self::String), + proto::AtomicType::Boolean => Ok(Self::Boolean), + proto::AtomicType::Bytes => Ok(Self::Bytes), + proto::AtomicType::Unspecified => Err(SchemaError::ProtoConversion( + "Unspecified atomic type".into(), + )), + } + } +} + +impl From<FieldType> for proto::FieldType { + fn from(ft: FieldType) -> Self { + Self::from(&ft) + } +} + +impl From<&FieldType> for proto::FieldType { + fn from(ft: &FieldType) -> Self { + let type_info = match &ft.type_info { + TypeInfo::Atomic(at) => { + proto::field_type::TypeInfo::AtomicType(proto::AtomicType::from(*at) as i32) + } + TypeInfo::Array(elem) => { + proto::field_type::TypeInfo::ArrayType(Box::new(proto::ArrayType { + element_type: Some(Box::new(proto::FieldType::from(elem.as_ref()))), + })) + } + TypeInfo::Iterable(elem) => { + proto::field_type::TypeInfo::IterableType(Box::new(proto::IterableType { + element_type: Some(Box::new(proto::FieldType::from(elem.as_ref()))), + })) + } + TypeInfo::Map(k, v) => proto::field_type::TypeInfo::MapType(Box::new(proto::MapType { + key_type: Some(Box::new(proto::FieldType::from(k.as_ref()))), + value_type: Some(Box::new(proto::FieldType::from(v.as_ref()))), + })), + TypeInfo::Row(schema) => proto::field_type::TypeInfo::RowType(proto::RowType { + schema: Some(proto::Schema::from(schema.as_ref())), + }), + TypeInfo::Logical { + urn, + payload, + representation, + argument, + } => { + let (argument_type, argument) = argument + .as_ref() + .map(|argument| { + let TypedValue { field_type, value } = argument.as_ref(); + (Box::new(proto::FieldType::from(field_type)), value.clone()) + }) + .unzip(); + proto::field_type::TypeInfo::LogicalType(Box::new(proto::LogicalType { + urn: urn.clone(), + payload: payload.clone(), + representation: Some(Box::new(proto::FieldType::from(representation.as_ref()))), + argument_type, + argument: argument.flatten(), + })) + } + }; + + proto::FieldType { + nullable: ft.nullable, + type_info: Some(type_info), + } + } +} + +impl TryFrom<proto::FieldType> for FieldType { + type Error = SchemaError; + + fn try_from(ft: proto::FieldType) -> Result<Self, Self::Error> { + let Some(type_info) = ft.type_info else { + return Err(SchemaError::ProtoConversion( + "Missing type_info in FieldType".into(), + )); + }; + + let info = match type_info { + proto::field_type::TypeInfo::AtomicType(raw) => { + let proto_atomic = proto::AtomicType::try_from(raw).map_err(|_| { + SchemaError::ProtoConversion(format!("Unknown atomic type: {raw}")) + })?; + TypeInfo::Atomic(AtomicType::try_from(proto_atomic)?) + } + proto::field_type::TypeInfo::ArrayType(arr) => { + let elem = arr.element_type.ok_or_else(|| { + SchemaError::ProtoConversion("Missing array element type".into()) + })?; + TypeInfo::Array(Box::new(FieldType::try_from(*elem)?)) + } + proto::field_type::TypeInfo::IterableType(iter) => { + let elem = iter.element_type.ok_or_else(|| { + SchemaError::ProtoConversion("Missing iterable element type".into()) + })?; + TypeInfo::Iterable(Box::new(FieldType::try_from(*elem)?)) + } + proto::field_type::TypeInfo::MapType(m) => { + let key = m + .key_type + .ok_or_else(|| SchemaError::ProtoConversion("Missing map key type".into()))?; + let val = m + .value_type + .ok_or_else(|| SchemaError::ProtoConversion("Missing map value type".into()))?; + TypeInfo::Map( + Box::new(FieldType::try_from(*key)?), + Box::new(FieldType::try_from(*val)?), + ) + } + proto::field_type::TypeInfo::RowType(r) => { + let s = r.schema.ok_or_else(|| { + SchemaError::ProtoConversion("Missing nested row schema".into()) + })?; + TypeInfo::Row(Arc::new(Schema::try_from(s)?)) + } + proto::field_type::TypeInfo::LogicalType(logical) => { + let proto::LogicalType { + urn, + payload, + representation, + argument_type, + argument, + } = *logical; + let rep = representation.ok_or_else(|| { + SchemaError::ProtoConversion("Missing logical representation type".into()) + })?; + let argument = argument_type + .map(|argument_type| { + FieldType::try_from(*argument_type).map(|field_type| TypedValue { + field_type, + value: argument, + }) + }) + .transpose()?; + TypeInfo::Logical { + urn, + payload, + representation: Box::new(FieldType::try_from(*rep)?), + argument: argument.map(Box::new), + } + } + }; + + Ok(FieldType::new(info, ft.nullable)) + } +} + +impl From<Field> for proto::Field { + fn from(f: Field) -> Self { + Self::from(&f) + } +} + +impl From<&Field> for proto::Field { + fn from(f: &Field) -> Self { + proto::Field { + name: f.name.clone(), + description: f.description.clone().unwrap_or_default(), + r#type: Some(proto::FieldType::from(&f.field_type)), + id: f.id.unwrap_or_default(), + encoding_position: f.encoding_position.unwrap_or_default(), + options: f.options.iter().map(Into::into).collect(), + } + } +} + +impl TryFrom<proto::Field> for Field { + type Error = SchemaError; + + /// Position 0 is the proto3 default, so only [`Schema::try_from`] can keep `Some(0)`. + fn try_from(f: proto::Field) -> Result<Self, Self::Error> { + let field_type = f.r#type.ok_or_else(|| { + SchemaError::ProtoConversion(format!("Missing type for field {}", f.name)) + })?; + Ok(Field { + name: f.name, + description: (!f.description.is_empty()).then_some(f.description), + field_type: FieldType::try_from(field_type)?, + id: (f.id != 0).then_some(f.id), + encoding_position: (f.encoding_position != 0).then_some(f.encoding_position), + options: options_from_proto(f.options)?, + }) + } +} + +impl From<Schema> for proto::Schema { + fn from(s: Schema) -> Self { + Self::from(&s) + } +} + +impl From<&Schema> for proto::Schema { + fn from(s: &Schema) -> Self { + proto::Schema { + fields: s + .fields + .iter() + .map(|f| proto::Field { + encoding_position: if s.encoding_positions_set { + f.encoding_position.unwrap_or_default() + } else { + 0 + }, + ..proto::Field::from(f) + }) + .collect(), + id: s.id.clone().unwrap_or_default(), + options: s.options.iter().map(Into::into).collect(), + encoding_positions_set: s.encoding_positions_set, + } + } +} + +impl TryFrom<proto::Schema> for Schema { + type Error = SchemaError; + + /// Keeps field encoding positions only when `encoding_positions_set` is true. + fn try_from(s: proto::Schema) -> Result<Self, Self::Error> { + let positions_set = s.encoding_positions_set; + let fields = s + .fields + .into_iter() + .map(|f| { + let position = f.encoding_position; + Field::try_from(f).map(|field| Field { + encoding_position: positions_set.then_some(position), + ..field + }) + }) + .collect::<Result<Vec<_>, _>>()?; + Ok(Schema { + fields, + id: (!s.id.is_empty()).then_some(s.id), + encoding_positions_set: positions_set, + options: options_from_proto(s.options)?, + }) + } +} + +impl From<SchemaOption> for proto::Option { + fn from(option: SchemaOption) -> Self { + Self::from(&option) + } +} + +impl From<&SchemaOption> for proto::Option { + fn from(option: &SchemaOption) -> Self { + proto::Option { + name: option.name.clone(), + r#type: Some(proto::FieldType::from(&option.value.field_type)), + value: option.value.value.clone(), + } + } +} + +impl TryFrom<proto::Option> for SchemaOption { + type Error = SchemaError; + + /// Keeps the value as it is. `TypedValue::value` checks it against the type. Review Comment: Does `TypedValue::value` exist ? ########## sdks/rust/beam/core/src/coders/traits.rs: ########## @@ -0,0 +1,254 @@ +/* + * 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. + */ + +//! Core traits and context definitions for Beam coders. + +use std::sync::Arc; +use thiserror::Error; + +/// Error encountered during element encoding or decoding. +#[derive(Error, Debug)] +pub enum CoderError { + #[error("IO error during encoding/decoding: {0}")] + Io(#[from] std::io::Error), + #[error("UTF-8 decoding error: {0}")] + Utf8(#[from] std::string::FromUtf8Error), + #[error("Schema error during encoding/decoding: {0}")] + Schema(#[from] crate::schema::SchemaError), + #[error("Decoding format error: {0}")] + Format(String), + /// Error from a runner state stream backing a state-backed iterable. + #[error("{0}")] + StateStream(String), +} + +/// Position of an element in the byte stream, which sets how it is delimited. In `Nested` +/// context (inside a tuple, a KV or a stream), a variable-length element must have a length +/// prefix. In `WholeStream` context, the element extends to the end of the stream. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Context { + WholeStream, + Nested, +} + +/// Maps each reader schema field to its position in a writer schema. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FieldMap { + /// The writer schema has the wire layout of the reader type. + Same, + /// For each reader field, the writer field index, or `None` for an absent nullable field. + /// The `Arc` lets a lazy iterable decoder share the map with no copy. + ByName(Arc<[Option<usize>]>), +} + +/// Keeps the [`FieldMap`] of one type for the last writer schema. A hit costs one pointer +/// compare, so call [`get`](Self::get) for each element. +#[derive(Clone, Debug, Default)] +pub struct FieldMapCache { + resolved: Option<(Arc<crate::schema::Schema>, Option<FieldMap>)>, +} + +impl FieldMapCache { + pub fn new() -> Self { + Self::default() + } + + /// Returns [`DefaultCoder::resolve_field_map`] of `T` for `schema`. Resolves again only + /// when `schema` is a different `Arc`. Returns `Ok(None)` when `schema` is `None` or `T` + /// has no field map. + pub fn get<T: DefaultCoder>( + &mut self, + schema: Option<&Arc<crate::schema::Schema>>, + ) -> Result<Option<&FieldMap>, crate::schema::SchemaError> { + let Some(schema) = schema else { + return Ok(None); + }; + let resolved = match self.resolved.take() { + Some((cached, map)) if Arc::ptr_eq(&cached, schema) => (cached, map), + Some(_) | None => (Arc::clone(schema), T::resolve_field_map(schema)?), + }; + Ok(self.resolved.insert(resolved).1.as_ref()) + } + + /// Decodes one element of `T` from `bytes` with the field map for `schema`. + pub fn decode<T: DefaultCoder>( + &mut self, + bytes: &[u8], + schema: Option<&Arc<crate::schema::Schema>>, + state_reader: Option<&Arc<dyn super::iterable::StateStreamReader>>, + ) -> Result<T, CoderError> { + let map = self.get::<T>(schema)?; + T::decode_with_context(bytes, schema, map, state_reader) + } +} + +/// Encodes and decodes values of type `T` in a Beam wire format. +pub trait Coder<T>: Send + Sync + 'static { + /// Returns the Runner API coder URN, standard or custom. + fn urn(&self) -> &'static str; + + fn encode(&self, value: &T, writer: &mut Vec<u8>, context: Context) -> Result<(), CoderError>; + + fn decode(&self, reader: &mut &[u8], context: Context) -> Result<T, CoderError>; +} + +/// Records coders in the Runner API pipeline components. +pub trait CoderRegistry { + fn register_coder(&self, urn: &str, component_coder_ids: Vec<String>) -> String; + + /// Registers a coder that carries a spec payload. `Pipeline` overrides this. The default + /// drops `payload` for URN-only test registries. + fn register_coder_with_payload( + &self, + urn: &str, + component_coder_ids: Vec<String>, + payload: Vec<u8>, + ) -> String { + let _ = payload; + self.register_coder(urn, component_coder_ids) + } +} + +impl<T: ?Sized + CoderRegistry> CoderRegistry for &T { + fn register_coder(&self, urn: &str, component_coder_ids: Vec<String>) -> String { + (**self).register_coder(urn, component_coder_ids) + } + + fn register_coder_with_payload( + &self, + urn: &str, + component_coder_ids: Vec<String>, + payload: Vec<u8>, + ) -> String { + (**self).register_coder_with_payload(urn, component_coder_ids, payload) Review Comment: Seems like the default implementation is dropping the payload here ? ########## sdks/rust/beam/core/src/time.rs: ########## @@ -0,0 +1,198 @@ +/* + * 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. + */ + +//! Event time. + +use std::fmt; +use std::ops::{Add, AddAssign, Sub, SubAssign}; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; + +use crate::coders::{ + Coder, CoderError, CoderRegistry, Context, DefaultCoder, FieldMap, StateStreamReader, + VarIntCoder, +}; +use crate::schema::Schema; + +/// A point in event or processing time, with millisecond precision. +/// +/// Arithmetic with [`Duration`] saturates at [`Instant::MIN`] and [`Instant::MAX`]. It never +/// moves a value in the wrong direction. Serde writes the milliseconds. +/// +/// ``` +/// # use beam_core as beam; +/// use std::time::Duration; +/// use beam::Instant; +/// +/// let t = Instant::from_millis(1_000); +/// assert_eq!(t + Duration::from_secs(1), Instant::from_millis(2_000)); +/// assert_eq!(t.to_string(), "1970-01-01T00:00:01.000Z"); +/// ``` +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct Instant(i64); + +impl Instant { + /// The smallest Beam timestamp, `MIN_TIMESTAMP_MILLIS` of the Runner API. The runner + /// gives it to the output of `Impulse`. + pub const MIN: Self = Self(i64::MIN / 1000); + /// The largest Beam timestamp, `MAX_TIMESTAMP_MILLIS` of the Runner API. A watermark + /// at this value closes all windows. + pub const MAX: Self = Self(i64::MAX / 1000); + /// The last timestamp of the global window, `GLOBAL_WINDOW_MAX_TIMESTAMP_MILLIS` of the + /// Runner API. It is one day before [`Instant::MAX`]. + pub const END_OF_GLOBAL_WINDOW: Self = Self(Self::MAX.0 - 86_400_000); + /// 1970-01-01T00:00:00Z. + pub const EPOCH: Self = Self(0); + + /// The instant `millis` milliseconds after the epoch. + pub const fn from_millis(millis: i64) -> Self { + Self(millis) + } + + /// Milliseconds since the epoch. + pub const fn as_millis(self) -> i64 { + self.0 + } + + /// The current system time. + pub fn now() -> Self { + SystemTime::now().into() + } + + /// The time from `earlier` to `self`, or `None` if `earlier` is later. + pub fn duration_since(self, earlier: Self) -> Option<Duration> { + u64::try_from(self.0.checked_sub(earlier.0)?) + .ok() + .map(Duration::from_millis) + } + + fn millis(d: Duration) -> i64 { + i64::try_from(d.as_millis()).unwrap_or(i64::MAX) + } +} + +impl From<SystemTime> for Instant { + fn from(t: SystemTime) -> Self { + match t.duration_since(UNIX_EPOCH) { + Ok(d) => Self::EPOCH + d, + Err(e) => Self::EPOCH - e.duration(), + } + } +} + +impl Add<Duration> for Instant { + type Output = Self; + fn add(self, d: Duration) -> Self { + // `max(self)` keeps a value above `MAX` where it is. + Self( + self.0 + .saturating_add(Self::millis(d)) + .min(Self::MAX.0) + .max(self.0), + ) + } +} + +impl Sub<Duration> for Instant { + type Output = Self; + fn sub(self, d: Duration) -> Self { + // `min(self)` keeps a value below `MIN` where it is. + Self( + self.0 + .saturating_sub(Self::millis(d)) + .max(Self::MIN.0) + .min(self.0), + ) + } +} + +impl AddAssign<Duration> for Instant { + fn add_assign(&mut self, d: Duration) { + *self = *self + d; + } +} + +impl SubAssign<Duration> for Instant { + fn sub_assign(&mut self, d: Duration) { + *self = *self - d; + } +} + +/// Formats as RFC 3339 in UTC with milliseconds, for example `2024-05-01T12:00:00.000Z`. +/// A year that chrono cannot show, as in [`Instant::MAX`], formats as `<millis>ms`. +impl fmt::Display for Instant { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match chrono::DateTime::from_timestamp_millis(self.0) { + Some(t) => write!(f, "{}", t.format("%Y-%m-%dT%H:%M:%S%.3fZ")), + None => write!(f, "{}ms", self.0), + } + } +} + +impl fmt::Debug for Instant { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +/// Encodes the milliseconds as a varint. +impl Coder<Instant> for VarIntCoder { + fn urn(&self) -> &'static str { + Coder::<i64>::urn(self) + } + + fn encode(&self, value: &Instant, writer: &mut Vec<u8>, cx: Context) -> Result<(), CoderError> { + Coder::<i64>::encode(self, &value.0, writer, cx) + } + + fn decode(&self, reader: &mut &[u8], cx: Context) -> Result<Instant, CoderError> { + Coder::<i64>::decode(self, reader, cx).map(Instant) + } +} + +impl DefaultCoder for Instant { + type Coder = VarIntCoder; + fn coder() -> Self::Coder { + VarIntCoder + } + + fn encode_element(&self, writer: &mut Vec<u8>) -> Result<(), CoderError> { + self.0.encode_element(writer) + } + + fn decode_element(reader: &mut &[u8]) -> Result<Self, CoderError> { + i64::decode_element(reader).map(Self) Review Comment: This encodes exactly like i64, please make sure that this is consistent with other SDKs and add tests. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
