foldkit-sync 0.14.0 → 0.16.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/README.md +558 -40
- package/dist/diagnostics.d.ts +74 -3
- package/dist/diagnostics.d.ts.map +1 -1
- package/dist/diagnostics.js +60 -4
- package/dist/diagnostics.js.map +1 -1
- package/dist/do.d.ts +49 -7
- package/dist/do.d.ts.map +1 -1
- package/dist/do.js +91 -8
- package/dist/do.js.map +1 -1
- package/dist/errors.d.ts +92 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +87 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +9 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/dist/journal.d.ts +52 -27
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +176 -64
- package/dist/journal.js.map +1 -1
- package/dist/make.d.ts +48 -17
- package/dist/make.d.ts.map +1 -1
- package/dist/make.js +11 -4
- package/dist/make.js.map +1 -1
- package/dist/migrations.d.ts +37 -0
- package/dist/migrations.d.ts.map +1 -0
- package/dist/migrations.js +56 -0
- package/dist/migrations.js.map +1 -0
- package/dist/mount.d.ts +1 -1
- package/dist/mount.d.ts.map +1 -1
- package/dist/mount.js +12 -6
- package/dist/mount.js.map +1 -1
- package/dist/refusal.d.ts +33 -0
- package/dist/refusal.d.ts.map +1 -0
- package/dist/refusal.js +47 -0
- package/dist/refusal.js.map +1 -0
- package/dist/serverJournal.d.ts +143 -0
- package/dist/serverJournal.d.ts.map +1 -0
- package/dist/serverJournal.js +503 -0
- package/dist/serverJournal.js.map +1 -0
- package/dist/sync.d.ts +132 -11
- package/dist/sync.d.ts.map +1 -1
- package/dist/sync.js +273 -64
- package/dist/sync.js.map +1 -1
- package/dist/transport.d.ts +5 -5
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js.map +1 -1
- package/package.json +11 -8
package/dist/sync.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.js","names":[],"sources":["../src/sync.ts"],"sourcesContent":["import {\n Effect,\n Exit,\n Metric,\n Option,\n PubSub,\n Queue,\n Ref,\n Schema,\n Stream,\n SynchronizedRef,\n} from 'effect'\nimport {\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nimport type { Storage } from './indexedDb.js'\nimport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n localSequence,\n sequence,\n} from './ids.js'\nimport { Transport, TransportError } from './transport.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { exchangeFailed, historyRebuilt } from './diagnostics.js'\n\n/** Wire and persisted-format versions. A bump must handle the older value explicitly. */\nconst PROTOCOL_VERSION = 1\nconst SCHEMA_VERSION = 1\n\n/** A client-authored operation envelope. `message` is the application's encoded Message. */\nconst OperationSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n localSequence: LocalSequence,\n opId: OpId,\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})\n/** Named to avoid colliding with `foldkit-durable`'s `Committed`. */\nexport type CommittedOperation = 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/** How long `start` waits after a failed exchange: doubling from the base, up to the cap, in ms. */\nconst START_RETRY_BASE = 500\nconst START_RETRY_MAX = 30_000\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\nexport interface Checkpoint<Shared> {\n readonly cursor: Sequence\n readonly model: Shared\n}\n\nexport interface Exchange<Shared> {\n /** Server-committed operations as they arrived; validated against `CommittedOperation` on adoption. */\n readonly operations: ReadonlyArray<unknown>\n readonly rejected: ReadonlyArray<OpId>\n /**\n * Why some of `rejected` were refused, in words the server chose for a person:\n * a policy's reason, never an internal error. One without a reason is still rejected.\n */\n readonly reasons?: ReadonlyArray<{ readonly opId: OpId; readonly reason: string }> | undefined\n /** Sends from the request that are durably committed, so the replica can drop them. */\n readonly acknowledged?: ReadonlyArray<OpId> | undefined\n /** The snapshot a replica predating compaction adopts in place of the log. */\n readonly checkpoint?: Checkpoint<Shared> | undefined\n /** The server sent only part of what is after the cursor; the replica asks again. */\n readonly more?: boolean | undefined\n /**\n * The identity of the server's history. The replica sends back the one it last saw; a\n * server that finds another answers from the start of its own history, and the replica,\n * seeing a new epoch, rebuilds its committed state from that answer and keeps its outbox.\n */\n readonly epoch?: string | undefined\n}\n\nexport interface ReplicaState<Shared> {\n readonly protocolVersion: typeof PROTOCOL_VERSION\n readonly schemaVersion: typeof SCHEMA_VERSION\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly revision: number\n readonly nextLocalSequence: LocalSequence\n readonly cursor: Sequence\n readonly committed: Shared\n readonly committedIds: ReadonlyArray<string>\n readonly pending: ReadonlyArray<Operation>\n /** The server history `cursor` points into, once an exchange has named one. */\n readonly epoch?: string\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 /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n exchange(\n cursor: Sequence,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ): Promise<unknown>\n}\n\n/** A redacted view of a replica's state, for a UI to explain and recover. */\nexport interface ReplicaStatus {\n readonly pending: number\n readonly cursor: Sequence\n /** The last exchange failure, cleared by a successful exchange. */\n readonly lastError: string | undefined\n /** Operations the server refused, most recent first, with its reason when it gave one. */\n readonly rejected: ReadonlyArray<Rejection>\n /**\n * The server history the cursor points into, once a server named one. A new\n * one means the server was reset: what the replica had committed is gone.\n */\n readonly epoch: Option.Option<string>\n}\n\n/**\n * An operation the server refused, and why, when it said. It carries the\n * operation itself: the replica drops it from the outbox in the same step,\n * so what it changed can be read from here rather than looked up in time.\n */\nexport interface Rejection {\n readonly opId: OpId\n readonly reason: Option.Option<string>\n readonly operation: Operation\n}\n\n/**\n * A consistent status and optimistic-shared pair, read from one replica state.\n * `Replica.changes` emits it so a UI can hold a single subscription.\n */\nexport interface ReplicaSnapshot<Shared> {\n readonly status: ReplicaStatus\n readonly shared: Shared\n /** The server-confirmed state the optimistic `shared` is built on. */\n readonly committed: Shared\n /**\n * The local sequence the next submitted operation takes. Only a successful\n * submit moves it, so a caller that submits one Message at a time can tell\n * from one snapshot whether `shared` already holds it.\n */\n readonly nextLocalSequence: LocalSequence\n}\n\nexport interface Replica<Message, Shared> {\n /** The id this replica's operations carry, one per tab: what its commits are stamped with. */\n readonly replicaId: ReplicaId\n /** The optimistic projection: committed state with pending operations replayed. */\n readonly shared: Effect.Effect<Shared>\n /**\n * The server-confirmed state through `cursor`, with no pending operation\n * applied. A pending edit reaches it only once the server commits it, and a\n * rejected one never does.\n */\n readonly committed: Effect.Effect<Shared>\n readonly pending: Effect.Effect<ReadonlyArray<Operation>>\n readonly cursor: Effect.Effect<Sequence>\n /**\n * Waiting/recovery information without exposing Messages or the Model. It is a\n * snapshot; `statusChanges` re-emits it after every submit and exchange.\n */\n readonly status: Effect.Effect<ReplicaStatus>\n /** The status, re-emitted after every submit and exchange. */\n readonly statusChanges: Stream.Stream<ReplicaStatus>\n /**\n * The status and the optimistic shared value together, re-emitted after every\n * submit and exchange, so a UI can subscribe once instead of to both.\n */\n readonly changes: Stream.Stream<ReplicaSnapshot<Shared>>\n /** The status, `shared`, `committed` and next local sequence, read from one replica state. */\n readonly snapshot: Effect.Effect<ReplicaSnapshot<Shared>>\n /** Records a durable Message in the outbox and applies it optimistically. */\n // A method, so a replica of the durable subset is still a `Replica` of the\n // application's Messages where one is only passed along (`Sync.mount`).\n 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 /**\n * The exchange loop: exchanges once, then after every `submit` and every\n * notice on the transport's `changes`, until the replica closes or the fiber\n * is interrupted. A failed exchange is recorded\n * in `status.lastError` and retried on a backoff (from 0.5 s, doubling up to\n * 30 s), or at once on the next `submit`, so the fiber never fails. Fork it\n * with `Effect.forkScoped` and provide `Transport`.\n */\n readonly start: Effect.Effect<void, never, Transport>\n readonly close: Effect.Effect<void>\n}\n\nexport interface SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> {\n readonly documentId: DocumentId\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 * Optional. Merges a durable Message into the one submitted before it, while that one\n * has not been sent: one operation instead of two, for a burst of typing. Replaying the\n * result must equal replaying `last` then `next`. Undefined keeps them apart.\n */\n readonly coalesce?: ((last: Message, next: Message) => Message | undefined) | undefined\n /**\n * Optional. Writes what the server's commit decided into a durable Message, on the\n * server only: the journal stores, reduces and sends the stamped Message, so every\n * replica replays the same one in place of what it sent.\n */\n readonly stamp?: ((message: Message, commit: CommitStamp) => Message) | undefined\n}\n\n/**\n * What a commit decided, for `stamp`: the operation's place in the order, who\n * committed it, and from which replica. `actorId` is the principal, shared by\n * every tab a person has open; `replicaId` tells those tabs apart.\n */\nexport interface CommitStamp {\n readonly sequence: number\n readonly actorId: string\n readonly replicaId: string\n}\n\n/**\n * A document's protocol. `Durable` is what a replica's `submit` takes: the\n * durable subset for a contract from `Sync.forApplication(App).make`, every\n * Message for one from `Sync.define`, which checks `durable` when called.\n */\nexport interface Sync<Message, Shared, Durable = Message> {\n readonly documentId: DocumentId\n /** Whether a Message is one the replica records and replays. */\n readonly durable: (message: Message) => boolean\n /**\n * Low-level wire codecs for adapters and the transport. Most applications use\n * `journalContract` and `openReplica`; these are exposed for a custom\n * transport or a server that must speak the operation envelope directly.\n */\n readonly codec: {\n readonly normalizeOperation: (input: unknown) => Operation\n readonly operationFrom: (input: unknown, documentId: DocumentId) => Operation\n readonly committedFrom: (input: unknown, documentId: DocumentId) => CommittedOperation\n readonly decodeExchange: (input: unknown) => Exchange<Shared>\n }\n /** The codecs and pure reducer `foldkit-durable`'s `makeJournal` consumes. */\n readonly journalContract: () => JournalContract<Operation, Shared>\n /**\n * Opens the replica a store holds. Its id is the store's: read back, or minted\n * when the store is empty, so two stores never share one. In a browser the\n * store is `Sync.tabStorage(name)`, one per tab.\n */\n readonly openReplica: (\n storage: Storage,\n options?: OpenReplicaOptions,\n ) => Effect.Effect<Replica<Durable, Shared>, ReplicaError>\n}\n\nexport interface OpenReplicaOptions {\n /**\n * The id the store must hold, for a test asserting operation ids or a replica\n * a server names. It names one store, never a person: operation ids are\n * `replicaId:localSequence`, so two stores under one id (a person's second\n * browser) reuse ids the journal refuses.\n */\n readonly replicaId?: ReplicaId | undefined\n}\n\n/** Structural match for `foldkit-durable`'s journal options; Sync stays independent. */\nexport interface JournalContract<Operation, Shared> {\n /** The replica each operation came from, which Durable binds to its first committer. */\n readonly replicaId: (operation: Operation) => string\n /** Sync's operation id includes the replica, even after Durable compacts its payload. */\n readonly legacyReplicaId: (opId: string) => string\n readonly operation: {\n /** Operations are stored in their encoded form, so this is the identity. */\n readonly encode: (operation: Operation) => Operation\n readonly decode: (input: unknown) => Operation\n }\n readonly snapshot: {\n readonly encode: (snapshot: Shared) => unknown\n readonly decode: (input: unknown) => Shared\n }\n readonly empty: () => Shared\n readonly reduce: (snapshot: Shared, operation: Operation) => Shared\n /** Present when the definition stamps: Durable's `stamp`, over the operation's Message. */\n readonly stamp?: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ) => Operation\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 const decodeShared = Schema.decodeUnknownSync(definition.shared, { onExcessProperty: 'error' })\n const encodeShared = Schema.encodeSync(definition.shared)\n\n const ReplicaStateSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n revision: Schema.Number,\n nextLocalSequence: LocalSequence,\n cursor: Sequence,\n committed: definition.shared,\n committedIds: Schema.Array(Schema.String),\n pending: Schema.Array(OperationSchema),\n epoch: Schema.optionalKey(Schema.NonEmptyString),\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(OpId),\n // A server's words for a person, bounded: a reply is not a place for a document.\n reasons: Schema.optional(\n Schema.Array(\n Schema.Struct({ opId: OpId, reason: Schema.String.check(Schema.isMaxLength(500)) }),\n ),\n ),\n acknowledged: Schema.optional(Schema.Array(OpId)),\n checkpoint: Schema.optional(CheckpointSchema),\n more: Schema.optional(Schema.Boolean),\n epoch: Schema.optional(Schema.NonEmptyString),\n })\n const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: 'error' })\n const encodeState = Schema.encodeSync(ReplicaStateSchema)\n const encodeOperation = Schema.encodeSync(OperationSchema)\n const VersionProbe = Schema.Struct({\n protocolVersion: Schema.optional(Schema.Number),\n schemaVersion: Schema.optional(Schema.Number),\n })\n /**\n * Tells a version this build does not understand apart from malformed data,\n * so the caller gets an actionable failure and the stored state is preserved.\n */\n const unsupportedVersion = (input: unknown): UnsupportedReplicaVersionError | undefined => {\n let found: {\n readonly protocolVersion?: number | undefined\n readonly schemaVersion?: number | undefined\n }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.protocolVersion === PROTOCOL_VERSION && found.schemaVersion === SCHEMA_VERSION)\n return undefined\n const protocolVersion = found.protocolVersion ?? null\n const schemaVersion = found.schemaVersion ?? null\n return new UnsupportedReplicaVersionError({\n protocolVersion,\n schemaVersion,\n message: `Stored replica uses protocol ${protocolVersion ?? '?'} / schema ${schemaVersion ?? '?'}; this build supports ${PROTOCOL_VERSION}/${SCHEMA_VERSION}`,\n })\n }\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 // `LocalSequence` already rejects a non-positive counter; this checks the\n // derived identity.\n if (operation.opId !== `${operation.replicaId}:${operation.localSequence}`) {\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: DocumentId): 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: DocumentId): 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: DocumentId,\n ): { readonly committed: CommittedOperation; 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: DocumentId): CommittedOperation =>\n decodeCommittedOperation(input, key).committed\n\n const journalContract = (): JournalContract<Operation, Shared> => ({\n replicaId: operation => operation.replicaId,\n legacyReplicaId: opId => opId.slice(0, opId.lastIndexOf(':')),\n // Operations are stored in their encoded form: `normalizeOperation` has\n // already encoded the Message and validated the identity.\n operation: { encode: operation => operation, decode: normalizeOperation },\n snapshot: { encode: encodeShared, decode: decodeShared },\n empty: () => definition.empty,\n reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),\n ...(definition.stamp === undefined\n ? {}\n : {\n stamp: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ): Operation => ({\n ...operation,\n message: encodeMessage(\n definition.stamp!(decodeMessage(operation.message), {\n ...commit,\n replicaId: operation.replicaId,\n }),\n ),\n }),\n }),\n })\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 = Effect.fn('Sync.openReplica')(\n function* (storage: Storage, options?: OpenReplicaOptions) {\n const saved = yield* storage.load()\n const initial: ReplicaState<Shared> = {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId: options?.replicaId ?? ReplicaId.make(crypto.randomUUID()),\n revision: 0,\n nextLocalSequence: localSequence(1),\n cursor: sequence(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 unsupportedVersion(saved) ??\n new InvalidReplicaHistoryError({\n message: 'Stored replica state is invalid',\n cause,\n }),\n })\n const replicaId = state.replicaId\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n if (\n state.documentId !== documentId ||\n (options?.replicaId !== undefined && replicaId !== options.replicaId)\n )\n return yield* new WrongReplicaStorageError({\n documentId,\n replicaId: options?.replicaId ?? 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 // Storage holds the schema's encoded side, so a transforming `shared`\n // codec round-trips: decode on load, encode before every save. Encoding\n // also rejects an invalid `empty` on first creation rather than at reload.\n const store = Effect.fn('Sync.store')(function* (\n next: ReplicaState<Shared>,\n expectedRevision: number | null,\n ) {\n const encoded = yield* Effect.try({\n try: () => encodeState(next),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the replica state',\n cause,\n }),\n })\n yield* storage.save(encoded, expectedRevision)\n })\n if (saved === undefined) yield* store(state, null)\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n const lastError = yield* Ref.make<string | undefined>(undefined)\n const rejectedOps = yield* Ref.make<ReadonlyArray<Rejection>>([])\n // Operations submitted since opening that no exchange has carried yet. Only these may\n // be coalesced: one that was sent may already be committed as it was.\n const unsent = yield* Ref.make<ReadonlySet<string>>(new Set())\n // One pending wake-up is enough: the loop exchanges the whole outbox.\n const wake = yield* Queue.sliding<void>(1)\n const statusSignals = yield* PubSub.sliding<void>(1)\n // The current value, then again after every change. Subscribed before the\n // first read, so a change made while a subscriber holds that value, or\n // between the read and the subscription, is still told.\n const following = <A>(read: Effect.Effect<A>): Stream.Stream<A> =>\n Stream.unwrap(\n Effect.map(PubSub.subscribe(statusSignals), signals =>\n Stream.concat(\n Stream.fromEffect(read),\n Stream.fromSubscription(signals).pipe(Stream.mapEffect(() => read)),\n ),\n ),\n )\n // The projection is pure over an immutable state, so a cached value is\n // reused until a write replaces the state object. A UI reads `shared` far\n // more often than it writes, and replaying a large outbox per read is\n // quadratic (see `bench/projection.bench.ts`).\n const projection = yield* Ref.make<\n { readonly state: ReplicaState<Shared>; readonly shared: Shared } | undefined\n >(undefined)\n const snapshot = Effect.fn('Sync.snapshot')(function* () {\n const current = yield* SynchronizedRef.get(stateRef)\n const cached = yield* Ref.get(projection)\n let projected: Shared\n if (cached !== undefined && cached.state === current) projected = cached.shared\n else {\n projected = optimistic(current)\n yield* Ref.set(projection, { state: current, shared: projected })\n }\n return {\n status: {\n pending: current.pending.length,\n cursor: current.cursor,\n lastError: yield* Ref.get(lastError),\n rejected: yield* Ref.get(rejectedOps),\n epoch: Option.fromUndefinedOr(current.epoch),\n },\n shared: projected,\n committed: current.committed,\n nextLocalSequence: current.nextLocalSequence,\n }\n })()\n const shared = Effect.map(snapshot, value => value.shared)\n const status = Effect.map(snapshot, value => value.status)\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 store(next, current.revision)\n\n const submit = Effect.fn('Sync.submit')(function* (message: Message) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const result = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n if (!definition.durable(message))\n return yield* new InvalidOutboxError({ message: 'Message is local-only' })\n const last = current.pending[current.pending.length - 1]\n const merged =\n last !== undefined &&\n definition.coalesce !== undefined &&\n (yield* Ref.get(unsent)).has(last.opId)\n ? definition.coalesce(decodeMessage(last.message), message)\n : undefined\n if (merged !== undefined && !definition.durable(merged))\n return yield* new InvalidOutboxError({\n message: 'coalesce returned a local-only Message',\n })\n // A merged Message takes the place of the last operation, under its identity.\n const operation = yield* Effect.try({\n try: () =>\n operationFrom(\n merged === undefined\n ? {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n localSequence: current.nextLocalSequence,\n opId: `${replicaId}:${current.nextLocalSequence}`,\n baseCursor: current.cursor,\n message: encodeMessage(message),\n }\n : { ...last!, message: encodeMessage(merged) },\n documentId,\n ),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n // Replay before writing: a Message replay refuses can never be\n // applied, here or on another replica, so it must not reach the\n // outbox. The result is the next optimistic projection, so the\n // cache is seeded instead of replaying the outbox on the next read.\n // Rebuilding the projection replays the outbox, which can throw\n // too (an upgrade that changed `update` for a pending Message), so\n // it sits inside the same typed error as the new Message's replay.\n const cached = yield* Ref.get(projection)\n const replayed = yield* Effect.try({\n try: () =>\n definition.replay(\n cached !== undefined && cached.state === current\n ? cached.shared\n : optimistic(current),\n message,\n ),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n // Validated and encoded by `persist`; decoding here would demand the\n // encoded side and break a transforming `shared` codec.\n // The sequence moves on a merge too, so every submit is visible in it; a gap\n // in local sequences is harmless.\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n nextLocalSequence: localSequence(current.nextLocalSequence + 1),\n pending: [\n ...(merged === undefined ? current.pending : current.pending.slice(0, -1)),\n operation,\n ],\n }\n // Only the new operation is written when the storage can append it.\n if (storage.append === undefined) yield* persist(next, current)\n else {\n const encoded = yield* Effect.try({\n try: () => encodeOperation(operation),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the operation',\n cause,\n }),\n })\n yield* storage.append(\n {\n revision: next.revision,\n nextLocalSequence: next.nextLocalSequence,\n localSequence: operation.localSequence,\n operation: encoded,\n },\n current.revision,\n )\n }\n yield* Ref.set(projection, { state: next, shared: replayed })\n yield* Ref.update(unsent, ids => new Set(ids).add(operation.opId))\n yield* Queue.offer(wake, undefined)\n return [undefined, next] as const\n }),\n )\n // Outside the lock, so a `statusChanges` subscriber reads the new state.\n yield* PubSub.publish(statusSignals, undefined)\n return result\n })\n\n /** One exchange; whether the server has more to send and this one made progress. */\n const exchangeOnce = Effect.fn('Sync.exchange')(function* () {\n yield* Effect.annotateCurrentSpan({ documentId })\n const transport = yield* Transport\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Read under the lock, as a submit writes, so no submit can merge into an operation\n // between its being read here and its being marked sent.\n const sent = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Ref.update(unsent, ids => {\n const left = new Set(ids)\n for (const operation of current.pending) left.delete(operation.opId)\n return left\n }).pipe(Effect.as([current, current] as const)),\n )\n yield* Metric.update(syncMetrics.exchanges, 1)\n yield* Metric.update(syncMetrics.exchangePending, sent.pending.length)\n const response = yield* Effect.gen(function* () {\n const raw = yield* transport.exchange(sent.cursor, sent.pending, sent.epoch)\n // The response is untrusted: a malformed shape is a typed failure, not\n // a defect that escapes the declared error channel.\n return yield* Effect.try({\n try: () => decodeExchange(raw),\n catch: cause =>\n new InvalidExchangeError({ message: 'Invalid sync exchange response', cause }),\n })\n })\n const restarted = 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 // Another epoch means the server's history is not the one the cursor points\n // into (it was reset): the answer starts from its beginning, so the committed\n // state is rebuilt from it. The outbox is the user's intent and is kept.\n const restarted =\n response.epoch !== undefined &&\n current.epoch !== undefined &&\n response.epoch !== current.epoch\n if (restarted) yield* Diagnostics.report(historyRebuilt(documentId, replicaId))\n let cursor = restarted ? sequence(0) : current.cursor\n let committed = restarted ? definition.empty : current.committed\n // A checkpoint folds committed history into its snapshot, so the\n // retained id set starts over from it, as it does on a new epoch.\n const ids =\n response.checkpoint === undefined && !restarted\n ? new Set(current.committedIds)\n : 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 acknowledged)\n if (!sentIds.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server acknowledged an operation that was not sent',\n })\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 // An id cannot be both; removal would be ambiguous and a faulty\n // server must not be able to make a pending operation vanish.\n if (acknowledged.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server both acknowledged and rejected an operation',\n })\n }\n for (const { opId } of response.reasons ?? [])\n if (!rejected.has(opId))\n return yield* new ForeignRejectionError({\n opId,\n message: 'Server gave a reason for an operation it did not reject',\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 // A throw here would be a defect, which bypasses `lastError` and leaves\n // `start` retrying the same page in silence.\n const replaying = committed\n committed = yield* Effect.try({\n try: () => definition.replay(replaying, message),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n ids.add(operation.opId)\n cursor = operation.serverSequence\n applied += 1\n }\n if (applied > 0) yield* Metric.update(syncMetrics.applied, applied)\n // Validated and encoded by `persist`, for the same reason as submit.\n const epoch = response.epoch ?? current.epoch\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n committed,\n cursor,\n ...(epoch === undefined ? {} : { epoch }),\n committedIds: [...ids].slice(-COMMITTED_ID_WINDOW),\n // While the server has more to send, an acknowledged operation's committed\n // copy may be on a later page, so it stays in the optimistic view until then.\n // An acknowledged operation the replica is already past (committed before a\n // checkpoint, say) never arrives, so it goes once there is no more to read.\n pending: current.pending.filter(\n operation =>\n !ids.has(operation.opId) &&\n !(acknowledged.has(operation.opId) && response.more !== true) &&\n !rejected.has(operation.opId),\n ),\n }\n yield* persist(next, current)\n return [restarted, next] as const\n }),\n )\n yield* Ref.set(lastError, undefined)\n if (response.rejected.length > 0) {\n const reasonOf = new Map(\n (response.reasons ?? []).map(({ opId, reason }) => [opId, reason] as const),\n )\n // Every rejected id was sent: an unknown one failed the exchange above.\n const sentOf = new Map(\n sent.pending.map(operation => [operation.opId, operation] as const),\n )\n const refused = response.rejected.map((opId): Rejection => ({\n opId,\n reason: Option.fromUndefinedOr(reasonOf.get(opId)),\n operation: sentOf.get(opId)!,\n }))\n yield* Ref.update(rejectedOps, previous => [...refused, ...previous].slice(0, 32))\n }\n yield* PubSub.publish(statusSignals, undefined)\n const reached = (yield* SynchronizedRef.get(stateRef)).cursor\n return response.more === true && reached > (restarted ? 0 : sent.cursor)\n })\n\n // A server that pages its answer says there is more, and the replica asks again at\n // once; a round that moves the cursor nowhere ends it.\n const synchronize = Effect.gen(function* () {\n while (yield* exchangeOnce()) {}\n }).pipe(\n Effect.withSpan('Sync.synchronize'),\n // Any failed exchange, a refused response included, is what a UI shows,\n // so it is recorded and announced rather than left for the next submit.\n Effect.tapError(error =>\n Effect.gen(function* () {\n yield* Diagnostics.report(exchangeFailed(documentId, replicaId, error))\n yield* Ref.set(lastError, error.message)\n yield* PubSub.publish(statusSignals, undefined)\n }),\n ),\n )\n\n const start: Effect.Effect<void, never, Transport> = Effect.gen(function* () {\n const transport = yield* Transport\n // A server's notice wakes the loop as a submit does; the fiber ends with this one.\n // It starts at once so it is subscribed before the first exchange, which a\n // notice may arrive during.\n if (transport.changes !== undefined)\n yield* Effect.forkChild(\n Stream.runForEach(transport.changes, () => Queue.offer(wake, undefined)),\n { startImmediately: true },\n )\n let failures = 0\n while (!(yield* Ref.get(closed))) {\n const exit = yield* Effect.exit(synchronize)\n if (yield* Ref.get(closed)) return\n if (exit._tag === 'Success') {\n failures = 0\n yield* Queue.take(wake)\n } else {\n // Retried on a backoff, or sooner on a submit: an outbox must not\n // wait for the next keystroke to be delivered.\n failures += 1\n const backoff = Math.min(\n START_RETRY_MAX,\n START_RETRY_BASE * 2 ** Math.min(failures - 1, 16),\n )\n yield* Effect.raceFirst(Queue.take(wake), Effect.sleep(backoff))\n }\n }\n })\n\n return {\n replicaId,\n shared,\n snapshot,\n committed: Effect.map(SynchronizedRef.get(stateRef), state => state.committed),\n pending: Effect.map(SynchronizedRef.get(stateRef), state => state.pending),\n cursor: Effect.map(SynchronizedRef.get(stateRef), state => state.cursor),\n status,\n statusChanges: following(status),\n changes: following(snapshot),\n submit,\n synchronize,\n start,\n close: Effect.fn('Sync.close')(function* () {\n yield* Ref.set(closed, true)\n // Wake `start` so it can observe `closed` and return.\n yield* Queue.offer(wake, undefined)\n yield* storage.close\n })(),\n }\n },\n (effect, storage) =>\n // Close a partially initialized storage on any failure, including a\n // defect, so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : storage.close.pipe(Effect.ignore),\n ),\n ),\n )\n\n return {\n documentId,\n durable: definition.durable,\n codec: { normalizeOperation, operationFrom, committedFrom, decodeExchange },\n journalContract,\n openReplica,\n }\n}\n"],"mappings":";;;;;;;;AAyCA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;AAGvB,MAAM,kBAAkB,OAAO,OAAO;CACpC,iBAAiB,OAAO,QAAQ,gBAAgB;CAChD,eAAe,OAAO,QAAQ,cAAc;CAC5C,YAAY;CACZ,WAAW;CACX,eAAe;CACf,MAAM;CACN,YAAY;CACZ,SAAS,OAAO;AAClB,CAAC;;AAID,MAAM,kBAAkB,OAAO,OAAO;CACpC,GAAG,gBAAgB;CACnB,gBAAgB,SAAS,MAAM,OAAO,uBAAuB,CAAC,CAAC;CAC/D,SAAS,OAAO;AAClB,CAAC;AAID,MAAM,kBAAkB,OAAO,kBAAkB,iBAAiB,EAAE,kBAAkB,QAAQ,CAAC;AAC/F,MAAM,kBAAkB,OAAO,kBAAkB,iBAAiB,EAAE,kBAAkB,QAAQ,CAAC;;AAU/F,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;;AAGxB,MAAa,cAAc;CACzB,WAAW,OAAO,QAAQ,8BAA8B;CACxD,SAAS,OAAO,QAAQ,oCAAoC;CAC5D,aAAa,OAAO,QA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,CACnD;KACA,OAAO,OAAO,UAAU,MAAM,KAAK,IAAI,GAAG,OAAO,MAAM,OAAO,CAAC;IACjE;GACF;EACF,CAAC;EAED,OAAO;GACL;GACA;GACA;GACA,WAAW,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,SAAS;GAC7E,SAAS,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,OAAO;GACzE,QAAQ,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,MAAM;GACvE;GACA,eAAe,UAAU,MAAM;GAC/B,SAAS,UAAU,QAAQ;GAC3B;GACA;GACA;GACA,OAAO,OAAO,GAAG,YAAY,CAAC,CAAC,aAAa;IAC1C,OAAO,IAAI,IAAI,QAAQ,IAAI;IAE3B,OAAO,MAAM,MAAM,MAAM,KAAA,CAAS;IAClC,OAAO,QAAQ;GACjB,CAAC,CAAC,CAAC;EACL;CACF,IACC,QAAQ,YAGP,OAAO,KACL,OAAO,QAAO,SACZ,KAAK,UAAU,IAAI,IAAI,OAAO,OAAO,QAAQ,MAAM,KAAK,OAAO,MAAM,CACvE,CACF,CACJ;CAEA,OAAO;EACL;EACA,SAAS,WAAW;EACpB,OAAO;GAAE;GAAoB;GAAe;GAAe;EAAe;EAC1E;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"sync.js","names":[],"sources":["../src/sync.ts"],"sourcesContent":["import {\n Effect,\n Exit,\n Metric,\n Option,\n PubSub,\n Queue,\n Ref,\n Result,\n Schema,\n Stream,\n SynchronizedRef,\n} from 'effect'\nimport {\n AmbiguousMessageError,\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n ServerOnlyMessageError,\n UnreadableMessageError,\n UnsupportedMessageVersionError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nimport { historyOf, migrations, type Migrations } from './migrations.js'\nimport type { Storage } from './indexedDb.js'\nimport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n localSequence,\n sequence,\n} from './ids.js'\nimport { Transport, TransportError } from './transport.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { exchangeFailed, historyRebuilt, unknownRefusal } from './diagnostics.js'\nimport { fitWords, SyncRefusal } from './refusal.js'\n\n/** Wire and persisted-format versions. A bump must handle the older value explicitly. */\nconst PROTOCOL_VERSION = 1\nconst SCHEMA_VERSION = 1\n\n/**\n * Replica ids the server's own operations use (`foldkit-sync/journal`'s\n * `serverJournal`): a sent entry may not claim one, or it could bind the id to\n * its actor first and have the server's append refused.\n */\nexport const SERVER_REPLICA_PREFIX = 'server/'\n/** The longest replica id a sent entry may name. A stored one is read whatever its length. */\nconst MAX_SENT_REPLICA_ID = 128\n\n/**\n * A client-authored operation envelope. `message` is the application's\n * Message, encoded at the current version of the document's history.\n */\nconst OperationSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n localSequence: LocalSequence,\n opId: OpId,\n baseCursor: Sequence,\n message: Schema.Unknown,\n})\nexport type Operation = typeof OperationSchema.Type\n\n/**\n * An operation as it was written: what a replica keeps in its outbox and\n * sends, with its Message at the version it was written at. `messageVersion`\n * is absent for version 1, so a document with no migrations writes today's\n * envelope byte for byte.\n */\nconst WrittenFields = Schema.Struct({\n ...OperationSchema.fields,\n messageVersion: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))),\n})\n/** The written shape, unbranded: what the codec reads before it vouches for anything. */\ntype WrittenShape = typeof WrittenFields.Type\n/**\n * Branded, so only Sync makes one: decoding an entry, or writing an\n * `Operation` at the current version (`journalContract().operation.encode`).\n * A decoded `Operation` is not one, since its missing `messageVersion` would\n * read as version 1 and be upcast again.\n */\nconst WrittenOperationSchema = WrittenFields.pipe(Schema.brand('foldkit-sync/WrittenOperation'))\nexport type WrittenOperation = typeof WrittenOperationSchema.Type\n/** What the codec has checked or written itself. */\nconst vouched = (operation: WrittenShape): WrittenOperation => operation as WrittenOperation\n\nconst committedFields = {\n serverSequence: Sequence.check(Schema.isGreaterThanOrEqualTo(1)),\n actorId: Schema.NonEmptyString,\n}\n/** An operation the server committed, with its authoritative order and actor. */\nconst CommittedSchema = Schema.Struct({ ...OperationSchema.fields, ...committedFields })\n/** Named to avoid colliding with `foldkit-durable`'s `Committed`. */\nexport type CommittedOperation = typeof CommittedSchema.Type\n/** A committed operation as the server sends it: written at the server's current version. */\nconst CommittedWrittenSchema = Schema.Struct({\n ...WrittenFields.fields,\n ...committedFields,\n})\n\nconst decodeWritten = Schema.decodeUnknownSync(WrittenOperationSchema, {\n onExcessProperty: 'error',\n})\n/**\n * An envelope as written, checked for its shape and nothing else: for the\n * server's own operations (`serverJournal`), whose bytes it wrote or recorded.\n * Never for an entry someone sent.\n */\nexport const writtenEnvelope = (input: unknown): WrittenOperation => decodeWritten(input)\nconst decodeCommittedWritten = Schema.decodeUnknownSync(CommittedWrittenSchema, {\n onExcessProperty: 'error',\n})\n/** The version an operation was written at: absent is 1. */\nconst versionOf = (operation: WrittenShape): number => operation.messageVersion ?? 1\nconst decodeRefusal = Schema.decodeUnknownResult(SyncRefusal, { 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/** How long `start` waits after a failed exchange: doubling from the base, up to the cap, in ms. */\nconst START_RETRY_BASE = 500\nconst START_RETRY_MAX = 30_000\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\nexport interface Checkpoint<Shared> {\n readonly cursor: Sequence\n readonly model: Shared\n}\n\nexport interface Exchange<Shared> {\n /** Server-committed operations as they arrived; validated against `CommittedOperation` on adoption. */\n readonly operations: ReadonlyArray<unknown>\n readonly rejected: ReadonlyArray<OpId>\n /**\n * Why some of `rejected` were refused, each an encoded `SyncRefusal`. One\n * without a refusal is still rejected.\n */\n readonly refusals?:\n | ReadonlyArray<{ readonly opId: OpId; readonly refusal: typeof SyncRefusal.Encoded }>\n | undefined\n /**\n * @deprecated Send `refusals`; removed in the next release. Words the server\n * chose for a person, for some of `rejected`.\n */\n readonly reasons?: ReadonlyArray<{ readonly opId: OpId; readonly reason: string }> | undefined\n /** Sends from the request that are durably committed, so the replica can drop them. */\n readonly acknowledged?: ReadonlyArray<OpId> | undefined\n /** The snapshot a replica predating compaction adopts in place of the log. */\n readonly checkpoint?: Checkpoint<Shared> | undefined\n /** The server sent only part of what is after the cursor; the replica asks again. */\n readonly more?: boolean | undefined\n /**\n * The identity of the server's history. The replica sends back the one it last saw; a\n * server that finds another answers from the start of its own history, and the replica,\n * seeing a new epoch, rebuilds its committed state from that answer and keeps its outbox.\n */\n readonly epoch?: string | undefined\n}\n\nexport interface ReplicaState<Shared> {\n readonly protocolVersion: typeof PROTOCOL_VERSION\n readonly schemaVersion: typeof SCHEMA_VERSION\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly revision: number\n readonly nextLocalSequence: LocalSequence\n readonly cursor: Sequence\n readonly committed: Shared\n readonly committedIds: ReadonlyArray<string>\n /** Operations not yet committed, as written. */\n readonly pending: ReadonlyArray<WrittenOperation>\n /** Operations this build cannot read, kept as written until dismissed; absent when none. */\n readonly refused?: ReadonlyArray<WrittenOperation>\n /** The server history `cursor` points into, once an exchange has named one. */\n readonly epoch?: string\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 /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n exchange(\n cursor: Sequence,\n pending: ReadonlyArray<WrittenOperation>,\n epoch?: string | undefined,\n ): Promise<unknown>\n}\n\n/** A redacted view of a replica's state, for a UI to explain and recover. */\nexport interface ReplicaStatus {\n readonly pending: number\n readonly cursor: Sequence\n /** The last exchange failure, cleared by a successful exchange. */\n readonly lastError: string | undefined\n /** Operations the server refused, most recent first, with its reason when it gave one. */\n readonly rejected: ReadonlyArray<Rejection>\n /**\n * Operations this build cannot read, as written: an older version of the\n * document's Message that no step of its history reads, found in the outbox\n * or refused by the server as `Unreadable`. Never sent; kept, with their\n * payload, until `Replica.dismiss`.\n */\n readonly refused: ReadonlyArray<WrittenOperation>\n /**\n * The server history the cursor points into, once a server named one. A new\n * one means the server was reset: what the replica had committed is gone.\n */\n readonly epoch: Option.Option<string>\n}\n\n/**\n * An operation the server refused, and why, when it said. It carries the\n * operation itself: the replica drops it from the outbox in the same step,\n * so what it changed can be read from here rather than looked up in time.\n */\nexport interface Rejection {\n readonly opId: OpId\n /**\n * Why, typed. None when the server named no refusal (an older or a custom\n * server), or one this build cannot read (reported as `UnknownRefusal`).\n */\n readonly refusal: Option.Option<SyncRefusal>\n /**\n * @deprecated Read `refusal`, through `SyncRefusal.match`; removed in the\n * next release. The server's words from its `reasons`.\n */\n readonly reason: Option.Option<string>\n /** The operation as it was sent: its Message at the version it was written at. */\n readonly operation: WrittenOperation\n /** The operation's Message, encoded at the current version: what to read it by. */\n readonly message: unknown\n}\n\n/**\n * A consistent status and optimistic-shared pair, read from one replica state.\n * `Replica.changes` emits it so a UI can hold a single subscription.\n */\nexport interface ReplicaSnapshot<Shared> {\n readonly status: ReplicaStatus\n readonly shared: Shared\n /** The server-confirmed state the optimistic `shared` is built on. */\n readonly committed: Shared\n /**\n * The local sequence the next submitted operation takes. Only a successful\n * submit moves it, so a caller that submits one Message at a time can tell\n * from one snapshot whether `shared` already holds it.\n */\n readonly nextLocalSequence: LocalSequence\n}\n\nexport interface Replica<Message, Shared> {\n /** The id this replica's operations carry, one per tab: what its commits are stamped with. */\n readonly replicaId: ReplicaId\n /** The optimistic projection: committed state with pending operations replayed. */\n readonly shared: Effect.Effect<Shared>\n /**\n * The server-confirmed state through `cursor`, with no pending operation\n * applied. A pending edit reaches it only once the server commits it, and a\n * rejected one never does.\n */\n readonly committed: Effect.Effect<Shared>\n /** The outbox, as written. */\n readonly pending: Effect.Effect<ReadonlyArray<WrittenOperation>>\n readonly cursor: Effect.Effect<Sequence>\n /**\n * Waiting/recovery information without exposing Messages or the Model. It is a\n * snapshot; `statusChanges` re-emits it after every submit and exchange.\n */\n readonly status: Effect.Effect<ReplicaStatus>\n /** The status, re-emitted after every submit and exchange. */\n readonly statusChanges: Stream.Stream<ReplicaStatus>\n /**\n * The status and the optimistic shared value together, re-emitted after every\n * submit and exchange, so a UI can subscribe once instead of to both.\n */\n readonly changes: Stream.Stream<ReplicaSnapshot<Shared>>\n /** The status, `shared`, `committed` and next local sequence, read from one replica state. */\n readonly snapshot: Effect.Effect<ReplicaSnapshot<Shared>>\n /** Records a durable Message in the outbox and applies it optimistically. */\n // A method, so a replica of the durable subset is still a `Replica` of the\n // application's Messages where one is only passed along (`Sync.mount`).\n 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 /**\n * The exchange loop: exchanges once, then after every `submit` and every\n * notice on the transport's `changes`, until the replica closes or the fiber\n * is interrupted. A failed exchange is recorded\n * in `status.lastError` and retried on a backoff (from 0.5 s, doubling up to\n * 30 s), or at once on the next `submit`, so the fiber never fails. Fork it\n * with `Effect.forkScoped` and provide `Transport`.\n */\n readonly start: Effect.Effect<void, never, Transport>\n /** Forgets a `status.refused` operation, its payload with it. One that is not there changes nothing. */\n dismiss(opId: OpId): Effect.Effect<void, ReplicaError>\n readonly close: Effect.Effect<void>\n}\n\n/**\n * The document's Message: one Schema, at version 1, or its history\n * (`Sync.migrations`), whose current Schema is the Message.\n */\nexport type MessageHistory<Message, MessageEncoded> =\n | {\n readonly message: Schema.Codec<Message, MessageEncoded, never, never>\n readonly migrations?: undefined\n }\n | {\n /** The Schemas operations may be stored in, and how each becomes the next. */\n readonly migrations: Migrations<Message, MessageEncoded>\n readonly message?: undefined\n }\n\nexport type SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> = SyncDefinitionOptions<\n Message,\n Shared,\n SharedEncoded\n> &\n MessageHistory<Message, MessageEncoded>\n\nexport interface SyncDefinitionOptions<Message, Shared, SharedEncoded> {\n readonly documentId: DocumentId\n readonly shared: Schema.Codec<Shared, SharedEncoded, never, never>\n readonly empty: Shared\n readonly durable: (message: Message) => boolean\n /**\n * Optional. The Messages only the server appends: stored and replayed like\n * durable ones, never accepted from a replica. A Message both predicates\n * accept is refused wherever it is read.\n */\n readonly serverOnly?: ((message: Message) => boolean) | undefined\n readonly replay: (shared: Shared, message: Message) => Shared\n /**\n * Optional. Merges a durable Message into the one submitted before it, while that one\n * has not been sent: one operation instead of two, for a burst of typing. Replaying the\n * result must equal replaying `last` then `next`. Undefined keeps them apart.\n */\n readonly coalesce?: ((last: Message, next: Message) => Message | undefined) | undefined\n /**\n * Optional. Writes what the server's commit decided into a durable Message, on the\n * server only: the journal stores, reduces and sends the stamped Message, so every\n * replica replays the same one in place of what it sent.\n */\n readonly stamp?: ((message: Message, commit: CommitStamp) => Message) | undefined\n}\n\n/**\n * What a commit decided, for `stamp`: the operation's place in the order, who\n * committed it, and from which replica. `actorId` is the principal, shared by\n * every tab a person has open; `replicaId` tells those tabs apart.\n */\nexport interface CommitStamp {\n readonly sequence: number\n readonly actorId: string\n readonly replicaId: string\n}\n\n/**\n * A document's protocol. `Durable` is what a replica's `submit` takes: the\n * durable subset for a contract from `Sync.forApplication(App).make`, every\n * Message for one from `Sync.define`, which checks `durable` when called.\n */\nexport interface Sync<Message, Shared, Durable = Message> {\n readonly documentId: DocumentId\n /** Whether a Message is one the replica records and replays. */\n readonly durable: (message: Message) => boolean\n /** Whether a Message is one only the server appends: replicas replay it and never submit it. */\n readonly serverOnly: (message: Message) => boolean\n /**\n * Low-level wire codecs for adapters and the transport. Most applications use\n * `journalContract` and `openReplica`; these are exposed for a custom\n * transport or a server that must speak the operation envelope directly.\n */\n readonly codec: {\n /** The current version of the document's Message history: 1 with no migrations. */\n readonly messageVersion: number\n /** The document's Message at its current version: what every hook decodes. */\n readonly message: Schema.Codec<Message, unknown, never, never>\n /**\n * An entry someone sent, read: its Message upcast to the current version.\n * Throws `UnsupportedMessageVersionError` for a newer version,\n * `UnreadableMessageError` for an older one no step reads, and\n * `ServerOnlyMessageError` for a Message only the server appends; it\n * refuses a replica id under `server/` or past 128 characters. Read\n * stored history with `journalContract().operation.decode`, which takes\n * the server's Messages too.\n */\n readonly normalizeOperation: (input: unknown) => Operation\n /** `normalizeOperation`, of this document only. */\n readonly operationFrom: (input: unknown, documentId: DocumentId) => Operation\n /**\n * An entry as received, checked as an envelope of this document and read\n * as `normalizeOperation` reads it, and returned as written: what a server\n * appends. A custom server reads every entry with it before appending.\n * Never pass it an `Operation`: that Message is already current and would\n * be read as version 1. Write one with `journalContract().operation.encode`.\n */\n readonly writtenFrom: (input: unknown, documentId: DocumentId) => WrittenOperation\n readonly committedFrom: (input: unknown, documentId: DocumentId) => CommittedOperation\n readonly decodeExchange: (input: unknown) => Exchange<Shared>\n }\n /** The codecs and pure reducer `foldkit-durable`'s `makeJournal` consumes. */\n readonly journalContract: () => JournalContract<Operation, Shared>\n /**\n * Opens the replica a store holds. Its id is the store's: read back, or minted\n * when the store is empty, so two stores never share one. In a browser the\n * store is `Sync.tabStorage(name)`, one per tab.\n */\n readonly openReplica: (\n storage: Storage,\n options?: OpenReplicaOptions,\n ) => Effect.Effect<Replica<Durable, Shared>, ReplicaError>\n}\n\nexport interface OpenReplicaOptions {\n /**\n * The id the store must hold, for a test asserting operation ids or a replica\n * a server names. It names one store, never a person: operation ids are\n * `replicaId:localSequence`, so two stores under one id (a person's second\n * browser) reuse ids the journal refuses.\n */\n readonly replicaId?: ReplicaId | undefined\n}\n\n/** Structural match for `foldkit-durable`'s journal options; Sync stays independent. */\nexport interface JournalContract<Operation, Shared> {\n /** The replica each operation came from, which Durable binds to its first committer. */\n readonly replicaId: (operation: Operation) => string\n /** Sync's operation id includes the replica, even after Durable compacts its payload. */\n readonly legacyReplicaId: (opId: string) => string\n readonly operation: {\n /** Written at the current version: what the journal stores. */\n readonly encode: (operation: Operation) => WrittenOperation\n /**\n * Read from any version the history has, upcast to the current one: stored\n * history, so the server's own Messages read too. Never the reader of an\n * entry someone sent (`codec.writtenFrom`).\n */\n readonly decode: (input: unknown) => Operation\n /**\n * What a retransmission is compared by: the operation normalized at the\n * version it was written at, as the build that wrote it normalized it, so\n * an edit committed before a deploy is still recognized after it.\n */\n readonly compared: (input: unknown) => WrittenOperation\n }\n readonly snapshot: {\n readonly encode: (snapshot: Shared) => unknown\n readonly decode: (input: unknown) => Shared\n }\n readonly empty: () => Shared\n readonly reduce: (snapshot: Shared, operation: Operation) => Shared\n /** Present when the definition stamps: Durable's `stamp`, over the operation's Message. */\n readonly stamp?: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ) => Operation\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 messages = definition.migrations ?? migrations(definition.message)\n const history = historyOf(messages as Migrations<unknown, unknown>)\n const current = history.version\n const decodeMessage = Schema.decodeUnknownSync(messages.current, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(messages.current)\n const decodeShared = Schema.decodeUnknownSync(definition.shared, { onExcessProperty: 'error' })\n const encodeShared = Schema.encodeSync(definition.shared)\n\n const ReplicaStateSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n revision: Schema.Number,\n nextLocalSequence: LocalSequence,\n cursor: Sequence,\n committed: definition.shared,\n committedIds: Schema.Array(Schema.String),\n pending: Schema.Array(WrittenOperationSchema),\n refused: Schema.optionalKey(Schema.Array(WrittenOperationSchema)),\n epoch: Schema.optionalKey(Schema.NonEmptyString),\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(OpId),\n // Each refusal is decoded on its own, when the rejection is read: one this\n // build cannot read must not fail the exchange that rejected its operation.\n refusals: Schema.optional(Schema.Array(Schema.Struct({ opId: OpId, refusal: Schema.Unknown }))),\n // A server's words for a person, bounded: a reply is not a place for a document.\n reasons: Schema.optional(\n Schema.Array(\n Schema.Struct({ opId: OpId, reason: Schema.String.check(Schema.isMaxLength(500)) }),\n ),\n ),\n acknowledged: Schema.optional(Schema.Array(OpId)),\n checkpoint: Schema.optional(CheckpointSchema),\n more: Schema.optional(Schema.Boolean),\n epoch: Schema.optional(Schema.NonEmptyString),\n })\n const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: 'error' })\n const encodeState = Schema.encodeSync(ReplicaStateSchema)\n const encodeWritten = Schema.encodeSync(WrittenOperationSchema)\n const VersionProbe = Schema.Struct({\n protocolVersion: Schema.optional(Schema.Number),\n schemaVersion: Schema.optional(Schema.Number),\n })\n /**\n * Tells a version this build does not understand apart from malformed data,\n * so the caller gets an actionable failure and the stored state is preserved.\n */\n const unsupportedVersion = (input: unknown): UnsupportedReplicaVersionError | undefined => {\n let found: {\n readonly protocolVersion?: number | undefined\n readonly schemaVersion?: number | undefined\n }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.protocolVersion === PROTOCOL_VERSION && found.schemaVersion === SCHEMA_VERSION)\n return undefined\n const protocolVersion = found.protocolVersion ?? null\n const schemaVersion = found.schemaVersion ?? null\n return new UnsupportedReplicaVersionError({\n protocolVersion,\n schemaVersion,\n message: `Stored replica uses protocol ${protocolVersion ?? '?'} / schema ${schemaVersion ?? '?'}; this build supports ${PROTOCOL_VERSION}/${SCHEMA_VERSION}`,\n })\n }\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 // `LocalSequence` already rejects a non-positive counter; this checks the\n // derived identity.\n if (operation.opId !== `${operation.replicaId}:${operation.localSequence}`) {\n throw new Error('Invalid operation identity')\n }\n }\n /**\n * An operation's Message, upcast to the current version and decoded. The\n * durable check runs on the current Message, so a step that maps an old\n * variant onto a local-only one is refused as that one is.\n */\n const newer = (opId: string, version: number) =>\n new UnsupportedMessageVersionError({\n opId,\n found: version,\n supported: current,\n message: `Operation ${opId} was written at Message version ${version}; this build reads up to ${current}`,\n })\n const serverOnly = definition.serverOnly ?? (() => false)\n /**\n * `sent` is an entry someone sent, which may carry only what a replica\n * submits; `history` is what the journal stored, the server's Messages too.\n */\n const messageOf = (operation: WrittenShape, kind: 'sent' | 'history'): Message => {\n const version = versionOf(operation)\n if (version > current) throw newer(operation.opId, version)\n let decoded: Message\n if (version === current) decoded = decodeMessage(operation.message)\n else\n try {\n decoded = decodeMessage(history.upcast(version, operation.message))\n } catch (cause) {\n throw new UnreadableMessageError({\n opId: operation.opId,\n version,\n message: `No step of the Message history reads operation ${operation.opId}, written at version ${version}`,\n cause,\n })\n }\n const durable = definition.durable(decoded)\n const server = serverOnly(decoded)\n if (durable && server)\n throw new AmbiguousMessageError({\n opId: operation.opId,\n message: `Operation ${operation.opId} carries a Message both durable and server-only`,\n })\n if (server && kind === 'sent')\n throw new ServerOnlyMessageError({\n opId: operation.opId,\n message: `Operation ${operation.opId} carries a Message only the server appends`,\n })\n if (!durable && !server) throw new Error('Message is local-only')\n return decoded\n }\n /** The envelope alone: the decoded side holds no version, only the current Message. */\n const envelopeOf = <O extends WrittenShape>({\n messageVersion: _,\n ...envelope\n }: O): Omit<O, 'messageVersion'> => envelope\n /** Written at the current version, which an explicit 1 is not. */\n const write = (operation: Operation): WrittenOperation => {\n const envelope = envelopeOf(operation)\n return vouched(current === 1 ? envelope : { ...envelope, messageVersion: current })\n }\n const assertDocument = <O extends WrittenShape>(operation: O, key: DocumentId): O => {\n if (operation.documentId !== key) throw new Error('Wrong document')\n return operation\n }\n /** What a sent entry may not name: the server's replica ids, or one past the bound. */\n const checkSentReplica = (operation: WrittenShape): void => {\n if (operation.replicaId.startsWith(SERVER_REPLICA_PREFIX))\n throw new Error('The replica id is reserved for the server')\n if (operation.replicaId.length > MAX_SENT_REPLICA_ID)\n throw new Error('The replica id is too long')\n }\n const read = (written: WrittenShape, kind: 'sent' | 'history'): Operation => {\n checkIdentity(written)\n if (kind === 'sent') checkSentReplica(written)\n return { ...envelopeOf(written), message: encodeMessage(messageOf(written, kind)) }\n }\n const normalizeOperation = (input: unknown): Operation => read(decodeWritten(input), 'sent')\n const operationFrom = (input: unknown, key: DocumentId): Operation =>\n read(assertDocument(decodeWritten(input), key), 'sent')\n const writtenFrom = (input: unknown, key: DocumentId): WrittenOperation => {\n const written = assertDocument(decodeWritten(input), key)\n // Read for its checks and discarded: what is appended is what was sent.\n read(written, 'sent')\n return written\n }\n /** Stored history: the server's Messages read, and a stored replica id of any length. */\n const readStored = (input: unknown): Operation => read(decodeWritten(input), 'history')\n /** An outbox entry this replica wrote: history, since it may predate a deploy that moved its variant. */\n const storedFrom = (input: unknown, key: DocumentId): Operation =>\n read(assertDocument(decodeWritten(input), key), 'history')\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.\n */\n const decodeCommittedOperation = (\n input: unknown,\n key: DocumentId,\n ): { readonly committed: CommittedOperation; readonly message: Message } => {\n const written = assertDocument(decodeCommittedWritten(input), key)\n checkIdentity(written)\n const message = messageOf(written, 'history')\n return { committed: { ...envelopeOf(written), message: encodeMessage(message) }, message }\n }\n const committedFrom = (input: unknown, key: DocumentId): CommittedOperation =>\n decodeCommittedOperation(input, key).committed\n /**\n * Normalized at the version it was written at, with no upcast: what the\n * build that wrote it hashed. An explicit `messageVersion: 1` is dropped,\n * so it and an absent one compare alike.\n */\n const compared = (input: unknown): WrittenOperation => {\n const written = decodeWritten(input)\n const version = versionOf(written)\n if (version > current) throw newer(written.opId, version)\n const envelope = envelopeOf(written)\n return vouched({\n ...envelope,\n ...(version === 1 ? {} : { messageVersion: version }),\n message: history.normalize(version, written.message),\n })\n }\n\n const journalContract = (): JournalContract<Operation, Shared> => ({\n replicaId: operation => operation.replicaId,\n legacyReplicaId: opId => opId.slice(0, opId.lastIndexOf(':')),\n // Stored written at the current version; read from any version the history has.\n operation: { encode: write, decode: readStored, compared },\n snapshot: { encode: encodeShared, decode: decodeShared },\n empty: () => definition.empty,\n reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),\n ...(definition.stamp === undefined\n ? {}\n : {\n stamp: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ): Operation => ({\n ...operation,\n message: encodeMessage(\n definition.stamp!(decodeMessage(operation.message), {\n ...commit,\n replicaId: operation.replicaId,\n }),\n ),\n }),\n }),\n })\n\n /** `state` with `refused` set; the key is absent when none is, so such a state is as before. */\n const withRefused = (\n { refused: _, ...state }: ReplicaState<Shared>,\n refused: ReadonlyArray<WrittenOperation>,\n ): ReplicaState<Shared> => (refused.length === 0 ? state : { ...state, refused })\n\n const optimistic = (state: ReplicaState<Shared>): Shared =>\n state.pending.reduce(\n (model, operation) => definition.replay(model, messageOf(operation, 'history')),\n state.committed,\n )\n\n const openReplica = Effect.fn('Sync.openReplica')(\n function* (storage: Storage, options?: OpenReplicaOptions) {\n const saved = yield* storage.load()\n const initial: ReplicaState<Shared> = {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId: options?.replicaId ?? ReplicaId.make(crypto.randomUUID()),\n revision: 0,\n nextLocalSequence: localSequence(1),\n cursor: sequence(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 unsupportedVersion(saved) ??\n new InvalidReplicaHistoryError({\n message: 'Stored replica state is invalid',\n cause,\n }),\n })\n const replicaId = state.replicaId\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n if (\n state.documentId !== documentId ||\n (options?.replicaId !== undefined && replicaId !== options.replicaId)\n )\n return yield* new WrongReplicaStorageError({\n documentId,\n replicaId: options?.replicaId ?? 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 // Written at an older version no step reads: refused by its id, kept as\n // written, so the rest of the outbox opens and sends.\n const unreadable = new Set<WrittenOperation>()\n for (const pending of state.pending) {\n if (\n pending.replicaId !== replicaId ||\n pending.localSequence >= state.nextLocalSequence ||\n committedIds.has(pending.opId) ||\n pendingIds.has(pending.opId)\n )\n return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n pendingIds.add(pending.opId)\n try {\n storedFrom(pending, documentId)\n } catch (cause) {\n // A newer build wrote it: nothing is removed, and that build reads it.\n if (cause instanceof UnsupportedMessageVersionError) return yield* cause\n if (cause instanceof UnreadableMessageError) unreadable.add(pending)\n else return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n }\n }\n // Storage holds the schema's encoded side, so a transforming `shared`\n // codec round-trips: decode on load, encode before every save. Encoding\n // also rejects an invalid `empty` on first creation rather than at reload.\n const store = Effect.fn('Sync.store')(function* (\n next: ReplicaState<Shared>,\n expectedRevision: number | null,\n ) {\n const encoded = yield* Effect.try({\n try: () => encodeState(next),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the replica state',\n cause,\n }),\n })\n yield* storage.save(encoded, expectedRevision)\n })\n if (saved === undefined) yield* store(state, null)\n // The one write an open makes, under the loaded revision: a tab that\n // opened the same store meanwhile fails it as a conflict.\n const opened: ReplicaState<Shared> =\n unreadable.size === 0\n ? state\n : withRefused(\n {\n ...state,\n revision: state.revision + 1,\n pending: state.pending.filter(operation => !unreadable.has(operation)),\n },\n [...(state.refused ?? []), ...unreadable],\n )\n if (opened !== state) yield* store(opened, state.revision)\n\n const stateRef = yield* SynchronizedRef.make(opened)\n const closed = yield* Ref.make(false)\n const lastError = yield* Ref.make<string | undefined>(undefined)\n const rejectedOps = yield* Ref.make<ReadonlyArray<Rejection>>([])\n // Operations submitted since opening that no exchange has carried yet. Only these may\n // be coalesced: one that was sent may already be committed as it was.\n const unsent = yield* Ref.make<ReadonlySet<string>>(new Set())\n // One pending wake-up is enough: the loop exchanges the whole outbox.\n const wake = yield* Queue.sliding<void>(1)\n const statusSignals = yield* PubSub.sliding<void>(1)\n // The current value, then again after every change. Subscribed before the\n // first read, so a change made while a subscriber holds that value, or\n // between the read and the subscription, is still told.\n const following = <A>(read: Effect.Effect<A>): Stream.Stream<A> =>\n Stream.unwrap(\n Effect.map(PubSub.subscribe(statusSignals), signals =>\n Stream.concat(\n Stream.fromEffect(read),\n Stream.fromSubscription(signals).pipe(Stream.mapEffect(() => read)),\n ),\n ),\n )\n // The projection is pure over an immutable state, so a cached value is\n // reused until a write replaces the state object. A UI reads `shared` far\n // more often than it writes, and replaying a large outbox per read is\n // quadratic (see `bench/projection.bench.ts`).\n const projection = yield* Ref.make<\n { readonly state: ReplicaState<Shared>; readonly shared: Shared } | undefined\n >(undefined)\n const snapshot = Effect.fn('Sync.snapshot')(function* () {\n const current = yield* SynchronizedRef.get(stateRef)\n const cached = yield* Ref.get(projection)\n let projected: Shared\n if (cached !== undefined && cached.state === current) projected = cached.shared\n else {\n projected = optimistic(current)\n yield* Ref.set(projection, { state: current, shared: projected })\n }\n return {\n status: {\n pending: current.pending.length,\n cursor: current.cursor,\n lastError: yield* Ref.get(lastError),\n rejected: yield* Ref.get(rejectedOps),\n refused: current.refused ?? [],\n epoch: Option.fromUndefinedOr(current.epoch),\n },\n shared: projected,\n committed: current.committed,\n nextLocalSequence: current.nextLocalSequence,\n }\n })()\n const shared = Effect.map(snapshot, value => value.shared)\n const status = Effect.map(snapshot, value => value.status)\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 store(next, current.revision)\n\n const submit = Effect.fn('Sync.submit')(function* (message: Message) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const result = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n if (serverOnly(message))\n return yield* new InvalidOutboxError({\n message: 'Message is one only the server appends',\n })\n if (!definition.durable(message))\n return yield* new InvalidOutboxError({ message: 'Message is local-only' })\n const last = current.pending[current.pending.length - 1]\n const merged =\n last !== undefined &&\n definition.coalesce !== undefined &&\n (yield* Ref.get(unsent)).has(last.opId)\n ? definition.coalesce(messageOf(last, 'history'), message)\n : undefined\n if (merged !== undefined && !definition.durable(merged))\n return yield* new InvalidOutboxError({\n message: 'coalesce returned a local-only Message',\n })\n if (merged !== undefined && serverOnly(merged))\n return yield* new InvalidOutboxError({\n message: 'coalesce returned a Message only the server appends',\n })\n // A merged Message takes the place of the last operation, under its identity.\n const operation = yield* Effect.try({\n try: () =>\n write(\n storedFrom(\n write(\n merged === undefined\n ? {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n localSequence: current.nextLocalSequence,\n opId: OpId.make(`${replicaId}:${current.nextLocalSequence}`),\n baseCursor: current.cursor,\n message: encodeMessage(message),\n }\n : { ...envelopeOf(last!), message: encodeMessage(merged) },\n ),\n documentId,\n ),\n ),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n // Replay before writing: a Message replay refuses can never be\n // applied, here or on another replica, so it must not reach the\n // outbox. The result is the next optimistic projection, so the\n // cache is seeded instead of replaying the outbox on the next read.\n // Rebuilding the projection replays the outbox, which can throw\n // too (an upgrade that changed `update` for a pending Message), so\n // it sits inside the same typed error as the new Message's replay.\n const cached = yield* Ref.get(projection)\n const replayed = yield* Effect.try({\n try: () =>\n definition.replay(\n cached !== undefined && cached.state === current\n ? cached.shared\n : optimistic(current),\n message,\n ),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n // Validated and encoded by `persist`; decoding here would demand the\n // encoded side and break a transforming `shared` codec.\n // The sequence moves on a merge too, so every submit is visible in it; a gap\n // in local sequences is harmless.\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n nextLocalSequence: localSequence(current.nextLocalSequence + 1),\n pending: [\n ...(merged === undefined ? current.pending : current.pending.slice(0, -1)),\n operation,\n ],\n }\n // Only the new operation is written when the storage can append it.\n if (storage.append === undefined) yield* persist(next, current)\n else {\n const encoded = yield* Effect.try({\n try: () => encodeWritten(operation),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the operation',\n cause,\n }),\n })\n yield* storage.append(\n {\n revision: next.revision,\n nextLocalSequence: next.nextLocalSequence,\n localSequence: operation.localSequence,\n operation: encoded,\n },\n current.revision,\n )\n }\n yield* Ref.set(projection, { state: next, shared: replayed })\n yield* Ref.update(unsent, ids => new Set(ids).add(operation.opId))\n yield* Queue.offer(wake, undefined)\n return [undefined, next] as const\n }),\n )\n // Outside the lock, so a `statusChanges` subscriber reads the new state.\n yield* PubSub.publish(statusSignals, undefined)\n return result\n })\n\n /** One exchange; whether the server has more to send and this one made progress. */\n const exchangeOnce = Effect.fn('Sync.exchange')(function* () {\n yield* Effect.annotateCurrentSpan({ documentId })\n const transport = yield* Transport\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Read under the lock, as a submit writes, so no submit can merge into an operation\n // between its being read here and its being marked sent.\n const sent = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Ref.update(unsent, ids => {\n const left = new Set(ids)\n for (const operation of current.pending) left.delete(operation.opId)\n return left\n }).pipe(Effect.as([current, current] as const)),\n )\n yield* Metric.update(syncMetrics.exchanges, 1)\n yield* Metric.update(syncMetrics.exchangePending, sent.pending.length)\n const response = yield* Effect.gen(function* () {\n const raw = yield* transport.exchange(sent.cursor, sent.pending, sent.epoch)\n // The response is untrusted: a malformed shape is a typed failure, not\n // a defect that escapes the declared error channel.\n return yield* Effect.try({\n try: () => decodeExchange(raw),\n catch: cause =>\n new InvalidExchangeError({ message: 'Invalid sync exchange response', cause }),\n })\n })\n const { restarted, refusals } = 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 // Another epoch means the server's history is not the one the cursor points\n // into (it was reset): the answer starts from its beginning, so the committed\n // state is rebuilt from it. The outbox is the user's intent and is kept.\n const restarted =\n response.epoch !== undefined &&\n current.epoch !== undefined &&\n response.epoch !== current.epoch\n if (restarted) yield* Diagnostics.report(historyRebuilt(documentId, replicaId))\n let cursor = restarted ? sequence(0) : current.cursor\n let committed = restarted ? definition.empty : current.committed\n // A checkpoint folds committed history into its snapshot, so the\n // retained id set starts over from it, as it does on a new epoch.\n const ids =\n response.checkpoint === undefined && !restarted\n ? new Set(current.committedIds)\n : 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 acknowledged)\n if (!sentIds.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server acknowledged an operation that was not sent',\n })\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 // An id cannot be both; removal would be ambiguous and a faulty\n // server must not be able to make a pending operation vanish.\n if (acknowledged.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server both acknowledged and rejected an operation',\n })\n }\n for (const { opId } of [...(response.refusals ?? []), ...(response.reasons ?? [])])\n if (!rejected.has(opId))\n return yield* new ForeignRejectionError({\n opId,\n message: 'Server gave a reason for an operation it did not reject',\n })\n // One each, so there are no more to decode than operations it rejected.\n const refusing = new Set<string>()\n for (const { opId } of response.refusals ?? []) {\n if (refusing.has(opId))\n return yield* new ForeignRejectionError({\n opId,\n message: 'Server gave two refusals for one operation',\n })\n refusing.add(opId)\n }\n const refusals = (response.refusals ?? []).map(\n ({ opId, refusal }) => [opId, decodeRefusal(refusal)] as const,\n )\n // What the server could not read is kept, as this build cannot either\n // once their chains agree: never sent again, never lost.\n const unreadableIds = new Set(\n refusals.flatMap(([opId, refusal]) =>\n Result.match(refusal, {\n onFailure: (): ReadonlyArray<OpId> => [],\n onSuccess: SyncRefusal.match({\n Forbidden: (): ReadonlyArray<OpId> => [],\n Invalid: () => [],\n Unreadable: () => [opId],\n }),\n }),\n ),\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 cause instanceof UnsupportedMessageVersionError\n ? cause\n : new InvalidReplicaHistoryError({\n message: 'Invalid committed operation',\n cause,\n }),\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 // A throw here would be a defect, which bypasses `lastError` and leaves\n // `start` retrying the same page in silence.\n const replaying = committed\n committed = yield* Effect.try({\n try: () => definition.replay(replaying, message),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n ids.add(operation.opId)\n cursor = operation.serverSequence\n applied += 1\n }\n if (applied > 0) yield* Metric.update(syncMetrics.applied, applied)\n // Validated and encoded by `persist`, for the same reason as submit.\n const epoch = response.epoch ?? current.epoch\n const next = withRefused(\n {\n ...current,\n revision: current.revision + 1,\n committed,\n cursor,\n ...(epoch === undefined ? {} : { epoch }),\n committedIds: [...ids].slice(-COMMITTED_ID_WINDOW),\n // While the server has more to send, an acknowledged operation's committed\n // copy may be on a later page, so it stays in the optimistic view until then.\n // An acknowledged operation the replica is already past (committed before a\n // checkpoint, say) never arrives, so it goes once there is no more to read.\n pending: current.pending.filter(\n operation =>\n !ids.has(operation.opId) &&\n !(acknowledged.has(operation.opId) && response.more !== true) &&\n !rejected.has(operation.opId),\n ),\n },\n [\n ...(current.refused ?? []),\n // A refusal names only a rejected id (anything else failed the\n // exchange above), so what moves here has left `pending`.\n ...current.pending.filter(operation => unreadableIds.has(operation.opId)),\n ],\n )\n yield* persist(next, current)\n return [{ restarted, refusals }, next] as const\n }),\n )\n yield* Ref.set(lastError, undefined)\n if (response.rejected.length > 0) {\n const reasonOf = new Map(\n (response.reasons ?? []).map(({ opId, reason }) => [opId, reason] as const),\n )\n const refusalOf = new Map<string, SyncRefusal>()\n for (const [opId, decoded] of refusals) {\n if (Result.isSuccess(decoded)) refusalOf.set(opId, decoded.success)\n else\n yield* Diagnostics.report(\n unknownRefusal(documentId, replicaId, opId, fitWords(decoded.failure.message)),\n )\n }\n // Every rejected id was sent: an unknown one failed the exchange above.\n const sentOf = new Map(\n sent.pending.map(operation => [operation.opId, operation] as const),\n )\n // Every pending operation reads: one that did not was refused on open.\n const refused = response.rejected.map((opId): Rejection => {\n const operation = sentOf.get(opId)!\n return {\n opId,\n refusal: Option.fromUndefinedOr(refusalOf.get(opId)),\n reason: Option.fromUndefinedOr(reasonOf.get(opId)),\n operation,\n message: encodeMessage(messageOf(operation, 'history')),\n }\n })\n yield* Ref.update(rejectedOps, previous => [...refused, ...previous].slice(0, 32))\n }\n yield* PubSub.publish(statusSignals, undefined)\n const reached = (yield* SynchronizedRef.get(stateRef)).cursor\n return response.more === true && reached > (restarted ? 0 : sent.cursor)\n })\n\n // A server that pages its answer says there is more, and the replica asks again at\n // once; a round that moves the cursor nowhere ends it.\n const synchronize = Effect.gen(function* () {\n while (yield* exchangeOnce()) {}\n }).pipe(\n Effect.withSpan('Sync.synchronize'),\n // Any failed exchange, a refused response included, is what a UI shows,\n // so it is recorded and announced rather than left for the next submit.\n Effect.tapError(error =>\n Effect.gen(function* () {\n yield* Diagnostics.report(exchangeFailed(documentId, replicaId, error))\n yield* Ref.set(lastError, error.message)\n yield* PubSub.publish(statusSignals, undefined)\n }),\n ),\n )\n\n const start: Effect.Effect<void, never, Transport> = Effect.gen(function* () {\n const transport = yield* Transport\n // A server's notice wakes the loop as a submit does; the fiber ends with this one.\n // It starts at once so it is subscribed before the first exchange, which a\n // notice may arrive during.\n if (transport.changes !== undefined)\n yield* Effect.forkChild(\n Stream.runForEach(transport.changes, () => Queue.offer(wake, undefined)),\n { startImmediately: true },\n )\n let failures = 0\n while (!(yield* Ref.get(closed))) {\n const exit = yield* Effect.exit(synchronize)\n if (yield* Ref.get(closed)) return\n yield* Exit.match(exit, {\n onSuccess: () => {\n failures = 0\n return Queue.take(wake)\n },\n onFailure: () => {\n // Retried on a backoff, or sooner on a submit: an outbox must not\n // wait for the next keystroke to be delivered.\n failures += 1\n const backoff = Math.min(\n START_RETRY_MAX,\n START_RETRY_BASE * 2 ** Math.min(failures - 1, 16),\n )\n return Effect.raceFirst(Queue.take(wake), Effect.sleep(backoff))\n },\n })\n }\n })\n\n const dismiss = Effect.fn('Sync.dismiss')(function* (opId: OpId) {\n const dismissed = yield* 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 refused = current.refused ?? []\n const left = refused.filter(operation => operation.opId !== opId)\n if (left.length === refused.length) return [false, current] as const\n const next = withRefused({ ...current, revision: current.revision + 1 }, left)\n yield* persist(next, current)\n return [true, next] as const\n }),\n )\n if (dismissed) yield* PubSub.publish(statusSignals, undefined)\n })\n\n return {\n replicaId,\n shared,\n snapshot,\n committed: Effect.map(SynchronizedRef.get(stateRef), state => state.committed),\n pending: Effect.map(SynchronizedRef.get(stateRef), state => state.pending),\n cursor: Effect.map(SynchronizedRef.get(stateRef), state => state.cursor),\n status,\n statusChanges: following(status),\n changes: following(snapshot),\n submit,\n synchronize,\n start,\n dismiss,\n close: Effect.fn('Sync.close')(function* () {\n yield* Ref.set(closed, true)\n // Wake `start` so it can observe `closed` and return.\n yield* Queue.offer(wake, undefined)\n yield* storage.close\n })(),\n }\n },\n (effect, storage) =>\n // Close a partially initialized storage on any failure, including a\n // defect, so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : storage.close.pipe(Effect.ignore),\n ),\n ),\n )\n\n return {\n documentId,\n durable: definition.durable,\n serverOnly,\n codec: {\n messageVersion: current,\n message: messages.current as Schema.Codec<Message, unknown, never, never>,\n normalizeOperation,\n operationFrom,\n writtenFrom,\n committedFrom,\n decodeExchange,\n },\n journalContract,\n openReplica,\n }\n}\n"],"mappings":";;;;;;;;;;AAgDA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;;;;;AAOvB,MAAa,wBAAwB;;AAErC,MAAM,sBAAsB;;;;;AAM5B,MAAM,kBAAkB,OAAO,OAAO;CACpC,iBAAiB,OAAO,QAAQ,gBAAgB;CAChD,eAAe,OAAO,QAAQ,cAAc;CAC5C,YAAY;CACZ,WAAW;CACX,eAAe;CACf,MAAM;CACN,YAAY;CACZ,SAAS,OAAO;AAClB,CAAC;;;;;;;AASD,MAAM,gBAAgB,OAAO,OAAO;CAClC,GAAG,gBAAgB;CACnB,gBAAgB,OAAO,YAAY,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC,CAAC;AACvF,CAAC;;;;;;;AASD,MAAM,yBAAyB,cAAc,KAAK,OAAO,MAAM,+BAA+B,CAAC;;AAG/F,MAAM,WAAW,cAA8C;AAE/D,MAAM,kBAAkB;CACtB,gBAAgB,SAAS,MAAM,OAAO,uBAAuB,CAAC,CAAC;CAC/D,SAAS,OAAO;AAClB;AAEwB,OAAO,OAAO;CAAE,GAAG,gBAAgB;CAAQ,GAAG;AAAgB,CAAC;;AAIvF,MAAM,yBAAyB,OAAO,OAAO;CAC3C,GAAG,cAAc;CACjB,GAAG;AACL,CAAC;AAED,MAAM,gBAAgB,OAAO,kBAAkB,wBAAwB,EACrE,kBAAkB,QACpB,CAAC;;;;;;AAMD,MAAa,mBAAmB,UAAqC,cAAc,KAAK;AACxF,MAAM,yBAAyB,OAAO,kBAAkB,wBAAwB,EAC9E,kBAAkB,QACpB,CAAC;;AAED,MAAM,aAAa,cAAoC,UAAU,kBAAkB;AACnF,MAAM,gBAAgB,OAAO,oBAAoB,aAAa,EAAE,kBAAkB,QAAQ,CAAC;;AAU3F,MAAM,mBAAmB;AACzB,MAAM,kBAAkB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E,SAAS,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,OAAO;GACzE,QAAQ,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,MAAM;GACvE;GACA,eAAe,UAAU,MAAM;GAC/B,SAAS,UAAU,QAAQ;GAC3B;GACA;GACA;GACA;GACA,OAAO,OAAO,GAAG,YAAY,CAAC,CAAC,aAAa;IAC1C,OAAO,IAAI,IAAI,QAAQ,IAAI;IAE3B,OAAO,MAAM,MAAM,MAAM,KAAA,CAAS;IAClC,OAAO,QAAQ;GACjB,CAAC,CAAC,CAAC;EACL;CACF,IACC,QAAQ,YAGP,OAAO,KACL,OAAO,QAAO,SACZ,KAAK,UAAU,IAAI,IAAI,OAAO,OAAO,QAAQ,MAAM,KAAK,OAAO,MAAM,CACvE,CACF,CACJ;CAEA,OAAO;EACL;EACA,SAAS,WAAW;EACpB;EACA,OAAO;GACL,gBAAgB;GAChB,SAAS,SAAS;GAClB;GACA;GACA;GACA;GACA;EACF;EACA;EACA;CACF;AACF"}
|
package/dist/transport.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Context, Duration, Effect, Layer, Schema, Stream } from "effect";
|
|
2
|
-
import {
|
|
2
|
+
import { TransportClient, WrittenOperation } from "./sync.js";
|
|
3
3
|
declare const TransportError_base: Schema.Class<TransportError, Schema.TaggedStruct<"SyncTransportError", {
|
|
4
4
|
readonly message: Schema.String;
|
|
5
5
|
}>, import("effect/Cause").YieldableError>;
|
|
@@ -9,7 +9,7 @@ export declare class TransportError extends TransportError_base {}
|
|
|
9
9
|
export interface ExchangeFrame {
|
|
10
10
|
readonly id: string;
|
|
11
11
|
readonly cursor: number;
|
|
12
|
-
readonly pending: ReadonlyArray<
|
|
12
|
+
readonly pending: ReadonlyArray<WrittenOperation>;
|
|
13
13
|
readonly epoch?: string | undefined;
|
|
14
14
|
}
|
|
15
15
|
export interface ExchangeReply {
|
|
@@ -27,7 +27,7 @@ export interface NotifyFrame {
|
|
|
27
27
|
}
|
|
28
28
|
export interface TransportShape {
|
|
29
29
|
/** `epoch` is the server history the replica's cursor points into, when it knows one. */
|
|
30
|
-
readonly exchange: (cursor: number, pending: ReadonlyArray<
|
|
30
|
+
readonly exchange: (cursor: number, pending: ReadonlyArray<WrittenOperation>, epoch?: string | undefined) => Effect.Effect<unknown, TransportError>;
|
|
31
31
|
/**
|
|
32
32
|
* Emits when the server may have something new, for a transport that can hear
|
|
33
33
|
* it: `Replica.start` exchanges on each. A wake-up, not data.
|
|
@@ -53,7 +53,7 @@ declare const TransportSocket_base: Context.ServiceClass<TransportSocket, "foldk
|
|
|
53
53
|
*/
|
|
54
54
|
export declare class TransportSocket extends TransportSocket_base {}
|
|
55
55
|
/** A transport backed by an in-process handler, for tests and single-process demos. */
|
|
56
|
-
export declare const layerLoopback: (handler: (cursor: number, pending: ReadonlyArray<
|
|
56
|
+
export declare const layerLoopback: (handler: (cursor: number, pending: ReadonlyArray<WrittenOperation>, epoch?: string | undefined) => unknown | Promise<unknown>) => Layer.Layer<Transport>;
|
|
57
57
|
/** Wraps the promise-based client the replica already speaks. */
|
|
58
58
|
export declare const layerFromPromise: (transport: TransportClient) => Layer.Layer<Transport>;
|
|
59
59
|
/** Bridges the service back to the promise client the replica consumes. */
|
|
@@ -68,7 +68,7 @@ export declare const toPromise: (transport: TransportShape) => TransportClient;
|
|
|
68
68
|
* Returns a function that stops serving.
|
|
69
69
|
*/
|
|
70
70
|
export declare const serveSocket: (socket: SocketLike, options: {
|
|
71
|
-
readonly exchange: (cursor: number, pending: ReadonlyArray<
|
|
71
|
+
readonly exchange: (cursor: number, pending: ReadonlyArray<WrittenOperation>, epoch?: string | undefined) => unknown | Promise<unknown>;
|
|
72
72
|
/** Subscribes to the document's commits; returns the unsubscribe. */
|
|
73
73
|
readonly changes?: ((listener: () => void) => () => void) | undefined;
|
|
74
74
|
}) => (() => void);
|
package/dist/transport.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.d.ts","names":[],"sources":["../src/transport.ts"],"mappings":";;;;;;qBAOa,uBAAuB;;iBAKnB;WACN;WACA;WACA,SAAS,cAAc;WACvB;;iBAGM;WACN;WACA;WACA;;;;;;;iBAQM;WACN;;iBAGM;;WAEN,WACP,gBACA,SAAS,cAAc,
|
|
1
|
+
{"version":3,"file":"transport.d.ts","names":[],"sources":["../src/transport.ts"],"mappings":";;;;;;qBAOa,uBAAuB;;iBAKnB;WACN;WACA;WACA,SAAS,cAAc;WACvB;;iBAGM;WACN;WACA;WACA;;;;;;;iBAQM;WACN;;iBAGM;;WAEN,WACP,gBACA,SAAS,cAAc,mBACvB,+BACG,OAAO,gBAAgB;;;;;WAKnB,UAAU,OAAO;;;;;;;;;;qBAUf,kBAAkB;;;;;;;;;qBAWlB,wBAAwB;;qBAQxB,gBAAa,UAEtB,gBACA,SAAS,cAAc,mBACvB,yCACa,qBACd,MAAM,MAAM;;qBAUF,mBAAgB,WAAe,oBAAkB,MAAM,MAAM;;qBAU7D,YAAS,WAAe,mBAAiB;;;;;;;;;;qBAczC,cAAW,QACd,YAAU;WAEP,WACP,gBACA,SAAS,cAAc,mBACvB,yCACa;;WAEN,YAAY;;;iBAgER;EACf,KAAK;EACL;EACA,UAAU,WAAW;EACrB,QAAQ;;;;;EAKR,QAAQ;;;;;;;YAQE,gBAAgB;WAEX;WAAsB;;WACtB,kBAAkB;WAAqB;;UAG9C;;;;;;WAMC;;WAEA,YAAY,SAAS;;WAErB,gBAAgB,SAAS;;WAEzB;;;qBAIE,eAAY,gBAAkB;;;;;;;;qBAiC9B,aAAU,MACf,aAAW;WACG,SAAS;MAC5B;;;;;;;;qBAwCU,eAAY,QAAY,cAAY;;;;;;;;;;;;;;;;;qBAuEpC,cAAW,SACb,kBACR,MAAM,MAAM,YAAY,iBAAiB"}
|
package/dist/transport.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.js","names":[],"sources":["../src/transport.ts"],"sourcesContent":["import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { Operation, TransportClient } from './sync.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { listenerFailed } from './diagnostics.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 readonly epoch?: string | undefined\n}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\n/**\n * Sent by a server, unasked, when the document may have changed. It carries no\n * data: the replica exchanges from its own cursor, so a notice that is lost,\n * late, or one of many is harmless.\n */\nexport interface NotifyFrame {\n readonly notify: true\n}\n\nexport interface TransportShape {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => Effect.Effect<unknown, TransportError>\n /**\n * Emits when the server may have something new, for a transport that can hear\n * it: `Replica.start` exchanges on each. A wake-up, not data.\n */\n readonly changes?: Stream.Stream<void> | undefined\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\n/**\n * The connection `layerSocket` keeps, for another protocol to share, such as\n * presence: a send goes to the socket open now and is dropped while none is,\n * and messages from every socket the transport opens arrive here. It is the\n * transport's to close. Only a socket transport provides it, so a layer that\n * has one says so in its type.\n */\nexport class TransportSocket extends Context.Service<TransportSocket, SocketLike>()(\n 'foldkit-sync/TransportSocket',\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: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => Promise.resolve(handler(cursor, pending, epoch)),\n catch: failure,\n }),\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, epoch) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending, epoch),\n catch: failure,\n }),\n })\n\n/** Bridges the service back to the promise client the replica consumes. */\nexport const toPromise = (transport: TransportShape): TransportClient => ({\n exchange: (cursor, pending, epoch) =>\n Effect.runPromise(transport.exchange(cursor, pending, epoch)),\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. With `changes`, a\n * subscription to the document's commits, the socket is also sent a\n * `NotifyFrame` after each, so a client hears of others' edits without polling.\n * Returns a function that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>\n /** Subscribes to the document's commits; returns the unsubscribe. */\n readonly changes?: ((listener: () => void) => () => void) | undefined\n },\n): (() => void) => {\n const send = (reply: ExchangeReply | NotifyFrame): 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, epoch } = parsed as {\n id?: unknown\n cursor?: unknown\n pending?: unknown\n epoch?: unknown\n }\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 (epoch !== undefined && typeof epoch !== 'string')\n ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = {\n id,\n cursor,\n pending: pending as ReadonlyArray<Operation>,\n epoch: typeof epoch === 'string' ? epoch : undefined,\n }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending, frame.epoch)\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 stopChanges = options.changes?.(() => send({ notify: true }))\n const stop = (): void => {\n stopMessage()\n stopChanges?.()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\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\n/**\n * Where `layerSocket` connects: a `url` for the platform `WebSocket`, or a\n * `makeSocket` that opens any other `SocketLike` (a port, a test socket), called\n * again on every reconnect.\n */\nexport type SocketOptions = SocketTuning &\n (\n | { readonly url: string; readonly makeSocket?: undefined }\n | { readonly makeSocket: () => SocketLike; readonly url?: undefined }\n )\n\ninterface SocketTuning {\n /**\n * Consecutive failed connections after which queued work fails and new\n * exchanges fail fast until a connection is healthy again. Reconnecting goes\n * on regardless. Default 5.\n */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: Duration.Input | undefined\n /** Longest wait between reconnect attempts. Default `5 seconds`. */\n readonly maxRetryDelay?: 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 socket over a `MessagePort`, for either end: its frames are the port's\n * string messages, and anything else on the port is ignored. A port tells\n * neither end when the other goes, so `onClose` fires once, on `close()` or\n * when `signal` aborts; a host that serves a pane aborts it when the pane is\n * gone, which stops `serveSocket` and anything else listening.\n */\nexport const portSocket = (\n port: MessagePort,\n options: { readonly signal?: AbortSignal | undefined } = {},\n): SocketLike => {\n const closeListeners = new Set<() => void>()\n let closed = false\n const close = (): void => {\n closed = true\n port.close()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n options.signal?.addEventListener('abort', close, { once: true })\n if (options.signal?.aborted === true) close()\n port.start()\n return {\n send: data => port.postMessage(data),\n close,\n onMessage: listener => {\n const handler = (event: MessageEvent): void => {\n if (typeof event.data === 'string') listener(event.data)\n }\n port.addEventListener('message', handler)\n return () => port.removeEventListener('message', handler)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\n/**\n * A socket over an existing `WebSocket`: the accepted end of a Cloudflare\n * `WebSocketPair`, or any other socket the platform hands over. Unlike\n * `nativeSocket` it opens nothing — accept the pair first — and unlike\n * `portSocket` there is no signal: the socket closing, erroring, or being\n * closed fires `onClose` once, which is how a host stops serving it.\n */\nexport const workerSocket = (socket: WebSocket): SocketLike => {\n const messageListeners = new Set<(data: string) => void>()\n const closeListeners = new Set<() => void>()\n let closed = false\n const forget = (): void => {\n socket.removeEventListener('message', onMessageEvent)\n socket.removeEventListener('close', onClosedEvent)\n socket.removeEventListener('error', onClosedEvent)\n }\n const fireClose = (): void => {\n closed = true\n forget()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n const onMessageEvent = (event: MessageEvent): void => {\n for (const listener of [...messageListeners]) listener(String(event.data))\n }\n const onClosedEvent = (): void => {\n fireClose()\n }\n socket.addEventListener('message', onMessageEvent)\n socket.addEventListener('close', onClosedEvent)\n socket.addEventListener('error', onClosedEvent)\n return {\n send: data => socket.send(data),\n close: () => {\n try {\n socket.close()\n } catch {\n // Already gone: still report the close.\n }\n fireClose()\n },\n onMessage: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\nconst connector = (options: SocketOptions): (() => SocketLike) => {\n if (options.makeSocket !== undefined) return options.makeSocket\n const { url } = options\n return () => nativeSocket(url)\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. It never stops reconnecting: after `maxRetries` consecutive failures\n * queued work fails with a `TransportError`, and exchanges fail fast while no\n * socket is up, until a socket opens. The count resets only when a connection\n * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:\n * a server that accepts a socket and drops it at once is backed off like one\n * that refuses it. A queue over `maxQueue` fails new\n * exchanges with backpressure. The socket is released when the layer's scope\n * ends.\n */\nexport const layerSocket = (\n options: SocketOptions,\n): Layer.Layer<Transport | TransportSocket, TransportError> =>\n Layer.effectContext(\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = connector(options)\n const maxQueue = options.maxQueue ?? 64\n const maxRetries = options.maxRetries ?? 5\n const retryBase = Duration.toMillis(\n Duration.fromInputUnsafe(options.retryBase ?? '50 millis'),\n )\n const maxRetryDelay = Duration.toMillis(\n Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'),\n )\n const clock = yield* Clock.Clock\n // Listeners run in a socket's callback, outside any Effect: their\n // failures go to the reporter this layer was built with.\n const reporter = yield* Effect.service(Diagnostics.Reporter)\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly epoch: string | undefined\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\n }\n const notices = yield* PubSub.sliding<void>(1)\n const listeners = new Set<(data: string) => void>()\n const shared: SocketLike = {\n send: data => {\n if (ready) socket?.send(data)\n },\n close: () => {},\n onMessage: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n onClose: () => () => {},\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 // Closes since a connection last proved healthy. Past `maxRetries` the\n // transport is offline: nothing waits for a socket that may be minutes away.\n let failures = 0\n const healthy = (): void => {\n failures = 0\n }\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 ...(entry.epoch === undefined ? {} : { epoch: entry.epoch }),\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()\n socket = next\n ready = next.onOpen === undefined\n let openedAt = ready ? clock.currentTimeMillisUnsafe() : undefined\n // A socket that just (re)connected may have missed notices, so opening is one.\n const opened = (): void => {\n PubSub.publishUnsafe(notices, undefined)\n }\n const offOpen = next.onOpen?.(() => {\n ready = true\n openedAt = clock.currentTimeMillisUnsafe()\n opened()\n flush()\n })\n const offMessage = next.onMessage(data => {\n // Another protocol's listener must not cost an exchange its reply.\n for (const listener of [...listeners]) {\n try {\n listener(data)\n } catch (thrown) {\n Effect.runFork(\n Diagnostics.report(listenerFailed('Socket', thrown)).pipe(\n Effect.provideService(Diagnostics.Reporter, reporter),\n ),\n )\n }\n }\n let reply: ExchangeReply | NotifyFrame\n try {\n reply = JSON.parse(data) as ExchangeReply | NotifyFrame\n } catch {\n return\n }\n if (typeof reply !== 'object' || reply === null) return\n if ('notify' in reply) {\n if (reply.notify === true) PubSub.publishUnsafe(notices, undefined)\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\n healthy()\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 if (\n openedAt !== undefined &&\n clock.currentTimeMillisUnsafe() - openedAt >= maxRetryDelay\n )\n healthy()\n // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) {\n opened()\n flush()\n }\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n Effect.gen(function* () {\n while (!disposed) {\n yield* Effect.exit(connect)\n if (disposed) return\n failures += 1\n if (failures > maxRetries) failAll('transport closed')\n const backoff = Math.min(maxRetryDelay, retryBase * 2 ** Math.min(failures - 1, 30))\n yield* Effect.sleep(backoff * (0.8 + Math.random() * 0.4))\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 const transport = Transport.of({\n changes: Stream.fromPubSub(notices),\n exchange: (cursor, pending, epoch) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (failures > maxRetries && !ready) {\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, epoch, resume }\n if (ready) send(entry)\n else queued.push(entry)\n // A caller interrupted before a reply must release its slot, or a\n // socket that never replies can exhaust the queue with abandoned\n // work. The frame may already be on the wire; only the local waiter\n // is forgotten, and a late reply for it is ignored.\n return Effect.sync(() => {\n const queuedIndex = queued.indexOf(entry)\n if (queuedIndex >= 0) queued.splice(queuedIndex, 1)\n if (inFlight.get(entry.id) === entry) inFlight.delete(entry.id)\n })\n }),\n })\n return Context.make(Transport, transport).pipe(Context.add(TransportSocket, shared))\n })(),\n )\n"],"mappings":";;;;;;AAOA,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CAAC,sBAAsB,EAC7F,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;;;;;;;;AA8CJ,IAAa,YAAb,cAA+B,QAAQ,QAAmC,CAAC,CACzE,wBACF,CAAC,CAAC,CAAC;;;;;;;;AASH,IAAa,kBAAb,cAAqC,QAAQ,QAAqC,CAAC,CACjF,8BACF,CAAC,CAAC,CAAC;AAEH,MAAM,WAAW,UACf,IAAI,eAAe,EAAE,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;;AAGxF,MAAa,iBACX,YAMA,MAAM,QAAQ,WAAW,EACvB,WAAW,QAAQ,SAAS,UAC1B,OAAO,WAAW;CAChB,WAAW,QAAQ,QAAQ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AAG;EAC7B,SAAS,OAAO,WAAW,OAAO;EAClC,WAAW,QAAQ,SAAS,UAC1B,OAAO,UAAkC,WAAU;GACjD,IAAI,UAAU;IACZ,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,mBAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,WAAW,cAAc,CAAC,OAAO;IACnC,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,mBAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,OAAO,SAAS,SAAS,QAAQ,UAAU;IAC7C,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,uBAAuB,CAAC,CAAC,CAAC;IAC3E;GACF;GACA,MAAM,QAAe;IAAE,IAAI,OAAO,QAAQ;IAAG;IAAQ;IAAS;IAAO;GAAO;GAC5E,IAAI,OAAO,KAAK,KAAK;QAChB,OAAO,KAAK,KAAK;GAKtB,OAAO,OAAO,WAAW;IACvB,MAAM,cAAc,OAAO,QAAQ,KAAK;IACxC,IAAI,eAAe,GAAG,OAAO,OAAO,aAAa,CAAC;IAClD,IAAI,SAAS,IAAI,MAAM,EAAE,MAAM,OAAO,SAAS,OAAO,MAAM,EAAE;GAChE,CAAC;EACH,CAAC;CACL,CAAC;CACD,OAAO,QAAQ,KAAK,WAAW,SAAS,CAAC,CAAC,KAAK,QAAQ,IAAI,iBAAiB,MAAM,CAAC;AACrF,CAAC,CAAC,CAAC,CACL"}
|
|
1
|
+
{"version":3,"file":"transport.js","names":[],"sources":["../src/transport.ts"],"sourcesContent":["import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { TransportClient, WrittenOperation } from './sync.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { listenerFailed } from './diagnostics.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<WrittenOperation>\n readonly epoch?: string | undefined\n}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\n/**\n * Sent by a server, unasked, when the document may have changed. It carries no\n * data: the replica exchanges from its own cursor, so a notice that is lost,\n * late, or one of many is harmless.\n */\nexport interface NotifyFrame {\n readonly notify: true\n}\n\nexport interface TransportShape {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<WrittenOperation>,\n epoch?: string | undefined,\n ) => Effect.Effect<unknown, TransportError>\n /**\n * Emits when the server may have something new, for a transport that can hear\n * it: `Replica.start` exchanges on each. A wake-up, not data.\n */\n readonly changes?: Stream.Stream<void> | undefined\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\n/**\n * The connection `layerSocket` keeps, for another protocol to share, such as\n * presence: a send goes to the socket open now and is dropped while none is,\n * and messages from every socket the transport opens arrive here. It is the\n * transport's to close. Only a socket transport provides it, so a layer that\n * has one says so in its type.\n */\nexport class TransportSocket extends Context.Service<TransportSocket, SocketLike>()(\n 'foldkit-sync/TransportSocket',\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: (\n cursor: number,\n pending: ReadonlyArray<WrittenOperation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => Promise.resolve(handler(cursor, pending, epoch)),\n catch: failure,\n }),\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, epoch) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending, epoch),\n catch: failure,\n }),\n })\n\n/** Bridges the service back to the promise client the replica consumes. */\nexport const toPromise = (transport: TransportShape): TransportClient => ({\n exchange: (cursor, pending, epoch) =>\n Effect.runPromise(transport.exchange(cursor, pending, epoch)),\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. With `changes`, a\n * subscription to the document's commits, the socket is also sent a\n * `NotifyFrame` after each, so a client hears of others' edits without polling.\n * Returns a function that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<WrittenOperation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>\n /** Subscribes to the document's commits; returns the unsubscribe. */\n readonly changes?: ((listener: () => void) => () => void) | undefined\n },\n): (() => void) => {\n const send = (reply: ExchangeReply | NotifyFrame): 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, epoch } = parsed as {\n id?: unknown\n cursor?: unknown\n pending?: unknown\n epoch?: unknown\n }\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 (epoch !== undefined && typeof epoch !== 'string')\n ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = {\n id,\n cursor,\n pending: pending as ReadonlyArray<WrittenOperation>,\n epoch: typeof epoch === 'string' ? epoch : undefined,\n }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending, frame.epoch)\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 stopChanges = options.changes?.(() => send({ notify: true }))\n const stop = (): void => {\n stopMessage()\n stopChanges?.()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\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\n/**\n * Where `layerSocket` connects: a `url` for the platform `WebSocket`, or a\n * `makeSocket` that opens any other `SocketLike` (a port, a test socket), called\n * again on every reconnect.\n */\nexport type SocketOptions = SocketTuning &\n (\n | { readonly url: string; readonly makeSocket?: undefined }\n | { readonly makeSocket: () => SocketLike; readonly url?: undefined }\n )\n\ninterface SocketTuning {\n /**\n * Consecutive failed connections after which queued work fails and new\n * exchanges fail fast until a connection is healthy again. Reconnecting goes\n * on regardless. Default 5.\n */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: Duration.Input | undefined\n /** Longest wait between reconnect attempts. Default `5 seconds`. */\n readonly maxRetryDelay?: 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 socket over a `MessagePort`, for either end: its frames are the port's\n * string messages, and anything else on the port is ignored. A port tells\n * neither end when the other goes, so `onClose` fires once, on `close()` or\n * when `signal` aborts; a host that serves a pane aborts it when the pane is\n * gone, which stops `serveSocket` and anything else listening.\n */\nexport const portSocket = (\n port: MessagePort,\n options: { readonly signal?: AbortSignal | undefined } = {},\n): SocketLike => {\n const closeListeners = new Set<() => void>()\n let closed = false\n const close = (): void => {\n closed = true\n port.close()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n options.signal?.addEventListener('abort', close, { once: true })\n if (options.signal?.aborted === true) close()\n port.start()\n return {\n send: data => port.postMessage(data),\n close,\n onMessage: listener => {\n const handler = (event: MessageEvent): void => {\n if (typeof event.data === 'string') listener(event.data)\n }\n port.addEventListener('message', handler)\n return () => port.removeEventListener('message', handler)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\n/**\n * A socket over an existing `WebSocket`: the accepted end of a Cloudflare\n * `WebSocketPair`, or any other socket the platform hands over. Unlike\n * `nativeSocket` it opens nothing — accept the pair first — and unlike\n * `portSocket` there is no signal: the socket closing, erroring, or being\n * closed fires `onClose` once, which is how a host stops serving it.\n */\nexport const workerSocket = (socket: WebSocket): SocketLike => {\n const messageListeners = new Set<(data: string) => void>()\n const closeListeners = new Set<() => void>()\n let closed = false\n const forget = (): void => {\n socket.removeEventListener('message', onMessageEvent)\n socket.removeEventListener('close', onClosedEvent)\n socket.removeEventListener('error', onClosedEvent)\n }\n const fireClose = (): void => {\n closed = true\n forget()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n const onMessageEvent = (event: MessageEvent): void => {\n for (const listener of [...messageListeners]) listener(String(event.data))\n }\n const onClosedEvent = (): void => {\n fireClose()\n }\n socket.addEventListener('message', onMessageEvent)\n socket.addEventListener('close', onClosedEvent)\n socket.addEventListener('error', onClosedEvent)\n return {\n send: data => socket.send(data),\n close: () => {\n try {\n socket.close()\n } catch {\n // Already gone: still report the close.\n }\n fireClose()\n },\n onMessage: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\nconst connector = (options: SocketOptions): (() => SocketLike) => {\n if (options.makeSocket !== undefined) return options.makeSocket\n const { url } = options\n return () => nativeSocket(url)\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. It never stops reconnecting: after `maxRetries` consecutive failures\n * queued work fails with a `TransportError`, and exchanges fail fast while no\n * socket is up, until a socket opens. The count resets only when a connection\n * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:\n * a server that accepts a socket and drops it at once is backed off like one\n * that refuses it. A queue over `maxQueue` fails new\n * exchanges with backpressure. The socket is released when the layer's scope\n * ends.\n */\nexport const layerSocket = (\n options: SocketOptions,\n): Layer.Layer<Transport | TransportSocket, TransportError> =>\n Layer.effectContext(\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = connector(options)\n const maxQueue = options.maxQueue ?? 64\n const maxRetries = options.maxRetries ?? 5\n const retryBase = Duration.toMillis(\n Duration.fromInputUnsafe(options.retryBase ?? '50 millis'),\n )\n const maxRetryDelay = Duration.toMillis(\n Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'),\n )\n const clock = yield* Clock.Clock\n // Listeners run in a socket's callback, outside any Effect: their\n // failures go to the reporter this layer was built with.\n const reporter = yield* Effect.service(Diagnostics.Reporter)\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<WrittenOperation>\n readonly epoch: string | undefined\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\n }\n const notices = yield* PubSub.sliding<void>(1)\n const listeners = new Set<(data: string) => void>()\n const shared: SocketLike = {\n send: data => {\n if (ready) socket?.send(data)\n },\n close: () => {},\n onMessage: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n onClose: () => () => {},\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 // Closes since a connection last proved healthy. Past `maxRetries` the\n // transport is offline: nothing waits for a socket that may be minutes away.\n let failures = 0\n const healthy = (): void => {\n failures = 0\n }\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 ...(entry.epoch === undefined ? {} : { epoch: entry.epoch }),\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()\n socket = next\n ready = next.onOpen === undefined\n let openedAt = ready ? clock.currentTimeMillisUnsafe() : undefined\n // A socket that just (re)connected may have missed notices, so opening is one.\n const opened = (): void => {\n PubSub.publishUnsafe(notices, undefined)\n }\n const offOpen = next.onOpen?.(() => {\n ready = true\n openedAt = clock.currentTimeMillisUnsafe()\n opened()\n flush()\n })\n const offMessage = next.onMessage(data => {\n // Another protocol's listener must not cost an exchange its reply.\n for (const listener of [...listeners]) {\n try {\n listener(data)\n } catch (thrown) {\n Effect.runFork(\n Diagnostics.report(listenerFailed('Socket', thrown)).pipe(\n Effect.provideService(Diagnostics.Reporter, reporter),\n ),\n )\n }\n }\n let reply: ExchangeReply | NotifyFrame\n try {\n reply = JSON.parse(data) as ExchangeReply | NotifyFrame\n } catch {\n return\n }\n if (typeof reply !== 'object' || reply === null) return\n if ('notify' in reply) {\n if (reply.notify === true) PubSub.publishUnsafe(notices, undefined)\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\n healthy()\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 if (\n openedAt !== undefined &&\n clock.currentTimeMillisUnsafe() - openedAt >= maxRetryDelay\n )\n healthy()\n // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) {\n opened()\n flush()\n }\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n Effect.gen(function* () {\n while (!disposed) {\n yield* Effect.exit(connect)\n if (disposed) return\n failures += 1\n if (failures > maxRetries) failAll('transport closed')\n const backoff = Math.min(maxRetryDelay, retryBase * 2 ** Math.min(failures - 1, 30))\n yield* Effect.sleep(backoff * (0.8 + Math.random() * 0.4))\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 const transport = Transport.of({\n changes: Stream.fromPubSub(notices),\n exchange: (cursor, pending, epoch) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (failures > maxRetries && !ready) {\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, epoch, resume }\n if (ready) send(entry)\n else queued.push(entry)\n // A caller interrupted before a reply must release its slot, or a\n // socket that never replies can exhaust the queue with abandoned\n // work. The frame may already be on the wire; only the local waiter\n // is forgotten, and a late reply for it is ignored.\n return Effect.sync(() => {\n const queuedIndex = queued.indexOf(entry)\n if (queuedIndex >= 0) queued.splice(queuedIndex, 1)\n if (inFlight.get(entry.id) === entry) inFlight.delete(entry.id)\n })\n }),\n })\n return Context.make(Transport, transport).pipe(Context.add(TransportSocket, shared))\n })(),\n )\n"],"mappings":";;;;;;AAOA,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CAAC,sBAAsB,EAC7F,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;;;;;;;;AA8CJ,IAAa,YAAb,cAA+B,QAAQ,QAAmC,CAAC,CACzE,wBACF,CAAC,CAAC,CAAC;;;;;;;;AASH,IAAa,kBAAb,cAAqC,QAAQ,QAAqC,CAAC,CACjF,8BACF,CAAC,CAAC,CAAC;AAEH,MAAM,WAAW,UACf,IAAI,eAAe,EAAE,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;;AAGxF,MAAa,iBACX,YAMA,MAAM,QAAQ,WAAW,EACvB,WAAW,QAAQ,SAAS,UAC1B,OAAO,WAAW;CAChB,WAAW,QAAQ,QAAQ,QAAQ,QAAQ,SAAS,KAAK,CAAC;CAC1D,OAAO;AACT,CAAC,EACL,CAAC;;AAGH,MAAa,oBAAoB,cAC/B,MAAM,QAAQ,WAAW,EACvB,WAAW,QAAQ,SAAS,UAC1B,OAAO,WAAW;CAChB,WAAW,UAAU,SAAS,SAAS,MAAM,GAAG,SAAS,KAAK;CAC9D,OAAO;AACT,CAAC,EACL,CAAC;;AAGH,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AAe,EAAE,SAAS,mBAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,OAAO,SAAS,SAAS,QAAQ,UAAU;IAC7C,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,uBAAuB,CAAC,CAAC,CAAC;IAC3E;GACF;GACA,MAAM,QAAe;IAAE,IAAI,OAAO,QAAQ;IAAG;IAAQ;IAAS;IAAO;GAAO;GAC5E,IAAI,OAAO,KAAK,KAAK;QAChB,OAAO,KAAK,KAAK;GAKtB,OAAO,OAAO,WAAW;IACvB,MAAM,cAAc,OAAO,QAAQ,KAAK;IACxC,IAAI,eAAe,GAAG,OAAO,OAAO,aAAa,CAAC;IAClD,IAAI,SAAS,IAAI,MAAM,EAAE,MAAM,OAAO,SAAS,OAAO,MAAM,EAAE;GAChE,CAAC;EACH,CAAC;CACL,CAAC;CACD,OAAO,QAAQ,KAAK,WAAW,SAAS,CAAC,CAAC,KAAK,QAAQ,IAAI,iBAAiB,MAAM,CAAC;AACrF,CAAC,CAAC,CAAC,CACL"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foldkit-sync",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "A local-first replica of a shared Foldkit projection: offline outbox, optimistic updates, and reconciliation.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foldkit",
|
|
@@ -59,13 +59,13 @@
|
|
|
59
59
|
"LICENSE"
|
|
60
60
|
],
|
|
61
61
|
"dependencies": {
|
|
62
|
-
"foldkit-surface": "0.
|
|
62
|
+
"foldkit-surface": "0.14.0"
|
|
63
63
|
},
|
|
64
64
|
"peerDependencies": {
|
|
65
65
|
"effect": "^4.1.0",
|
|
66
66
|
"foldkit": "^0.170.0",
|
|
67
|
-
"foldkit-
|
|
68
|
-
"foldkit-
|
|
67
|
+
"foldkit-durable": "0.13.0",
|
|
68
|
+
"foldkit-remote": "0.25.0"
|
|
69
69
|
},
|
|
70
70
|
"peerDependenciesMeta": {
|
|
71
71
|
"foldkit-durable": {
|
|
@@ -79,17 +79,20 @@
|
|
|
79
79
|
"@cloudflare/workers-types": "5.20261022.1",
|
|
80
80
|
"@effect/platform-browser": "^4.1.1",
|
|
81
81
|
"@effect/sql-d1": "^4.1.1",
|
|
82
|
+
"@types/ws": "^8.18.2",
|
|
82
83
|
"effect": "^4.1.1",
|
|
83
84
|
"esbuild": "0.28.2",
|
|
85
|
+
"fake-indexeddb": "6.2.6",
|
|
84
86
|
"foldkit": "0.170.0",
|
|
85
87
|
"jsdom": "30.1.3",
|
|
86
88
|
"miniflare": "4.20260730.0",
|
|
87
89
|
"tsdown": "^0.23.1",
|
|
88
90
|
"typescript": "7.0.2",
|
|
89
|
-
"
|
|
90
|
-
"foldkit-
|
|
91
|
-
"foldkit-
|
|
92
|
-
"foldkit-entity": "0.
|
|
91
|
+
"ws": "^8.22.0",
|
|
92
|
+
"foldkit-agent": "0.12.0",
|
|
93
|
+
"foldkit-durable": "0.13.0",
|
|
94
|
+
"foldkit-entity": "0.17.0",
|
|
95
|
+
"foldkit-remote": "0.25.0"
|
|
93
96
|
},
|
|
94
97
|
"scripts": {
|
|
95
98
|
"build": "node ../../scripts/declarations.mjs . && tsdown && node ../../scripts/declared-any.mjs .",
|