Skip to main content

type_history/
lib.rs

1//! Versioned Rust records with explicit field conversions and frozen schema checks.
2//!
3//! A shop starts by storing receipts with an amount in US cents. Later, it adds a
4//! currency field. New code needs that field, but old receipts still contain only
5//! the amount. Type History keeps the old record shape and runs your conversion
6//! to supply `"USD"` when those receipts are read.
7//!
8//! `#[versioned]` generates a Rust struct for each supported version of a record.
9//! A new `ReceiptCreated` history starts with `ReceiptCreatedV1`. Later versions
10//! add `ReceiptCreatedV2`, `ReceiptCreatedV3`, and so on. The original name aliases
11//! the latest struct: at V2, the macro generates `pub type ReceiptCreated = ReceiptCreatedV2;`.
12//!
13//! Use the alias's `into_versioned` method to create a [`Versioned`] containing
14//! the data and its generated metadata.
15//! Serialize that record with JSON or named-field MessagePack, and store the
16//! bytes where your application chooses. After deserialization, the alias's
17//! `from_versioned` method applies the declared conversions and returns the
18//! latest type. Application code reads and writes through that alias.
19//!
20//! After [setting up a library package](https://github.com/sformisano/type-history/blob/v0.3.3/book/src/setup.md),
21//! start the receipt history with a stable name:
22//!
23//! ```rust,ignore
24//! use type_history::versioned;
25//!
26//! #[versioned(stable_name = "shop.receipt.created")]
27//! pub struct ReceiptCreated {
28//!     pub amount_cents: u64,
29//! }
30//! ```
31//!
32//! The stable name is frozen with the schemas. Builds reject changes to that value,
33//! even when the Rust type or its module is renamed.
34//! Frozen schemas protect the stored shape; your conversion functions and tests
35//! must preserve what the values mean.
36//!
37//! Conversions run from older versions to the current version. A consumer built
38//! with only V1 rejects a V2 receipt. Services sharing a types crate must therefore
39//! coordinate which versions they publish and accept; see the
40//! [distributed-system walkthrough](https://github.com/sformisano/type-history/blob/v0.3.3/README.md#using-type-history-in-a-distributed-system).
41//!
42//! Install the matching 0.3.3 crates from crates.io. The [package setup guide](https://github.com/sformisano/type-history/blob/v0.3.3/book/src/setup.md)
43//! shows the matching runtime, build hook, and CLI configuration.
44//! The guide configures schema checks and initializes the ledger before any history declaration.
45//! The current setup requires Rust 1.97 or later. Type History supports Linux and
46//! macOS. Windows is not supported.
47//! The [book](https://github.com/sformisano/type-history/blob/v0.3.3/book/README.md)
48//! links to field rules, lifecycle commands, and error handling.
49//!
50//! For existing storage that keeps JSON payloads and metadata separately, the
51//! low-level [`decode`] API reads the payload using that metadata. Validate it
52//! when reading it from storage:
53//!
54//! ```
55//! # use std::error::Error;
56//! use type_history::{PayloadVersion, StableName};
57//!
58//! let stable_name = StableName::try_from("billing.invoice.issued".to_owned())?;
59//! let version = PayloadVersion::try_from(1_u32)?;
60//! assert_eq!(stable_name.as_str(), "billing.invoice.issued");
61//! assert_eq!(version.get(), 1);
62//! assert!(PayloadVersion::try_from(0_u32).is_err());
63//! # Ok::<(), Box<dyn Error>>(())
64//! ```
65//!
66//! A receipt may contain another record or an enum. The [`Schema`] derive
67//! describes how those supporting types are serialized so changes can be checked
68//! against frozen schemas. It supports named records, nonempty tuple structs,
69//! and externally tagged enums, including inside supported containers.
70//! Keep earlier enum definitions when a containing field
71//! changes type; `#[versioned]` remains restricted to concrete named-field structs.
72//! [`ResolvedSchema`], [`JsonSchemaField`], and [`FieldSchema`] provide the
73//! underlying schema description and export traits.
74//!
75//! String-keyed hash/tree maps share a storage contract. Sets carry an explicit
76//! [`SetMembership`] contract and differ from vectors. Custom membership IDs are
77//! trusted declarations of equality; schema derivation does not verify custom
78//! `Eq`, `Hash`, or `Ord`. A membership change requires a versioned field update.
79//! Bare tuples support arities 1 through 16. Owned `Box` values preserve the inner
80//! contract; feature `rc` adds `Rc` and `Arc` by value.
81//! Histories containing tuples above arity 12 must set `derive_debug = false`
82//! and `derive_partial_eq = false`.
83//!
84//! Optional features `typed-floats`, `uuid`, `rust-decimal`, `chrono`, and `time`
85//! add finite numeric types and checked [`adapters`]. Defaults are empty. Adapters
86//! own their serialization, so native dependencies' Serde features do not change
87//! stored profiles. See the [field integration guide](https://github.com/sformisano/type-history/blob/v0.3.3/book/src/integration.md).
88
89extern crate self as type_history;
90
91pub use type_history_core::resolved::{
92    ConstantMembership, FieldSchema, JsonSchemaField, ResolvedSchema, SetMembership,
93};
94pub use type_history_core::{
95    adapters, decode, DecodeContext, DecodeError, DecodeFailureKind, HasHistory, History,
96    InvalidPayloadVersion, InvalidStableName, PayloadVersion, ReadError, StableName, Versioned,
97};
98pub use type_history_macros::{versioned, Schema};
99
100/// Dependencies addressed by generated code.
101#[doc(hidden)]
102pub mod __private {
103    pub use type_history_core::resolved::*;
104    pub use type_history_core::*;
105}
106
107#[cfg(test)]
108mod tests {
109    use super::{ResolvedSchema, Schema};
110    use type_history_core::resolved::{
111        export_json_schema, FieldPresence, SchemaField, SchemaShape,
112    };
113    use type_history_core::serde_json::Value;
114
115    // These authored records exercise the supporting derive without adding codecs.
116    #[allow(dead_code)]
117    #[derive(Schema)]
118    struct Address {
119        number: u32,
120    }
121
122    #[allow(dead_code)]
123    #[derive(Schema)]
124    // A public record may keep the nominal type of a private field private.
125    pub struct Envelope {
126        address: Option<Address>,
127    }
128
129    #[test]
130    fn schema_derive_resolves_nested_record_fields_and_exports_their_closed_shape() {
131        assert_eq!(
132            Envelope::resolved_wire_schema(),
133            SchemaShape::Record {
134                fields: vec![SchemaField {
135                    name: "address".to_owned(),
136                    presence: FieldPresence::Optional,
137                    schema: SchemaShape::Option {
138                        value: Box::new(SchemaShape::Record {
139                            fields: vec![SchemaField {
140                                name: "number".to_owned(),
141                                presence: FieldPresence::Required,
142                                schema: SchemaShape::U32,
143                            }],
144                        }),
145                    },
146                }],
147            }
148        );
149        let exported = export_json_schema::<Envelope>();
150        assert_eq!(exported["additionalProperties"], false);
151        let address = &exported["properties"]["address"];
152        // Raw schemas can express nullability through either types or alternatives.
153        let alternatives = address["anyOf"]
154            .as_array()
155            .map(Vec::as_slice)
156            .unwrap_or_else(|| std::slice::from_ref(address));
157        let has_type = |shape: &Value, expected: &str| {
158            shape["type"] == expected
159                || shape["type"]
160                    .as_array()
161                    .is_some_and(|types| types.iter().any(|ty| ty == expected))
162        };
163        assert!(alternatives.iter().any(|shape| has_type(shape, "null")));
164        let address = alternatives
165            .iter()
166            .find(|shape| has_type(shape, "object"))
167            .expect("nested record shape");
168        assert_eq!(address["additionalProperties"], false);
169        assert_eq!(address["properties"]["number"]["type"], "integer");
170        assert_eq!(address["required"][0], "number");
171    }
172}