Crate tirea_state

Crate tirea_state 

Source
Expand description

Typed state + JSON patch library for deterministic immutable state management.

tirea-state provides typed access to JSON state with automatic patch collection, enabling deterministic state transitions and full replay capability.

§Core Concepts

  • State: Trait for types that can create typed state references
  • StateRef: Generated typed accessor for reading and writing state
  • PatchSink: Automatic operation collector (transparent to developers)
  • StateContext: Provides typed state access with automatic patch collection
  • StateManager: Manages immutable state with patch history and replay
  • Patch: A serializable record of operations to apply to state

§Deterministic State Transitions

State' = apply_patch(State, Patch)
  • Same (State, Patch) always produces the same State'
  • apply_patch is a pure function that never mutates its input
  • Full history enables replay to any point in time

§Quick Start

use tirea_state::{apply_patch, Patch, Op, path};
use serde_json::json;

// Create initial state
let state = json!({"count": 0, "name": "counter"});

// Build a patch
let patch = Patch::new()
    .with_op(Op::set(path!("count"), json!(10)))
    .with_op(Op::set(path!("updated"), json!(true)));

// Apply patch (pure function)
let new_state = apply_patch(&state, &patch).unwrap();

assert_eq!(new_state["count"], 10);
assert_eq!(new_state["updated"], true);
assert_eq!(state["count"], 0); // Original unchanged

§Using Typed State (with derive macro)

For type-safe access with automatic patch collection:

use tirea_state::{StateContext, State};
use tirea_state_derive::State;
use serde::{Serialize, Deserialize};
use serde_json::json;

#[derive(Debug, Clone, Serialize, Deserialize, State)]
struct Counter {
    value: i64,
    label: String,
}

// In a tool implementation:
async fn execute(&self, ctx: &StateContext<'_>) -> Result<()> {
    let counter = ctx.state::<Counter>("counters.main");

    // Read
    let current = counter.value()?;

    // Write (automatically collected)
    counter.set_value(current + 1);
    counter.set_label("Updated");

    Ok(())
}
// Framework calls ctx.take_patch() after execution

§Using JsonWriter

For dynamic JSON manipulation without typed structs:

use tirea_state::{JsonWriter, path};
use serde_json::json;

let mut w = JsonWriter::new();
w.set(path!("user", "name"), json!("Alice"));
w.append(path!("user", "roles"), json!("admin"));
w.increment(path!("user", "login_count"), 1i64);

let patch = w.build();

Re-exports§

pub use lattice::Flag;
pub use lattice::GCounter;
pub use lattice::GSet;
pub use lattice::Lattice;
pub use lattice::LatticeMerger;
pub use lattice::LatticeRegistry;
pub use lattice::MaxReg;
pub use lattice::MinReg;
pub use lattice::ORMap;
pub use lattice::ORSet;
pub use runtime::SealedState;
pub use runtime::SealedStateError;

Modules§

lattice
Lattice trait and CRDT primitive types for conflict-free parallel state merging.
runtime
Sealed state: an ephemeral, non-persistent key/value container.

Macros§

path
Construct a Path from a sequence of segments.

Structs§

ApplyResult
Result of applying patches.
Conflict
Conflict information between two patches.
DeltaTracked
A collection with cursor-based delta tracking.
DocCell
Shared mutable document for write-through-read state access.
JsonWriter
A generic writer for building patches on arbitrary JSON structures.
Patch
A collection of operations to apply atomically.
PatchSink
Collector for patch operations.
Path
A complete path into a JSON structure.
StateContext
Pure state context with automatic patch collection.
StateManager
StateManager manages immutable state with patch history.
TrackedPatch
A patch with tracking metadata.

Enums§

ConflictKind
Types of conflicts that can occur between patches.
Number
A numeric value that can be used in increment/decrement operations.
Op
A single patch operation.
Seg
A single segment in a JSON path.
StateError
Errors that can occur during state management.
StateScope
Lifecycle scope of a StateSpec type.
TireaError
Errors that can occur during tirea-state operations.
Value
Represents any valid JSON value.

Traits§

PatchExt
Extension trait for Patch to compute touched paths.
State
Trait for types that can create typed state references.
StateExt
Extension trait providing convenience methods for State types.
StateSpec
Extends State with a typed action and a pure reducer.

Functions§

apply_patch
Apply a patch to a JSON document (pure function).
apply_patch_with_registry
Apply a patch to a JSON document using a LatticeRegistry for proper merges.
apply_patches
Apply multiple patches to a JSON document in sequence (pure function).
apply_patches_with_registry
Apply multiple patches to a JSON document using a LatticeRegistry for proper merges.
compute_touched
Compute the set of paths touched by a patch.
conflicts_with_registry
Registry-aware conflict detection between two patches.
detect_conflicts
Detect conflicts between two sets of touched paths.
get_at_path
Get a reference to a value at a path (for reading).
parse_path
Parse a dot-separated path string into a Path.
value_type_name
Get the type name of a JSON value.

Type Aliases§

TireaResult
Result type alias for tirea-state operations.

Derive Macros§

Lattice
Derive the Lattice trait for a struct with named fields.
State
Derive the State trait for a struct.