State

Struct State 

pub struct State { /* private fields */ }
Expand description

A concurrent, type-safe state container that agents read from and write to.

By default, set() writes directly to the inner store. When delta tracking is enabled via with_delta_tracking(), writes go to a separate delta map (with tombstones) that can be atomically committed or rolled back.

Implementations§

§

impl State

pub fn new() -> State

Create a new empty state container.

pub fn with_delta_tracking(&self) -> State

Create a new State with delta tracking enabled. Writes go to the delta map; reads check delta first, then inner.

pub fn set_journal_sink(&self, sink: Arc<dyn JournalSink>)

Install a durable JournalSink that receives every state mutation.

The sink is shared with all clones and delta views of this State (like the in-memory ring) and is invoked synchronously on the write path — keep it cheap. The in-memory ring keeps serving recent_mutations/evidence; the sink adds unbounded durability.

pub fn with_journal_sink(self, sink: Arc<dyn JournalSink>) -> State

Builder-style variant of set_journal_sink.

pub fn get<T>(&self, key: &str) -> Option<T>

Get a value by key, attempting to deserialize to the requested type. When delta tracking is enabled, checks delta first, then inner.

pub fn with<F, R>(&self, key: &str, f: F) -> Option<R>
where F: FnOnce(&Value) -> R,

Borrow a value by key without cloning, applying f to the reference.

This is the zero-copy alternative to get_raw(). The closure receives a &Value directly from the DashMap ref-guard, avoiding the Value::clone() + serde_json::from_value() overhead of get().

Lookup order: delta (if tracking) → inner → derived fallback.

pub fn get_raw(&self, key: &str) -> Option<Value>

Get a raw JSON value by key. When delta tracking is enabled, checks delta first, then inner. If the key is not found and doesn’t contain a prefix, also checks derived:{key} as a transparent fallback for computed variables.

pub fn get_key<T>(&self, key: &StateKey<T>) -> Option<T>

Get a typed value using a StateKey<T>.

pub fn set_key<T>(&self, key: &StateKey<T>, value: T) -> Result<(), StateError>
where T: Serialize,

Set a typed value using a StateKey<T>.

Returns StateError if value cannot be serialized to JSON.

pub fn with_key<T, F, R>(&self, key: &StateKey<T>, f: F) -> Option<R>
where F: FnOnce(&Value) -> R,

Zero-copy borrow using a StateKey<T>.

pub fn set( &self, key: impl Into<String>, value: impl Serialize, ) -> Result<(), StateError>

Set a value by key.

When delta tracking is enabled, writes to the delta view instead of the committed store. Returns StateError if value cannot be serialized to JSON — a public SDK write never panics on caller data.

pub fn set_committed( &self, key: impl Into<String>, value: impl Serialize, ) -> Result<(), StateError>

Set a value directly in the committed store, bypassing delta tracking.

Returns StateError if value cannot be serialized to JSON.

pub fn modify<T, F>(&self, key: &str, default: T, f: F) -> Result<T, StateError>
where T: Serialize + DeserializeOwned, F: FnOnce(T) -> T,

Atomically read-modify-write a value under a per-key lock.

If the key doesn’t exist, default is used as the initial value. The function f receives the current value and returns the new value. The read-modify-write is performed while holding the map shard for key, so concurrent modify calls on the same key do not lose updates. Returns the new value, or StateError if it cannot be serialized.

pub fn contains(&self, key: &str) -> bool

Check if a key exists (in delta or inner).

pub fn remove(&self, key: &str) -> Option<Value>

Remove a key.

In delta-tracking mode this records a tombstone in the delta view and leaves the committed store untouched, so a subsequent rollback() fully restores the base state. Returns the value that was visible before removal.

pub fn keys(&self) -> Vec<String>

Get all keys (from both inner and delta when tracking).

Keys tombstoned in the delta are excluded.

pub fn pick(&self, keys: &[&str]) -> State

Create a new State containing only the specified keys.

pub fn merge(&self, other: &State)

Merge another state into this one (other’s values overwrite on conflict).

pub fn rename(&self, from: &str, to: &str)

Rename a key.

pub fn is_tracking_delta(&self) -> bool

Whether delta tracking is enabled.

pub fn has_delta(&self) -> bool

Whether there are uncommitted delta changes.

pub fn delta(&self) -> HashMap<String, Value>

Get a snapshot of the current delta’s pending writes (tombstones omitted).

pub fn commit(&self)

Commit delta changes into the inner store, then clear the delta.

Pending puts are applied and tombstones remove the committed key, so a removal made under delta tracking becomes durable only at commit time.

pub fn rollback(&self)

Discard all uncommitted delta changes, restoring the committed base state.

Because removals and prefix clears under delta tracking only write tombstones (never mutating inner), dropping the delta is sufficient to restore the base — including keys that were removed in the transaction.

pub fn app(&self) -> PrefixedState<'_>

Access state with the app: prefix scope.

pub fn user(&self) -> PrefixedState<'_>

Access state with the user: prefix scope.

pub fn temp(&self) -> PrefixedState<'_>

Access state with the temp: prefix scope.

pub fn session(&self) -> PrefixedState<'_>

Access state with the session: prefix scope (auto-tracked signals).

pub fn turn(&self) -> PrefixedState<'_>

Access state with the turn: prefix scope (reset each turn).

pub fn bg(&self) -> PrefixedState<'_>

Access state with the bg: prefix scope (background tasks).

pub fn derived(&self) -> ReadOnlyPrefixedState<'_>

Access read-only state with the derived: prefix scope (computed vars only).

pub fn snapshot_values(&self, keys: &[&str]) -> HashMap<String, Value>

Snapshot the values of specific keys. Returns HashMap of key -> current value. Used by watchers to capture state before mutations.

pub fn diff_values( &self, prev: &HashMap<String, Value>, keys: &[&str], ) -> Vec<(String, Value, Value)>

Diff current state against a previous snapshot. Returns Vec of (key, old_value, new_value) for keys that changed.

pub fn to_hashmap(&self) -> HashMap<String, Value>

Export all state as a HashMap (for persistence/serialization).

pub fn from_hashmap(&self, map: HashMap<String, Value>)

Restore state from a HashMap (for persistence/deserialization).

pub fn clear_prefix(&self, prefix: &str)

Remove all keys with the given prefix.

In delta-tracking mode this writes tombstones for matching keys (from both the committed store and pending delta puts) without mutating the committed store, so rollback() restores everything that was cleared.

pub fn recent_mutations(&self) -> Vec<StateMutation>

Return a snapshot of recent state mutations.

pub fn mutation_cursor(&self) -> u64

Return the current monotonic cursor for the mutation journal.

pub fn mutations_since(&self, cursor: u64) -> Vec<StateMutation>

Return mutations appended after a previously captured cursor.

pub fn drain_mutations(&self) -> Vec<StateMutation>

Drain and return all recorded state mutations.

pub fn evidence(&self, key: &str) -> SlotEvidence

Aggregate the SlotEvidence for a key: its current value, provenance (state_meta:{key}), confidence, and most-recent journal write.

Trait Implementations§

§

impl Clone for State

§

fn clone(&self) -> State

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for State

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for State

§

fn default() -> State

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for State

§

impl !RefUnwindSafe for State

§

impl Send for State

§

impl Sync for State

§

impl Unpin for State

§

impl !UnwindSafe for State

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,