foldkit-sync 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +154 -0
- package/dist/index.d.mts +378 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +817 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +52 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/indexedDb.ts","../src/errors.ts","../src/lww.ts","../src/presence.ts","../src/transport.ts","../src/sync.ts"],"sourcesContent":["/** Persists a replica's state with compare-and-swap on its revision. */\nexport interface Storage<State = unknown> {\n load(): Promise<unknown>\n save(state: State, expectedRevision: number | null): Promise<void>\n close(): void\n}\n\n/** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */\nexport const indexedDb = async <State = unknown>(\n name: string,\n factory: IDBFactory = globalThis.indexedDB,\n): Promise<Storage<State>> => {\n const database = await new Promise<IDBDatabase>((resolve, reject) => {\n const request = factory.open(name, 1)\n request.onupgradeneeded = () => request.result.createObjectStore('replica')\n request.onsuccess = () => resolve(request.result)\n request.onerror = () => reject(request.error)\n })\n database.onversionchange = () => database.close()\n return {\n load: () =>\n new Promise((resolve, reject) => {\n const transaction = database.transaction('replica', 'readonly')\n const request = transaction.objectStore('replica').get('state')\n transaction.oncomplete = () => resolve(request.result)\n transaction.onabort = () => reject(transaction.error ?? new Error('IndexedDB read aborted'))\n }),\n save: (state, expectedRevision) =>\n new Promise((resolve, reject) => {\n const transaction = database.transaction('replica', 'readwrite', { durability: 'strict' })\n const store = transaction.objectStore('replica')\n const request = store.get('state')\n let conflict = false\n request.onsuccess = () => {\n const current = request.result as { revision: number } | undefined\n if ((current?.revision ?? null) !== expectedRevision) {\n conflict = true\n transaction.abort()\n return\n }\n store.put(state, 'state')\n }\n transaction.oncomplete = () => resolve()\n transaction.onabort = () =>\n reject(\n conflict\n ? new Error('Replica was changed by another writer')\n : (transaction.error ?? new Error('IndexedDB write aborted')),\n )\n }),\n close: () => database.close(),\n }\n}\n","import { Schema } from 'effect'\n\n/** The persisted storage could not be read or written. */\nexport class StorageError extends Schema.TaggedError<StorageError>()('StorageError', {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n}) {}\n\n/** The storage holds a different replica's state. */\nexport class WrongReplicaStorageError extends Schema.TaggedError<WrongReplicaStorageError>()(\n 'WrongReplicaStorageError',\n {\n documentId: Schema.String,\n replicaId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The persisted replica history is internally inconsistent. */\nexport class InvalidReplicaHistoryError extends Schema.TaggedError<InvalidReplicaHistoryError>()(\n 'InvalidReplicaHistoryError',\n {\n message: Schema.String,\n cause: Schema.optional(Schema.Unknown),\n },\n) {}\n\n/** A persisted pending operation could not have been produced by this replica. */\nexport class InvalidOutboxError extends Schema.TaggedError<InvalidOutboxError>()(\n 'InvalidOutboxError',\n {\n message: Schema.String,\n },\n) {}\n\n/** The server sent a checkpoint older than the replica's cursor. */\nexport class CheckpointRegressionError extends Schema.TaggedError<CheckpointRegressionError>()(\n 'CheckpointRegressionError',\n {\n cursor: Schema.Number,\n checkpointCursor: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** Committed operations were not contiguous from the replica's cursor. */\nexport class CommittedOrderError extends Schema.TaggedError<CommittedOrderError>()(\n 'CommittedOrderError',\n {\n expected: Schema.Number,\n actual: Schema.Number,\n message: Schema.String,\n },\n) {}\n\n/** The server rejected an operation the replica never sent. */\nexport class ForeignRejectionError extends Schema.TaggedError<ForeignRejectionError>()(\n 'ForeignRejectionError',\n {\n opId: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/** The replica was closed while work was still being submitted. */\nexport class ReplicaClosedError extends Schema.TaggedError<ReplicaClosedError>()(\n 'ReplicaClosedError',\n {\n message: Schema.String,\n },\n) {}\n\nexport type ReplicaError =\n | StorageError\n | WrongReplicaStorageError\n | InvalidReplicaHistoryError\n | InvalidOutboxError\n | CheckpointRegressionError\n | CommittedOrderError\n | ForeignRejectionError\n | ReplicaClosedError\n","import { Schema } from 'effect'\nimport type { Storage } from './indexedDb.js'\n\n/** A logical write time; replica ids break concurrent ties using UTF-16 order. */\nconst Stamp = Schema.Struct({\n counter: Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n ),\n replicaId: Schema.NonEmptyString,\n})\n\nconst ClockState = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n documentId: Schema.NonEmptyString,\n replicaId: Stamp.fields.replicaId,\n // The high-water counter also serves as the storage's CAS revision.\n revision: Stamp.fields.counter,\n})\nexport type LwwClockState = typeof ClockState.Type\n\nexport interface LwwClock {\n /** Persists a timestamp beyond the saved counter and supplied observation. */\n next(observedCounter?: number): Promise<typeof Stamp.Type>\n /** Drains accepted allocations and closes storage; repeated calls share completion. */\n close(): Promise<void>\n}\n\nconst decodeClock = Schema.decodeUnknownSync(ClockState, { onExcessProperty: 'error' })\nconst decodeCounter = Schema.decodeUnknownSync(Stamp.fields.counter)\n\n/** Opens a durable clock in its own storage, taking ownership even if opening fails. */\nexport const openLwwClock = async ({\n documentId,\n replicaId,\n storage,\n}: {\n readonly documentId: string\n readonly replicaId: string\n readonly storage: Storage<LwwClockState>\n}): Promise<LwwClock> => {\n let state: LwwClockState\n try {\n const initial = decodeClock({\n schemaVersion: 1,\n documentId,\n replicaId,\n revision: 0,\n })\n const saved = await storage.load()\n state = saved === undefined ? initial : decodeClock(saved)\n if (state.documentId !== documentId || state.replicaId !== replicaId)\n throw new Error('Wrong clock storage')\n if (saved === undefined) await storage.save(state, null)\n } catch (error) {\n storage.close()\n throw error\n }\n\n let tail = Promise.resolve()\n let closing: Promise<void> | undefined\n return {\n next: (observedCounter = 0) => {\n if (closing !== undefined) return Promise.reject(new Error('Clock is closed'))\n const allocation = tail.then(async () => {\n const next = decodeClock({\n ...state,\n revision: Math.max(state.revision, decodeCounter(observedCounter)) + 1,\n })\n // A crash after this save may skip a timestamp, but must never reuse it.\n await storage.save(next, state.revision)\n state = next\n return { counter: next.revision, replicaId }\n })\n tail = allocation.then(\n () => {},\n () => {},\n )\n return allocation\n },\n close: () => (closing ??= tail.then(() => storage.close())),\n }\n}\n\n/**\n * A schema and reducer helper for a last-writer-wins register.\n * Allocate a unique stamp per write before dispatch, and retain it in the Message.\n * Merge is for decoded values; the application's schema validates wire input.\n */\nexport const lwwRegister = <Value, Encoded, RD, RE>(\n value: Schema.Codec<Value, Encoded, RD, RE>,\n) => {\n const schema = Schema.Struct({ stamp: Stamp, value })\n type Register = typeof schema.Type\n const equivalent = Schema.toEquivalence(value)\n\n const merge = (left: Register, right: Register): Register => {\n if (left.stamp.counter !== right.stamp.counter)\n return left.stamp.counter > right.stamp.counter ? left : right\n if (left.stamp.replicaId !== right.stamp.replicaId)\n return left.stamp.replicaId > right.stamp.replicaId ? left : right\n // Reusing a write identity for different values would make arrival order win.\n if (!equivalent(left.value, right.value)) throw new Error('Conflicting LWW write identity')\n return left\n }\n\n return { schema, merge }\n}\n","import type { SocketLike } from './transport.js'\n\n/** One peer's presence. A `null` value means the peer left. */\nexport interface PresenceUpdate<Update> {\n readonly id: string\n readonly value: Update | null\n}\n\n/**\n * The ephemeral channel presence travels on.\n *\n * Deliberately not the durable transport: presence is broadcast, never\n * journaled, so a dropped or duplicated update is harmless.\n */\nexport interface PresenceChannel<Update> {\n publish(update: PresenceUpdate<Update>): void\n subscribe(listener: (update: PresenceUpdate<Update>) => void): () => void\n}\n\nexport interface PresenceOptions<Update> {\n /** This peer's identity on the channel. */\n readonly id: string\n /** Milliseconds without an update before a peer is dropped. */\n readonly ttl: number\n /**\n * Validates the untrusted value a peer sends before it is stored. Presence\n * crosses a wire, so this is required rather than trusting the type\n * parameter; a value it rejects is dropped.\n */\n readonly decodeValue: (value: unknown) => Update\n readonly channel?: PresenceChannel<Update> | undefined\n /** Injectable clock, for tests. */\n readonly now?: (() => number) | undefined\n}\n\nexport interface PresencePeer<Update> {\n readonly id: string\n readonly value: Update\n readonly updatedAt: number\n}\n\nexport interface Presence<Update> {\n /** Sets this peer's value and broadcasts it. */\n set(value: Update): void\n /** Removes this peer and broadcasts the departure. */\n leave(): void\n /** Live peers, self included, with stale ones excluded. */\n peers(): ReadonlyArray<PresencePeer<Update>>\n /** Drops expired peers; notifies if any went. */\n prune(): void\n subscribe(listener: () => void): () => void\n /** Stops listening to the channel. */\n close(): void\n}\n\n/**\n * Tracks ephemeral peers with a time-to-live.\n *\n * Nothing here touches the durable log: presence is state a peer refreshes, and\n * a peer that stops refreshing is dropped, not replayed.\n */\nexport const createPresence = <Update>(options: PresenceOptions<Update>): Presence<Update> => {\n const now = options.now ?? (() => Date.now())\n const peers = new Map<string, PresencePeer<Update>>()\n const listeners = new Set<() => void>()\n /** A subscriber must never fail an update. */\n const notify = (): void => {\n for (const listener of [...listeners]) {\n try {\n listener()\n } catch {\n // Deliberately swallowed.\n }\n }\n }\n const expired = (peer: PresencePeer<Update>, at: number): boolean =>\n at - peer.updatedAt > options.ttl\n\n const receive = (update: PresenceUpdate<Update>): void => {\n if (update.id === options.id) return\n if (update.value === null) {\n if (peers.delete(update.id)) notify()\n return\n }\n let value: Update\n try {\n value = options.decodeValue(update.value)\n } catch {\n // A peer's value that fails the contract is dropped, never stored.\n return\n }\n peers.set(update.id, { id: update.id, value, updatedAt: now() })\n notify()\n }\n const unsubscribe = options.channel?.subscribe(receive)\n\n return {\n set: value => {\n peers.set(options.id, { id: options.id, value, updatedAt: now() })\n options.channel?.publish({ id: options.id, value })\n notify()\n },\n leave: () => {\n peers.delete(options.id)\n options.channel?.publish({ id: options.id, value: null })\n notify()\n },\n peers: () => {\n const at = now()\n return [...peers.values()].filter(peer => !expired(peer, at)).map(peer => ({ ...peer }))\n },\n prune: () => {\n const at = now()\n let changed = false\n for (const [id, peer] of peers) {\n if (expired(peer, at)) {\n peers.delete(id)\n changed = true\n }\n }\n if (changed) notify()\n },\n subscribe: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n close: () => {\n unsubscribe?.()\n listeners.clear()\n },\n }\n}\n\n/** An in-process channel, for tests and single-process demos. */\nexport const loopbackPresenceChannel = <Update>(): PresenceChannel<Update> => {\n const listeners = new Set<(update: PresenceUpdate<Update>) => void>()\n return {\n publish: update => {\n for (const listener of [...listeners]) {\n try {\n listener(update)\n } catch {\n // A subscriber must never fail an update.\n }\n }\n },\n subscribe: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n }\n}\n\n/** Broadcasts presence updates among connected peers. */\nexport interface PresenceHub<Update> {\n /** Registers a peer's send; returns a leave function. */\n join(send: (update: PresenceUpdate<Update>) => void): () => void\n /** Fans an update out to every joined peer. */\n publish(update: PresenceUpdate<Update>): void\n}\n\nexport const createPresenceHub = <Update>(): PresenceHub<Update> => {\n const peers = new Set<(update: PresenceUpdate<Update>) => void>()\n return {\n join: send => {\n peers.add(send)\n return () => peers.delete(send)\n },\n publish: update => {\n for (const send of [...peers]) {\n try {\n send(update)\n } catch {\n // One broken peer must not starve the rest of the fan-out.\n }\n }\n },\n }\n}\n\nconst frameType = 'presence'\n\n/** Decodes a presence frame, ignoring anything else a socket may carry. */\nconst decodePresence = <Update>(data: string): PresenceUpdate<Update> | undefined => {\n let frame: Record<string, unknown>\n try {\n frame = JSON.parse(data) as Record<string, unknown>\n } catch {\n return undefined\n }\n const value = frame[frameType]\n if (typeof value !== 'object' || value === null) return undefined\n const { id, value: payload } = value as { id?: unknown; value?: unknown }\n if (typeof id !== 'string') return undefined\n return { id, value: (payload ?? null) as Update | null }\n}\n\n/** A presence channel carried on a socket, alongside exchange frames. */\nexport const socketPresenceChannel = <Update>(socket: SocketLike): PresenceChannel<Update> => ({\n publish: update => socket.send(JSON.stringify({ [frameType]: update })),\n subscribe: listener =>\n socket.onMessage(data => {\n const update = decodePresence<Update>(data)\n if (update !== undefined) listener(update)\n }),\n})\n\n/** Serves presence frames on an accepted socket, fanning them through the hub. */\nexport const servePresence = <Update>(\n socket: SocketLike,\n hub: PresenceHub<Update>,\n): (() => void) => {\n const send = (update: PresenceUpdate<Update>): void =>\n socket.send(JSON.stringify({ [frameType]: update }))\n const leave = hub.join(send)\n const off = socket.onMessage(data => {\n const update = decodePresence<Update>(data)\n if (update !== undefined) hub.publish(update)\n })\n return () => {\n off()\n leave()\n }\n}\n","import { Context, Duration, Effect, Layer, Schedule, Schema } from 'effect'\nimport type { Operation, TransportClient } from './sync.js'\n\n/** The wire failure of a transport. A refusal is a result, not an error. */\nexport class TransportError extends Schema.TaggedError<TransportError>()('SyncTransportError', {\n message: Schema.String,\n}) {}\n\n/** One request/response frame, as it crosses a wire. */\nexport interface ExchangeFrame {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\nexport interface TransportShape {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n ) => Effect.Effect<unknown, TransportError>\n}\n\n/**\n * The seam the replica syncs through.\n *\n * A service, not a concrete client, so an application substitutes an in-process\n * transport, a socket, or a test double without the replica knowing. A refusal\n * arrives in the exchange result; only a wire failure is a `TransportError`.\n */\nexport class Transport extends Context.Service<Transport, TransportShape>()(\n 'foldkit-sync/Transport',\n) {}\n\nconst failure = (error: unknown): TransportError =>\n new TransportError({ message: error instanceof Error ? error.message : String(error) })\n\n/** A transport backed by an in-process handler, for tests and single-process demos. */\nexport const layerLoopback = (\n handler: (cursor: number, pending: ReadonlyArray<Operation>) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending) =>\n Effect.tryPromise({ try: () => Promise.resolve(handler(cursor, pending)), catch: failure }),\n })\n\n/** Wraps the promise-based client the replica already speaks. */\nexport const layerFromPromise = (transport: TransportClient): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending) =>\n Effect.tryPromise({ try: () => transport.exchange(cursor, pending), catch: failure }),\n })\n\n/** Bridges the service back to the promise client the replica consumes. */\nexport const toPromise = (transport: TransportShape): TransportClient => ({\n exchange: (cursor, pending) => Effect.runPromise(transport.exchange(cursor, pending)),\n})\n\n/**\n * Serves one accepted socket, answering each exchange frame.\n *\n * The counterpart to `layerSocket`: the handler returns the exchange result, or\n * throws and the failure is written back as an error frame. Returns a function\n * that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n ) => unknown | Promise<unknown>\n },\n): (() => void) => {\n const send = (reply: ExchangeReply): void => {\n try {\n socket.send(JSON.stringify(reply))\n } catch {\n // The socket may have closed while the handler was running.\n }\n }\n const stopMessage = socket.onMessage(data => {\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch {\n return\n }\n if (typeof parsed !== 'object' || parsed === null) return\n const { id, cursor, pending } = parsed as { id?: unknown; cursor?: unknown; pending?: unknown }\n // Without an id there is nobody to answer, so drop the frame.\n if (typeof id !== 'string') return\n if (\n typeof cursor !== 'number' ||\n !Number.isSafeInteger(cursor) ||\n cursor < 0 ||\n !Array.isArray(pending)\n ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = { id, cursor, pending: pending as ReadonlyArray<Operation> }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending)\n send({ id: frame.id, result })\n } catch (error) {\n send({ id: frame.id, error: error instanceof Error ? error.message : String(error) })\n }\n })()\n })\n const stopClose = socket.onClose(() => stopMessage())\n return () => {\n stopMessage()\n stopClose()\n }\n}\n\n/** The minimal socket the layer needs; the global `WebSocket` satisfies it. */\nexport interface SocketLike {\n send(data: string): void\n close(): void\n onMessage(listener: (data: string) => void): () => void\n onClose(listener: () => void): () => void\n /**\n * Optional. When provided, exchanges wait for it before sending, so a\n * transport can connect asynchronously. Absent means already connected.\n */\n onOpen?(listener: () => void): () => void\n}\n\nexport interface SocketOptions {\n readonly url: string\n /** Injectable for tests; defaults to the platform `WebSocket`. */\n readonly makeSocket?: ((url: string) => SocketLike) | undefined\n /** Reconnect attempts after a close before queued work fails. Default 5. */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: Duration.Input | undefined\n /** Exchanges queued or in flight before new ones fail. Default 64. */\n readonly maxQueue?: number | undefined\n}\n\n/** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */\nexport const nativeSocket = (url: string): SocketLike => {\n const socket = new WebSocket(url)\n return {\n send: data => socket.send(data),\n close: () => socket.close(),\n onOpen: listener => {\n if (socket.readyState === WebSocket.OPEN) {\n listener()\n return () => {}\n }\n socket.addEventListener('open', listener)\n return () => socket.removeEventListener('open', listener)\n },\n onMessage: listener => {\n const handler = (event: MessageEvent): void => listener(String(event.data))\n socket.addEventListener('message', handler)\n return () => socket.removeEventListener('message', handler)\n },\n onClose: listener => {\n const handler = (): void => listener()\n socket.addEventListener('close', handler)\n return () => socket.removeEventListener('close', handler)\n },\n }\n}\n\n/**\n * A WebSocket client transport.\n *\n * One connection is live at a time. While it is connecting, exchanges queue; if\n * it closes, the transport reconnects on an exponential, jittered backoff and\n * re-sends every queued and in-flight frame with its original id, so a lost\n * reply is answered rather than dropped and a late reply cannot resolve a newer\n * frame. Once the retries are exhausted (or the layer closes) queued work fails\n * with a `TransportError`; a queue over `maxQueue` fails new exchanges with\n * backpressure. The socket is released when the layer's scope ends.\n */\nexport const layerSocket = (options: SocketOptions): Layer.Layer<Transport, TransportError> =>\n Layer.effect(\n Transport,\n Effect.gen(function* () {\n const makeSocket = options.makeSocket ?? nativeSocket\n const maxQueue = options.maxQueue ?? 64\n const retry = Schedule.exponential(options.retryBase ?? '50 millis').pipe(\n Schedule.jittered,\n Schedule.upTo({ times: options.maxRetries ?? 5 }),\n )\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\n }\n const queued: Array<Entry> = []\n const inFlight = new Map<string, Entry>()\n let socket: SocketLike | undefined\n let ready = false\n let nextId = 0\n let disposed = false\n\n const send = (entry: Entry): void => {\n inFlight.set(entry.id, entry)\n socket?.send(\n JSON.stringify({\n id: entry.id,\n cursor: entry.cursor,\n pending: entry.pending,\n } satisfies ExchangeFrame),\n )\n }\n const flush = (): void => {\n if (socket === undefined || !ready) return\n for (const entry of queued.splice(0)) send(entry)\n }\n const requeue = (): void => {\n queued.unshift(...inFlight.values())\n inFlight.clear()\n }\n const failAll = (message: string): void => {\n const entries = [...queued.splice(0), ...inFlight.values()]\n inFlight.clear()\n for (const entry of entries) entry.resume(Effect.fail(new TransportError({ message })))\n }\n\n const connect = Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n const next = makeSocket(options.url)\n socket = next\n ready = next.onOpen === undefined\n const offOpen = next.onOpen?.(() => {\n ready = true\n flush()\n })\n const offMessage = next.onMessage(data => {\n let reply: ExchangeReply\n try {\n reply = JSON.parse(data) as ExchangeReply\n } catch {\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\n inFlight.delete(reply.id)\n entry.resume(\n reply.error === undefined\n ? Effect.succeed(reply.result)\n : Effect.fail(new TransportError({ message: reply.error })),\n )\n })\n const offClose = next.onClose(() => {\n offOpen?.()\n offMessage()\n offClose()\n socket = undefined\n ready = false\n // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) flush()\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n connect.pipe(\n Effect.retry(retry),\n Effect.catch(error =>\n Effect.sync(() => {\n if (!disposed) failAll(error.message)\n }),\n ),\n ),\n )\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n disposed = true\n ready = false\n socket?.close()\n socket = undefined\n failAll('transport closed')\n }),\n )\n\n return {\n exchange: (cursor, pending) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (queued.length + inFlight.size >= maxQueue) {\n resume(Effect.fail(new TransportError({ message: 'transport queue full' })))\n return\n }\n const entry: Entry = { id: String(nextId++), cursor, pending, resume }\n if (ready) send(entry)\n else queued.push(entry)\n }),\n }\n }),\n )\n","import { Effect, Metric, Ref, Schema, SynchronizedRef } from 'effect'\nimport {\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignRejectionError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplicaClosedError,\n StorageError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nimport type { Storage } from './indexedDb.js'\nimport { Transport, TransportError } from './transport.js'\n\nconst Sequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n)\n\n/** A client-authored operation envelope. `message` is the application's encoded Message. */\nconst OperationSchema = Schema.Struct({\n protocolVersion: Schema.Literal(1),\n schemaVersion: Schema.Literal(1),\n documentId: Schema.NonEmptyString,\n replicaId: Schema.NonEmptyString,\n localSequence: Sequence,\n opId: Schema.NonEmptyString,\n baseCursor: Sequence,\n message: Schema.Unknown,\n})\nexport type Operation = typeof OperationSchema.Type\n\n/** An operation the server committed, with its authoritative order and actor. */\nconst CommittedSchema = Schema.Struct({\n ...OperationSchema.fields,\n serverSequence: Sequence.check(Schema.isGreaterThanOrEqualTo(1)),\n actorId: Schema.NonEmptyString,\n})\nexport type Committed = typeof CommittedSchema.Type\n\nconst decodeOperation = Schema.decodeUnknownSync(OperationSchema, { onExcessProperty: 'error' })\nconst decodeCommitted = Schema.decodeUnknownSync(CommittedSchema, { onExcessProperty: 'error' })\n\n/**\n * How many committed-operation ids a replica retains for duplicate detection.\n * Committed sequences are contiguous and the server enforces `opId`\n * uniqueness, so this is defence in depth; bounding it keeps replica state from\n * growing without limit on a log that is never checkpointed.\n */\nconst COMMITTED_ID_WINDOW = 1024\n\n/** Counters and a histogram an application can scrape. */\nexport const syncMetrics = {\n exchanges: Metric.counter('foldkit_sync_exchanges_total'),\n applied: Metric.counter('foldkit_sync_commits_applied_total'),\n checkpoints: Metric.counter('foldkit_sync_checkpoints_adopted_total'),\n exchangePending: Metric.histogram('foldkit_sync_exchange_pending', {\n boundaries: [1, 4, 16, 64, 256, 1024],\n }),\n}\n\n/** Keeps the storage driver's message visible on the typed failure. */\nconst storageError = (context: string, cause: unknown): StorageError =>\n new StorageError({\n message: `${context}: ${cause instanceof Error ? cause.message : String(cause)}`,\n cause,\n })\n\nexport interface Checkpoint<Shared> {\n readonly cursor: number\n readonly model: Shared\n}\n\nexport interface Exchange<Shared> {\n readonly operations: ReadonlyArray<unknown>\n readonly rejected: ReadonlyArray<string>\n /** Sends from the request that are durably committed, so the replica can drop them. */\n readonly acknowledged?: ReadonlyArray<string> | undefined\n /** The snapshot a replica predating compaction adopts in place of the log. */\n readonly checkpoint?: Checkpoint<Shared> | undefined\n}\n\nexport interface ReplicaState<Shared> {\n readonly protocolVersion: 1\n readonly schemaVersion: 1\n readonly documentId: string\n readonly replicaId: string\n readonly revision: number\n readonly nextLocalSequence: number\n readonly cursor: number\n readonly committed: Shared\n readonly committedIds: ReadonlyArray<string>\n readonly pending: ReadonlyArray<Operation>\n}\n\n/**\n * What the promise-based edge adapter consumes; the Effect `Transport` service\n * is the primary seam.\n */\nexport interface TransportClient {\n exchange(cursor: number, pending: ReadonlyArray<Operation>): Promise<unknown>\n}\n\nexport interface Replica<Message, Shared> {\n /** The optimistic projection: committed state with pending operations replayed. */\n readonly shared: Effect.Effect<Shared>\n readonly pending: Effect.Effect<ReadonlyArray<Operation>>\n readonly cursor: Effect.Effect<number>\n readonly submit: (message: Message) => Effect.Effect<void, ReplicaError>\n /** Reconciles against the server. The `Transport` service must be provided. */\n readonly synchronize: Effect.Effect<void, ReplicaError | TransportError, Transport>\n readonly close: Effect.Effect<void>\n}\n\nexport interface SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> {\n readonly documentId: string\n readonly message: Schema.Codec<Message, MessageEncoded, never, never>\n readonly shared: Schema.Codec<Shared, SharedEncoded, never, never>\n readonly empty: Shared\n readonly durable: (message: Message) => boolean\n readonly replay: (shared: Shared, message: Message) => Shared\n}\n\nexport interface Sync<Message, Shared> {\n readonly documentId: string\n readonly normalizeOperation: (input: unknown) => Operation\n readonly operationFrom: (input: unknown, documentId: string) => Operation\n readonly committedFrom: (input: unknown, documentId: string) => Committed\n readonly decodeExchange: (input: unknown) => Exchange<Shared>\n readonly openReplica: (\n replicaId: string,\n storage: Storage<ReplicaState<Shared>>,\n ) => Effect.Effect<Replica<Message, Shared>, ReplicaError>\n}\n\n/**\n * Binds the replicated-state protocol to one application contract.\n *\n * The returned codecs decide what is a valid operation and what the shared\n * projection means; the replica owns the local outbox, optimistic projection,\n * and reconciliation as Effects, and never runs a second reducer.\n */\nexport const defineSync = <Message, Shared, MessageEncoded, SharedEncoded>(\n definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>,\n): Sync<Message, Shared> => {\n const documentId = definition.documentId\n const decodeMessage = Schema.decodeUnknownSync(definition.message, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(definition.message)\n\n const ReplicaStateSchema = Schema.Struct({\n protocolVersion: Schema.Literal(1),\n schemaVersion: Schema.Literal(1),\n documentId: Schema.NonEmptyString,\n replicaId: Schema.NonEmptyString,\n revision: Sequence,\n nextLocalSequence: Sequence,\n cursor: Sequence,\n committed: definition.shared,\n committedIds: Schema.Array(Schema.String),\n pending: Schema.Array(OperationSchema),\n })\n const CheckpointSchema = Schema.Struct({ cursor: Sequence, model: definition.shared })\n const ExchangeSchema = Schema.Struct({\n operations: Schema.Array(Schema.Unknown),\n rejected: Schema.Array(Schema.NonEmptyString),\n acknowledged: Schema.optional(Schema.Array(Schema.NonEmptyString)),\n checkpoint: Schema.optional(CheckpointSchema),\n })\n const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: 'error' })\n const decodeExchange = (input: unknown): Exchange<Shared> =>\n Schema.decodeUnknownSync(ExchangeSchema, { onExcessProperty: 'error' })(\n input,\n ) as Exchange<Shared>\n\n const checkIdentity = (operation: Operation): void => {\n if (\n operation.localSequence < 1 ||\n operation.opId !== `${operation.replicaId}:${operation.localSequence}`\n ) {\n throw new Error('Invalid operation identity')\n }\n }\n const decodeDurable = (message: unknown): Message => {\n const decoded = decodeMessage(message)\n if (!definition.durable(decoded)) throw new Error('Message is local-only')\n return decoded\n }\n const shape = <O extends Operation>(operation: O): O => {\n checkIdentity(operation)\n return { ...operation, message: encodeMessage(decodeDurable(operation.message)) }\n }\n const assertDocument = <O extends Operation>(operation: O, key: string): O => {\n if (operation.documentId !== key) throw new Error('Wrong document')\n return operation\n }\n const normalizeOperation = (input: unknown): Operation => shape(decodeOperation(input))\n const operationFrom = (input: unknown, key: string): Operation =>\n assertDocument(normalizeOperation(input), key)\n /**\n * A committed operation arrives with its message already encoded, so decode it\n * once for the contract check and hand it to `replay` instead of decoding and\n * re-encoding it on the way through `shape`.\n */\n const decodeCommittedOperation = (\n input: unknown,\n key: string,\n ): { readonly committed: Committed; readonly message: Message } => {\n const committed = assertDocument(decodeCommitted(input), key)\n checkIdentity(committed)\n return { committed, message: decodeDurable(committed.message) }\n }\n const committedFrom = (input: unknown, key: string): Committed =>\n decodeCommittedOperation(input, key).committed\n\n const optimistic = (state: ReplicaState<Shared>): Shared =>\n state.pending.reduce(\n (model, operation) => definition.replay(model, decodeMessage(operation.message)),\n state.committed,\n )\n\n const openReplica = (\n replicaId: string,\n storage: Storage<ReplicaState<Shared>>,\n ): Effect.Effect<Replica<Message, Shared>, ReplicaError> =>\n Effect.gen(function* () {\n const saved = yield* Effect.tryPromise({\n try: () => storage.load(),\n catch: cause => storageError('Could not read the replica', cause),\n })\n const initial: ReplicaState<Shared> = {\n protocolVersion: 1,\n schemaVersion: 1,\n documentId,\n replicaId,\n revision: 0,\n nextLocalSequence: 1,\n cursor: 0,\n committed: definition.empty,\n committedIds: [],\n pending: [],\n }\n const state: ReplicaState<Shared> =\n saved === undefined\n ? initial\n : yield* Effect.try({\n try: () => decodeState(saved),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Stored replica state is invalid',\n cause,\n }),\n })\n if (state.documentId !== documentId || state.replicaId !== replicaId)\n return yield* new WrongReplicaStorageError({\n documentId,\n replicaId,\n message: 'The stored replica belongs to a different document or replica',\n })\n const committedIds = new Set(state.committedIds)\n if (state.nextLocalSequence < 1 || committedIds.size !== state.committedIds.length)\n return yield* new InvalidReplicaHistoryError({ message: 'Invalid replica history' })\n const pendingIds = new Set<string>()\n for (const pending of state.pending) {\n const operation = yield* Effect.try({\n try: () => operationFrom(pending, documentId),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n if (\n operation.replicaId !== replicaId ||\n operation.localSequence >= state.nextLocalSequence ||\n committedIds.has(operation.opId) ||\n pendingIds.has(operation.opId)\n )\n return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n pendingIds.add(operation.opId)\n }\n if (saved === undefined)\n yield* Effect.tryPromise({\n try: () => storage.save(state, null),\n catch: cause => storageError('Could not save the replica', cause),\n })\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n\n // `SynchronizedRef.modifyEffect` installs the returned state itself, so\n // persisting must not also set the ref (that would re-enter the lock).\n const persist = (next: ReplicaState<Shared>, current: ReplicaState<Shared>) =>\n Effect.tryPromise({\n try: () => storage.save(next, current.revision),\n catch: cause => storageError('Could not save the replica', cause),\n })\n\n const submit = (message: Message): Effect.Effect<void, ReplicaError> =>\n // The closed check belongs inside the lock: a `close` between an outer\n // check and acquiring the lock would otherwise still persist.\n SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n const operation = yield* Effect.try({\n try: () =>\n operationFrom(\n {\n protocolVersion: 1,\n schemaVersion: 1,\n documentId,\n replicaId,\n localSequence: current.nextLocalSequence,\n opId: `${replicaId}:${current.nextLocalSequence}`,\n baseCursor: current.cursor,\n message: encodeMessage(message),\n },\n documentId,\n ),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n const next = yield* Effect.try({\n try: () =>\n decodeState({\n ...current,\n revision: current.revision + 1,\n nextLocalSequence: current.nextLocalSequence + 1,\n pending: [...current.pending, operation],\n }),\n catch: cause =>\n new InvalidReplicaHistoryError({ message: 'Invalid replica state', cause }),\n })\n yield* persist(next, current)\n return [undefined, next] as const\n }),\n ).pipe(Effect.withSpan('Sync.submit', { attributes: { documentId, replicaId } }))\n\n const synchronize: Replica<Message, Shared>['synchronize'] = Effect.gen(function* () {\n const transport = yield* Transport\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n const sent = yield* SynchronizedRef.get(stateRef)\n yield* Metric.update(syncMetrics.exchanges, 1)\n yield* Metric.update(syncMetrics.exchangePending, sent.pending.length)\n const response = decodeExchange(\n yield* transport.exchange(sent.cursor, sent.pending).pipe(\n Effect.tapError(error =>\n Effect.logWarning('sync exchange failed', {\n documentId,\n replicaId,\n error: error.message,\n }),\n ),\n ),\n )\n yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // A `close` during the exchange must not persist its result.\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n let cursor = current.cursor\n let committed = current.committed\n // A checkpoint folds committed history into its snapshot, so the\n // retained id set starts over from it.\n const ids =\n response.checkpoint === undefined ? new Set(current.committedIds) : new Set<string>()\n if (response.checkpoint !== undefined) {\n if (response.checkpoint.cursor < cursor)\n return yield* new CheckpointRegressionError({\n cursor,\n checkpointCursor: response.checkpoint.cursor,\n message: 'Checkpoint is behind the replica',\n })\n committed = response.checkpoint.model\n cursor = response.checkpoint.cursor\n yield* Metric.update(syncMetrics.checkpoints, 1)\n yield* Effect.logDebug('sync checkpoint adopted', { documentId, replicaId, cursor })\n }\n const acknowledged = new Set(response.acknowledged ?? [])\n const rejected = new Set(response.rejected)\n const sentIds = new Set(sent.pending.map(operation => operation.opId))\n for (const id of rejected)\n if (!sentIds.has(id))\n return yield* new ForeignRejectionError({\n opId: id,\n message: 'Server rejected an operation that was not sent',\n })\n let applied = 0\n for (const raw of response.operations) {\n const { committed: operation, message } = yield* Effect.try({\n try: () => decodeCommittedOperation(raw, documentId),\n catch: cause =>\n new InvalidReplicaHistoryError({ message: 'Invalid committed operation', cause }),\n })\n if (operation.serverSequence <= cursor) continue\n if (operation.serverSequence !== cursor + 1 || ids.has(operation.opId))\n return yield* new CommittedOrderError({\n expected: cursor + 1,\n actual: operation.serverSequence,\n message: 'Invalid committed order',\n })\n committed = definition.replay(committed, message)\n ids.add(operation.opId)\n cursor = operation.serverSequence\n applied += 1\n }\n if (applied > 0) yield* Metric.update(syncMetrics.applied, applied)\n const next = yield* Effect.try({\n try: () =>\n decodeState({\n ...current,\n revision: current.revision + 1,\n committed,\n cursor,\n committedIds: [...ids].slice(-COMMITTED_ID_WINDOW),\n pending: current.pending.filter(\n operation =>\n !ids.has(operation.opId) &&\n !acknowledged.has(operation.opId) &&\n !rejected.has(operation.opId),\n ),\n }),\n catch: cause =>\n new InvalidReplicaHistoryError({ message: 'Invalid replica state', cause }),\n })\n yield* persist(next, current)\n return [undefined, next] as const\n }),\n )\n }).pipe(Effect.withSpan('Sync.synchronize', { attributes: { documentId } }))\n\n return {\n shared: Effect.map(SynchronizedRef.get(stateRef), optimistic),\n pending: Effect.map(SynchronizedRef.get(stateRef), state => state.pending),\n cursor: Effect.map(SynchronizedRef.get(stateRef), state => state.cursor),\n submit,\n synchronize,\n close: Effect.gen(function* () {\n yield* Ref.set(closed, true)\n yield* Effect.sync(() => storage.close())\n }),\n }\n }).pipe(Effect.withSpan('Sync.openReplica', { attributes: { documentId, replicaId } }))\n\n return {\n documentId,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I,QAAQ,IAAG,UAAS,MAAM,OAAO;GACzE,QAAQ,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,MAAM;GACvE;GACA;GACA,OAAO,OAAO,IAAI,aAAa;IAC7B,OAAO,IAAI,IAAI,QAAQ,IAAI;IAC3B,OAAO,OAAO,WAAW,QAAQ,MAAM,CAAC;GAC1C,CAAC;EACH;CACF,CAAC,CAAC,CAAC,KAAK,OAAO,SAAS,oBAAoB,EAAE,YAAY;EAAE;EAAY;CAAU,EAAE,CAAC,CAAC;CAExF,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "foldkit-sync",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A local-first replica of a shared Foldkit projection: offline outbox, optimistic updates, and reconciliation.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"foldkit",
|
|
7
|
+
"effect",
|
|
8
|
+
"local-first",
|
|
9
|
+
"offline",
|
|
10
|
+
"replication",
|
|
11
|
+
"indexeddb"
|
|
12
|
+
],
|
|
13
|
+
"type": "module",
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"author": "Patrick Glenn <doeixd@gmail.com>",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/doeixd/foldkit-plus.git",
|
|
19
|
+
"directory": "packages/sync"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://github.com/doeixd/foldkit-plus/tree/main/packages/sync#readme",
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/doeixd/foldkit-plus/issues"
|
|
24
|
+
},
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.mts",
|
|
32
|
+
"import": "./dist/index.mjs"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"README.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"effect": "^4.0.0-rc.112"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"effect": "4.0.0-rc.112",
|
|
45
|
+
"tsdown": "^0.23.0",
|
|
46
|
+
"typescript": "^5.7.2"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "tsdown",
|
|
50
|
+
"typecheck": "tsc -b"
|
|
51
|
+
}
|
|
52
|
+
}
|