foldkit-sync 0.17.0 → 0.18.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 +149 -24
- package/dist/diagnostics.d.ts +29 -2
- package/dist/diagnostics.d.ts.map +1 -1
- package/dist/diagnostics.js +33 -4
- package/dist/diagnostics.js.map +1 -1
- package/dist/do.d.ts +11 -8
- package/dist/do.d.ts.map +1 -1
- package/dist/do.js +3 -4
- package/dist/do.js.map +1 -1
- package/dist/errors.d.ts +16 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -3
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +9 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/journal.d.ts +15 -9
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +48 -19
- package/dist/journal.js.map +1 -1
- package/dist/make.d.ts +40 -6
- package/dist/make.d.ts.map +1 -1
- package/dist/make.js +35 -3
- package/dist/make.js.map +1 -1
- package/dist/mount.d.ts.map +1 -1
- package/dist/mount.js +27 -2
- package/dist/mount.js.map +1 -1
- package/dist/refusal.d.ts +10 -2
- package/dist/refusal.d.ts.map +1 -1
- package/dist/refusal.js +10 -4
- package/dist/refusal.js.map +1 -1
- package/dist/serverJournal.d.ts +6 -1
- package/dist/serverJournal.d.ts.map +1 -1
- package/dist/serverJournal.js.map +1 -1
- package/dist/sync.d.ts +26 -0
- package/dist/sync.d.ts.map +1 -1
- package/dist/sync.js +23 -3
- package/dist/sync.js.map +1 -1
- package/dist/transport.d.ts +25 -2
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js +41 -8
- package/dist/transport.js.map +1 -1
- package/package.json +12 -12
package/dist/sync.d.ts
CHANGED
|
@@ -290,6 +290,20 @@ export interface SyncDefinitionOptions<Message, Shared, SharedEncoded> {
|
|
|
290
290
|
* replica replays the same one in place of what it sent.
|
|
291
291
|
*/
|
|
292
292
|
readonly stamp?: ((message: Message, commit: CommitStamp) => Message) | undefined;
|
|
293
|
+
/**
|
|
294
|
+
* Optional. The document's laws, over the snapshot before an operation and
|
|
295
|
+
* the one it leaves: the first broken one, or none. The server's journal
|
|
296
|
+
* refuses an operation that breaks one, and a replica's `submit` refuses a
|
|
297
|
+
* Message whose optimistic result does. `forApplication(...).make`'s `laws`
|
|
298
|
+
* builds it.
|
|
299
|
+
*/
|
|
300
|
+
readonly judge?: ((before: Shared, after: Shared) => Option.Option<DeclaredLaw>) | undefined;
|
|
301
|
+
}
|
|
302
|
+
/** A law of a document, as declared: its id, its words, and the shared fields it names. */
|
|
303
|
+
export interface DeclaredLaw<Id extends string = string> {
|
|
304
|
+
readonly id: Id;
|
|
305
|
+
readonly message: string;
|
|
306
|
+
readonly path: ReadonlyArray<string>;
|
|
293
307
|
}
|
|
294
308
|
/**
|
|
295
309
|
* What a commit decided, for `stamp`: the operation's place in the order, who
|
|
@@ -394,6 +408,18 @@ export interface JournalContract<Operation, Shared> {
|
|
|
394
408
|
};
|
|
395
409
|
readonly empty: () => Shared;
|
|
396
410
|
readonly reduce: (snapshot: Shared, operation: Operation) => Shared;
|
|
411
|
+
/**
|
|
412
|
+
* Present when the definition has laws: Durable's `judge`, run after
|
|
413
|
+
* `reduce` and before the operation is written.
|
|
414
|
+
*/
|
|
415
|
+
readonly judge?: (request: {
|
|
416
|
+
readonly before: Shared;
|
|
417
|
+
readonly after: Shared;
|
|
418
|
+
}) => true | {
|
|
419
|
+
readonly rule: string;
|
|
420
|
+
readonly message: string;
|
|
421
|
+
readonly path: ReadonlyArray<string>;
|
|
422
|
+
};
|
|
397
423
|
/** Present when the definition stamps: Durable's `stamp`, over the operation's Message. */
|
|
398
424
|
readonly stamp?: (operation: Operation, commit: {
|
|
399
425
|
readonly sequence: number;
|
package/dist/sync.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.d.ts","names":[],"sources":["../src/sync.ts"],"mapp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A,YAAY,eACT,qBAAqB;aACjB,iBAAiB,mBAAmB,SAAS;;;WAG/C,uBAAuB,gBAAgB,WAAW;;;;;;WAMlD,cACP,SAAS,SACT,UAAU,uBACP,OAAO,OAAO,QAAQ,SAAS,SAAS;;iBAG9B;;;;;;;WAON,YAAY;;;iBAIN,gBAAgB,WAAW;;WAEjC,YAAY,WAAW;;WAEvB,kBAAkB;WAClB;;aAEE,SACP,WAAW;eAAuB;UAC/B;;;;;;aAMI,SAAS,OAAO,qBAAqB;;;;;;;aAOrC,WAAW;;WAEb;aACE,SAAS,UAAU;aACnB,SAAS,mBAAmB;;WAE9B,aAAa;WACb,SAAS,UAAU,QAAQ,WAAW,cAAc;;;;;WAKpD,SAAS;aACP,QAAQ;aACR,OAAO;;aAGH;aAAuB;aAA0B,MAAM;;;WAE7D,SACP,WAAW,WACX;aAAmB;aAA2B;QAC3C;;;;;;;;;qBAUM,aAAc,SAAS,QAAQ,gBAAgB,eAAa,YAC3D,eAAe,SAAS,QAAQ,gBAAgB,mBAC3D,KAAK,SAAS"}
|
package/dist/sync.js
CHANGED
|
@@ -5,7 +5,7 @@ import { Transport } from "./transport.js";
|
|
|
5
5
|
import { historyOf, migrations } from "./migrations.js";
|
|
6
6
|
import { SyncRefusal, fitWords } from "./refusal.js";
|
|
7
7
|
import { DocumentId, LocalSequence, OpId, ReplicaId, Sequence, localSequence, sequence } from "./ids.js";
|
|
8
|
-
import { AmbiguousMessageError, CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, ReplayError, ReplicaClosedError, ServerOnlyMessageError, UnreadableMessageError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError } from "./errors.js";
|
|
8
|
+
import { AmbiguousMessageError, CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, LawBrokenError, ReplayError, ReplicaClosedError, ServerOnlyMessageError, UnreadableMessageError, UnsupportedMessageVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError } from "./errors.js";
|
|
9
9
|
// src/sync.ts
|
|
10
10
|
/** Wire and persisted-format versions. A bump must handle the older value explicitly. */
|
|
11
11
|
const PROTOCOL_VERSION = 1;
|
|
@@ -303,6 +303,14 @@ const defineSync = (definition) => {
|
|
|
303
303
|
},
|
|
304
304
|
empty: () => definition.empty,
|
|
305
305
|
reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),
|
|
306
|
+
...definition.judge === void 0 ? {} : { judge: ({ before, after }) => Option.match(definition.judge(before, after), {
|
|
307
|
+
onNone: () => true,
|
|
308
|
+
onSome: (law) => ({
|
|
309
|
+
rule: law.id,
|
|
310
|
+
message: law.message,
|
|
311
|
+
path: law.path
|
|
312
|
+
})
|
|
313
|
+
}) },
|
|
306
314
|
...definition.stamp === void 0 ? {} : { stamp: (operation, commit) => ({
|
|
307
315
|
...operation,
|
|
308
316
|
message: encodeMessage(definition.stamp(decodeMessage(operation.message), {
|
|
@@ -448,13 +456,25 @@ const defineSync = (definition) => {
|
|
|
448
456
|
catch: () => new InvalidOutboxError({ message: "Invalid outbox" })
|
|
449
457
|
});
|
|
450
458
|
const cached = yield* Ref.get(projection);
|
|
451
|
-
const replayed = yield* Effect.try({
|
|
452
|
-
try: () =>
|
|
459
|
+
const { replayed, broken } = yield* Effect.try({
|
|
460
|
+
try: () => {
|
|
461
|
+
const before = cached !== void 0 && cached.state === current ? cached.shared : optimistic(current);
|
|
462
|
+
const replayed = definition.replay(before, message);
|
|
463
|
+
return {
|
|
464
|
+
replayed,
|
|
465
|
+
broken: definition.judge === void 0 ? Option.none() : definition.judge(before, replayed)
|
|
466
|
+
};
|
|
467
|
+
},
|
|
453
468
|
catch: (cause) => new ReplayError({
|
|
454
469
|
message: cause instanceof Error ? cause.message : "Replay failed",
|
|
455
470
|
cause
|
|
456
471
|
})
|
|
457
472
|
});
|
|
473
|
+
if (Option.isSome(broken)) return yield* new LawBrokenError({
|
|
474
|
+
rule: broken.value.id,
|
|
475
|
+
message: broken.value.message,
|
|
476
|
+
path: broken.value.path
|
|
477
|
+
});
|
|
458
478
|
const next = {
|
|
459
479
|
...current,
|
|
460
480
|
revision: current.revision + 1,
|
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 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/**\n * A type-only mark on what `codec.committedFrom` returns. It reads its input as\n * history, so it skips the checks of a sent entry, and\n * `journalContract().operation.encode` refuses it, stripped of its commit or not.\n */\nexport interface ReadAsHistory {\n readonly '~foldkit-sync/history': true\n}\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 /**\n * `epoch` is the server history the replica's cursor points into, when it\n * knows one. `pending` is unread, as on every transport seam: a server reads\n * each entry with `codec.writtenFrom`, which refuses what only it may append.\n */\n exchange(\n cursor: Sequence,\n pending: ReadonlyArray<unknown>,\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: (\n input: unknown,\n documentId: DocumentId,\n ) => CommittedOperation & ReadAsHistory\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: (\n operation: Operation & { readonly '~foldkit-sync/history'?: never },\n ) => 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: WrittenOperation) => 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. Only\n * hashed: never an entry to append.\n */\n readonly compared: (input: unknown) => unknown\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 & ReadAsHistory =>\n decodeCommittedOperation(input, key).committed as CommittedOperation & ReadAsHistory\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. Not branded: it skips the checks\n * of a sent entry, so it must never reach `append`.\n */\n const compared = (input: unknown): WrittenShape => {\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 {\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,kBA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AAO,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"}
|
|
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 LawBrokenError,\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/**\n * A type-only mark on what `codec.committedFrom` returns. It reads its input as\n * history, so it skips the checks of a sent entry, and\n * `journalContract().operation.encode` refuses it, stripped of its commit or not.\n */\nexport interface ReadAsHistory {\n readonly '~foldkit-sync/history': true\n}\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 /**\n * `epoch` is the server history the replica's cursor points into, when it\n * knows one. `pending` is unread, as on every transport seam: a server reads\n * each entry with `codec.writtenFrom`, which refuses what only it may append.\n */\n exchange(\n cursor: Sequence,\n pending: ReadonlyArray<unknown>,\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 * Optional. The document's laws, over the snapshot before an operation and\n * the one it leaves: the first broken one, or none. The server's journal\n * refuses an operation that breaks one, and a replica's `submit` refuses a\n * Message whose optimistic result does. `forApplication(...).make`'s `laws`\n * builds it.\n */\n readonly judge?: ((before: Shared, after: Shared) => Option.Option<DeclaredLaw>) | undefined\n}\n\n/** A law of a document, as declared: its id, its words, and the shared fields it names. */\nexport interface DeclaredLaw<Id extends string = string> {\n readonly id: Id\n readonly message: string\n readonly path: ReadonlyArray<string>\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: (\n input: unknown,\n documentId: DocumentId,\n ) => CommittedOperation & ReadAsHistory\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: (\n operation: Operation & { readonly '~foldkit-sync/history'?: never },\n ) => 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: WrittenOperation) => 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. Only\n * hashed: never an entry to append.\n */\n readonly compared: (input: unknown) => unknown\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 /**\n * Present when the definition has laws: Durable's `judge`, run after\n * `reduce` and before the operation is written.\n */\n readonly judge?: (request: {\n readonly before: Shared\n readonly after: Shared\n }) =>\n | true\n | { readonly rule: string; readonly message: string; readonly path: ReadonlyArray<string> }\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 & ReadAsHistory =>\n decodeCommittedOperation(input, key).committed as CommittedOperation & ReadAsHistory\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. Not branded: it skips the checks\n * of a sent entry, so it must never reach `append`.\n */\n const compared = (input: unknown): WrittenShape => {\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 {\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.judge === undefined\n ? {}\n : {\n judge: ({ before, after }: { readonly before: Shared; readonly after: Shared }) =>\n Option.match(definition.judge!(before, after), {\n onNone: () => true as const,\n onSome: law => ({ rule: law.id, message: law.message, path: law.path }),\n }),\n }),\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 // The laws judge the result there too, a hint over what is held: the\n // server judges again over the snapshot it commits on.\n const { replayed, broken } = yield* Effect.try({\n try: () => {\n const before =\n cached !== undefined && cached.state === current\n ? cached.shared\n : optimistic(current)\n const replayed = definition.replay(before, message)\n return {\n replayed,\n broken:\n definition.judge === undefined\n ? Option.none()\n : definition.judge(before, replayed),\n }\n },\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n if (Option.isSome(broken))\n return yield* new LawBrokenError({\n rule: broken.value.id,\n message: broken.value.message,\n path: broken.value.path,\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":";;;;;;;;;;AAiDA,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,g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AAG,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;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,7 +1,10 @@
|
|
|
1
1
|
import { Context, Duration, Effect, Layer, Schema, Stream } from "effect";
|
|
2
|
+
import { ReportDiagnostic } from "foldkit-surface";
|
|
2
3
|
import { TransportClient } from "./sync.js";
|
|
3
4
|
declare const TransportError_base: Schema.Class<TransportError, Schema.TaggedStruct<"SyncTransportError", {
|
|
4
5
|
readonly message: Schema.String;
|
|
6
|
+
/** The id a server reported its own failure under (`ExchangeDefect`), when it answered with one. */
|
|
7
|
+
readonly incident: Schema.optional<Schema.String>;
|
|
5
8
|
}>, import("effect/Cause").YieldableError>;
|
|
6
9
|
/** The wire failure of a transport. A refusal is a result, not an error. */
|
|
7
10
|
export declare class TransportError extends TransportError_base {}
|
|
@@ -12,10 +15,21 @@ export interface ExchangeFrame {
|
|
|
12
15
|
readonly pending: ReadonlyArray<unknown>;
|
|
13
16
|
readonly epoch?: string | undefined;
|
|
14
17
|
}
|
|
18
|
+
declare const ExchangeRefused_base: Schema.Class<ExchangeRefused, Schema.TaggedStruct<"SyncExchangeRefused", {
|
|
19
|
+
readonly message: Schema.String;
|
|
20
|
+
}>, import("effect/Cause").YieldableError>;
|
|
21
|
+
/**
|
|
22
|
+
* A failed exchange in words written for the replica: throw it from a served
|
|
23
|
+
* exchange (`serveSocket`) and its `message` is sent as it is. Anything else a
|
|
24
|
+
* handler throws is the server's own, and is answered "Exchange failed".
|
|
25
|
+
*/
|
|
26
|
+
export declare class ExchangeRefused extends ExchangeRefused_base {}
|
|
15
27
|
export interface ExchangeReply {
|
|
16
28
|
readonly id: string;
|
|
17
29
|
readonly result?: unknown;
|
|
18
30
|
readonly error?: string;
|
|
31
|
+
/** Beside `error`, when the server failed on its own side: the id it reported the cause under. */
|
|
32
|
+
readonly incident?: string;
|
|
19
33
|
}
|
|
20
34
|
/**
|
|
21
35
|
* Sent by a server, unasked, when the document may have changed. It carries no
|
|
@@ -65,8 +79,15 @@ export declare const toPromise: (transport: TransportShape) => TransportClient;
|
|
|
65
79
|
/**
|
|
66
80
|
* Serves one accepted socket, answering each exchange frame.
|
|
67
81
|
*
|
|
68
|
-
* The counterpart to `layerSocket`: the handler returns the exchange result,
|
|
69
|
-
* throws
|
|
82
|
+
* The counterpart to `layerSocket`: the handler returns the exchange result,
|
|
83
|
+
* or throws. An `ExchangeRefused`, and a replica newer than this server
|
|
84
|
+
* (`UnsupportedMessageVersionError`), are words for the replica, sent as they
|
|
85
|
+
* are. Anything else thrown is this side's (a journal's failure, a driver's
|
|
86
|
+
* words): it is reported as an `ExchangeDefect`, and the error frame says only
|
|
87
|
+
* "Exchange failed" and the incident it was reported under; a stored
|
|
88
|
+
* operation no build reads (`UnreadableHistoryError`) is reported so too, and
|
|
89
|
+
* its frame carries the journal's sentence for it, which names no operation.
|
|
90
|
+
* With `changes`, a
|
|
70
91
|
* subscription to the document's commits, the socket is also sent a
|
|
71
92
|
* `NotifyFrame` after each, so a client hears of others' edits without polling.
|
|
72
93
|
* Returns a function that stops serving.
|
|
@@ -75,6 +96,8 @@ export declare const serveSocket: (socket: SocketLike, options: {
|
|
|
75
96
|
readonly exchange: (cursor: number, pending: ReadonlyArray<unknown>, epoch?: string | undefined) => unknown | Promise<unknown>;
|
|
76
97
|
/** Subscribes to the document's commits; returns the unsubscribe. */
|
|
77
98
|
readonly changes?: ((listener: () => void) => () => void) | undefined;
|
|
99
|
+
/** Where an exchange that threw is reported; the default reporter when not given, since this runs outside any context. */
|
|
100
|
+
readonly diagnostics?: ReportDiagnostic | undefined;
|
|
78
101
|
}) => (() => void);
|
|
79
102
|
/** The minimal socket the layer needs; the global `WebSocket` satisfies it. */
|
|
80
103
|
export interface SocketLike {
|
package/dist/transport.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.d.ts","names":[],"sources":["../src/transport.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"transport.d.ts","names":[],"sources":["../src/transport.ts"],"mappings":";;;;;;;;;qBAQa,uBAAuB;;iBAOnB;WACN;WACA;WACA,SAAS;WACT;;;;;;;;;;qBAQE,wBAAwB;iBAIpB;WACN;WACA;WACA;;WAEA;;;;;;;iBAWM;WACN;;iBAGM;;;;;;WAMN,WACP,gBACA,SAAS,wBACT,+BACG,OAAO,gBAAgB;;;;;WAKnB,UAAU,OAAO;;;;;;;;;;qBAUf,kBAAkB;;;;;;;;;qBAWlB,wBAAwB;;qBAQxB,gBAAa,UAEtB,gBACA,SAAS,wBACT,yCACa,qBACd,MAAM,MAAM;;qBAUF,mBAAgB,WAAe,oBAAkB,MAAM,MAAM;;qBAU7D,YAAS,WAAe,mBAAiB;;;;;;;;;;;;;;;;;qBAqBzC,cAAW,QACd,YAAU;WAEP,WACP,gBACA,SAAS,wBACT,yCACa;;WAEN,YAAY;;WAEZ,cAAc;;;iBA4EV;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"}
|