foldkit-sync 0.12.3 → 0.13.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 +76 -24
- package/dist/diagnostics.d.ts +71 -0
- package/dist/diagnostics.d.ts.map +1 -0
- package/dist/diagnostics.js +67 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/{do.d.mts → do.d.ts} +12 -2
- package/dist/do.d.ts.map +1 -0
- package/dist/{do.mjs → do.js} +15 -9
- package/dist/do.js.map +1 -0
- package/dist/{entity.d.mts → entity.d.ts} +1 -1
- package/dist/entity.d.ts.map +1 -0
- package/dist/{entity.mjs → entity.js} +1 -1
- package/dist/entity.js.map +1 -0
- package/dist/errors.d.ts +91 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +75 -0
- package/dist/errors.js.map +1 -0
- package/dist/ids.d.ts +30 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +28 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +106 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +77 -0
- package/dist/index.js.map +1 -0
- package/dist/indexedDb.d.ts +62 -0
- package/dist/indexedDb.d.ts.map +1 -0
- package/dist/indexedDb.js +128 -0
- package/dist/indexedDb.js.map +1 -0
- package/dist/{journal.d.mts → journal.d.ts} +29 -5
- package/dist/journal.d.ts.map +1 -0
- package/dist/{journal-D5h-jqXE.mjs → journal.js} +43 -32
- package/dist/journal.js.map +1 -0
- package/dist/lww.d.ts +76 -0
- package/dist/lww.d.ts.map +1 -0
- package/dist/lww.js +121 -0
- package/dist/lww.js.map +1 -0
- package/dist/make.d.ts +162 -0
- package/dist/make.d.ts.map +1 -0
- package/dist/make.js +153 -0
- package/dist/make.js.map +1 -0
- package/dist/mount.d.ts +138 -0
- package/dist/mount.d.ts.map +1 -0
- package/dist/mount.js +344 -0
- package/dist/mount.js.map +1 -0
- package/dist/presence.d.ts +116 -0
- package/dist/presence.d.ts.map +1 -0
- package/dist/presence.js +277 -0
- package/dist/presence.js.map +1 -0
- package/dist/{remote.d.mts → remote.d.ts} +2 -2
- package/dist/remote.d.ts.map +1 -0
- package/dist/{remote.mjs → remote.js} +1 -1
- package/dist/remote.js.map +1 -0
- package/dist/revalidate.d.ts +6 -0
- package/dist/revalidate.d.ts.map +1 -0
- package/dist/revalidate.js +10 -0
- package/dist/revalidate.js.map +1 -0
- package/dist/sync.d.ts +276 -0
- package/dist/sync.d.ts.map +1 -0
- package/dist/sync.js +512 -0
- package/dist/sync.js.map +1 -0
- package/dist/transport.d.ts +151 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/{transport-BZ6utYmB.mjs → transport.js} +20 -30
- package/dist/transport.js.map +1 -0
- package/package.json +24 -24
- package/dist/do.d.mts.map +0 -1
- package/dist/do.mjs.map +0 -1
- package/dist/entity.d.mts.map +0 -1
- package/dist/entity.mjs.map +0 -1
- package/dist/index.d.mts +0 -397
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -1613
- package/dist/index.mjs.map +0 -1
- package/dist/journal-D5h-jqXE.mjs.map +0 -1
- package/dist/journal.d.mts.map +0 -1
- package/dist/journal.mjs +0 -1
- package/dist/make-DJ0Q1SSc.d.mts +0 -702
- package/dist/make-DJ0Q1SSc.d.mts.map +0 -1
- package/dist/remote.d.mts.map +0 -1
- package/dist/remote.mjs.map +0 -1
- package/dist/transport-BZ6utYmB.mjs.map +0 -1
package/dist/sync.js
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
import { Effect, Exit, Metric, Option, PubSub, Queue, Ref, Schema, Stream, SynchronizedRef } from "effect";
|
|
2
|
+
import { Diagnostics } from "foldkit-surface";
|
|
3
|
+
import { exchangeFailed, historyRebuilt } from "./diagnostics.js";
|
|
4
|
+
import { Transport } from "./transport.js";
|
|
5
|
+
import { DocumentId, LocalSequence, OpId, ReplicaId, Sequence, localSequence, sequence } from "./ids.js";
|
|
6
|
+
import { CheckpointRegressionError, CommittedOrderError, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, ReplayError, ReplicaClosedError, UnsupportedReplicaVersionError, WrongReplicaStorageError } from "./errors.js";
|
|
7
|
+
// src/sync.ts
|
|
8
|
+
/** Wire and persisted-format versions. A bump must handle the older value explicitly. */
|
|
9
|
+
const PROTOCOL_VERSION = 1;
|
|
10
|
+
const SCHEMA_VERSION = 1;
|
|
11
|
+
/** A client-authored operation envelope. `message` is the application's encoded Message. */
|
|
12
|
+
const OperationSchema = Schema.Struct({
|
|
13
|
+
protocolVersion: Schema.Literal(PROTOCOL_VERSION),
|
|
14
|
+
schemaVersion: Schema.Literal(SCHEMA_VERSION),
|
|
15
|
+
documentId: DocumentId,
|
|
16
|
+
replicaId: ReplicaId,
|
|
17
|
+
localSequence: LocalSequence,
|
|
18
|
+
opId: OpId,
|
|
19
|
+
baseCursor: Sequence,
|
|
20
|
+
message: Schema.Unknown
|
|
21
|
+
});
|
|
22
|
+
/** An operation the server committed, with its authoritative order and actor. */
|
|
23
|
+
const CommittedSchema = Schema.Struct({
|
|
24
|
+
...OperationSchema.fields,
|
|
25
|
+
serverSequence: Sequence.check(Schema.isGreaterThanOrEqualTo(1)),
|
|
26
|
+
actorId: Schema.NonEmptyString
|
|
27
|
+
});
|
|
28
|
+
const decodeOperation = Schema.decodeUnknownSync(OperationSchema, { onExcessProperty: "error" });
|
|
29
|
+
const decodeCommitted = Schema.decodeUnknownSync(CommittedSchema, { onExcessProperty: "error" });
|
|
30
|
+
/** How long `start` waits after a failed exchange: doubling from the base, up to the cap, in ms. */
|
|
31
|
+
const START_RETRY_BASE = 500;
|
|
32
|
+
const START_RETRY_MAX = 3e4;
|
|
33
|
+
/** Counters and a histogram an application can scrape. */
|
|
34
|
+
const syncMetrics = {
|
|
35
|
+
exchanges: Metric.counter("foldkit_sync_exchanges_total"),
|
|
36
|
+
applied: Metric.counter("foldkit_sync_commits_applied_total"),
|
|
37
|
+
checkpoints: Metric.counter("foldkit_sync_checkpoints_adopted_total"),
|
|
38
|
+
exchangePending: Metric.histogram("foldkit_sync_exchange_pending", { boundaries: [
|
|
39
|
+
1,
|
|
40
|
+
4,
|
|
41
|
+
16,
|
|
42
|
+
64,
|
|
43
|
+
256,
|
|
44
|
+
1024
|
|
45
|
+
] })
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Binds the replicated-state protocol to one application contract.
|
|
49
|
+
*
|
|
50
|
+
* The returned codecs decide what is a valid operation and what the shared
|
|
51
|
+
* projection means; the replica owns the local outbox, optimistic projection,
|
|
52
|
+
* and reconciliation as Effects, and never runs a second reducer.
|
|
53
|
+
*/
|
|
54
|
+
const defineSync = (definition) => {
|
|
55
|
+
const documentId = definition.documentId;
|
|
56
|
+
const decodeMessage = Schema.decodeUnknownSync(definition.message, { onExcessProperty: "error" });
|
|
57
|
+
const encodeMessage = Schema.encodeSync(definition.message);
|
|
58
|
+
const decodeShared = Schema.decodeUnknownSync(definition.shared, { onExcessProperty: "error" });
|
|
59
|
+
const encodeShared = Schema.encodeSync(definition.shared);
|
|
60
|
+
const ReplicaStateSchema = Schema.Struct({
|
|
61
|
+
protocolVersion: Schema.Literal(PROTOCOL_VERSION),
|
|
62
|
+
schemaVersion: Schema.Literal(SCHEMA_VERSION),
|
|
63
|
+
documentId: DocumentId,
|
|
64
|
+
replicaId: ReplicaId,
|
|
65
|
+
revision: Schema.Number,
|
|
66
|
+
nextLocalSequence: LocalSequence,
|
|
67
|
+
cursor: Sequence,
|
|
68
|
+
committed: definition.shared,
|
|
69
|
+
committedIds: Schema.Array(Schema.String),
|
|
70
|
+
pending: Schema.Array(OperationSchema),
|
|
71
|
+
epoch: Schema.optionalKey(Schema.NonEmptyString)
|
|
72
|
+
});
|
|
73
|
+
const CheckpointSchema = Schema.Struct({
|
|
74
|
+
cursor: Sequence,
|
|
75
|
+
model: definition.shared
|
|
76
|
+
});
|
|
77
|
+
const ExchangeSchema = Schema.Struct({
|
|
78
|
+
operations: Schema.Array(Schema.Unknown),
|
|
79
|
+
rejected: Schema.Array(OpId),
|
|
80
|
+
reasons: Schema.optional(Schema.Array(Schema.Struct({
|
|
81
|
+
opId: OpId,
|
|
82
|
+
reason: Schema.String.check(Schema.isMaxLength(500))
|
|
83
|
+
}))),
|
|
84
|
+
acknowledged: Schema.optional(Schema.Array(OpId)),
|
|
85
|
+
checkpoint: Schema.optional(CheckpointSchema),
|
|
86
|
+
more: Schema.optional(Schema.Boolean),
|
|
87
|
+
epoch: Schema.optional(Schema.NonEmptyString)
|
|
88
|
+
});
|
|
89
|
+
const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: "error" });
|
|
90
|
+
const encodeState = Schema.encodeSync(ReplicaStateSchema);
|
|
91
|
+
const encodeOperation = Schema.encodeSync(OperationSchema);
|
|
92
|
+
const VersionProbe = Schema.Struct({
|
|
93
|
+
protocolVersion: Schema.optional(Schema.Number),
|
|
94
|
+
schemaVersion: Schema.optional(Schema.Number)
|
|
95
|
+
});
|
|
96
|
+
/**
|
|
97
|
+
* Tells a version this build does not understand apart from malformed data,
|
|
98
|
+
* so the caller gets an actionable failure and the stored state is preserved.
|
|
99
|
+
*/
|
|
100
|
+
const unsupportedVersion = (input) => {
|
|
101
|
+
let found;
|
|
102
|
+
try {
|
|
103
|
+
found = Schema.decodeUnknownSync(VersionProbe)(input);
|
|
104
|
+
} catch {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (found.protocolVersion === PROTOCOL_VERSION && found.schemaVersion === SCHEMA_VERSION) return void 0;
|
|
108
|
+
const protocolVersion = found.protocolVersion ?? null;
|
|
109
|
+
const schemaVersion = found.schemaVersion ?? null;
|
|
110
|
+
return new UnsupportedReplicaVersionError({
|
|
111
|
+
protocolVersion,
|
|
112
|
+
schemaVersion,
|
|
113
|
+
message: `Stored replica uses protocol ${protocolVersion ?? "?"} / schema ${schemaVersion ?? "?"}; this build supports ${PROTOCOL_VERSION}/${SCHEMA_VERSION}`
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
const decodeExchange = (input) => Schema.decodeUnknownSync(ExchangeSchema, { onExcessProperty: "error" })(input);
|
|
117
|
+
const checkIdentity = (operation) => {
|
|
118
|
+
if (operation.opId !== `${operation.replicaId}:${operation.localSequence}`) throw new Error("Invalid operation identity");
|
|
119
|
+
};
|
|
120
|
+
const decodeDurable = (message) => {
|
|
121
|
+
const decoded = decodeMessage(message);
|
|
122
|
+
if (!definition.durable(decoded)) throw new Error("Message is local-only");
|
|
123
|
+
return decoded;
|
|
124
|
+
};
|
|
125
|
+
const shape = (operation) => {
|
|
126
|
+
checkIdentity(operation);
|
|
127
|
+
return {
|
|
128
|
+
...operation,
|
|
129
|
+
message: encodeMessage(decodeDurable(operation.message))
|
|
130
|
+
};
|
|
131
|
+
};
|
|
132
|
+
const assertDocument = (operation, key) => {
|
|
133
|
+
if (operation.documentId !== key) throw new Error("Wrong document");
|
|
134
|
+
return operation;
|
|
135
|
+
};
|
|
136
|
+
const normalizeOperation = (input) => shape(decodeOperation(input));
|
|
137
|
+
const operationFrom = (input, key) => assertDocument(normalizeOperation(input), key);
|
|
138
|
+
/**
|
|
139
|
+
* A committed operation arrives with its message already encoded, so decode it
|
|
140
|
+
* once for the contract check and hand it to `replay` instead of decoding and
|
|
141
|
+
* re-encoding it on the way through `shape`.
|
|
142
|
+
*/
|
|
143
|
+
const decodeCommittedOperation = (input, key) => {
|
|
144
|
+
const committed = assertDocument(decodeCommitted(input), key);
|
|
145
|
+
checkIdentity(committed);
|
|
146
|
+
return {
|
|
147
|
+
committed,
|
|
148
|
+
message: decodeDurable(committed.message)
|
|
149
|
+
};
|
|
150
|
+
};
|
|
151
|
+
const committedFrom = (input, key) => decodeCommittedOperation(input, key).committed;
|
|
152
|
+
const journalContract = () => ({
|
|
153
|
+
replicaId: (operation) => operation.replicaId,
|
|
154
|
+
legacyReplicaId: (opId) => opId.slice(0, opId.lastIndexOf(":")),
|
|
155
|
+
operation: {
|
|
156
|
+
encode: (operation) => operation,
|
|
157
|
+
decode: normalizeOperation
|
|
158
|
+
},
|
|
159
|
+
snapshot: {
|
|
160
|
+
encode: encodeShared,
|
|
161
|
+
decode: decodeShared
|
|
162
|
+
},
|
|
163
|
+
empty: () => definition.empty,
|
|
164
|
+
reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),
|
|
165
|
+
...definition.stamp === void 0 ? {} : { stamp: (operation, commit) => ({
|
|
166
|
+
...operation,
|
|
167
|
+
message: encodeMessage(definition.stamp(decodeMessage(operation.message), {
|
|
168
|
+
...commit,
|
|
169
|
+
replicaId: operation.replicaId
|
|
170
|
+
}))
|
|
171
|
+
}) }
|
|
172
|
+
});
|
|
173
|
+
const optimistic = (state) => state.pending.reduce((model, operation) => definition.replay(model, decodeMessage(operation.message)), state.committed);
|
|
174
|
+
const openReplica = Effect.fn("Sync.openReplica")(function* (storage, options) {
|
|
175
|
+
const saved = yield* storage.load();
|
|
176
|
+
const initial = {
|
|
177
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
178
|
+
schemaVersion: SCHEMA_VERSION,
|
|
179
|
+
documentId,
|
|
180
|
+
replicaId: options?.replicaId ?? ReplicaId.make(crypto.randomUUID()),
|
|
181
|
+
revision: 0,
|
|
182
|
+
nextLocalSequence: localSequence(1),
|
|
183
|
+
cursor: sequence(0),
|
|
184
|
+
committed: definition.empty,
|
|
185
|
+
committedIds: [],
|
|
186
|
+
pending: []
|
|
187
|
+
};
|
|
188
|
+
const state = saved === void 0 ? initial : yield* Effect.try({
|
|
189
|
+
try: () => decodeState(saved),
|
|
190
|
+
catch: (cause) => unsupportedVersion(saved) ?? new InvalidReplicaHistoryError({
|
|
191
|
+
message: "Stored replica state is invalid",
|
|
192
|
+
cause
|
|
193
|
+
})
|
|
194
|
+
});
|
|
195
|
+
const replicaId = state.replicaId;
|
|
196
|
+
yield* Effect.annotateCurrentSpan({
|
|
197
|
+
documentId,
|
|
198
|
+
replicaId
|
|
199
|
+
});
|
|
200
|
+
if (state.documentId !== documentId || options?.replicaId !== void 0 && replicaId !== options.replicaId) return yield* new WrongReplicaStorageError({
|
|
201
|
+
documentId,
|
|
202
|
+
replicaId: options?.replicaId ?? replicaId,
|
|
203
|
+
message: "The stored replica belongs to a different document or replica"
|
|
204
|
+
});
|
|
205
|
+
const committedIds = new Set(state.committedIds);
|
|
206
|
+
if (state.nextLocalSequence < 1 || committedIds.size !== state.committedIds.length) return yield* new InvalidReplicaHistoryError({ message: "Invalid replica history" });
|
|
207
|
+
const pendingIds = /* @__PURE__ */ new Set();
|
|
208
|
+
for (const pending of state.pending) {
|
|
209
|
+
const operation = yield* Effect.try({
|
|
210
|
+
try: () => operationFrom(pending, documentId),
|
|
211
|
+
catch: () => new InvalidOutboxError({ message: "Invalid outbox" })
|
|
212
|
+
});
|
|
213
|
+
if (operation.replicaId !== replicaId || operation.localSequence >= state.nextLocalSequence || committedIds.has(operation.opId) || pendingIds.has(operation.opId)) return yield* new InvalidOutboxError({ message: "Invalid outbox" });
|
|
214
|
+
pendingIds.add(operation.opId);
|
|
215
|
+
}
|
|
216
|
+
const store = Effect.fn("Sync.store")(function* (next, expectedRevision) {
|
|
217
|
+
const encoded = yield* Effect.try({
|
|
218
|
+
try: () => encodeState(next),
|
|
219
|
+
catch: (cause) => new InvalidReplicaHistoryError({
|
|
220
|
+
message: "Could not encode the replica state",
|
|
221
|
+
cause
|
|
222
|
+
})
|
|
223
|
+
});
|
|
224
|
+
yield* storage.save(encoded, expectedRevision);
|
|
225
|
+
});
|
|
226
|
+
if (saved === void 0) yield* store(state, null);
|
|
227
|
+
const stateRef = yield* SynchronizedRef.make(state);
|
|
228
|
+
const closed = yield* Ref.make(false);
|
|
229
|
+
const lastError = yield* Ref.make(void 0);
|
|
230
|
+
const rejectedOps = yield* Ref.make([]);
|
|
231
|
+
const unsent = yield* Ref.make(/* @__PURE__ */ new Set());
|
|
232
|
+
const wake = yield* Queue.sliding(1);
|
|
233
|
+
const statusSignals = yield* PubSub.sliding(1);
|
|
234
|
+
const following = (read) => Stream.unwrap(Effect.map(PubSub.subscribe(statusSignals), (signals) => Stream.concat(Stream.fromEffect(read), Stream.fromSubscription(signals).pipe(Stream.mapEffect(() => read)))));
|
|
235
|
+
const projection = yield* Ref.make(void 0);
|
|
236
|
+
const snapshot = Effect.fn("Sync.snapshot")(function* () {
|
|
237
|
+
const current = yield* SynchronizedRef.get(stateRef);
|
|
238
|
+
const cached = yield* Ref.get(projection);
|
|
239
|
+
let projected;
|
|
240
|
+
if (cached !== void 0 && cached.state === current) projected = cached.shared;
|
|
241
|
+
else {
|
|
242
|
+
projected = optimistic(current);
|
|
243
|
+
yield* Ref.set(projection, {
|
|
244
|
+
state: current,
|
|
245
|
+
shared: projected
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
status: {
|
|
250
|
+
pending: current.pending.length,
|
|
251
|
+
cursor: current.cursor,
|
|
252
|
+
lastError: yield* Ref.get(lastError),
|
|
253
|
+
rejected: yield* Ref.get(rejectedOps),
|
|
254
|
+
epoch: Option.fromUndefinedOr(current.epoch)
|
|
255
|
+
},
|
|
256
|
+
shared: projected,
|
|
257
|
+
committed: current.committed,
|
|
258
|
+
nextLocalSequence: current.nextLocalSequence
|
|
259
|
+
};
|
|
260
|
+
})();
|
|
261
|
+
const shared = Effect.map(snapshot, (value) => value.shared);
|
|
262
|
+
const status = Effect.map(snapshot, (value) => value.status);
|
|
263
|
+
const persist = (next, current) => store(next, current.revision);
|
|
264
|
+
const submit = Effect.fn("Sync.submit")(function* (message) {
|
|
265
|
+
yield* Effect.annotateCurrentSpan({
|
|
266
|
+
documentId,
|
|
267
|
+
replicaId
|
|
268
|
+
});
|
|
269
|
+
const result = yield* SynchronizedRef.modifyEffect(stateRef, (current) => Effect.gen(function* () {
|
|
270
|
+
if (yield* Ref.get(closed)) return yield* new ReplicaClosedError({ message: "Replica is closed" });
|
|
271
|
+
if (!definition.durable(message)) return yield* new InvalidOutboxError({ message: "Message is local-only" });
|
|
272
|
+
const last = current.pending[current.pending.length - 1];
|
|
273
|
+
const merged = last !== void 0 && definition.coalesce !== void 0 && (yield* Ref.get(unsent)).has(last.opId) ? definition.coalesce(decodeMessage(last.message), message) : void 0;
|
|
274
|
+
if (merged !== void 0 && !definition.durable(merged)) return yield* new InvalidOutboxError({ message: "coalesce returned a local-only Message" });
|
|
275
|
+
const operation = yield* Effect.try({
|
|
276
|
+
try: () => operationFrom(merged === void 0 ? {
|
|
277
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
278
|
+
schemaVersion: SCHEMA_VERSION,
|
|
279
|
+
documentId,
|
|
280
|
+
replicaId,
|
|
281
|
+
localSequence: current.nextLocalSequence,
|
|
282
|
+
opId: `${replicaId}:${current.nextLocalSequence}`,
|
|
283
|
+
baseCursor: current.cursor,
|
|
284
|
+
message: encodeMessage(message)
|
|
285
|
+
} : {
|
|
286
|
+
...last,
|
|
287
|
+
message: encodeMessage(merged)
|
|
288
|
+
}, documentId),
|
|
289
|
+
catch: () => new InvalidOutboxError({ message: "Invalid outbox" })
|
|
290
|
+
});
|
|
291
|
+
const cached = yield* Ref.get(projection);
|
|
292
|
+
const replayed = yield* Effect.try({
|
|
293
|
+
try: () => definition.replay(cached !== void 0 && cached.state === current ? cached.shared : optimistic(current), message),
|
|
294
|
+
catch: (cause) => new ReplayError({
|
|
295
|
+
message: cause instanceof Error ? cause.message : "Replay failed",
|
|
296
|
+
cause
|
|
297
|
+
})
|
|
298
|
+
});
|
|
299
|
+
const next = {
|
|
300
|
+
...current,
|
|
301
|
+
revision: current.revision + 1,
|
|
302
|
+
nextLocalSequence: localSequence(current.nextLocalSequence + 1),
|
|
303
|
+
pending: [...merged === void 0 ? current.pending : current.pending.slice(0, -1), operation]
|
|
304
|
+
};
|
|
305
|
+
if (storage.append === void 0) yield* persist(next, current);
|
|
306
|
+
else {
|
|
307
|
+
const encoded = yield* Effect.try({
|
|
308
|
+
try: () => encodeOperation(operation),
|
|
309
|
+
catch: (cause) => new InvalidReplicaHistoryError({
|
|
310
|
+
message: "Could not encode the operation",
|
|
311
|
+
cause
|
|
312
|
+
})
|
|
313
|
+
});
|
|
314
|
+
yield* storage.append({
|
|
315
|
+
revision: next.revision,
|
|
316
|
+
nextLocalSequence: next.nextLocalSequence,
|
|
317
|
+
localSequence: operation.localSequence,
|
|
318
|
+
operation: encoded
|
|
319
|
+
}, current.revision);
|
|
320
|
+
}
|
|
321
|
+
yield* Ref.set(projection, {
|
|
322
|
+
state: next,
|
|
323
|
+
shared: replayed
|
|
324
|
+
});
|
|
325
|
+
yield* Ref.update(unsent, (ids) => new Set(ids).add(operation.opId));
|
|
326
|
+
yield* Queue.offer(wake, void 0);
|
|
327
|
+
return [void 0, next];
|
|
328
|
+
}));
|
|
329
|
+
yield* PubSub.publish(statusSignals, void 0);
|
|
330
|
+
return result;
|
|
331
|
+
});
|
|
332
|
+
/** One exchange; whether the server has more to send and this one made progress. */
|
|
333
|
+
const exchangeOnce = Effect.fn("Sync.exchange")(function* () {
|
|
334
|
+
yield* Effect.annotateCurrentSpan({ documentId });
|
|
335
|
+
const transport = yield* Transport;
|
|
336
|
+
if (yield* Ref.get(closed)) return yield* new ReplicaClosedError({ message: "Replica is closed" });
|
|
337
|
+
const sent = yield* SynchronizedRef.modifyEffect(stateRef, (current) => Ref.update(unsent, (ids) => {
|
|
338
|
+
const left = new Set(ids);
|
|
339
|
+
for (const operation of current.pending) left.delete(operation.opId);
|
|
340
|
+
return left;
|
|
341
|
+
}).pipe(Effect.as([current, current])));
|
|
342
|
+
yield* Metric.update(syncMetrics.exchanges, 1);
|
|
343
|
+
yield* Metric.update(syncMetrics.exchangePending, sent.pending.length);
|
|
344
|
+
const response = yield* Effect.gen(function* () {
|
|
345
|
+
const raw = yield* transport.exchange(sent.cursor, sent.pending, sent.epoch);
|
|
346
|
+
return yield* Effect.try({
|
|
347
|
+
try: () => decodeExchange(raw),
|
|
348
|
+
catch: (cause) => new InvalidExchangeError({
|
|
349
|
+
message: "Invalid sync exchange response",
|
|
350
|
+
cause
|
|
351
|
+
})
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
const restarted = yield* SynchronizedRef.modifyEffect(stateRef, (current) => Effect.gen(function* () {
|
|
355
|
+
if (yield* Ref.get(closed)) return yield* new ReplicaClosedError({ message: "Replica is closed" });
|
|
356
|
+
const restarted = response.epoch !== void 0 && current.epoch !== void 0 && response.epoch !== current.epoch;
|
|
357
|
+
if (restarted) yield* Diagnostics.report(historyRebuilt(documentId, replicaId));
|
|
358
|
+
let cursor = restarted ? sequence(0) : current.cursor;
|
|
359
|
+
let committed = restarted ? definition.empty : current.committed;
|
|
360
|
+
const ids = response.checkpoint === void 0 && !restarted ? new Set(current.committedIds) : /* @__PURE__ */ new Set();
|
|
361
|
+
if (response.checkpoint !== void 0) {
|
|
362
|
+
if (response.checkpoint.cursor < cursor) return yield* new CheckpointRegressionError({
|
|
363
|
+
cursor,
|
|
364
|
+
checkpointCursor: response.checkpoint.cursor,
|
|
365
|
+
message: "Checkpoint is behind the replica"
|
|
366
|
+
});
|
|
367
|
+
committed = response.checkpoint.model;
|
|
368
|
+
cursor = response.checkpoint.cursor;
|
|
369
|
+
yield* Metric.update(syncMetrics.checkpoints, 1);
|
|
370
|
+
yield* Effect.logDebug("sync checkpoint adopted", {
|
|
371
|
+
documentId,
|
|
372
|
+
replicaId,
|
|
373
|
+
cursor
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
const acknowledged = new Set(response.acknowledged ?? []);
|
|
377
|
+
const rejected = new Set(response.rejected);
|
|
378
|
+
const sentIds = new Set(sent.pending.map((operation) => operation.opId));
|
|
379
|
+
for (const id of acknowledged) if (!sentIds.has(id)) return yield* new ForeignAcknowledgementError({
|
|
380
|
+
opId: id,
|
|
381
|
+
message: "Server acknowledged an operation that was not sent"
|
|
382
|
+
});
|
|
383
|
+
for (const id of rejected) {
|
|
384
|
+
if (!sentIds.has(id)) return yield* new ForeignRejectionError({
|
|
385
|
+
opId: id,
|
|
386
|
+
message: "Server rejected an operation that was not sent"
|
|
387
|
+
});
|
|
388
|
+
if (acknowledged.has(id)) return yield* new ForeignAcknowledgementError({
|
|
389
|
+
opId: id,
|
|
390
|
+
message: "Server both acknowledged and rejected an operation"
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
for (const { opId } of response.reasons ?? []) if (!rejected.has(opId)) return yield* new ForeignRejectionError({
|
|
394
|
+
opId,
|
|
395
|
+
message: "Server gave a reason for an operation it did not reject"
|
|
396
|
+
});
|
|
397
|
+
let applied = 0;
|
|
398
|
+
for (const raw of response.operations) {
|
|
399
|
+
const { committed: operation, message } = yield* Effect.try({
|
|
400
|
+
try: () => decodeCommittedOperation(raw, documentId),
|
|
401
|
+
catch: (cause) => new InvalidReplicaHistoryError({
|
|
402
|
+
message: "Invalid committed operation",
|
|
403
|
+
cause
|
|
404
|
+
})
|
|
405
|
+
});
|
|
406
|
+
if (operation.serverSequence <= cursor) continue;
|
|
407
|
+
if (operation.serverSequence !== cursor + 1 || ids.has(operation.opId)) return yield* new CommittedOrderError({
|
|
408
|
+
expected: cursor + 1,
|
|
409
|
+
actual: operation.serverSequence,
|
|
410
|
+
message: "Invalid committed order"
|
|
411
|
+
});
|
|
412
|
+
const replaying = committed;
|
|
413
|
+
committed = yield* Effect.try({
|
|
414
|
+
try: () => definition.replay(replaying, message),
|
|
415
|
+
catch: (cause) => new ReplayError({
|
|
416
|
+
message: cause instanceof Error ? cause.message : "Replay failed",
|
|
417
|
+
cause
|
|
418
|
+
})
|
|
419
|
+
});
|
|
420
|
+
ids.add(operation.opId);
|
|
421
|
+
cursor = operation.serverSequence;
|
|
422
|
+
applied += 1;
|
|
423
|
+
}
|
|
424
|
+
if (applied > 0) yield* Metric.update(syncMetrics.applied, applied);
|
|
425
|
+
const epoch = response.epoch ?? current.epoch;
|
|
426
|
+
const next = {
|
|
427
|
+
...current,
|
|
428
|
+
revision: current.revision + 1,
|
|
429
|
+
committed,
|
|
430
|
+
cursor,
|
|
431
|
+
...epoch === void 0 ? {} : { epoch },
|
|
432
|
+
committedIds: [...ids].slice(-1024),
|
|
433
|
+
pending: current.pending.filter((operation) => !ids.has(operation.opId) && !(acknowledged.has(operation.opId) && response.more !== true) && !rejected.has(operation.opId))
|
|
434
|
+
};
|
|
435
|
+
yield* persist(next, current);
|
|
436
|
+
return [restarted, next];
|
|
437
|
+
}));
|
|
438
|
+
yield* Ref.set(lastError, void 0);
|
|
439
|
+
if (response.rejected.length > 0) {
|
|
440
|
+
const reasonOf = new Map((response.reasons ?? []).map(({ opId, reason }) => [opId, reason]));
|
|
441
|
+
const sentOf = new Map(sent.pending.map((operation) => [operation.opId, operation]));
|
|
442
|
+
const refused = response.rejected.map((opId) => ({
|
|
443
|
+
opId,
|
|
444
|
+
reason: Option.fromUndefinedOr(reasonOf.get(opId)),
|
|
445
|
+
operation: sentOf.get(opId)
|
|
446
|
+
}));
|
|
447
|
+
yield* Ref.update(rejectedOps, (previous) => [...refused, ...previous].slice(0, 32));
|
|
448
|
+
}
|
|
449
|
+
yield* PubSub.publish(statusSignals, void 0);
|
|
450
|
+
const reached = (yield* SynchronizedRef.get(stateRef)).cursor;
|
|
451
|
+
return response.more === true && reached > (restarted ? 0 : sent.cursor);
|
|
452
|
+
});
|
|
453
|
+
const synchronize = Effect.gen(function* () {
|
|
454
|
+
while (yield* exchangeOnce());
|
|
455
|
+
}).pipe(Effect.withSpan("Sync.synchronize"), Effect.tapError((error) => Effect.gen(function* () {
|
|
456
|
+
yield* Diagnostics.report(exchangeFailed(documentId, replicaId, error));
|
|
457
|
+
yield* Ref.set(lastError, error.message);
|
|
458
|
+
yield* PubSub.publish(statusSignals, void 0);
|
|
459
|
+
})));
|
|
460
|
+
const start = Effect.gen(function* () {
|
|
461
|
+
const transport = yield* Transport;
|
|
462
|
+
if (transport.changes !== void 0) yield* Effect.forkChild(Stream.runForEach(transport.changes, () => Queue.offer(wake, void 0)), { startImmediately: true });
|
|
463
|
+
let failures = 0;
|
|
464
|
+
while (!(yield* Ref.get(closed))) {
|
|
465
|
+
const exit = yield* Effect.exit(synchronize);
|
|
466
|
+
if (yield* Ref.get(closed)) return;
|
|
467
|
+
if (exit._tag === "Success") {
|
|
468
|
+
failures = 0;
|
|
469
|
+
yield* Queue.take(wake);
|
|
470
|
+
} else {
|
|
471
|
+
failures += 1;
|
|
472
|
+
const backoff = Math.min(START_RETRY_MAX, START_RETRY_BASE * 2 ** Math.min(failures - 1, 16));
|
|
473
|
+
yield* Effect.raceFirst(Queue.take(wake), Effect.sleep(backoff));
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
});
|
|
477
|
+
return {
|
|
478
|
+
replicaId,
|
|
479
|
+
shared,
|
|
480
|
+
snapshot,
|
|
481
|
+
committed: Effect.map(SynchronizedRef.get(stateRef), (state) => state.committed),
|
|
482
|
+
pending: Effect.map(SynchronizedRef.get(stateRef), (state) => state.pending),
|
|
483
|
+
cursor: Effect.map(SynchronizedRef.get(stateRef), (state) => state.cursor),
|
|
484
|
+
status,
|
|
485
|
+
statusChanges: following(status),
|
|
486
|
+
changes: following(snapshot),
|
|
487
|
+
submit,
|
|
488
|
+
synchronize,
|
|
489
|
+
start,
|
|
490
|
+
close: Effect.fn("Sync.close")(function* () {
|
|
491
|
+
yield* Ref.set(closed, true);
|
|
492
|
+
yield* Queue.offer(wake, void 0);
|
|
493
|
+
yield* storage.close;
|
|
494
|
+
})()
|
|
495
|
+
};
|
|
496
|
+
}, (effect, storage) => effect.pipe(Effect.onExit((exit) => Exit.isSuccess(exit) ? Effect.void : storage.close.pipe(Effect.ignore))));
|
|
497
|
+
return {
|
|
498
|
+
documentId,
|
|
499
|
+
durable: definition.durable,
|
|
500
|
+
codec: {
|
|
501
|
+
normalizeOperation,
|
|
502
|
+
operationFrom,
|
|
503
|
+
committedFrom,
|
|
504
|
+
decodeExchange
|
|
505
|
+
},
|
|
506
|
+
journalContract,
|
|
507
|
+
openReplica
|
|
508
|
+
};
|
|
509
|
+
};
|
|
510
|
+
export { defineSync, syncMetrics };
|
|
511
|
+
|
|
512
|
+
//# sourceMappingURL=sync.js.map
|
package/dist/sync.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sync.js","names":[],"sources":["../src/sync.ts"],"sourcesContent":["import {\n Effect,\n Exit,\n Metric,\n Option,\n PubSub,\n Queue,\n Ref,\n Schema,\n Stream,\n SynchronizedRef,\n} from 'effect'\nimport {\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nimport type { Storage } from './indexedDb.js'\nimport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n localSequence,\n sequence,\n} from './ids.js'\nimport { Transport, TransportError } from './transport.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { exchangeFailed, historyRebuilt } from './diagnostics.js'\n\n/** Wire and persisted-format versions. A bump must handle the older value explicitly. */\nconst PROTOCOL_VERSION = 1\nconst SCHEMA_VERSION = 1\n\n/** A client-authored operation envelope. `message` is the application's encoded Message. */\nconst OperationSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n localSequence: LocalSequence,\n opId: OpId,\n baseCursor: Sequence,\n message: Schema.Unknown,\n})\nexport type Operation = typeof OperationSchema.Type\n\n/** An operation the server committed, with its authoritative order and actor. */\nconst CommittedSchema = Schema.Struct({\n ...OperationSchema.fields,\n serverSequence: Sequence.check(Schema.isGreaterThanOrEqualTo(1)),\n actorId: Schema.NonEmptyString,\n})\n/** Named to avoid colliding with `foldkit-durable`'s `Committed`. */\nexport type CommittedOperation = typeof CommittedSchema.Type\n\nconst decodeOperation = Schema.decodeUnknownSync(OperationSchema, { onExcessProperty: 'error' })\nconst decodeCommitted = Schema.decodeUnknownSync(CommittedSchema, { onExcessProperty: 'error' })\n\n/**\n * How many committed-operation ids a replica retains for duplicate detection.\n * Committed sequences are contiguous and the server enforces `opId`\n * uniqueness, so this is defence in depth; bounding it keeps replica state from\n * growing without limit on a log that is never checkpointed.\n */\nconst COMMITTED_ID_WINDOW = 1024\n/** How long `start` waits after a failed exchange: doubling from the base, up to the cap, in ms. */\nconst START_RETRY_BASE = 500\nconst START_RETRY_MAX = 30_000\n\n/** Counters and a histogram an application can scrape. */\nexport const syncMetrics = {\n exchanges: Metric.counter('foldkit_sync_exchanges_total'),\n applied: Metric.counter('foldkit_sync_commits_applied_total'),\n checkpoints: Metric.counter('foldkit_sync_checkpoints_adopted_total'),\n exchangePending: Metric.histogram('foldkit_sync_exchange_pending', {\n boundaries: [1, 4, 16, 64, 256, 1024],\n }),\n}\n\nexport interface Checkpoint<Shared> {\n readonly cursor: Sequence\n readonly model: Shared\n}\n\nexport interface Exchange<Shared> {\n /** Server-committed operations as they arrived; validated against `CommittedOperation` on adoption. */\n readonly operations: ReadonlyArray<unknown>\n readonly rejected: ReadonlyArray<OpId>\n /**\n * Why some of `rejected` were refused, in words the server chose for a person:\n * a policy's reason, never an internal error. One without a reason is still rejected.\n */\n readonly reasons?: ReadonlyArray<{ readonly opId: OpId; readonly reason: string }> | undefined\n /** Sends from the request that are durably committed, so the replica can drop them. */\n readonly acknowledged?: ReadonlyArray<OpId> | undefined\n /** The snapshot a replica predating compaction adopts in place of the log. */\n readonly checkpoint?: Checkpoint<Shared> | undefined\n /** The server sent only part of what is after the cursor; the replica asks again. */\n readonly more?: boolean | undefined\n /**\n * The identity of the server's history. The replica sends back the one it last saw; a\n * server that finds another answers from the start of its own history, and the replica,\n * seeing a new epoch, rebuilds its committed state from that answer and keeps its outbox.\n */\n readonly epoch?: string | undefined\n}\n\nexport interface ReplicaState<Shared> {\n readonly protocolVersion: typeof PROTOCOL_VERSION\n readonly schemaVersion: typeof SCHEMA_VERSION\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly revision: number\n readonly nextLocalSequence: LocalSequence\n readonly cursor: Sequence\n readonly committed: Shared\n readonly committedIds: ReadonlyArray<string>\n readonly pending: ReadonlyArray<Operation>\n /** The server history `cursor` points into, once an exchange has named one. */\n readonly epoch?: string\n}\n\n/**\n * What the promise-based edge adapter consumes; the Effect `Transport` service\n * is the primary seam.\n */\nexport interface TransportClient {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n exchange(\n cursor: Sequence,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ): Promise<unknown>\n}\n\n/** A redacted view of a replica's state, for a UI to explain and recover. */\nexport interface ReplicaStatus {\n readonly pending: number\n readonly cursor: Sequence\n /** The last exchange failure, cleared by a successful exchange. */\n readonly lastError: string | undefined\n /** Operations the server refused, most recent first, with its reason when it gave one. */\n readonly rejected: ReadonlyArray<Rejection>\n /**\n * The server history the cursor points into, once a server named one. A new\n * one means the server was reset: what the replica had committed is gone.\n */\n readonly epoch: Option.Option<string>\n}\n\n/**\n * An operation the server refused, and why, when it said. It carries the\n * operation itself: the replica drops it from the outbox in the same step,\n * so what it changed can be read from here rather than looked up in time.\n */\nexport interface Rejection {\n readonly opId: OpId\n readonly reason: Option.Option<string>\n readonly operation: Operation\n}\n\n/**\n * A consistent status and optimistic-shared pair, read from one replica state.\n * `Replica.changes` emits it so a UI can hold a single subscription.\n */\nexport interface ReplicaSnapshot<Shared> {\n readonly status: ReplicaStatus\n readonly shared: Shared\n /** The server-confirmed state the optimistic `shared` is built on. */\n readonly committed: Shared\n /**\n * The local sequence the next submitted operation takes. Only a successful\n * submit moves it, so a caller that submits one Message at a time can tell\n * from one snapshot whether `shared` already holds it.\n */\n readonly nextLocalSequence: LocalSequence\n}\n\nexport interface Replica<Message, Shared> {\n /** The id this replica's operations carry, one per tab: what its commits are stamped with. */\n readonly replicaId: ReplicaId\n /** The optimistic projection: committed state with pending operations replayed. */\n readonly shared: Effect.Effect<Shared>\n /**\n * The server-confirmed state through `cursor`, with no pending operation\n * applied. A pending edit reaches it only once the server commits it, and a\n * rejected one never does.\n */\n readonly committed: Effect.Effect<Shared>\n readonly pending: Effect.Effect<ReadonlyArray<Operation>>\n readonly cursor: Effect.Effect<Sequence>\n /**\n * Waiting/recovery information without exposing Messages or the Model. It is a\n * snapshot; `statusChanges` re-emits it after every submit and exchange.\n */\n readonly status: Effect.Effect<ReplicaStatus>\n /** The status, re-emitted after every submit and exchange. */\n readonly statusChanges: Stream.Stream<ReplicaStatus>\n /**\n * The status and the optimistic shared value together, re-emitted after every\n * submit and exchange, so a UI can subscribe once instead of to both.\n */\n readonly changes: Stream.Stream<ReplicaSnapshot<Shared>>\n /** The status, `shared`, `committed` and next local sequence, read from one replica state. */\n readonly snapshot: Effect.Effect<ReplicaSnapshot<Shared>>\n /** Records a durable Message in the outbox and applies it optimistically. */\n // A method, so a replica of the durable subset is still a `Replica` of the\n // application's Messages where one is only passed along (`Sync.mount`).\n submit(message: Message): Effect.Effect<void, ReplicaError>\n /** Reconciles against the server. The `Transport` service must be provided. */\n readonly synchronize: Effect.Effect<void, ReplicaError | TransportError, Transport>\n /**\n * The exchange loop: exchanges once, then after every `submit` and every\n * notice on the transport's `changes`, until the replica closes or the fiber\n * is interrupted. A failed exchange is recorded\n * in `status.lastError` and retried on a backoff (from 0.5 s, doubling up to\n * 30 s), or at once on the next `submit`, so the fiber never fails. Fork it\n * with `Effect.forkScoped` and provide `Transport`.\n */\n readonly start: Effect.Effect<void, never, Transport>\n readonly close: Effect.Effect<void>\n}\n\nexport interface SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> {\n readonly documentId: DocumentId\n readonly message: Schema.Codec<Message, MessageEncoded, never, never>\n readonly shared: Schema.Codec<Shared, SharedEncoded, never, never>\n readonly empty: Shared\n readonly durable: (message: Message) => boolean\n readonly replay: (shared: Shared, message: Message) => Shared\n /**\n * Optional. Merges a durable Message into the one submitted before it, while that one\n * has not been sent: one operation instead of two, for a burst of typing. Replaying the\n * result must equal replaying `last` then `next`. Undefined keeps them apart.\n */\n readonly coalesce?: ((last: Message, next: Message) => Message | undefined) | undefined\n /**\n * Optional. Writes what the server's commit decided into a durable Message, on the\n * server only: the journal stores, reduces and sends the stamped Message, so every\n * replica replays the same one in place of what it sent.\n */\n readonly stamp?: ((message: Message, commit: CommitStamp) => Message) | undefined\n}\n\n/**\n * What a commit decided, for `stamp`: the operation's place in the order, who\n * committed it, and from which replica. `actorId` is the principal, shared by\n * every tab a person has open; `replicaId` tells those tabs apart.\n */\nexport interface CommitStamp {\n readonly sequence: number\n readonly actorId: string\n readonly replicaId: string\n}\n\n/**\n * A document's protocol. `Durable` is what a replica's `submit` takes: the\n * durable subset for a contract from `Sync.forApplication(App).make`, every\n * Message for one from `Sync.define`, which checks `durable` when called.\n */\nexport interface Sync<Message, Shared, Durable = Message> {\n readonly documentId: DocumentId\n /** Whether a Message is one the replica records and replays. */\n readonly durable: (message: Message) => boolean\n /**\n * Low-level wire codecs for adapters and the transport. Most applications use\n * `journalContract` and `openReplica`; these are exposed for a custom\n * transport or a server that must speak the operation envelope directly.\n */\n readonly codec: {\n readonly normalizeOperation: (input: unknown) => Operation\n readonly operationFrom: (input: unknown, documentId: DocumentId) => Operation\n readonly committedFrom: (input: unknown, documentId: DocumentId) => CommittedOperation\n readonly decodeExchange: (input: unknown) => Exchange<Shared>\n }\n /** The codecs and pure reducer `foldkit-durable`'s `makeJournal` consumes. */\n readonly journalContract: () => JournalContract<Operation, Shared>\n /**\n * Opens the replica a store holds. Its id is the store's: read back, or minted\n * when the store is empty, so two stores never share one. In a browser the\n * store is `Sync.tabStorage(name)`, one per tab.\n */\n readonly openReplica: (\n storage: Storage,\n options?: OpenReplicaOptions,\n ) => Effect.Effect<Replica<Durable, Shared>, ReplicaError>\n}\n\nexport interface OpenReplicaOptions {\n /**\n * The id the store must hold, for a test asserting operation ids or a replica\n * a server names. It names one store, never a person: operation ids are\n * `replicaId:localSequence`, so two stores under one id (a person's second\n * browser) reuse ids the journal refuses.\n */\n readonly replicaId?: ReplicaId | undefined\n}\n\n/** Structural match for `foldkit-durable`'s journal options; Sync stays independent. */\nexport interface JournalContract<Operation, Shared> {\n /** The replica each operation came from, which Durable binds to its first committer. */\n readonly replicaId: (operation: Operation) => string\n /** Sync's operation id includes the replica, even after Durable compacts its payload. */\n readonly legacyReplicaId: (opId: string) => string\n readonly operation: {\n /** Operations are stored in their encoded form, so this is the identity. */\n readonly encode: (operation: Operation) => Operation\n readonly decode: (input: unknown) => Operation\n }\n readonly snapshot: {\n readonly encode: (snapshot: Shared) => unknown\n readonly decode: (input: unknown) => Shared\n }\n readonly empty: () => Shared\n readonly reduce: (snapshot: Shared, operation: Operation) => Shared\n /** Present when the definition stamps: Durable's `stamp`, over the operation's Message. */\n readonly stamp?: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ) => Operation\n}\n\n/**\n * Binds the replicated-state protocol to one application contract.\n *\n * The returned codecs decide what is a valid operation and what the shared\n * projection means; the replica owns the local outbox, optimistic projection,\n * and reconciliation as Effects, and never runs a second reducer.\n */\nexport const defineSync = <Message, Shared, MessageEncoded, SharedEncoded>(\n definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>,\n): Sync<Message, Shared> => {\n const documentId = definition.documentId\n const decodeMessage = Schema.decodeUnknownSync(definition.message, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(definition.message)\n const decodeShared = Schema.decodeUnknownSync(definition.shared, { onExcessProperty: 'error' })\n const encodeShared = Schema.encodeSync(definition.shared)\n\n const ReplicaStateSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n revision: Schema.Number,\n nextLocalSequence: LocalSequence,\n cursor: Sequence,\n committed: definition.shared,\n committedIds: Schema.Array(Schema.String),\n pending: Schema.Array(OperationSchema),\n epoch: Schema.optionalKey(Schema.NonEmptyString),\n })\n const CheckpointSchema = Schema.Struct({ cursor: Sequence, model: definition.shared })\n const ExchangeSchema = Schema.Struct({\n operations: Schema.Array(Schema.Unknown),\n rejected: Schema.Array(OpId),\n // A server's words for a person, bounded: a reply is not a place for a document.\n reasons: Schema.optional(\n Schema.Array(\n Schema.Struct({ opId: OpId, reason: Schema.String.check(Schema.isMaxLength(500)) }),\n ),\n ),\n acknowledged: Schema.optional(Schema.Array(OpId)),\n checkpoint: Schema.optional(CheckpointSchema),\n more: Schema.optional(Schema.Boolean),\n epoch: Schema.optional(Schema.NonEmptyString),\n })\n const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: 'error' })\n const encodeState = Schema.encodeSync(ReplicaStateSchema)\n const encodeOperation = Schema.encodeSync(OperationSchema)\n const VersionProbe = Schema.Struct({\n protocolVersion: Schema.optional(Schema.Number),\n schemaVersion: Schema.optional(Schema.Number),\n })\n /**\n * Tells a version this build does not understand apart from malformed data,\n * so the caller gets an actionable failure and the stored state is preserved.\n */\n const unsupportedVersion = (input: unknown): UnsupportedReplicaVersionError | undefined => {\n let found: {\n readonly protocolVersion?: number | undefined\n readonly schemaVersion?: number | undefined\n }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.protocolVersion === PROTOCOL_VERSION && found.schemaVersion === SCHEMA_VERSION)\n return undefined\n const protocolVersion = found.protocolVersion ?? null\n const schemaVersion = found.schemaVersion ?? null\n return new UnsupportedReplicaVersionError({\n protocolVersion,\n schemaVersion,\n message: `Stored replica uses protocol ${protocolVersion ?? '?'} / schema ${schemaVersion ?? '?'}; this build supports ${PROTOCOL_VERSION}/${SCHEMA_VERSION}`,\n })\n }\n const decodeExchange = (input: unknown): Exchange<Shared> =>\n Schema.decodeUnknownSync(ExchangeSchema, { onExcessProperty: 'error' })(\n input,\n ) as Exchange<Shared>\n\n const checkIdentity = (operation: Operation): void => {\n // `LocalSequence` already rejects a non-positive counter; this checks the\n // derived identity.\n if (operation.opId !== `${operation.replicaId}:${operation.localSequence}`) {\n throw new Error('Invalid operation identity')\n }\n }\n const decodeDurable = (message: unknown): Message => {\n const decoded = decodeMessage(message)\n if (!definition.durable(decoded)) throw new Error('Message is local-only')\n return decoded\n }\n const shape = <O extends Operation>(operation: O): O => {\n checkIdentity(operation)\n return { ...operation, message: encodeMessage(decodeDurable(operation.message)) }\n }\n const assertDocument = <O extends Operation>(operation: O, key: DocumentId): O => {\n if (operation.documentId !== key) throw new Error('Wrong document')\n return operation\n }\n const normalizeOperation = (input: unknown): Operation => shape(decodeOperation(input))\n const operationFrom = (input: unknown, key: DocumentId): Operation =>\n assertDocument(normalizeOperation(input), key)\n /**\n * A committed operation arrives with its message already encoded, so decode it\n * once for the contract check and hand it to `replay` instead of decoding and\n * re-encoding it on the way through `shape`.\n */\n const decodeCommittedOperation = (\n input: unknown,\n key: DocumentId,\n ): { readonly committed: CommittedOperation; readonly message: Message } => {\n const committed = assertDocument(decodeCommitted(input), key)\n checkIdentity(committed)\n return { committed, message: decodeDurable(committed.message) }\n }\n const committedFrom = (input: unknown, key: DocumentId): CommittedOperation =>\n decodeCommittedOperation(input, key).committed\n\n const journalContract = (): JournalContract<Operation, Shared> => ({\n replicaId: operation => operation.replicaId,\n legacyReplicaId: opId => opId.slice(0, opId.lastIndexOf(':')),\n // Operations are stored in their encoded form: `normalizeOperation` has\n // already encoded the Message and validated the identity.\n operation: { encode: operation => operation, decode: normalizeOperation },\n snapshot: { encode: encodeShared, decode: decodeShared },\n empty: () => definition.empty,\n reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),\n ...(definition.stamp === undefined\n ? {}\n : {\n stamp: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ): Operation => ({\n ...operation,\n message: encodeMessage(\n definition.stamp!(decodeMessage(operation.message), {\n ...commit,\n replicaId: operation.replicaId,\n }),\n ),\n }),\n }),\n })\n\n const optimistic = (state: ReplicaState<Shared>): Shared =>\n state.pending.reduce(\n (model, operation) => definition.replay(model, decodeMessage(operation.message)),\n state.committed,\n )\n\n const openReplica = Effect.fn('Sync.openReplica')(\n function* (storage: Storage, options?: OpenReplicaOptions) {\n const saved = yield* storage.load()\n const initial: ReplicaState<Shared> = {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId: options?.replicaId ?? ReplicaId.make(crypto.randomUUID()),\n revision: 0,\n nextLocalSequence: localSequence(1),\n cursor: sequence(0),\n committed: definition.empty,\n committedIds: [],\n pending: [],\n }\n const state: ReplicaState<Shared> =\n saved === undefined\n ? initial\n : yield* Effect.try({\n try: () => decodeState(saved),\n catch: cause =>\n unsupportedVersion(saved) ??\n new InvalidReplicaHistoryError({\n message: 'Stored replica state is invalid',\n cause,\n }),\n })\n const replicaId = state.replicaId\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n if (\n state.documentId !== documentId ||\n (options?.replicaId !== undefined && replicaId !== options.replicaId)\n )\n return yield* new WrongReplicaStorageError({\n documentId,\n replicaId: options?.replicaId ?? replicaId,\n message: 'The stored replica belongs to a different document or replica',\n })\n const committedIds = new Set(state.committedIds)\n if (state.nextLocalSequence < 1 || committedIds.size !== state.committedIds.length)\n return yield* new InvalidReplicaHistoryError({ message: 'Invalid replica history' })\n const pendingIds = new Set<string>()\n for (const pending of state.pending) {\n const operation = yield* Effect.try({\n try: () => operationFrom(pending, documentId),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n if (\n operation.replicaId !== replicaId ||\n operation.localSequence >= state.nextLocalSequence ||\n committedIds.has(operation.opId) ||\n pendingIds.has(operation.opId)\n )\n return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n pendingIds.add(operation.opId)\n }\n // Storage holds the schema's encoded side, so a transforming `shared`\n // codec round-trips: decode on load, encode before every save. Encoding\n // also rejects an invalid `empty` on first creation rather than at reload.\n const store = Effect.fn('Sync.store')(function* (\n next: ReplicaState<Shared>,\n expectedRevision: number | null,\n ) {\n const encoded = yield* Effect.try({\n try: () => encodeState(next),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the replica state',\n cause,\n }),\n })\n yield* storage.save(encoded, expectedRevision)\n })\n if (saved === undefined) yield* store(state, null)\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n const lastError = yield* Ref.make<string | undefined>(undefined)\n const rejectedOps = yield* Ref.make<ReadonlyArray<Rejection>>([])\n // Operations submitted since opening that no exchange has carried yet. Only these may\n // be coalesced: one that was sent may already be committed as it was.\n const unsent = yield* Ref.make<ReadonlySet<string>>(new Set())\n // One pending wake-up is enough: the loop exchanges the whole outbox.\n const wake = yield* Queue.sliding<void>(1)\n const statusSignals = yield* PubSub.sliding<void>(1)\n // The current value, then again after every change. Subscribed before the\n // first read, so a change made while a subscriber holds that value, or\n // between the read and the subscription, is still told.\n const following = <A>(read: Effect.Effect<A>): Stream.Stream<A> =>\n Stream.unwrap(\n Effect.map(PubSub.subscribe(statusSignals), signals =>\n Stream.concat(\n Stream.fromEffect(read),\n Stream.fromSubscription(signals).pipe(Stream.mapEffect(() => read)),\n ),\n ),\n )\n // The projection is pure over an immutable state, so a cached value is\n // reused until a write replaces the state object. A UI reads `shared` far\n // more often than it writes, and replaying a large outbox per read is\n // quadratic (see `bench/projection.bench.ts`).\n const projection = yield* Ref.make<\n { readonly state: ReplicaState<Shared>; readonly shared: Shared } | undefined\n >(undefined)\n const snapshot = Effect.fn('Sync.snapshot')(function* () {\n const current = yield* SynchronizedRef.get(stateRef)\n const cached = yield* Ref.get(projection)\n let projected: Shared\n if (cached !== undefined && cached.state === current) projected = cached.shared\n else {\n projected = optimistic(current)\n yield* Ref.set(projection, { state: current, shared: projected })\n }\n return {\n status: {\n pending: current.pending.length,\n cursor: current.cursor,\n lastError: yield* Ref.get(lastError),\n rejected: yield* Ref.get(rejectedOps),\n epoch: Option.fromUndefinedOr(current.epoch),\n },\n shared: projected,\n committed: current.committed,\n nextLocalSequence: current.nextLocalSequence,\n }\n })()\n const shared = Effect.map(snapshot, value => value.shared)\n const status = Effect.map(snapshot, value => value.status)\n\n // `SynchronizedRef.modifyEffect` installs the returned state itself, so\n // persisting must not also set the ref (that would re-enter the lock).\n const persist = (next: ReplicaState<Shared>, current: ReplicaState<Shared>) =>\n store(next, current.revision)\n\n const submit = Effect.fn('Sync.submit')(function* (message: Message) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const result = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n if (!definition.durable(message))\n return yield* new InvalidOutboxError({ message: 'Message is local-only' })\n const last = current.pending[current.pending.length - 1]\n const merged =\n last !== undefined &&\n definition.coalesce !== undefined &&\n (yield* Ref.get(unsent)).has(last.opId)\n ? definition.coalesce(decodeMessage(last.message), message)\n : undefined\n if (merged !== undefined && !definition.durable(merged))\n return yield* new InvalidOutboxError({\n message: 'coalesce returned a local-only Message',\n })\n // A merged Message takes the place of the last operation, under its identity.\n const operation = yield* Effect.try({\n try: () =>\n operationFrom(\n merged === undefined\n ? {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n localSequence: current.nextLocalSequence,\n opId: `${replicaId}:${current.nextLocalSequence}`,\n baseCursor: current.cursor,\n message: encodeMessage(message),\n }\n : { ...last!, message: encodeMessage(merged) },\n documentId,\n ),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n // Replay before writing: a Message replay refuses can never be\n // applied, here or on another replica, so it must not reach the\n // outbox. The result is the next optimistic projection, so the\n // cache is seeded instead of replaying the outbox on the next read.\n // Rebuilding the projection replays the outbox, which can throw\n // too (an upgrade that changed `update` for a pending Message), so\n // it sits inside the same typed error as the new Message's replay.\n const cached = yield* Ref.get(projection)\n const replayed = yield* Effect.try({\n try: () =>\n definition.replay(\n cached !== undefined && cached.state === current\n ? cached.shared\n : optimistic(current),\n message,\n ),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n // Validated and encoded by `persist`; decoding here would demand the\n // encoded side and break a transforming `shared` codec.\n // The sequence moves on a merge too, so every submit is visible in it; a gap\n // in local sequences is harmless.\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n nextLocalSequence: localSequence(current.nextLocalSequence + 1),\n pending: [\n ...(merged === undefined ? current.pending : current.pending.slice(0, -1)),\n operation,\n ],\n }\n // Only the new operation is written when the storage can append it.\n if (storage.append === undefined) yield* persist(next, current)\n else {\n const encoded = yield* Effect.try({\n try: () => encodeOperation(operation),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the operation',\n cause,\n }),\n })\n yield* storage.append(\n {\n revision: next.revision,\n nextLocalSequence: next.nextLocalSequence,\n localSequence: operation.localSequence,\n operation: encoded,\n },\n current.revision,\n )\n }\n yield* Ref.set(projection, { state: next, shared: replayed })\n yield* Ref.update(unsent, ids => new Set(ids).add(operation.opId))\n yield* Queue.offer(wake, undefined)\n return [undefined, next] as const\n }),\n )\n // Outside the lock, so a `statusChanges` subscriber reads the new state.\n yield* PubSub.publish(statusSignals, undefined)\n return result\n })\n\n /** One exchange; whether the server has more to send and this one made progress. */\n const exchangeOnce = Effect.fn('Sync.exchange')(function* () {\n yield* Effect.annotateCurrentSpan({ documentId })\n const transport = yield* Transport\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Read under the lock, as a submit writes, so no submit can merge into an operation\n // between its being read here and its being marked sent.\n const sent = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Ref.update(unsent, ids => {\n const left = new Set(ids)\n for (const operation of current.pending) left.delete(operation.opId)\n return left\n }).pipe(Effect.as([current, current] as const)),\n )\n yield* Metric.update(syncMetrics.exchanges, 1)\n yield* Metric.update(syncMetrics.exchangePending, sent.pending.length)\n const response = yield* Effect.gen(function* () {\n const raw = yield* transport.exchange(sent.cursor, sent.pending, sent.epoch)\n // The response is untrusted: a malformed shape is a typed failure, not\n // a defect that escapes the declared error channel.\n return yield* Effect.try({\n try: () => decodeExchange(raw),\n catch: cause =>\n new InvalidExchangeError({ message: 'Invalid sync exchange response', cause }),\n })\n })\n const restarted = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // A `close` during the exchange must not persist its result.\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Another epoch means the server's history is not the one the cursor points\n // into (it was reset): the answer starts from its beginning, so the committed\n // state is rebuilt from it. The outbox is the user's intent and is kept.\n const restarted =\n response.epoch !== undefined &&\n current.epoch !== undefined &&\n response.epoch !== current.epoch\n if (restarted) yield* Diagnostics.report(historyRebuilt(documentId, replicaId))\n let cursor = restarted ? sequence(0) : current.cursor\n let committed = restarted ? definition.empty : current.committed\n // A checkpoint folds committed history into its snapshot, so the\n // retained id set starts over from it, as it does on a new epoch.\n const ids =\n response.checkpoint === undefined && !restarted\n ? new Set(current.committedIds)\n : new Set<string>()\n if (response.checkpoint !== undefined) {\n if (response.checkpoint.cursor < cursor)\n return yield* new CheckpointRegressionError({\n cursor,\n checkpointCursor: response.checkpoint.cursor,\n message: 'Checkpoint is behind the replica',\n })\n committed = response.checkpoint.model\n cursor = response.checkpoint.cursor\n yield* Metric.update(syncMetrics.checkpoints, 1)\n yield* Effect.logDebug('sync checkpoint adopted', { documentId, replicaId, cursor })\n }\n const acknowledged = new Set(response.acknowledged ?? [])\n const rejected = new Set(response.rejected)\n const sentIds = new Set(sent.pending.map(operation => operation.opId))\n for (const id of acknowledged)\n if (!sentIds.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server acknowledged an operation that was not sent',\n })\n for (const id of rejected) {\n if (!sentIds.has(id))\n return yield* new ForeignRejectionError({\n opId: id,\n message: 'Server rejected an operation that was not sent',\n })\n // An id cannot be both; removal would be ambiguous and a faulty\n // server must not be able to make a pending operation vanish.\n if (acknowledged.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server both acknowledged and rejected an operation',\n })\n }\n for (const { opId } of response.reasons ?? [])\n if (!rejected.has(opId))\n return yield* new ForeignRejectionError({\n opId,\n message: 'Server gave a reason for an operation it did not reject',\n })\n let applied = 0\n for (const raw of response.operations) {\n const { committed: operation, message } = yield* Effect.try({\n try: () => decodeCommittedOperation(raw, documentId),\n catch: cause =>\n new InvalidReplicaHistoryError({ message: 'Invalid committed operation', cause }),\n })\n if (operation.serverSequence <= cursor) continue\n if (operation.serverSequence !== cursor + 1 || ids.has(operation.opId))\n return yield* new CommittedOrderError({\n expected: cursor + 1,\n actual: operation.serverSequence,\n message: 'Invalid committed order',\n })\n // A throw here would be a defect, which bypasses `lastError` and leaves\n // `start` retrying the same page in silence.\n const replaying = committed\n committed = yield* Effect.try({\n try: () => definition.replay(replaying, message),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n ids.add(operation.opId)\n cursor = operation.serverSequence\n applied += 1\n }\n if (applied > 0) yield* Metric.update(syncMetrics.applied, applied)\n // Validated and encoded by `persist`, for the same reason as submit.\n const epoch = response.epoch ?? current.epoch\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n committed,\n cursor,\n ...(epoch === undefined ? {} : { epoch }),\n committedIds: [...ids].slice(-COMMITTED_ID_WINDOW),\n // While the server has more to send, an acknowledged operation's committed\n // copy may be on a later page, so it stays in the optimistic view until then.\n // An acknowledged operation the replica is already past (committed before a\n // checkpoint, say) never arrives, so it goes once there is no more to read.\n pending: current.pending.filter(\n operation =>\n !ids.has(operation.opId) &&\n !(acknowledged.has(operation.opId) && response.more !== true) &&\n !rejected.has(operation.opId),\n ),\n }\n yield* persist(next, current)\n return [restarted, next] as const\n }),\n )\n yield* Ref.set(lastError, undefined)\n if (response.rejected.length > 0) {\n const reasonOf = new Map(\n (response.reasons ?? []).map(({ opId, reason }) => [opId, reason] as const),\n )\n // Every rejected id was sent: an unknown one failed the exchange above.\n const sentOf = new Map(\n sent.pending.map(operation => [operation.opId, operation] as const),\n )\n const refused = response.rejected.map((opId): Rejection => ({\n opId,\n reason: Option.fromUndefinedOr(reasonOf.get(opId)),\n operation: sentOf.get(opId)!,\n }))\n yield* Ref.update(rejectedOps, previous => [...refused, ...previous].slice(0, 32))\n }\n yield* PubSub.publish(statusSignals, undefined)\n const reached = (yield* SynchronizedRef.get(stateRef)).cursor\n return response.more === true && reached > (restarted ? 0 : sent.cursor)\n })\n\n // A server that pages its answer says there is more, and the replica asks again at\n // once; a round that moves the cursor nowhere ends it.\n const synchronize = Effect.gen(function* () {\n while (yield* exchangeOnce()) {}\n }).pipe(\n Effect.withSpan('Sync.synchronize'),\n // Any failed exchange, a refused response included, is what a UI shows,\n // so it is recorded and announced rather than left for the next submit.\n Effect.tapError(error =>\n Effect.gen(function* () {\n yield* Diagnostics.report(exchangeFailed(documentId, replicaId, error))\n yield* Ref.set(lastError, error.message)\n yield* PubSub.publish(statusSignals, undefined)\n }),\n ),\n )\n\n const start: Effect.Effect<void, never, Transport> = Effect.gen(function* () {\n const transport = yield* Transport\n // A server's notice wakes the loop as a submit does; the fiber ends with this one.\n // It starts at once so it is subscribed before the first exchange, which a\n // notice may arrive during.\n if (transport.changes !== undefined)\n yield* Effect.forkChild(\n Stream.runForEach(transport.changes, () => Queue.offer(wake, undefined)),\n { startImmediately: true },\n )\n let failures = 0\n while (!(yield* Ref.get(closed))) {\n const exit = yield* Effect.exit(synchronize)\n if (yield* Ref.get(closed)) return\n if (exit._tag === 'Success') {\n failures = 0\n yield* Queue.take(wake)\n } else {\n // Retried on a backoff, or sooner on a submit: an outbox must not\n // wait for the next keystroke to be delivered.\n failures += 1\n const backoff = Math.min(\n START_RETRY_MAX,\n START_RETRY_BASE * 2 ** Math.min(failures - 1, 16),\n )\n yield* Effect.raceFirst(Queue.take(wake), Effect.sleep(backoff))\n }\n }\n })\n\n return {\n replicaId,\n shared,\n snapshot,\n committed: Effect.map(SynchronizedRef.get(stateRef), state => state.committed),\n pending: Effect.map(SynchronizedRef.get(stateRef), state => state.pending),\n cursor: Effect.map(SynchronizedRef.get(stateRef), state => state.cursor),\n status,\n statusChanges: following(status),\n changes: following(snapshot),\n submit,\n synchronize,\n start,\n close: Effect.fn('Sync.close')(function* () {\n yield* Ref.set(closed, true)\n // Wake `start` so it can observe `closed` and return.\n yield* Queue.offer(wake, undefined)\n yield* storage.close\n })(),\n }\n },\n (effect, storage) =>\n // Close a partially initialized storage on any failure, including a\n // defect, so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : storage.close.pipe(Effect.ignore),\n ),\n ),\n )\n\n return {\n documentId,\n durable: definition.durable,\n codec: { normalizeOperation, operationFrom, committedFrom, decodeExchange },\n journalContract,\n openReplica,\n }\n}\n"],"mappings":";;;;;;;;AAyCA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;AAGvB,MAAM,kBAAkB,OAAO,OAAO;CACpC,iBAAiB,OAAO,QAAQ,gBAAgB;CAChD,eAAe,OAAO,QAAQ,cAAc;CAC5C,YAAY;CACZ,WAAW;CACX,eAAe;CACf,MAAM;CACN,YAAY;CACZ,SAAS,OAAO;AAClB,CAAC;;AAID,MAAM,kBAAkB,OAAO,OAAO;CACpC,GAAG,gBAAgB;CACnB,gBAAgB,SAAS,MAAM,OAAO,uBAAuB,CAAC,CAAC;CAC/D,SAAS,OAAO;AAClB,CAAC;AAID,MAAM,kBAAkB,OAAO,kBAAkB,iBAAiB,EAAE,kBAAkB,QAAQ,CAAC;AAC/F,MAAM,kBAAkB,OAAO,kBAAkB,iBAAiB,EAAE,kBAAkB,QAAQ,CAAC;;AAU/F,MAAM,mBAAmB;AACzB,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