Architecture Specification
이 콘텐츠는 아직 번역되지 않았습니다.
This document specifies the 3-Layer Star-Topology Architecture implemented identically across the TypeScript (@zwire/*) and Rust (zwire*) workspaces of zwire.
1. Design Principles
Section titled “1. Design Principles”- Zero Module-Level Mutable State: Every reactive graph runs inside an isolated scope (
ReactiveScopein TypeScript;Scope/SyncScopein Rust).defaultScopeprovides zero-ceremony client ergonomics in TS, whilecreateScope({ mode: 'ssr' })/Scope::ssr()isolates concurrent SSR/Edge requests with silent watcher registration. - GC-Safe Unwatched Computeds Without
O(V+E)Cliffs: Unwatched derived nodes track dependencies using forward-only links (comp._deps -> dep, never inserted intodep._subs). In JS, abandoned computeds are immediately eligible for GC (64/64WeakRefcollection); in Rust, generational arena handles cleanly detect disposal (CoreError::Disposed). A single-root version fast-path keeps repeated unwatched reads atO(1), while subscribing promotes forward links into bidirectionaldep._subslinks and unsubscribing cascadesunlinkSubback upstream. - Zero-Try Happy-Path Flushing & Engine Monomorphism:
- TypeScript (
ts/packages/core/src/core/): All core nodes share an identical prefix layout (BaseNode) initialized in fixed order withdeclarefields (zero ES2022[[DefineOwnProperty]]overhead).flushScope()executes_drain()with zerotry/catchinside the hot loop, falling back to_drainErr()only when an exception occurs so sibling subscribers drain cleanly without poisoning the queue. - Rust (
rust/crates/zwire-core/): Generational arenaScopewithCopyhandles, zero-Cloneclosure reads (with,get_rc), RAIISubscription/HookGuarddrops, panic-safe flush unwinding, and deadlock-freeSyncScopereleasingMutexGuardbefore every user callback.
- TypeScript (
- Strict 2-Tier Star Topology (0B Extension Overhead in Core):
- Core (
ts/packages/core/src/core/*,rust/crates/zwire-core/*) never imports any companion subpath, adapter, or crate. - Companion subpaths and crates never import each other; cross-feature composition (
ObjectStore.field(k)+OptimisticLayer,focus()+Draft,Collection.topK(k)+batch(),SyncBridge+OptimisticLayer) occurs solely through 5 lazy extension slots (ts/packages/core/src/core/internal.ts,zwire_core::internal). - UI framework adapters live in
ts/packages/adapters/{react,vue,solid,svelte}/and depend only on published@zwire/coreentry points. An adapter’s root entry imports@zwire/corealone; an adapter subpath@zwire/<fw>/<x>may additionally import its mirror@zwire/core/<x>and nothing else from core. Adapters never importcore/internal.ts, another core subpath, or another adapter, which keeps@zwire/corefree of UI framework peer dependencies, compiler constraints, and version coupling (ADR-002).
- Core (
2. Layer Boundaries & Cross-Language Module Map
Section titled “2. Layer Boundaries & Cross-Language Module Map”subgraph BRG["Optional Bridges (Dependency-Bearing)"] WASM["bridges/wasm (zwire-wasm: wasm-bindgen scope transport)"] SERDE["bridges/serde (zwire-serde: no_std serde WireValue/StatePatch bridge)"]end
subgraph L2["Layer 2: Open Protocols & Specialized Engines"] PROTO["@zwire/core/protocol <-> zwire-protocol (Hydration, ExternalSource, SyncBridge, Inspector)"] COL["@zwire/core/collections <-> zwire-collections + zwire::{ReactiveCollection, PureReactiveCollection, SyncReactiveCollection, SyncPureReactiveCollection} (Collection · KeyedCollection)"]end
subgraph L1_UI["Layer 1b: TS Framework Adapter Packages (peerDep: @zwire/core)"] RCT["@zwire/react (React 18/19 Compiler-Safe Hooks + SelectorStabilizer)"] VUE["@zwire/vue (Vue 3.5+ Read-Through customRef + v-model Atoms)"] SLD["@zwire/solid (Solid 2 Accessors + Owner-Scoped Subscriptions)"] SVT["@zwire/svelte (Svelte 5.7+ createSubscriber Refs + Store Contract)"]end
subgraph L1["Layer 1a: Opt-In Tree-Shakeable Extensions (0B in Core)"] TX["@zwire/core/tx <-> zwire-tx (OptimisticLayer, runOptimistic/OptimisticGuard, STM Draft)"] STR["@zwire/core/store <-> zwire::store + #[derive(ReactiveStore)] (ObjectStore, DeepStore, createSelector, createProjection, reconcile · MapStore, projection)"] OPT["@zwire/core/optics <-> zwire::optics (TS: createAtomMap, focus/lens · Rust: Lens)"] RES["@zwire/core/resource <-> zwire::resource (TS: lazy resource, isPending, resolve · Rust: no_std Resource<T, E>)"] DEV["@zwire/core/devtools (TS: WeakRef createInspectableScope + inspectGraph)"]end
subgraph L0["Layer 0: Core Engine"] CORE["@zwire/core <-> zwire-core (Scoped Push-Pull · Split Effect · Optional Microtask Scheduler · Lexical Owner · NotReady · Disposal · 5 Lazy Slots · SyncScope)"]end
SPEC -.-> PROTO & COL & TXBRG --> PROTOL2 --> COREL1 --> COREL1_UI --> CORE"><pre class="zwire-mermaid__fallback"><code>flowchart TBSPEC["spec/ (protocol.md · wire.schema.json · conformance.json)"]
subgraph BRG["Optional Bridges (Dependency-Bearing)"] WASM["bridges/wasm (zwire-wasm: wasm-bindgen scope transport)"] SERDE["bridges/serde (zwire-serde: no_std serde WireValue/StatePatch bridge)"]end
subgraph L2["Layer 2: Open Protocols & Specialized Engines"] PROTO["@zwire/core/protocol <-> zwire-protocol (Hydration, ExternalSource, SyncBridge, Inspector)"] COL["@zwire/core/collections <-> zwire-collections + zwire::{ReactiveCollection, PureReactiveCollection, SyncReactiveCollection, SyncPureReactiveCollection} (Collection · KeyedCollection)"]end
subgraph L1_UI["Layer 1b: TS Framework Adapter Packages (peerDep: @zwire/core)"] RCT["@zwire/react (React 18/19 Compiler-Safe Hooks + SelectorStabilizer)"] VUE["@zwire/vue (Vue 3.5+ Read-Through customRef + v-model Atoms)"] SLD["@zwire/solid (Solid 2 Accessors + Owner-Scoped Subscriptions)"] SVT["@zwire/svelte (Svelte 5.7+ createSubscriber Refs + Store Contract)"]end
subgraph L1["Layer 1a: Opt-In Tree-Shakeable Extensions (0B in Core)"] TX["@zwire/core/tx <-> zwire-tx (OptimisticLayer, runOptimistic/OptimisticGuard, STM Draft)"] STR["@zwire/core/store <-> zwire::store + #[derive(ReactiveStore)] (ObjectStore, DeepStore, createSelector, createProjection, reconcile · MapStore, projection)"] OPT["@zwire/core/optics <-> zwire::optics (TS: createAtomMap, focus/lens · Rust: Lens)"] RES["@zwire/core/resource <-> zwire::resource (TS: lazy resource, isPending, resolve · Rust: no_std Resource<T, E>)"] DEV["@zwire/core/devtools (TS: WeakRef createInspectableScope + inspectGraph)"]end
subgraph L0["Layer 0: Core Engine"] CORE["@zwire/core <-> zwire-core (Scoped Push-Pull · Split Effect · Optional Microtask Scheduler · Lexical Owner · NotReady · Disposal · 5 Lazy Slots · SyncScope)"]end
SPEC -.-> PROTO & COL & TXBRG --> PROTOL2 --> COREL1 --> COREL1_UI --> CORE</code></pre></div>3. Five Zero-Cost Core Extension Slots
Section titled “3. Five Zero-Cost Core Extension Slots”Both ts/packages/core/src/core/scope.ts and rust/crates/zwire-core/src/internal.rs implement the same 5 lazy slots:
| Slot | Location | Initial Value | Consumers | Hot-Path Cost |
|---|---|---|---|---|
_ext |
Atom node | undefined / None |
tx (OptimisticLayer intent folding), TS store (field CoW sync) |
1 null/option check in set() |
_draft |
Scope | undefined / None |
tx (Draft CoW overlay & STM read-set tracking) |
1 null/option check in get()/set() |
_flushHooks |
Scope | undefined / empty |
collections (1x/batch topK materialization), protocol (SyncBridge batch push) |
1 check in drain |
_keyed / _hydrated |
Scope | undefined / empty |
protocol (out-of-order hydration w/ delete-on-consume + SyncBridge) |
Only touched when keyed |
_inst |
Scope | undefined / empty |
protocol (attachInspector), devtools (createInspectableScope), tx (settle / try_settle atomic rollback undo log) |
1 check; timing skipped when detached |
4. Key Architectural Invariants
Section titled “4. Key Architectural Invariants”- Snapshot Immutability (
@zwire/core/store):createObjectStoreuses_sh(snapshotShared) lazy Copy-on-Write:setKey()mutates in-place ONLY while no caller has observed the current snapshot; onceget()exposes the snapshot, the nextsetKey()clones once, guaranteeing React 19useSyncExternalStoreimmutability without eager per-write cloning. - Concurrent-Abort-Safe React 19 Selectors (
@zwire/react):SelectorStabilizer(ts/packages/adapters/react/src/stabilizer.ts) separates uncommitted render-phase memoization from committed subscription state (synced strictly insideuseInsertionEffect). An aborted concurrent render can never corruptshouldNotify(). - Zero-Flicker Atomic
settle()/try_settle()(tx): Snapshots committed values/versions of touched atoms, intercepts any writes inside the settle closure via_inst, strips the layer insidebatch(), and restores every base atom atomically if the settle callback throws/returnsErr/panics. - External Pull Bitflag (
F_EXTERNAL): Propagates bitwise during dependency linking so unwatched computeds readingfromExternalSource()orcol.topK(k)always observe fresh external snapshots. - Deterministic Total-Order Collection Index (
collections): Wraps usercompare(a, b)with deterministic key tie-breaking over a 2-level Chunked Sorted Block Index (BLOCK_TARGET = 128, split> 256, merge< 32), paired withO(1)Top-K boundary checks; Rust also providesKeyedCollection(BTreeSet<(S, K, u32)>),PureReactiveCollection, and thread-safeSyncReactiveCollection/SyncPureReactiveCollection. The thread-safe pair mutates its index under anRwLockand, after releasing it, publishes each Top-K view and range revision as an immutable versioned snapshot throughzwire_core::internal::sync_publish_external_versioned:SyncScopecompares the version, checks for subscribers, and writes in one critical section, so racing writers, unwatched pull-on-read refreshes, and new subscribers can never regress a signal or miss a committed write. - Read-Through UI Framework Adapters (
@zwire/{vue,solid,svelte}): Each adapter holds only a notification primitive in the host framework and reads values directly fromsignal.get(), never copying or deeply proxying snapshots, and releasing listeners with the host component’s ownership scope. - Re-entrancy & Deadlock Freedom (Rust): Every
RefCellborrow andMutexGuardis dropped before invoking user callbacks; scope-owned closures storeWeakScope/WeakSyncScope(never strong clones) to guarantee zeroRc/Arccycles.
5. Shared Cross-Language Spec & Parity
Section titled “5. Shared Cross-Language Spec & Parity”spec/protocol.mdandspec/wire.schema.jsondefine the canonical RFC-8259 wire representation (including losslessi64/u64safe-integer string encoding above±(2^53 - 1)).spec/conformance.jsonvalidates identical optimistic rebase, STM draft, Top-K ordering/pruning, and JSON wire round-trips across TypeScript (ts/tests/conformance.test.ts) and Rust (rust/crates/zwire/tests/conformance.rs), synchronized viascripts/sync-spec.ts.examples/rust-ts-sync/verifies live cross-process Rust ↔ TypeScript sync in CI.
6. TypeScript Compiler Pipeline (tsrs + tsc Parity & .d.ts Rewrite)
Section titled “6. TypeScript Compiler Pipeline (tsrs + tsc Parity & .d.ts Rewrite)”- Source files use explicit
.tsrelative specifiers for native TypeScript execution on Node 26+ and Bun 1.3+, with"rewriteRelativeImportExtensions": trueand"isolatedDeclarations": true. - Because both
tsrs@7.1.0-beta.tsrs9and stocktscpreserve.tsspecifiers in emitted.d.tsfiles,ts/scripts/build.tsrunsts/scripts/rewrite-dts-extensions.tsimmediately aftertsrsemit. ts/scripts/verify-dist.tscontinuously enforces producer parity (tsc --emitDeclarationOnlymatchingtsrsfile sets and exported symbol surfaces across all 5 packages) and consumer parity (NodeNext+Bundlertypechecks under bothtsrsandtscfor both a@zwire/core-only consumer and a full adapter consumer).