Skip to content

About

Framework-agnostic multi-client state synchronization over a pluggable document transport.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

state-sync

Framework-agnostic multi-client state synchronization over a pluggable document transport.

Most "shared document" sync overwrites the whole document on every save, so the last writer wins and concurrent edits clobber each other. state-sync instead writes field-level change-sets inside a transaction, so independent writers merge rather than overwrite, empty or stale saves cannot wipe live state, and version numbers stay comparable across clients.

It ships with a Firestore adapter but has zero framework or database imports in its core. The transport, identity, clock, and scheduler are all injected, so it runs unchanged in a browser, in Node, or against an in-memory mock (which is how the test suite drives it).

Install

npm install   # no runtime dependencies; tests run on plain node
npm test

Or vendor src/state-sync.mjs directly — it is a single dependency-free ES module.

Quick start (Firestore, compat SDK)

import { createStateSync, firestoreTransport } from './src/state-sync.mjs';

const sync = createStateSync({
  transport: firestoreTransport(firebase.firestore(), firebase.firestore.FieldValue),
  collection: 'board_state',
  channelId: () => currentReportHash,          // which document this client is bound to
  identity:  () => auth.currentUser.uid,
  interactive: () => userActiveInLast(120_000), // was a human driving recently?
  codeVersion: '1.0_APP_20260101',
  groups: {
    // named {key: value} maps, each with its own policy
    assignments: { keyStability: 'volatile', carryAcrossChannels: false, wipeGuard: 'interactive-only' },
    staff:       { keyStability: 'stable',   carryAcrossChannels: true,  wipeGuard: 'interactive-only' },
    notes:       { keyStability: 'stable',   carryAcrossChannels: true,  wipeGuard: 'none', countsTowardContent: false },
  },
  hooks: {
    onWritten:      ({ version }) => {},
    onRemoteApplied:({ version }) => render(sync.snapshot()),
    onBlocked:      ({ reason })  => console.warn('sync blocked:', reason),
    onFleetReload:  () => location.reload(),    // a newer app version is writing — refresh
  },
});

sync.start();
sync.subscribe((state, origin) => render(state));         // 'local' | 'remote' | 'rotate'
sync.notifyLocalChange('assignments', { changed: { r1: { station: 'Orange' } } });
sync.notifyLocalChange('assignments', { cleared: ['r2'] }); // explicit delete, not a null

A modular-SDK adapter (firestoreTransportModular) is included for apps that import the tree-shakable firebase/firestore.

What it guarantees

  • Field-level merge, not whole-document overwrite. A write only ever touches the keys it changed or cleared; untouched keys are never present in the payload, so "null padding" is unrepresentable and two clients editing different keys both survive.
  • Explicit deletes. Clearing a key emits a DELETE marker (mapped to FieldValue.delete()), so an absent key never silently erases a field.
  • Monotonic versions across writers. documentVersion is incremented inside the transaction, so it is comparable across clients instead of a per-tab counter that resets on reload.
  • Wipe + mass-delete guards. A non-interactive client (a wall display, an auto-refreshing kiosk) cannot empty a group, and clears above a configurable fraction are blocked unless a human is driving.
  • Read screening. Legacy whole-document writers that arrive with an all-empty group are screened out on the read path, so they cannot wipe a client that holds content.
  • Channel rotation without leader election. When the bound document id changes (e.g. a new data snapshot), state seeds the new channel transactionally; whoever gets there first wins the seed, everyone else adopts it — no coordinator required.
  • Fleet code-version refresh. Writes carry the writing client's code version; an older client that sees a newer one reloads instead of applying state it doesn't understand.
  • Silent-listener recovery. checkHealth() detects a listener that has gone quiet while the document actually advanced, and resubscribes.
  • Failure containment. A transport error (offline, permission denied) is caught, surfaced via onError, and the pending change-set is retained for retry — it never escapes as an unhandled rejection.

Transport contract

Any backend works by implementing five methods (see firestoreTransport for a reference):

get(path)                 -> { exists, data }
set(path, doc)            (channel creation only)
update(path, fieldMap)    (dotted paths; the DELETE symbol marks a field delete)
onSnapshot(path, cb)      -> unsubscribe
runTransaction(fn)        (fn receives a tx with get/set/update)
serverTimestamp()         -> opaque timestamp

Group policy

option default meaning
keyStability stable volatile keys churn with the source data (dropped on channel rotation)
carryAcrossChannels true seed this group into a newly-rotated channel document
wipeGuard interactive-only interactive-only = only a human may empty the group; none = unguarded
countsTowardContent true whether this group satisfies "the state has content" checks
massDeleteFraction 0.5 non-interactive clears above this fraction are blocked

Tests

node test/state-sync.test.mjs          # engine invariants, in-memory transport
node test/firestore-adapter.test.mjs   # Firestore adapter contract

The invariant suite exercises field-merge writes, wipe/mass-delete guards, read screening, cross-writer version monotonicity, echo suppression, channel rotation, fleet refresh, listener health, and transport-failure containment — each mapped to a real production incident.

License

MIT © Steven Benjamin

About

Framework-agnostic multi-client state synchronization over a pluggable document transport.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages