Rust: zwire Crates
이 콘텐츠는 아직 번역되지 않았습니다.
For complete rustdoc signatures, trait bounds, and generated examples, see docs.rs/zwire.
8. zwire-core
Section titled “8. zwire-core”- Single-threaded arena (
Scope,no_std + alloc):Scope::new(),Scope::ssr(),Scope::with_mode(ScopeMode),scope.dispose(signal) -> bool,scope.dispose_id(id) -> bool,scope.dispose_scope(),scope.is_disposed()scope.atom(val)/scope.atom_with(val, AtomOptions)->Atom<T>(scope-boundCopygenerational handle;NodeId/Signal<T>)scope.computed(|cx| ...)/scope.computed_with(..., ComputedOptions)->Computed<T>(scope-boundCopy;EvalContextwithcx.peek/cx.try_peek),scope.projection(initial, |cx, draft| ...)- Auto-tracking effects & watchers:
scope.effect(|cx| ...) -> Subscription(returnsOption<CleanupFn>),scope.split_effect(track, run) -> Subscription,scope.watch(sig, cb, WatchOptions) -> Subscription,scope.subscribe_selected(sig, selector, listener) -> Subscription - Zero-
Clonereads:scope.with(sig, |v| ...),scope.get_rc(sig), plusscope.get(sig)(T: Clone),scope.try_get(sig) -> Result<T, CoreError>,scope.peek(sig)/scope.try_peek(sig) - Writes & batching:
scope.set(atom, val),scope.update(atom, |v| ...),scope.batch(|| ...),scope.batch_guard() -> BatchGuard<'_>,scope.untracked(|| ...) - Lifecycle & RAII guards (
#[must_use]):scope.subscribe(sig, |v| ...) -> Subscription,scope.on_watched(sig, ...) -> HookGuard,scope.on_unwatched(sig, ...) -> HookGuard - Weak back-references:
scope.downgrade() -> WeakScope
- Thread-safe arena (
SyncScope,feature = "sync",Send + Sync):SyncScope::new(),SyncScope::ssr(),sync.dispose(signal) -> bool,sync.dispose_id(id) -> bool,sync.dispose_scope(),sync.is_disposed(),sync.downgrade() -> WeakSyncScopesync.atom/atom_with(SyncAtomOptions) ->SyncAtom<T>/SyncSignal<T>,sync.computed/computed_with(SyncComputedOptions) ->SyncComputed<T>(SyncEvalContextwithpeek/try_peek),sync.effect(SyncCleanupFn),sync.split_effect,sync.watch,sync.subscribe_selected->SyncSubscriptionsync.get,sync.try_get,sync.peek,sync.try_peek,sync.get_arc,sync.with,sync.set,sync.update(optimistic retry),sync.try_update_once,sync.batch,sync.batch_guard() -> SyncBatchGuard<'_>,sync.subscribe,sync.on_watched/sync.on_unwatched->SyncHookGuard,sync.has_commit_observers()SyncAtomOptions::keyassigns a protocol key. Register aWireCodecthroughregister_sync_hydratableto encode and decode that atom.- The arena uses
std::sync::RwLockfor shared concurrent reads and releases locks before equality, replay, encoding and subscriber callbacks;Dropcleans up remaining hooks and owners. Thesyncfeature requiresstd. The single-threadedScoperemains available withallocon embedded targets.
- Both scopes expose arena-backed
owner() -> Owner/create_root() -> Owner(SyncOwneronSyncScope, identified byOwnerId) for lexical ownership trees withchild_root(),on_cleanup(),effect(),subscribe(), and cascading LIFO disposal.changes(signal)returns a coalescingChanges(SyncChanges) snapshot stream.changed(signal).awaitwaits once and drops its subscription. Snapshots useRc<T>locally andArc<T>across threads. - The facade exports
zwire::optics::Lens<S, A>with borrowed field reads, focused updates, and a subscribablesignal(). - Errors:
CoreError::{Cycle, Disposed, TypeMismatch}(unconditionalcore::error::Error) andErrorSource.
9. zwire-tx
Section titled “9. zwire-tx”OptimisticLayer:OptimisticLayer::new(&scope),update(atom, |v| ...),revert(),settle(),settle_with(|| ...),try_settle(|| -> Result<R, E>)(atomicDropGuard-backed rollback on bothErrand panic).OptimisticGuard(#[must_use]): RAII wrapper auto-reverting on drop / early?return unless explicitly settled.Draft(Detached STM):Draft::new(&scope),Draft::with_base(&scope, DraftBase::Committed | DraftBase::Effective),get,get_rc,with,set,update,run,commit(),commit_verified(),discard().SyncOptimisticLayerandSyncOptimisticGuardrebase pure intents over concurrent authoritative writes. Stage server writes throughlayer.settle_with(|staged| staged.set(atom, value)).SyncDraft::with_baseselects committed or effective snapshots.get_arcshares values,setandupdatestage writes, andcommit_verifiedvalidates all read versions and publishes the complete write set under one lock.run_optimistic(&scope, apply, request, commit).awaitreverts on cancellation or request failure.run_sync_optimisticstages the authoritative response in aSyncSettlement.- Errors:
DraftError::{Closed, StmConflict { node }, Core(CoreError)}.
10. zwire-collections
Section titled “10. zwire-collections”Collection<T, K, Cmp, Flt, Sk = NoSortKey>: Standalone 2-level Chunked B-Tree (BLOCK_TARGET = 128, single-copy slot arena withNonZeroU64revision niche — zeroT: Clonerequired).- Constructors:
Collection::new(get_id, compare)(usingAcceptAllfilter),Collection::with_filter(get_id, compare, filter)(ItemFilter),Collection::with_sort_key(get_id, sort_key)/Collection::with_sort_key_and_filter(get_id, sort_key, filter)(inlineSortKeystrategy:NoSortKey,CachedSortKey,BySortKey) - Mutations:
insert,upsert,upsert_many,update_in_place,delete,clear range(offset, limit)borrows a sorted window and skips complete blocks.iter_sorted()traverses the index.set_ordering(compare, filter)installs new predicates and preserves view handles.- Queries & incremental views:
get,contains_key,len,indexed_len,top_k(k),watch_top_k(k) -> TopKViewId,unwatch_top_k(id),sync_view(id),view_items(id),view_mapped(id, f)
- Constructors:
KeyedCollection<T, K, S, IdFn, SkFn, Flt = AcceptAll>:BTreeSet<(S, K, u32)>-backed incremental collection for pureOrd + Copysort keys withO(1)Top-K boundary pruning (new,with_filter,from_parts,upsert,upsert_many,delete,clear,get,contains_key,len,is_empty,indexed_len,top_k,top_k_refs,watch_top_k,unwatch_top_k,sync_view,view_mapped,view_items,view_cloned).
With the facade’s sync and collections features, SyncReactiveCollection::new(&scope, id, compare) wraps RwLock<Collection<Arc<T>, K, ...>> for O(log N) multi-writer updates, filtered queries, O(1) Top-K boundary pruning (top_k_signal(k)), and range_signal(offset, limit) without full-map cloning (releasing locks before callbacks and SyncScope publication). For pure Ord + Copy sort keys, SyncPureReactiveCollection mirrors PureReactiveCollection on SyncScope backed directly by RwLock<KeyedCollection<Arc<T>, K, S, ...>> (new, with_filter, from_parts, upsert, upsert_many, update, delete, clear, get, contains_key, len, is_empty, indexed_len, get_top_k, top_k_signal, dispose_top_k_signal).
Bridge crates (bridges/)
Section titled “Bridge crates (bridges/)”zwire-wasm(bridges/wasm): Wraps a RustScopeinWireScope(WireScope::connect(&scope, peer),snapshot(),applyPatches(json)/apply_patches,takePatchBatch()/take_patch_batch), connecting toconnectWasm(scope, peer)from@zwire/core/protocol/wasm. React order book examplezwire-serde(bridges/serde): Optionalno_std + allocserdebridge exportingto_wire, zero-copy borrowedfrom_wire<'de>,to_wire_json,from_wire_json,SerdeWire<T>(WireCodec, plus fallibletry_to_wire),SerdeWireError, integer/boolean map keys, and#[serde(with)]moduleswire_valueandstate_patchwithout addingserdeto the corezwireworkspace. Serde bridge guide
11. zwire-protocol
Section titled “11. zwire-protocol”- Zero-dep RFC-8259 JSON Codec:
WireValue::{Null, Bool, Int(i64), Float(f64), String(String), Array(Vec<WireValue>), Object(BTreeMap<String, WireValue>)}with deterministic sorted-keyto_json()and strictfrom_json()(JsonError,WireError), plusWireCodectrait (bool, 8–64-bit and pointer-sized signed/unsigned integers,f32,f64,String,Option<T>,Vec<T>,BTreeMap<String, T>, tuples of one to four items, andWireValue). Bothi64andu64outside±(2^53 - 1)emit decimal strings for lossless JSBigIntinterop. - Enable the
derivefeature for#[derive(WireCodec)]on concrete named-field structs. Use#[wire(crate = zwire::protocol)]with the facade. Incoming objects must contain each declared field, and may contain additional fields. - Hydration:
HydratedState,hydratable(&scope, key, initial),register_hydratable,dehydrate(&scope),dehydrate_json(&scope),hydrate(&scope, state),hydrate_json(&scope, json). sync_hydratable,sync_hydrate,sync_hydrate_json,sync_dehydrate, andsync_dehydrate_jsonprovide the same wire format onSyncScope. A checkpoint captures the committed values of all registered keys in one critical section before running codecs.create_thread_sync_bridge(&scope, adapter) -> ThreadSyncBridgeaccepts aThreadSyncAdapter. Writes from each thread coalesce at its outermost batch. The bridge serializes transport calls and rejects superseded revisions and recent duplicate transaction IDs.from_sync_external_source(SyncExternalSource) polls unwatched snapshots and subscribes when watched.attach_sync_inspector(SyncInspectorHook,SyncInspectorGuard) observes commits, computations, flushes and errors. Commit callbacks run on the writer thread and carry per-atom base revisions for ordering.- External Sources:
from_external_source(&scope, source)/from_external_source_with_eqimplementingExternalSource<T>. - Sync Bridge:
create_sync_bridge(&scope, adapter: impl SyncAdapter, SyncBridgeOptions)-> RAIISyncBridge(pending_count(),flush(),dispose());StatePatch(PatchOrigin::{Local, Remote},slice_to_json,vec_from_json). - Inspector:
attach_inspector(&scope, InspectorHook) -> HookGuard(on_writewithWriteTraceEvent,on_computewithComputeTraceEvent,on_flushwithFlushTraceEvent,on_error).
12. zwire (Umbrella & ReactiveCollection)
Section titled “12. zwire (Umbrella & ReactiveCollection)”- Cargo features:
default = ["std", "core", "sync", "tx", "collections", "protocol"].- Pure
no_std + alloc/wasm32-unknown-unknown:default-features = false, features = ["core", "tx", "collections", "protocol"].
- Pure
ReactiveCollection<T, K>: Bridgeszwire-collections+zwire-coreviaScope’s_flushHooksslot, exposing reactivecol.top_k_signal(k)with 1x/batch coalesced materialization and STMDraftcompatibility.ReactiveCollectionalso exposesget_range,range_signal,iter_sorted,len_signal,indexed_len_signal,get_signal,has_signal, andset_ordering. Reactive reconfiguration accepts new closure types. Index policy callbacks run against detached values. A competing callback write wins, andtry_upsert,try_upsert_many, orset_orderingreturns false for the superseded edit.TransactionalCollection::edit(|rows: &mut RowEdit<_, _>| ...)andoptimistic(&mut layer, |rows| ...)support grouped row upserts, updates and deletions. A draft interceptseditwithindraft.run. Each edit clones the row map once, and each optimistic callback reruns on authoritative changes.PureReactiveCollection<T, K, S, IdFn, SkFn, Flt = AcceptAll>: High-frequency reactive collection backed directly byKeyedCollectionfor pure non-reentrantid,sort_key, andfilterclosures (new,with_filter,from_parts,upsert,upsert_many,delete,clear,get,contains_key,len,is_empty,indexed_len,get_top_k,top_k_signal,dispose_top_k_signal), releasing internal borrows before notifyingScope.- Stores & Projections (
zwire::store,#[derive(ReactiveStore)]underderivefeature):#[derive(ReactiveStore)]generates per-fieldAtom<Field>store structs (new,snapshot,patch, supporting#[store(crate = ...)]);MapStore<K, V>provides lazy per-keyAtom<Option<V>>withon_unwatchedpruning;projection(&scope, initial, |cx, draft| ...)provides mutable-draft incremental derived signals. - Executor-Agnostic
#![no_std]Async Resources (zwire::resource):Resource<T, E, K>andResourceState<T, E>(Pending,Refreshing(T),Ready(T),Error { error, previous },Disposed) with monotonic generation stale-response rejection (refetch,mutate,latest,is_pending,load,drive). zwire::prelude::*: Ergonomic re-export of all enabled crates’ primary types and functions.