foldkit-sync 0.12.4 → 0.14.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 +77 -25
- 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} +4 -11
- package/dist/remote.d.ts.map +1 -0
- package/dist/{remote.mjs → remote.js} +8 -7
- 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 +25 -25
- 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/index.mjs
DELETED
|
@@ -1,1613 +0,0 @@
|
|
|
1
|
-
import { _ as localSequence, a as layerSocket, b as sequence, c as serveSocket, d as DocumentId, f as LocalSequence, g as documentId, h as Sequence, i as layerLoopback, l as toPromise, m as ReplicaId, n as TransportError, o as nativeSocket, p as OpId, r as layerFromPromise, s as portSocket, t as Transport, u as workerSocket, v as opId, y as replicaId } from "./transport-BZ6utYmB.mjs";
|
|
2
|
-
import { Clock, Duration, Effect, Equal, Exit, Fiber, Metric, Option, Predicate, PubSub, Queue, Ref, Schema, Stream, SynchronizedRef } from "effect";
|
|
3
|
-
import { MessageSet, Projection, Surface } from "foldkit-surface";
|
|
4
|
-
import { absurd } from "effect/Function";
|
|
5
|
-
import * as Navigation from "foldkit/navigation";
|
|
6
|
-
import * as Port from "foldkit/port";
|
|
7
|
-
import * as Runtime from "foldkit/runtime";
|
|
8
|
-
import * as Subscription from "foldkit/subscription";
|
|
9
|
-
import * as Url from "foldkit/url";
|
|
10
|
-
// src/errors.ts
|
|
11
|
-
/** The persisted storage could not be read or written. */
|
|
12
|
-
var StorageError = class extends Schema.TaggedError()("StorageError", {
|
|
13
|
-
message: Schema.String,
|
|
14
|
-
cause: Schema.optional(Schema.Unknown)
|
|
15
|
-
}) {};
|
|
16
|
-
/** The stored clock state targets a schema version this build does not support. */
|
|
17
|
-
var UnsupportedClockVersionError = class extends Schema.TaggedError()("UnsupportedClockVersionError", {
|
|
18
|
-
schemaVersion: Schema.NullOr(Schema.Number),
|
|
19
|
-
message: Schema.String
|
|
20
|
-
}) {};
|
|
21
|
-
/** The storage holds a different replica's state. */
|
|
22
|
-
var WrongReplicaStorageError = class extends Schema.TaggedError()("WrongReplicaStorageError", {
|
|
23
|
-
documentId: Schema.String,
|
|
24
|
-
replicaId: Schema.String,
|
|
25
|
-
message: Schema.String
|
|
26
|
-
}) {};
|
|
27
|
-
/** The persisted replica history is internally inconsistent. */
|
|
28
|
-
var InvalidReplicaHistoryError = class extends Schema.TaggedError()("InvalidReplicaHistoryError", {
|
|
29
|
-
message: Schema.String,
|
|
30
|
-
cause: Schema.optional(Schema.Unknown)
|
|
31
|
-
}) {};
|
|
32
|
-
/** The server's exchange response did not match the protocol schema. */
|
|
33
|
-
var InvalidExchangeError = class extends Schema.TaggedError()("InvalidExchangeError", {
|
|
34
|
-
message: Schema.String,
|
|
35
|
-
cause: Schema.optional(Schema.Unknown)
|
|
36
|
-
}) {};
|
|
37
|
-
/** A persisted pending operation could not have been produced by this replica. */
|
|
38
|
-
var InvalidOutboxError = class extends Schema.TaggedError()("InvalidOutboxError", { message: Schema.String }) {};
|
|
39
|
-
/** The server sent a checkpoint older than the replica's cursor. */
|
|
40
|
-
var CheckpointRegressionError = class extends Schema.TaggedError()("CheckpointRegressionError", {
|
|
41
|
-
cursor: Schema.Number,
|
|
42
|
-
checkpointCursor: Schema.Number,
|
|
43
|
-
message: Schema.String
|
|
44
|
-
}) {};
|
|
45
|
-
/** Committed operations were not contiguous from the replica's cursor. */
|
|
46
|
-
var CommittedOrderError = class extends Schema.TaggedError()("CommittedOrderError", {
|
|
47
|
-
expected: Schema.Number,
|
|
48
|
-
actual: Schema.Number,
|
|
49
|
-
message: Schema.String
|
|
50
|
-
}) {};
|
|
51
|
-
/** The server rejected an operation the replica never sent. */
|
|
52
|
-
var ForeignRejectionError = class extends Schema.TaggedError()("ForeignRejectionError", {
|
|
53
|
-
opId: Schema.String,
|
|
54
|
-
message: Schema.String
|
|
55
|
-
}) {};
|
|
56
|
-
/**
|
|
57
|
-
* The server answered an operation this request never sent, or both
|
|
58
|
-
* acknowledged and rejected it. Acting on either would let a faulty or hostile
|
|
59
|
-
* server delete local work.
|
|
60
|
-
*/
|
|
61
|
-
var ForeignAcknowledgementError = class extends Schema.TaggedError()("ForeignAcknowledgementError", {
|
|
62
|
-
opId: Schema.String,
|
|
63
|
-
message: Schema.String
|
|
64
|
-
}) {};
|
|
65
|
-
/** The replica was closed while work was still being submitted. */
|
|
66
|
-
var ReplicaClosedError = class extends Schema.TaggedError()("ReplicaClosedError", { message: Schema.String }) {};
|
|
67
|
-
/** The stored replica state targets a protocol or schema version this build does not support. */
|
|
68
|
-
var UnsupportedReplicaVersionError = class extends Schema.TaggedError()("UnsupportedReplicaVersionError", {
|
|
69
|
-
protocolVersion: Schema.NullOr(Schema.Number),
|
|
70
|
-
schemaVersion: Schema.NullOr(Schema.Number),
|
|
71
|
-
message: Schema.String
|
|
72
|
-
}) {};
|
|
73
|
-
/**
|
|
74
|
-
* `replay` threw for a submitted Message, so it could never be applied here or
|
|
75
|
-
* on any other replica; nothing was written.
|
|
76
|
-
*/
|
|
77
|
-
var ReplayError = class extends Schema.TaggedError()("ReplayError", {
|
|
78
|
-
message: Schema.String,
|
|
79
|
-
cause: Schema.optional(Schema.Unknown)
|
|
80
|
-
}) {};
|
|
81
|
-
// src/indexedDb.ts
|
|
82
|
-
const storageError = (message, cause) => new StorageError({
|
|
83
|
-
message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
84
|
-
cause
|
|
85
|
-
});
|
|
86
|
-
const openDatabase = (name, factory) => Effect.tryPromise({
|
|
87
|
-
try: () => new Promise((resolve, reject) => {
|
|
88
|
-
const request = factory.open(name, 2);
|
|
89
|
-
request.onupgradeneeded = (event) => {
|
|
90
|
-
const database = request.result;
|
|
91
|
-
if (event.oldVersion < 1) database.createObjectStore("replica");
|
|
92
|
-
if (event.oldVersion < 2) database.createObjectStore("outbox");
|
|
93
|
-
};
|
|
94
|
-
let blocked = false;
|
|
95
|
-
request.onsuccess = () => blocked ? request.result.close() : resolve(request.result);
|
|
96
|
-
request.onerror = () => reject(request.error);
|
|
97
|
-
request.onblocked = () => {
|
|
98
|
-
blocked = true;
|
|
99
|
-
reject(/* @__PURE__ */ new Error("IndexedDB upgrade is blocked by another connection"));
|
|
100
|
-
};
|
|
101
|
-
}),
|
|
102
|
-
catch: (cause) => storageError("Could not open the storage", cause)
|
|
103
|
-
});
|
|
104
|
-
/** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */
|
|
105
|
-
const indexedDb = Effect.fn("Storage.indexedDb")(function* (name, factory = globalThis.indexedDB) {
|
|
106
|
-
const databaseName = typeof name === "string" ? name : yield* name.pipe(Effect.catchTag("ConfigError", (cause) => Effect.fail(storageError("Could not read the storage name", cause))));
|
|
107
|
-
const database = yield* Effect.acquireRelease(openDatabase(databaseName, factory), (database) => Effect.sync(() => database.close()));
|
|
108
|
-
database.onversionchange = () => database.close();
|
|
109
|
-
/**
|
|
110
|
-
* Writes under compare-and-swap: `write` runs only if the stored revision is the one
|
|
111
|
-
* expected. The revision is its own key, so an append need not read the state; a database
|
|
112
|
-
* written before it existed has it inside the state.
|
|
113
|
-
*/
|
|
114
|
-
const write = (expectedRevision, writing) => new Promise((resolve, reject) => {
|
|
115
|
-
const transaction = database.transaction(["replica", "outbox"], "readwrite", { durability: "strict" });
|
|
116
|
-
const replica = transaction.objectStore("replica");
|
|
117
|
-
let conflict = false;
|
|
118
|
-
const check = (revision) => {
|
|
119
|
-
if (revision !== expectedRevision) {
|
|
120
|
-
conflict = true;
|
|
121
|
-
transaction.abort();
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
writing(replica, transaction.objectStore("outbox"));
|
|
125
|
-
};
|
|
126
|
-
const stored = replica.get("revision");
|
|
127
|
-
stored.onsuccess = () => {
|
|
128
|
-
if (stored.result !== void 0) return check(stored.result);
|
|
129
|
-
const state = replica.get("state");
|
|
130
|
-
state.onsuccess = () => check(state.result?.revision ?? null);
|
|
131
|
-
};
|
|
132
|
-
transaction.oncomplete = () => resolve();
|
|
133
|
-
transaction.onabort = () => reject(conflict ? /* @__PURE__ */ new Error("Replica was changed by another writer") : transaction.error ?? /* @__PURE__ */ new Error("IndexedDB write aborted"));
|
|
134
|
-
});
|
|
135
|
-
return {
|
|
136
|
-
load: () => Effect.tryPromise({
|
|
137
|
-
try: () => new Promise((resolve, reject) => {
|
|
138
|
-
const transaction = database.transaction(["replica", "outbox"], "readonly");
|
|
139
|
-
const state = transaction.objectStore("replica").get("state");
|
|
140
|
-
const appended = transaction.objectStore("outbox").getAll();
|
|
141
|
-
transaction.oncomplete = () => {
|
|
142
|
-
const saved = state.result;
|
|
143
|
-
const entries = appended.result;
|
|
144
|
-
const latest = entries[entries.length - 1];
|
|
145
|
-
const replaced = new Set(entries.map((entry) => entry.localSequence));
|
|
146
|
-
resolve(saved === void 0 || latest === void 0 ? saved : {
|
|
147
|
-
...saved,
|
|
148
|
-
revision: latest.revision,
|
|
149
|
-
nextLocalSequence: latest.nextLocalSequence,
|
|
150
|
-
pending: [...saved.pending.filter((operation) => !replaced.has(operation.localSequence)), ...entries.map((entry) => entry.operation)]
|
|
151
|
-
});
|
|
152
|
-
};
|
|
153
|
-
transaction.onabort = () => reject(transaction.error ?? /* @__PURE__ */ new Error("IndexedDB read aborted"));
|
|
154
|
-
}),
|
|
155
|
-
catch: (cause) => storageError("Could not read the replica", cause)
|
|
156
|
-
}),
|
|
157
|
-
save: (state, expectedRevision) => Effect.tryPromise({
|
|
158
|
-
try: () => write(expectedRevision, (replica, outbox) => {
|
|
159
|
-
replica.put(state, "state");
|
|
160
|
-
replica.put(state.revision, "revision");
|
|
161
|
-
outbox.clear();
|
|
162
|
-
}),
|
|
163
|
-
catch: (cause) => storageError("Could not save the replica", cause)
|
|
164
|
-
}),
|
|
165
|
-
append: (entry, expectedRevision) => Effect.tryPromise({
|
|
166
|
-
try: () => write(expectedRevision, (replica, outbox) => {
|
|
167
|
-
outbox.put(entry, entry.localSequence);
|
|
168
|
-
replica.put(entry.revision, "revision");
|
|
169
|
-
}),
|
|
170
|
-
catch: (cause) => storageError("Could not save the replica", cause)
|
|
171
|
-
}),
|
|
172
|
-
close: Effect.sync(() => database.close())
|
|
173
|
-
};
|
|
174
|
-
});
|
|
175
|
-
// src/lww.ts
|
|
176
|
-
/** A logical write time; replica ids break concurrent ties using UTF-16 order. */
|
|
177
|
-
const Stamp = Schema.Struct({
|
|
178
|
-
counter: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)),
|
|
179
|
-
replicaId: ReplicaId
|
|
180
|
-
});
|
|
181
|
-
/** The persisted clock format. A bump must handle the older value explicitly. */
|
|
182
|
-
const CLOCK_SCHEMA_VERSION = 1;
|
|
183
|
-
const ClockState = Schema.Struct({
|
|
184
|
-
schemaVersion: Schema.Literal(CLOCK_SCHEMA_VERSION),
|
|
185
|
-
documentId: DocumentId,
|
|
186
|
-
replicaId: ReplicaId,
|
|
187
|
-
revision: Stamp.fields.counter
|
|
188
|
-
});
|
|
189
|
-
const decodeClock = Schema.decodeUnknownSync(ClockState, { onExcessProperty: "error" });
|
|
190
|
-
const decodeCounter = Schema.decodeUnknownSync(Stamp.fields.counter);
|
|
191
|
-
const clockError = (message, cause) => new StorageError({
|
|
192
|
-
message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
193
|
-
cause
|
|
194
|
-
});
|
|
195
|
-
const VersionProbe = Schema.Struct({ schemaVersion: Schema.optional(Schema.Number) });
|
|
196
|
-
/**
|
|
197
|
-
* Tells a version this build does not understand apart from malformed data, so
|
|
198
|
-
* the caller gets an actionable failure and the stored state is preserved.
|
|
199
|
-
*/
|
|
200
|
-
const unsupportedVersion = (input) => {
|
|
201
|
-
let found;
|
|
202
|
-
try {
|
|
203
|
-
found = Schema.decodeUnknownSync(VersionProbe)(input);
|
|
204
|
-
} catch {
|
|
205
|
-
return;
|
|
206
|
-
}
|
|
207
|
-
if (found.schemaVersion === CLOCK_SCHEMA_VERSION) return void 0;
|
|
208
|
-
return new UnsupportedClockVersionError({
|
|
209
|
-
schemaVersion: found.schemaVersion ?? null,
|
|
210
|
-
message: `Stored clock uses schema ${found.schemaVersion ?? "?"}; this build supports ${CLOCK_SCHEMA_VERSION}`
|
|
211
|
-
});
|
|
212
|
-
};
|
|
213
|
-
/**
|
|
214
|
-
* Opens a durable clock over the caller's storage.
|
|
215
|
-
*
|
|
216
|
-
* Allocations are serialized through a `SynchronizedRef` and each persists before
|
|
217
|
-
* its stamp is returned. A crash after the save may skip a timestamp but never
|
|
218
|
-
* reuse one. Storage is owned by the caller; a failed open closes it so a partial
|
|
219
|
-
* initialization does not leak the connection.
|
|
220
|
-
*/
|
|
221
|
-
const openLwwClock = Effect.fn("Lww.openClock")(function* (options) {
|
|
222
|
-
const { documentId, replicaId, storage } = options;
|
|
223
|
-
yield* Effect.annotateCurrentSpan({
|
|
224
|
-
documentId,
|
|
225
|
-
replicaId
|
|
226
|
-
});
|
|
227
|
-
const initial = decodeClock({
|
|
228
|
-
schemaVersion: CLOCK_SCHEMA_VERSION,
|
|
229
|
-
documentId,
|
|
230
|
-
replicaId,
|
|
231
|
-
revision: 0
|
|
232
|
-
});
|
|
233
|
-
const saved = yield* storage.load();
|
|
234
|
-
const state = yield* Effect.try({
|
|
235
|
-
try: () => saved === void 0 ? initial : decodeClock(saved),
|
|
236
|
-
catch: (cause) => unsupportedVersion(saved) ?? clockError("Stored clock state is invalid", cause)
|
|
237
|
-
});
|
|
238
|
-
if (state.documentId !== documentId || state.replicaId !== replicaId) return yield* new StorageError({ message: "Wrong clock storage" });
|
|
239
|
-
if (saved === void 0) yield* storage.save(state, null);
|
|
240
|
-
const stateRef = yield* SynchronizedRef.make(state);
|
|
241
|
-
const closed = yield* Ref.make(false);
|
|
242
|
-
return {
|
|
243
|
-
next: Effect.fn("Lww.next")(function* (observedCounter = 0) {
|
|
244
|
-
if (yield* Ref.get(closed)) return yield* new StorageError({ message: "Clock is closed" });
|
|
245
|
-
return yield* SynchronizedRef.modifyEffect(stateRef, (current) => Effect.gen(function* () {
|
|
246
|
-
if (yield* Ref.get(closed)) return yield* new StorageError({ message: "Clock is closed" });
|
|
247
|
-
const allocated = yield* Effect.try({
|
|
248
|
-
try: () => decodeClock({
|
|
249
|
-
...current,
|
|
250
|
-
revision: Math.max(current.revision, decodeCounter(observedCounter)) + 1
|
|
251
|
-
}),
|
|
252
|
-
catch: (cause) => clockError("Invalid clock allocation", cause)
|
|
253
|
-
});
|
|
254
|
-
yield* storage.save(allocated, current.revision);
|
|
255
|
-
return [{
|
|
256
|
-
counter: allocated.revision,
|
|
257
|
-
replicaId
|
|
258
|
-
}, allocated];
|
|
259
|
-
}));
|
|
260
|
-
}),
|
|
261
|
-
close: Effect.fn("Lww.close")(function* () {
|
|
262
|
-
if (yield* Ref.modify(closed, (current) => [current, true])) return;
|
|
263
|
-
yield* SynchronizedRef.modifyEffect(stateRef, (current) => Effect.succeed([void 0, current]));
|
|
264
|
-
yield* storage.close;
|
|
265
|
-
})()
|
|
266
|
-
};
|
|
267
|
-
}, (effect, options) => effect.pipe(Effect.onExit((exit) => Exit.isSuccess(exit) ? Effect.void : options.storage.close.pipe(Effect.ignore))));
|
|
268
|
-
/**
|
|
269
|
-
* A schema and reducer helper for a last-writer-wins register.
|
|
270
|
-
* Allocate a unique stamp per write before dispatch, and retain it in the Message.
|
|
271
|
-
* Merge is for decoded values; the application's schema validates wire input.
|
|
272
|
-
*/
|
|
273
|
-
const lwwRegister = (value) => {
|
|
274
|
-
const schema = Schema.Struct({
|
|
275
|
-
stamp: Stamp,
|
|
276
|
-
value
|
|
277
|
-
});
|
|
278
|
-
const equivalent = Schema.toEquivalence(value);
|
|
279
|
-
const merge = (left, right) => {
|
|
280
|
-
if (left.stamp.counter !== right.stamp.counter) return left.stamp.counter > right.stamp.counter ? left : right;
|
|
281
|
-
if (left.stamp.replicaId !== right.stamp.replicaId) return left.stamp.replicaId > right.stamp.replicaId ? left : right;
|
|
282
|
-
if (!equivalent(left.value, right.value)) throw new Error("Conflicting LWW write identity");
|
|
283
|
-
return left;
|
|
284
|
-
};
|
|
285
|
-
return {
|
|
286
|
-
schema,
|
|
287
|
-
merge
|
|
288
|
-
};
|
|
289
|
-
};
|
|
290
|
-
// src/sync.ts
|
|
291
|
-
/** Wire and persisted-format versions. A bump must handle the older value explicitly. */
|
|
292
|
-
const PROTOCOL_VERSION = 1;
|
|
293
|
-
const SCHEMA_VERSION = 1;
|
|
294
|
-
/** A client-authored operation envelope. `message` is the application's encoded Message. */
|
|
295
|
-
const OperationSchema = Schema.Struct({
|
|
296
|
-
protocolVersion: Schema.Literal(PROTOCOL_VERSION),
|
|
297
|
-
schemaVersion: Schema.Literal(SCHEMA_VERSION),
|
|
298
|
-
documentId: DocumentId,
|
|
299
|
-
replicaId: ReplicaId,
|
|
300
|
-
localSequence: LocalSequence,
|
|
301
|
-
opId: OpId,
|
|
302
|
-
baseCursor: Sequence,
|
|
303
|
-
message: Schema.Unknown
|
|
304
|
-
});
|
|
305
|
-
/** An operation the server committed, with its authoritative order and actor. */
|
|
306
|
-
const CommittedSchema = Schema.Struct({
|
|
307
|
-
...OperationSchema.fields,
|
|
308
|
-
serverSequence: Sequence.check(Schema.isGreaterThanOrEqualTo(1)),
|
|
309
|
-
actorId: Schema.NonEmptyString
|
|
310
|
-
});
|
|
311
|
-
const decodeOperation = Schema.decodeUnknownSync(OperationSchema, { onExcessProperty: "error" });
|
|
312
|
-
const decodeCommitted = Schema.decodeUnknownSync(CommittedSchema, { onExcessProperty: "error" });
|
|
313
|
-
/** How long `start` waits after a failed exchange: doubling from the base, up to the cap, in ms. */
|
|
314
|
-
const START_RETRY_BASE = 500;
|
|
315
|
-
const START_RETRY_MAX = 3e4;
|
|
316
|
-
/** Counters and a histogram an application can scrape. */
|
|
317
|
-
const syncMetrics = {
|
|
318
|
-
exchanges: Metric.counter("foldkit_sync_exchanges_total"),
|
|
319
|
-
applied: Metric.counter("foldkit_sync_commits_applied_total"),
|
|
320
|
-
checkpoints: Metric.counter("foldkit_sync_checkpoints_adopted_total"),
|
|
321
|
-
exchangePending: Metric.histogram("foldkit_sync_exchange_pending", { boundaries: [
|
|
322
|
-
1,
|
|
323
|
-
4,
|
|
324
|
-
16,
|
|
325
|
-
64,
|
|
326
|
-
256,
|
|
327
|
-
1024
|
|
328
|
-
] })
|
|
329
|
-
};
|
|
330
|
-
/**
|
|
331
|
-
* Binds the replicated-state protocol to one application contract.
|
|
332
|
-
*
|
|
333
|
-
* The returned codecs decide what is a valid operation and what the shared
|
|
334
|
-
* projection means; the replica owns the local outbox, optimistic projection,
|
|
335
|
-
* and reconciliation as Effects, and never runs a second reducer.
|
|
336
|
-
*/
|
|
337
|
-
const defineSync = (definition) => {
|
|
338
|
-
const documentId = definition.documentId;
|
|
339
|
-
const decodeMessage = Schema.decodeUnknownSync(definition.message, { onExcessProperty: "error" });
|
|
340
|
-
const encodeMessage = Schema.encodeSync(definition.message);
|
|
341
|
-
const decodeShared = Schema.decodeUnknownSync(definition.shared, { onExcessProperty: "error" });
|
|
342
|
-
const encodeShared = Schema.encodeSync(definition.shared);
|
|
343
|
-
const ReplicaStateSchema = Schema.Struct({
|
|
344
|
-
protocolVersion: Schema.Literal(PROTOCOL_VERSION),
|
|
345
|
-
schemaVersion: Schema.Literal(SCHEMA_VERSION),
|
|
346
|
-
documentId: DocumentId,
|
|
347
|
-
replicaId: ReplicaId,
|
|
348
|
-
revision: Schema.Number,
|
|
349
|
-
nextLocalSequence: LocalSequence,
|
|
350
|
-
cursor: Sequence,
|
|
351
|
-
committed: definition.shared,
|
|
352
|
-
committedIds: Schema.Array(Schema.String),
|
|
353
|
-
pending: Schema.Array(OperationSchema),
|
|
354
|
-
epoch: Schema.optionalKey(Schema.NonEmptyString)
|
|
355
|
-
});
|
|
356
|
-
const CheckpointSchema = Schema.Struct({
|
|
357
|
-
cursor: Sequence,
|
|
358
|
-
model: definition.shared
|
|
359
|
-
});
|
|
360
|
-
const ExchangeSchema = Schema.Struct({
|
|
361
|
-
operations: Schema.Array(Schema.Unknown),
|
|
362
|
-
rejected: Schema.Array(OpId),
|
|
363
|
-
reasons: Schema.optional(Schema.Array(Schema.Struct({
|
|
364
|
-
opId: OpId,
|
|
365
|
-
reason: Schema.String.check(Schema.isMaxLength(500))
|
|
366
|
-
}))),
|
|
367
|
-
acknowledged: Schema.optional(Schema.Array(OpId)),
|
|
368
|
-
checkpoint: Schema.optional(CheckpointSchema),
|
|
369
|
-
more: Schema.optional(Schema.Boolean),
|
|
370
|
-
epoch: Schema.optional(Schema.NonEmptyString)
|
|
371
|
-
});
|
|
372
|
-
const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: "error" });
|
|
373
|
-
const encodeState = Schema.encodeSync(ReplicaStateSchema);
|
|
374
|
-
const encodeOperation = Schema.encodeSync(OperationSchema);
|
|
375
|
-
const VersionProbe = Schema.Struct({
|
|
376
|
-
protocolVersion: Schema.optional(Schema.Number),
|
|
377
|
-
schemaVersion: Schema.optional(Schema.Number)
|
|
378
|
-
});
|
|
379
|
-
/**
|
|
380
|
-
* Tells a version this build does not understand apart from malformed data,
|
|
381
|
-
* so the caller gets an actionable failure and the stored state is preserved.
|
|
382
|
-
*/
|
|
383
|
-
const unsupportedVersion = (input) => {
|
|
384
|
-
let found;
|
|
385
|
-
try {
|
|
386
|
-
found = Schema.decodeUnknownSync(VersionProbe)(input);
|
|
387
|
-
} catch {
|
|
388
|
-
return;
|
|
389
|
-
}
|
|
390
|
-
if (found.protocolVersion === PROTOCOL_VERSION && found.schemaVersion === SCHEMA_VERSION) return void 0;
|
|
391
|
-
const protocolVersion = found.protocolVersion ?? null;
|
|
392
|
-
const schemaVersion = found.schemaVersion ?? null;
|
|
393
|
-
return new UnsupportedReplicaVersionError({
|
|
394
|
-
protocolVersion,
|
|
395
|
-
schemaVersion,
|
|
396
|
-
message: `Stored replica uses protocol ${protocolVersion ?? "?"} / schema ${schemaVersion ?? "?"}; this build supports ${PROTOCOL_VERSION}/${SCHEMA_VERSION}`
|
|
397
|
-
});
|
|
398
|
-
};
|
|
399
|
-
const decodeExchange = (input) => Schema.decodeUnknownSync(ExchangeSchema, { onExcessProperty: "error" })(input);
|
|
400
|
-
const checkIdentity = (operation) => {
|
|
401
|
-
if (operation.opId !== `${operation.replicaId}:${operation.localSequence}`) throw new Error("Invalid operation identity");
|
|
402
|
-
};
|
|
403
|
-
const decodeDurable = (message) => {
|
|
404
|
-
const decoded = decodeMessage(message);
|
|
405
|
-
if (!definition.durable(decoded)) throw new Error("Message is local-only");
|
|
406
|
-
return decoded;
|
|
407
|
-
};
|
|
408
|
-
const shape = (operation) => {
|
|
409
|
-
checkIdentity(operation);
|
|
410
|
-
return {
|
|
411
|
-
...operation,
|
|
412
|
-
message: encodeMessage(decodeDurable(operation.message))
|
|
413
|
-
};
|
|
414
|
-
};
|
|
415
|
-
const assertDocument = (operation, key) => {
|
|
416
|
-
if (operation.documentId !== key) throw new Error("Wrong document");
|
|
417
|
-
return operation;
|
|
418
|
-
};
|
|
419
|
-
const normalizeOperation = (input) => shape(decodeOperation(input));
|
|
420
|
-
const operationFrom = (input, key) => assertDocument(normalizeOperation(input), key);
|
|
421
|
-
/**
|
|
422
|
-
* A committed operation arrives with its message already encoded, so decode it
|
|
423
|
-
* once for the contract check and hand it to `replay` instead of decoding and
|
|
424
|
-
* re-encoding it on the way through `shape`.
|
|
425
|
-
*/
|
|
426
|
-
const decodeCommittedOperation = (input, key) => {
|
|
427
|
-
const committed = assertDocument(decodeCommitted(input), key);
|
|
428
|
-
checkIdentity(committed);
|
|
429
|
-
return {
|
|
430
|
-
committed,
|
|
431
|
-
message: decodeDurable(committed.message)
|
|
432
|
-
};
|
|
433
|
-
};
|
|
434
|
-
const committedFrom = (input, key) => decodeCommittedOperation(input, key).committed;
|
|
435
|
-
const journalContract = () => ({
|
|
436
|
-
replicaId: (operation) => operation.replicaId,
|
|
437
|
-
legacyReplicaId: (opId) => opId.slice(0, opId.lastIndexOf(":")),
|
|
438
|
-
operation: {
|
|
439
|
-
encode: (operation) => operation,
|
|
440
|
-
decode: normalizeOperation
|
|
441
|
-
},
|
|
442
|
-
snapshot: {
|
|
443
|
-
encode: encodeShared,
|
|
444
|
-
decode: decodeShared
|
|
445
|
-
},
|
|
446
|
-
empty: () => definition.empty,
|
|
447
|
-
reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),
|
|
448
|
-
...definition.stamp === void 0 ? {} : { stamp: (operation, commit) => ({
|
|
449
|
-
...operation,
|
|
450
|
-
message: encodeMessage(definition.stamp(decodeMessage(operation.message), {
|
|
451
|
-
...commit,
|
|
452
|
-
replicaId: operation.replicaId
|
|
453
|
-
}))
|
|
454
|
-
}) }
|
|
455
|
-
});
|
|
456
|
-
const optimistic = (state) => state.pending.reduce((model, operation) => definition.replay(model, decodeMessage(operation.message)), state.committed);
|
|
457
|
-
const openReplica = Effect.fn("Sync.openReplica")(function* (replicaId, storage) {
|
|
458
|
-
yield* Effect.annotateCurrentSpan({
|
|
459
|
-
documentId,
|
|
460
|
-
replicaId
|
|
461
|
-
});
|
|
462
|
-
const saved = yield* storage.load();
|
|
463
|
-
const initial = {
|
|
464
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
465
|
-
schemaVersion: SCHEMA_VERSION,
|
|
466
|
-
documentId,
|
|
467
|
-
replicaId,
|
|
468
|
-
revision: 0,
|
|
469
|
-
nextLocalSequence: localSequence(1),
|
|
470
|
-
cursor: sequence(0),
|
|
471
|
-
committed: definition.empty,
|
|
472
|
-
committedIds: [],
|
|
473
|
-
pending: []
|
|
474
|
-
};
|
|
475
|
-
const state = saved === void 0 ? initial : yield* Effect.try({
|
|
476
|
-
try: () => decodeState(saved),
|
|
477
|
-
catch: (cause) => unsupportedVersion(saved) ?? new InvalidReplicaHistoryError({
|
|
478
|
-
message: "Stored replica state is invalid",
|
|
479
|
-
cause
|
|
480
|
-
})
|
|
481
|
-
});
|
|
482
|
-
if (state.documentId !== documentId || state.replicaId !== replicaId) return yield* new WrongReplicaStorageError({
|
|
483
|
-
documentId,
|
|
484
|
-
replicaId,
|
|
485
|
-
message: "The stored replica belongs to a different document or replica"
|
|
486
|
-
});
|
|
487
|
-
const committedIds = new Set(state.committedIds);
|
|
488
|
-
if (state.nextLocalSequence < 1 || committedIds.size !== state.committedIds.length) return yield* new InvalidReplicaHistoryError({ message: "Invalid replica history" });
|
|
489
|
-
const pendingIds = /* @__PURE__ */ new Set();
|
|
490
|
-
for (const pending of state.pending) {
|
|
491
|
-
const operation = yield* Effect.try({
|
|
492
|
-
try: () => operationFrom(pending, documentId),
|
|
493
|
-
catch: () => new InvalidOutboxError({ message: "Invalid outbox" })
|
|
494
|
-
});
|
|
495
|
-
if (operation.replicaId !== replicaId || operation.localSequence >= state.nextLocalSequence || committedIds.has(operation.opId) || pendingIds.has(operation.opId)) return yield* new InvalidOutboxError({ message: "Invalid outbox" });
|
|
496
|
-
pendingIds.add(operation.opId);
|
|
497
|
-
}
|
|
498
|
-
const store = Effect.fn("Sync.store")(function* (next, expectedRevision) {
|
|
499
|
-
const encoded = yield* Effect.try({
|
|
500
|
-
try: () => encodeState(next),
|
|
501
|
-
catch: (cause) => new InvalidReplicaHistoryError({
|
|
502
|
-
message: "Could not encode the replica state",
|
|
503
|
-
cause
|
|
504
|
-
})
|
|
505
|
-
});
|
|
506
|
-
yield* storage.save(encoded, expectedRevision);
|
|
507
|
-
});
|
|
508
|
-
if (saved === void 0) yield* store(state, null);
|
|
509
|
-
const stateRef = yield* SynchronizedRef.make(state);
|
|
510
|
-
const closed = yield* Ref.make(false);
|
|
511
|
-
const lastError = yield* Ref.make(void 0);
|
|
512
|
-
const rejectedOps = yield* Ref.make([]);
|
|
513
|
-
const unsent = yield* Ref.make(/* @__PURE__ */ new Set());
|
|
514
|
-
const wake = yield* Queue.sliding(1);
|
|
515
|
-
const statusSignals = yield* PubSub.sliding(1);
|
|
516
|
-
const following = (read) => Stream.unwrap(Effect.map(PubSub.subscribe(statusSignals), (signals) => Stream.concat(Stream.fromEffect(read), Stream.fromSubscription(signals).pipe(Stream.mapEffect(() => read)))));
|
|
517
|
-
const projection = yield* Ref.make(void 0);
|
|
518
|
-
const snapshot = Effect.fn("Sync.snapshot")(function* () {
|
|
519
|
-
const current = yield* SynchronizedRef.get(stateRef);
|
|
520
|
-
const cached = yield* Ref.get(projection);
|
|
521
|
-
let projected;
|
|
522
|
-
if (cached !== void 0 && cached.state === current) projected = cached.shared;
|
|
523
|
-
else {
|
|
524
|
-
projected = optimistic(current);
|
|
525
|
-
yield* Ref.set(projection, {
|
|
526
|
-
state: current,
|
|
527
|
-
shared: projected
|
|
528
|
-
});
|
|
529
|
-
}
|
|
530
|
-
return {
|
|
531
|
-
status: {
|
|
532
|
-
pending: current.pending.length,
|
|
533
|
-
cursor: current.cursor,
|
|
534
|
-
lastError: yield* Ref.get(lastError),
|
|
535
|
-
rejected: yield* Ref.get(rejectedOps),
|
|
536
|
-
epoch: Option.fromUndefinedOr(current.epoch)
|
|
537
|
-
},
|
|
538
|
-
shared: projected,
|
|
539
|
-
committed: current.committed,
|
|
540
|
-
nextLocalSequence: current.nextLocalSequence
|
|
541
|
-
};
|
|
542
|
-
})();
|
|
543
|
-
const shared = Effect.map(snapshot, (value) => value.shared);
|
|
544
|
-
const status = Effect.map(snapshot, (value) => value.status);
|
|
545
|
-
const persist = (next, current) => store(next, current.revision);
|
|
546
|
-
const submit = Effect.fn("Sync.submit")(function* (message) {
|
|
547
|
-
yield* Effect.annotateCurrentSpan({
|
|
548
|
-
documentId,
|
|
549
|
-
replicaId
|
|
550
|
-
});
|
|
551
|
-
const result = yield* SynchronizedRef.modifyEffect(stateRef, (current) => Effect.gen(function* () {
|
|
552
|
-
if (yield* Ref.get(closed)) return yield* new ReplicaClosedError({ message: "Replica is closed" });
|
|
553
|
-
if (!definition.durable(message)) return yield* new InvalidOutboxError({ message: "Message is local-only" });
|
|
554
|
-
const last = current.pending[current.pending.length - 1];
|
|
555
|
-
const merged = last !== void 0 && definition.coalesce !== void 0 && (yield* Ref.get(unsent)).has(last.opId) ? definition.coalesce(decodeMessage(last.message), message) : void 0;
|
|
556
|
-
if (merged !== void 0 && !definition.durable(merged)) return yield* new InvalidOutboxError({ message: "coalesce returned a local-only Message" });
|
|
557
|
-
const operation = yield* Effect.try({
|
|
558
|
-
try: () => operationFrom(merged === void 0 ? {
|
|
559
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
560
|
-
schemaVersion: SCHEMA_VERSION,
|
|
561
|
-
documentId,
|
|
562
|
-
replicaId,
|
|
563
|
-
localSequence: current.nextLocalSequence,
|
|
564
|
-
opId: `${replicaId}:${current.nextLocalSequence}`,
|
|
565
|
-
baseCursor: current.cursor,
|
|
566
|
-
message: encodeMessage(message)
|
|
567
|
-
} : {
|
|
568
|
-
...last,
|
|
569
|
-
message: encodeMessage(merged)
|
|
570
|
-
}, documentId),
|
|
571
|
-
catch: () => new InvalidOutboxError({ message: "Invalid outbox" })
|
|
572
|
-
});
|
|
573
|
-
const cached = yield* Ref.get(projection);
|
|
574
|
-
const replayed = yield* Effect.try({
|
|
575
|
-
try: () => definition.replay(cached !== void 0 && cached.state === current ? cached.shared : optimistic(current), message),
|
|
576
|
-
catch: (cause) => new ReplayError({
|
|
577
|
-
message: cause instanceof Error ? cause.message : "Replay failed",
|
|
578
|
-
cause
|
|
579
|
-
})
|
|
580
|
-
});
|
|
581
|
-
const next = {
|
|
582
|
-
...current,
|
|
583
|
-
revision: current.revision + 1,
|
|
584
|
-
nextLocalSequence: localSequence(current.nextLocalSequence + 1),
|
|
585
|
-
pending: [...merged === void 0 ? current.pending : current.pending.slice(0, -1), operation]
|
|
586
|
-
};
|
|
587
|
-
if (storage.append === void 0) yield* persist(next, current);
|
|
588
|
-
else {
|
|
589
|
-
const encoded = yield* Effect.try({
|
|
590
|
-
try: () => encodeOperation(operation),
|
|
591
|
-
catch: (cause) => new InvalidReplicaHistoryError({
|
|
592
|
-
message: "Could not encode the operation",
|
|
593
|
-
cause
|
|
594
|
-
})
|
|
595
|
-
});
|
|
596
|
-
yield* storage.append({
|
|
597
|
-
revision: next.revision,
|
|
598
|
-
nextLocalSequence: next.nextLocalSequence,
|
|
599
|
-
localSequence: operation.localSequence,
|
|
600
|
-
operation: encoded
|
|
601
|
-
}, current.revision);
|
|
602
|
-
}
|
|
603
|
-
yield* Ref.set(projection, {
|
|
604
|
-
state: next,
|
|
605
|
-
shared: replayed
|
|
606
|
-
});
|
|
607
|
-
yield* Ref.update(unsent, (ids) => new Set(ids).add(operation.opId));
|
|
608
|
-
yield* Queue.offer(wake, void 0);
|
|
609
|
-
return [void 0, next];
|
|
610
|
-
}));
|
|
611
|
-
yield* PubSub.publish(statusSignals, void 0);
|
|
612
|
-
return result;
|
|
613
|
-
});
|
|
614
|
-
/** One exchange; whether the server has more to send and this one made progress. */
|
|
615
|
-
const exchangeOnce = Effect.fn("Sync.exchange")(function* () {
|
|
616
|
-
yield* Effect.annotateCurrentSpan({ documentId });
|
|
617
|
-
const transport = yield* Transport;
|
|
618
|
-
if (yield* Ref.get(closed)) return yield* new ReplicaClosedError({ message: "Replica is closed" });
|
|
619
|
-
const sent = yield* SynchronizedRef.modifyEffect(stateRef, (current) => Ref.update(unsent, (ids) => {
|
|
620
|
-
const left = new Set(ids);
|
|
621
|
-
for (const operation of current.pending) left.delete(operation.opId);
|
|
622
|
-
return left;
|
|
623
|
-
}).pipe(Effect.as([current, current])));
|
|
624
|
-
yield* Metric.update(syncMetrics.exchanges, 1);
|
|
625
|
-
yield* Metric.update(syncMetrics.exchangePending, sent.pending.length);
|
|
626
|
-
const response = yield* Effect.gen(function* () {
|
|
627
|
-
const raw = yield* transport.exchange(sent.cursor, sent.pending, sent.epoch);
|
|
628
|
-
return yield* Effect.try({
|
|
629
|
-
try: () => decodeExchange(raw),
|
|
630
|
-
catch: (cause) => new InvalidExchangeError({
|
|
631
|
-
message: "Invalid sync exchange response",
|
|
632
|
-
cause
|
|
633
|
-
})
|
|
634
|
-
});
|
|
635
|
-
});
|
|
636
|
-
const restarted = yield* SynchronizedRef.modifyEffect(stateRef, (current) => Effect.gen(function* () {
|
|
637
|
-
if (yield* Ref.get(closed)) return yield* new ReplicaClosedError({ message: "Replica is closed" });
|
|
638
|
-
const restarted = response.epoch !== void 0 && current.epoch !== void 0 && response.epoch !== current.epoch;
|
|
639
|
-
if (restarted) yield* Effect.logWarning("sync server history changed; rebuilding", {
|
|
640
|
-
documentId,
|
|
641
|
-
replicaId
|
|
642
|
-
});
|
|
643
|
-
let cursor = restarted ? sequence(0) : current.cursor;
|
|
644
|
-
let committed = restarted ? definition.empty : current.committed;
|
|
645
|
-
const ids = response.checkpoint === void 0 && !restarted ? new Set(current.committedIds) : /* @__PURE__ */ new Set();
|
|
646
|
-
if (response.checkpoint !== void 0) {
|
|
647
|
-
if (response.checkpoint.cursor < cursor) return yield* new CheckpointRegressionError({
|
|
648
|
-
cursor,
|
|
649
|
-
checkpointCursor: response.checkpoint.cursor,
|
|
650
|
-
message: "Checkpoint is behind the replica"
|
|
651
|
-
});
|
|
652
|
-
committed = response.checkpoint.model;
|
|
653
|
-
cursor = response.checkpoint.cursor;
|
|
654
|
-
yield* Metric.update(syncMetrics.checkpoints, 1);
|
|
655
|
-
yield* Effect.logDebug("sync checkpoint adopted", {
|
|
656
|
-
documentId,
|
|
657
|
-
replicaId,
|
|
658
|
-
cursor
|
|
659
|
-
});
|
|
660
|
-
}
|
|
661
|
-
const acknowledged = new Set(response.acknowledged ?? []);
|
|
662
|
-
const rejected = new Set(response.rejected);
|
|
663
|
-
const sentIds = new Set(sent.pending.map((operation) => operation.opId));
|
|
664
|
-
for (const id of acknowledged) if (!sentIds.has(id)) return yield* new ForeignAcknowledgementError({
|
|
665
|
-
opId: id,
|
|
666
|
-
message: "Server acknowledged an operation that was not sent"
|
|
667
|
-
});
|
|
668
|
-
for (const id of rejected) {
|
|
669
|
-
if (!sentIds.has(id)) return yield* new ForeignRejectionError({
|
|
670
|
-
opId: id,
|
|
671
|
-
message: "Server rejected an operation that was not sent"
|
|
672
|
-
});
|
|
673
|
-
if (acknowledged.has(id)) return yield* new ForeignAcknowledgementError({
|
|
674
|
-
opId: id,
|
|
675
|
-
message: "Server both acknowledged and rejected an operation"
|
|
676
|
-
});
|
|
677
|
-
}
|
|
678
|
-
for (const { opId } of response.reasons ?? []) if (!rejected.has(opId)) return yield* new ForeignRejectionError({
|
|
679
|
-
opId,
|
|
680
|
-
message: "Server gave a reason for an operation it did not reject"
|
|
681
|
-
});
|
|
682
|
-
let applied = 0;
|
|
683
|
-
for (const raw of response.operations) {
|
|
684
|
-
const { committed: operation, message } = yield* Effect.try({
|
|
685
|
-
try: () => decodeCommittedOperation(raw, documentId),
|
|
686
|
-
catch: (cause) => new InvalidReplicaHistoryError({
|
|
687
|
-
message: "Invalid committed operation",
|
|
688
|
-
cause
|
|
689
|
-
})
|
|
690
|
-
});
|
|
691
|
-
if (operation.serverSequence <= cursor) continue;
|
|
692
|
-
if (operation.serverSequence !== cursor + 1 || ids.has(operation.opId)) return yield* new CommittedOrderError({
|
|
693
|
-
expected: cursor + 1,
|
|
694
|
-
actual: operation.serverSequence,
|
|
695
|
-
message: "Invalid committed order"
|
|
696
|
-
});
|
|
697
|
-
const replaying = committed;
|
|
698
|
-
committed = yield* Effect.try({
|
|
699
|
-
try: () => definition.replay(replaying, message),
|
|
700
|
-
catch: (cause) => new ReplayError({
|
|
701
|
-
message: cause instanceof Error ? cause.message : "Replay failed",
|
|
702
|
-
cause
|
|
703
|
-
})
|
|
704
|
-
});
|
|
705
|
-
ids.add(operation.opId);
|
|
706
|
-
cursor = operation.serverSequence;
|
|
707
|
-
applied += 1;
|
|
708
|
-
}
|
|
709
|
-
if (applied > 0) yield* Metric.update(syncMetrics.applied, applied);
|
|
710
|
-
const epoch = response.epoch ?? current.epoch;
|
|
711
|
-
const next = {
|
|
712
|
-
...current,
|
|
713
|
-
revision: current.revision + 1,
|
|
714
|
-
committed,
|
|
715
|
-
cursor,
|
|
716
|
-
...epoch === void 0 ? {} : { epoch },
|
|
717
|
-
committedIds: [...ids].slice(-1024),
|
|
718
|
-
pending: current.pending.filter((operation) => !ids.has(operation.opId) && !(acknowledged.has(operation.opId) && response.more !== true) && !rejected.has(operation.opId))
|
|
719
|
-
};
|
|
720
|
-
yield* persist(next, current);
|
|
721
|
-
return [restarted, next];
|
|
722
|
-
}));
|
|
723
|
-
yield* Ref.set(lastError, void 0);
|
|
724
|
-
if (response.rejected.length > 0) {
|
|
725
|
-
const reasonOf = new Map((response.reasons ?? []).map(({ opId, reason }) => [opId, reason]));
|
|
726
|
-
const sentOf = new Map(sent.pending.map((operation) => [operation.opId, operation]));
|
|
727
|
-
const refused = response.rejected.map((opId) => ({
|
|
728
|
-
opId,
|
|
729
|
-
reason: Option.fromUndefinedOr(reasonOf.get(opId)),
|
|
730
|
-
operation: sentOf.get(opId)
|
|
731
|
-
}));
|
|
732
|
-
yield* Ref.update(rejectedOps, (previous) => [...refused, ...previous].slice(0, 32));
|
|
733
|
-
}
|
|
734
|
-
yield* PubSub.publish(statusSignals, void 0);
|
|
735
|
-
const reached = (yield* SynchronizedRef.get(stateRef)).cursor;
|
|
736
|
-
return response.more === true && reached > (restarted ? 0 : sent.cursor);
|
|
737
|
-
});
|
|
738
|
-
const synchronize = Effect.gen(function* () {
|
|
739
|
-
while (yield* exchangeOnce());
|
|
740
|
-
}).pipe(Effect.withSpan("Sync.synchronize"), Effect.tapError((error) => Effect.gen(function* () {
|
|
741
|
-
yield* Effect.logWarning("sync exchange failed", {
|
|
742
|
-
documentId,
|
|
743
|
-
replicaId,
|
|
744
|
-
error: error.message
|
|
745
|
-
});
|
|
746
|
-
yield* Ref.set(lastError, error.message);
|
|
747
|
-
yield* PubSub.publish(statusSignals, void 0);
|
|
748
|
-
})));
|
|
749
|
-
const start = Effect.gen(function* () {
|
|
750
|
-
const transport = yield* Transport;
|
|
751
|
-
if (transport.changes !== void 0) yield* Effect.forkChild(Stream.runForEach(transport.changes, () => Queue.offer(wake, void 0)), { startImmediately: true });
|
|
752
|
-
let failures = 0;
|
|
753
|
-
while (!(yield* Ref.get(closed))) {
|
|
754
|
-
const exit = yield* Effect.exit(synchronize);
|
|
755
|
-
if (yield* Ref.get(closed)) return;
|
|
756
|
-
if (exit._tag === "Success") {
|
|
757
|
-
failures = 0;
|
|
758
|
-
yield* Queue.take(wake);
|
|
759
|
-
} else {
|
|
760
|
-
failures += 1;
|
|
761
|
-
const backoff = Math.min(START_RETRY_MAX, START_RETRY_BASE * 2 ** Math.min(failures - 1, 16));
|
|
762
|
-
yield* Effect.raceFirst(Queue.take(wake), Effect.sleep(backoff));
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
});
|
|
766
|
-
return {
|
|
767
|
-
replicaId,
|
|
768
|
-
shared,
|
|
769
|
-
snapshot,
|
|
770
|
-
committed: Effect.map(SynchronizedRef.get(stateRef), (state) => state.committed),
|
|
771
|
-
pending: Effect.map(SynchronizedRef.get(stateRef), (state) => state.pending),
|
|
772
|
-
cursor: Effect.map(SynchronizedRef.get(stateRef), (state) => state.cursor),
|
|
773
|
-
status,
|
|
774
|
-
statusChanges: following(status),
|
|
775
|
-
changes: following(snapshot),
|
|
776
|
-
submit,
|
|
777
|
-
synchronize,
|
|
778
|
-
start,
|
|
779
|
-
close: Effect.fn("Sync.close")(function* () {
|
|
780
|
-
yield* Ref.set(closed, true);
|
|
781
|
-
yield* Queue.offer(wake, void 0);
|
|
782
|
-
yield* storage.close;
|
|
783
|
-
})()
|
|
784
|
-
};
|
|
785
|
-
}, (effect, _replicaId, storage) => effect.pipe(Effect.onExit((exit) => Exit.isSuccess(exit) ? Effect.void : storage.close.pipe(Effect.ignore))));
|
|
786
|
-
return {
|
|
787
|
-
documentId,
|
|
788
|
-
durable: definition.durable,
|
|
789
|
-
codec: {
|
|
790
|
-
normalizeOperation,
|
|
791
|
-
operationFrom,
|
|
792
|
-
committedFrom,
|
|
793
|
-
decodeExchange
|
|
794
|
-
},
|
|
795
|
-
journalContract,
|
|
796
|
-
openReplica
|
|
797
|
-
};
|
|
798
|
-
};
|
|
799
|
-
// src/make.ts
|
|
800
|
-
/**
|
|
801
|
-
* The Foldkit-facing sync layer: `Sync.forApplication(App).make(config)`
|
|
802
|
-
* compiles an application, a writable projection, and a durable Message subset
|
|
803
|
-
* into the low-level `defineSync` contract, and exposes a read-only Surface over
|
|
804
|
-
* the same projection.
|
|
805
|
-
*/
|
|
806
|
-
/** Reads the tag off a Foldkit Message constructor without constructing one. */
|
|
807
|
-
const messageTag = (constructor) => {
|
|
808
|
-
const literal = constructor.fields?._tag?.ast?.literal;
|
|
809
|
-
return typeof literal === "string" ? literal : void 0;
|
|
810
|
-
};
|
|
811
|
-
/** A Message's tag. The application's union is generic here, so its `_tag` is read, not typed. */
|
|
812
|
-
const tagOf = (message) => Predicate.hasProperty(message, "_tag") && typeof message._tag === "string" ? Option.some(message._tag) : Option.none();
|
|
813
|
-
/**
|
|
814
|
-
* Replay derived from the application's own `update`: install the shared slice
|
|
815
|
-
* into the initial Model, apply the Message, and read the slice back.
|
|
816
|
-
*
|
|
817
|
-
* A durable Message must be a deterministic, state-only transition of the shared
|
|
818
|
-
* projection. Replay refuses one that returns a Command (a live effect cannot be
|
|
819
|
-
* replayed) or that changes a Model field outside the projection (the change
|
|
820
|
-
* would be silently lost), so a Message that needs either stays local and emits
|
|
821
|
-
* a durable fact once the effect settles.
|
|
822
|
-
*/
|
|
823
|
-
const derivedReplay = (app, shared) => {
|
|
824
|
-
const { initial, update } = app;
|
|
825
|
-
const owned = new Set(shared.dependencies.filter((path) => path.length === 1).map((path) => path[0]));
|
|
826
|
-
const fields = Object.entries(app.Model.fields).filter(([key]) => !owned.has(key)).map(([key, field]) => [key, Schema.toEquivalence(field)]);
|
|
827
|
-
return (value, message) => {
|
|
828
|
-
const result = update(shared.set(initial, value), message);
|
|
829
|
-
if (result.commands !== void 0 && result.commands.length > 0) throw new Error(`Sync.forApplication: durable "${Option.getOrElse(tagOf(message), () => "untagged")}" returned ${result.commands.length} Command(s); a durable transition is state-only`);
|
|
830
|
-
const next = shared.get(result.model);
|
|
831
|
-
const written = shared.set(initial, next);
|
|
832
|
-
const actual = result.model;
|
|
833
|
-
const changed = fields.filter(([key, equal]) => !equal(actual[key], written[key]));
|
|
834
|
-
if (changed.length > 0) throw new Error(`Sync.forApplication: durable "${Option.getOrElse(tagOf(message), () => "untagged")}" changed Model fields outside the shared projection: ${changed.map(([key]) => key).join(", ")}`);
|
|
835
|
-
return next;
|
|
836
|
-
};
|
|
837
|
-
};
|
|
838
|
-
/**
|
|
839
|
-
* Merges fragments into one. The primitives reject a conflicting field, a
|
|
840
|
-
* duplicate tag, and a subset from another application.
|
|
841
|
-
*/
|
|
842
|
-
const composeFragments = (fragments) => {
|
|
843
|
-
const compose = Projection.compose;
|
|
844
|
-
const union = MessageSet.union;
|
|
845
|
-
return {
|
|
846
|
-
shared: compose(...fragments.map((fragment) => fragment.shared)),
|
|
847
|
-
durable: union(...fragments.map((fragment) => fragment.durable))
|
|
848
|
-
};
|
|
849
|
-
};
|
|
850
|
-
/**
|
|
851
|
-
* Specializes the sync constructors to a `Surface.application`, so
|
|
852
|
-
* `Sync.forApplication(App).make({ documentId, shared, durable })` derives the
|
|
853
|
-
* shared codec, the initial snapshot, the durable predicate, and replay from
|
|
854
|
-
* the application, and refuses a subset that belongs to another application.
|
|
855
|
-
* `defineSync` remains the protocol primitive when there is no application to
|
|
856
|
-
* derive from.
|
|
857
|
-
*/
|
|
858
|
-
const forApplication = (app) => build(app);
|
|
859
|
-
const build = (app) => {
|
|
860
|
-
const decodeMessage = Schema.decodeUnknownSync(app.Message);
|
|
861
|
-
const make = (options) => {
|
|
862
|
-
const { shared, durable } = options;
|
|
863
|
-
if (durable.owner !== app.owner) throw new Error("Sync.make: the durable subset belongs to a different application");
|
|
864
|
-
const replay = options.replay === void 0 ? derivedReplay(app, shared) : (value, message) => options.replay(value, message);
|
|
865
|
-
const durableTags = new Set(durable.constructors.map(messageTag).filter((tag) => tag !== void 0));
|
|
866
|
-
const sharedCodec = shared.schema;
|
|
867
|
-
const stamps = options.stamp;
|
|
868
|
-
const sync = defineSync({
|
|
869
|
-
documentId: options.documentId,
|
|
870
|
-
message: app.Message,
|
|
871
|
-
shared: sharedCodec,
|
|
872
|
-
empty: shared.get(app.initial),
|
|
873
|
-
durable: (message) => Option.exists(tagOf(message), (tag) => durableTags.has(tag)),
|
|
874
|
-
replay,
|
|
875
|
-
coalesce: options.coalesce,
|
|
876
|
-
...stamps === void 0 ? {} : { stamp: (message, commit) => Option.match(Option.flatMapNullishOr(tagOf(message), (tag) => stamps[tag]), {
|
|
877
|
-
onNone: () => message,
|
|
878
|
-
onSome: (rule) => {
|
|
879
|
-
const stamped = rule(message, commit);
|
|
880
|
-
if (!Equal.equals(tagOf(stamped), tagOf(message))) throw new Error("A stamp must return the variant it was given");
|
|
881
|
-
return stamped;
|
|
882
|
-
}
|
|
883
|
-
}) }
|
|
884
|
-
});
|
|
885
|
-
const rules = options.authorize;
|
|
886
|
-
const journalContract = () => {
|
|
887
|
-
const base = sync.journalContract();
|
|
888
|
-
if (rules === void 0) return base;
|
|
889
|
-
return {
|
|
890
|
-
...base,
|
|
891
|
-
authorize: ({ principal, operation, snapshot }) => {
|
|
892
|
-
const message = decodeMessage(operation.message);
|
|
893
|
-
return Option.match(Option.flatMapNullishOr(tagOf(message), (tag) => rules[tag]), {
|
|
894
|
-
onNone: () => true,
|
|
895
|
-
onSome: (rule) => rule({
|
|
896
|
-
principal,
|
|
897
|
-
message,
|
|
898
|
-
shared: snapshot
|
|
899
|
-
})
|
|
900
|
-
});
|
|
901
|
-
}
|
|
902
|
-
};
|
|
903
|
-
};
|
|
904
|
-
const readOnly = Projection.fromReader(sharedCodec, shared.get, { dependencies: shared.dependencies });
|
|
905
|
-
const surface = Surface.make(app, options.name ?? String(options.documentId), {
|
|
906
|
-
model: () => readOnly,
|
|
907
|
-
messages: durable.constructors
|
|
908
|
-
});
|
|
909
|
-
const contract = {
|
|
910
|
-
kind: "sync",
|
|
911
|
-
name: surface.name,
|
|
912
|
-
owner: app.owner,
|
|
913
|
-
owns: shared.dependencies,
|
|
914
|
-
observes: shared.dependencies,
|
|
915
|
-
messages: [...durable.tags],
|
|
916
|
-
metadata: []
|
|
917
|
-
};
|
|
918
|
-
return {
|
|
919
|
-
...sync,
|
|
920
|
-
journalContract,
|
|
921
|
-
surface,
|
|
922
|
-
projection: shared,
|
|
923
|
-
replay,
|
|
924
|
-
messages: durable.constructors,
|
|
925
|
-
contract,
|
|
926
|
-
wiring: () => ({
|
|
927
|
-
key: `sync:${contract.name}`,
|
|
928
|
-
handles: [],
|
|
929
|
-
contract
|
|
930
|
-
})
|
|
931
|
-
};
|
|
932
|
-
};
|
|
933
|
-
return {
|
|
934
|
-
withPrincipal: () => build(app),
|
|
935
|
-
fragment: (config) => {
|
|
936
|
-
if (config.durable.owner !== app.owner) throw new Error("Sync.fragment: the durable subset belongs to a different application");
|
|
937
|
-
return {
|
|
938
|
-
shared: config.shared,
|
|
939
|
-
durable: config.durable
|
|
940
|
-
};
|
|
941
|
-
},
|
|
942
|
-
compose: ((...fragments) => composeFragments(fragments)),
|
|
943
|
-
make
|
|
944
|
-
};
|
|
945
|
-
};
|
|
946
|
-
// src/mount.ts
|
|
947
|
-
/**
|
|
948
|
-
* `Sync.mount`: runs a Foldkit application over a replica with one reducer.
|
|
949
|
-
*
|
|
950
|
-
* A durable Message is a state-only, deterministic transition of the shared
|
|
951
|
-
* projection (the derived replay enforces it), so the application's own `update`
|
|
952
|
-
* is applied at once and the Message is persisted afterwards in a Command. The
|
|
953
|
-
* shared slice is re-installed from the replica when an exchange changes it or
|
|
954
|
-
* a persist fails, through one private Message the application never sees.
|
|
955
|
-
*/
|
|
956
|
-
const REFRESH = "foldkit-sync/Refresh";
|
|
957
|
-
const PERSISTED = "foldkit-sync/Persisted";
|
|
958
|
-
const FAILED = "foldkit-sync/PersistenceFailed";
|
|
959
|
-
const NAVIGATE = "foldkit-sync/Navigate";
|
|
960
|
-
const NAVIGATED = "foldkit-sync/Navigated";
|
|
961
|
-
const DISPATCHED = "foldkit-sync/Dispatched";
|
|
962
|
-
const PRIVATE = {
|
|
963
|
-
[REFRESH]: true,
|
|
964
|
-
[PERSISTED]: true,
|
|
965
|
-
[FAILED]: true,
|
|
966
|
-
[NAVIGATE]: true,
|
|
967
|
-
[NAVIGATED]: true,
|
|
968
|
-
[DISPATCHED]: true
|
|
969
|
-
};
|
|
970
|
-
const isPrivate = (message) => Object.hasOwn(PRIVATE, message._tag);
|
|
971
|
-
const FACT = Symbol.for("foldkit-sync/fact");
|
|
972
|
-
/**
|
|
973
|
-
* A Command that dispatches `message` as the next transition, which under `Sync.mount`
|
|
974
|
-
* means within this one: the mount applies it straight after the `update` that returned
|
|
975
|
-
* it, and persists it if it is durable, before any other Message is processed. This is
|
|
976
|
-
* how a local intent turns into a durable fact that needs something only the intent's
|
|
977
|
-
* transition knows, such as an id minted from local state, without a later Message
|
|
978
|
-
* seeing the Model before the fact. Elsewhere, or once a parent has mapped the Command,
|
|
979
|
-
* it is an ordinary Command that yields `message`, and so is one a durable Message's
|
|
980
|
-
* update returns: replay would not apply it, and with derived replay the durable Message's
|
|
981
|
-
* persist fails with `ReplayError` as for any Command.
|
|
982
|
-
*/
|
|
983
|
-
const fact = (message) => Object.defineProperty({
|
|
984
|
-
name: "foldkit-sync/fact",
|
|
985
|
-
effect: Effect.succeed(message)
|
|
986
|
-
}, FACT, {
|
|
987
|
-
value: message,
|
|
988
|
-
enumerable: false
|
|
989
|
-
});
|
|
990
|
-
const factOf = (command) => typeof command === "object" && command !== null && FACT in command ? { message: command[FACT] } : void 0;
|
|
991
|
-
/**
|
|
992
|
-
* Commits, rejections and acknowledgments change what the replica holds; a
|
|
993
|
-
* submit only echoes a local edit. An acknowledgment that does not return the
|
|
994
|
-
* operation moves no cursor, but it still drops the edit from the outbox.
|
|
995
|
-
*/
|
|
996
|
-
const sharedChanged = (previous, next) => previous === void 0 || previous.cursor !== next.cursor || next.pending < previous.pending || previous.rejected.length !== next.rejected.length || previous.rejected.some((rejection, index) => rejection.opId !== next.rejected[index]?.opId);
|
|
997
|
-
/**
|
|
998
|
-
* The edits a replica whose next local sequence is `next` does not hold yet.
|
|
999
|
-
* Submits run one at a time, so the one in flight is in the replica exactly
|
|
1000
|
-
* when its submit has moved the sequence past `started`.
|
|
1001
|
-
*/
|
|
1002
|
-
const unconfirmedEdits = (edits, next) => edits.filter((edit) => edit.started === void 0 || next <= edit.started).map((edit) => edit.message);
|
|
1003
|
-
const mount = (app, sync, options) => {
|
|
1004
|
-
if (options.container.id === "") throw new Error("Sync.mount: the container needs an id (`container.id = \"app\"`)");
|
|
1005
|
-
const { replica } = options;
|
|
1006
|
-
const durable = new Set(sync.contract.messages);
|
|
1007
|
-
const edits = [];
|
|
1008
|
-
const holdUnload = (event) => event.preventDefault();
|
|
1009
|
-
const unloadGuarded = (guarded) => {
|
|
1010
|
-
if (typeof window === "undefined") return;
|
|
1011
|
-
if (guarded) window.addEventListener("beforeunload", holdUnload);
|
|
1012
|
-
else window.removeEventListener("beforeunload", holdUnload);
|
|
1013
|
-
};
|
|
1014
|
-
let tail = Promise.resolve();
|
|
1015
|
-
let installedFrom;
|
|
1016
|
-
let editedSinceInstall = false;
|
|
1017
|
-
const install = (model) => {
|
|
1018
|
-
const snapshot = Effect.runSync(replica.snapshot);
|
|
1019
|
-
installedFrom = snapshot.shared;
|
|
1020
|
-
editedSinceInstall = false;
|
|
1021
|
-
const shared = unconfirmedEdits(edits, snapshot.nextLocalSequence).reduce((value, message) => {
|
|
1022
|
-
try {
|
|
1023
|
-
return sync.replay(value, message);
|
|
1024
|
-
} catch {
|
|
1025
|
-
return value;
|
|
1026
|
-
}
|
|
1027
|
-
}, snapshot.shared);
|
|
1028
|
-
return sync.projection.set(model, shared);
|
|
1029
|
-
};
|
|
1030
|
-
const inFlight = /* @__PURE__ */ new Set();
|
|
1031
|
-
let dispatchesOwed = 0;
|
|
1032
|
-
let persistsOwed = 0;
|
|
1033
|
-
let applied;
|
|
1034
|
-
let disposed = false;
|
|
1035
|
-
const waiters = /* @__PURE__ */ new Set();
|
|
1036
|
-
const quiet = () => dispatchesOwed === 0 && persistsOwed === 0 && !sharedChanged(applied, Effect.runSync(replica.status));
|
|
1037
|
-
const notifySettled = () => {
|
|
1038
|
-
if (!quiet()) return;
|
|
1039
|
-
for (const waiter of [...waiters]) {
|
|
1040
|
-
waiters.delete(waiter);
|
|
1041
|
-
waiter.resolve();
|
|
1042
|
-
}
|
|
1043
|
-
};
|
|
1044
|
-
/**
|
|
1045
|
-
* A private transition that leaves the Model as it was: the runtime sends
|
|
1046
|
-
* no Subscription the change, so `settled` is told here, once it returns.
|
|
1047
|
-
*/
|
|
1048
|
-
const unchanged = (model) => {
|
|
1049
|
-
queueMicrotask(notifySettled);
|
|
1050
|
-
return { model };
|
|
1051
|
-
};
|
|
1052
|
-
let latest = install(app.initial);
|
|
1053
|
-
const modelListeners = /* @__PURE__ */ new Set();
|
|
1054
|
-
const committedListeners = /* @__PURE__ */ new Set();
|
|
1055
|
-
const messageListeners = /* @__PURE__ */ new Set();
|
|
1056
|
-
const notifyEach = (listeners, value) => {
|
|
1057
|
-
for (const listener of [...listeners]) try {
|
|
1058
|
-
listener(value);
|
|
1059
|
-
} catch (error) {
|
|
1060
|
-
queueMicrotask(() => {
|
|
1061
|
-
throw error;
|
|
1062
|
-
});
|
|
1063
|
-
}
|
|
1064
|
-
};
|
|
1065
|
-
const notifyCommitted = () => notifyEach(committedListeners, void 0);
|
|
1066
|
-
const updatePrivate = (model, message) => {
|
|
1067
|
-
switch (message._tag) {
|
|
1068
|
-
case REFRESH: {
|
|
1069
|
-
const reset = applied !== void 0 && Option.isSome(applied.epoch) && Option.isSome(message.status.epoch) && applied.epoch.value !== message.status.epoch.value;
|
|
1070
|
-
applied = message.status;
|
|
1071
|
-
if (!message.changed || !editedSinceInstall && Effect.runSync(replica.snapshot).shared === installedFrom) return unchanged(model);
|
|
1072
|
-
return reinstalled(install(model), model, { reset });
|
|
1073
|
-
}
|
|
1074
|
-
case PERSISTED:
|
|
1075
|
-
persistsOwed--;
|
|
1076
|
-
return unchanged(model);
|
|
1077
|
-
case FAILED: {
|
|
1078
|
-
persistsOwed--;
|
|
1079
|
-
const { error } = message;
|
|
1080
|
-
const reverted = install(model);
|
|
1081
|
-
return reinstalled(options.onPersistenceFailure?.(reverted, error) ?? reverted, model, { reset: false });
|
|
1082
|
-
}
|
|
1083
|
-
case NAVIGATE: {
|
|
1084
|
-
const { request } = message;
|
|
1085
|
-
return {
|
|
1086
|
-
model,
|
|
1087
|
-
commands: [{
|
|
1088
|
-
name: "foldkit-sync/navigate",
|
|
1089
|
-
effect: (request._tag === "Internal" ? Navigation.pushUrl(Url.toString(request.url)) : Navigation.load(request.href)).pipe(Effect.as({ _tag: NAVIGATED }))
|
|
1090
|
-
}]
|
|
1091
|
-
};
|
|
1092
|
-
}
|
|
1093
|
-
case NAVIGATED: return { model };
|
|
1094
|
-
case DISPATCHED:
|
|
1095
|
-
dispatchesOwed--;
|
|
1096
|
-
return transition(model, message.message);
|
|
1097
|
-
default: return absurd(message);
|
|
1098
|
-
}
|
|
1099
|
-
};
|
|
1100
|
-
const update = (model, message) => {
|
|
1101
|
-
const result = isPrivate(message) ? updatePrivate(model, message) : transition(model, message);
|
|
1102
|
-
if (options.afterUpdate === void 0) return result;
|
|
1103
|
-
const after = applyFacts(options.afterUpdate(result.model));
|
|
1104
|
-
return after.model === result.model && (after.commands ?? []).length === 0 ? result : {
|
|
1105
|
-
model: after.model,
|
|
1106
|
-
commands: [...result.commands ?? [], ...after.commands ?? []]
|
|
1107
|
-
};
|
|
1108
|
-
};
|
|
1109
|
-
const reinstalled = (next, previous, change) => options.onReinstall === void 0 ? { model: next } : applyFacts(options.onReinstall(next, previous, change));
|
|
1110
|
-
/** The application's transition for one of its Messages, with the persist a durable one needs. */
|
|
1111
|
-
const step = (model, message) => {
|
|
1112
|
-
notifyEach(messageListeners, message);
|
|
1113
|
-
const result = app.update(model, message);
|
|
1114
|
-
if (!durable.has(message._tag)) return result;
|
|
1115
|
-
editedSinceInstall = true;
|
|
1116
|
-
persistsOwed++;
|
|
1117
|
-
const edit = {
|
|
1118
|
-
message,
|
|
1119
|
-
started: void 0
|
|
1120
|
-
};
|
|
1121
|
-
edits.push(edit);
|
|
1122
|
-
if (edits.length === 1) unloadGuarded(true);
|
|
1123
|
-
const previous = tail;
|
|
1124
|
-
let settle;
|
|
1125
|
-
const done = new Promise((resolve) => {
|
|
1126
|
-
settle = resolve;
|
|
1127
|
-
});
|
|
1128
|
-
tail = done;
|
|
1129
|
-
const release = () => {
|
|
1130
|
-
const index = edits.indexOf(edit);
|
|
1131
|
-
if (index !== -1) edits.splice(index, 1);
|
|
1132
|
-
if (edits.length === 0) unloadGuarded(false);
|
|
1133
|
-
inFlight.delete(done);
|
|
1134
|
-
settle();
|
|
1135
|
-
};
|
|
1136
|
-
const persist = {
|
|
1137
|
-
name: "foldkit-sync/persist",
|
|
1138
|
-
effect: Effect.gen(function* () {
|
|
1139
|
-
inFlight.add(done);
|
|
1140
|
-
yield* Effect.promise(() => previous);
|
|
1141
|
-
edit.started = (yield* replica.snapshot).nextLocalSequence;
|
|
1142
|
-
const outcome = yield* Effect.result(replica.submit(edit.message));
|
|
1143
|
-
return outcome._tag === "Success" ? { _tag: PERSISTED } : {
|
|
1144
|
-
_tag: FAILED,
|
|
1145
|
-
error: outcome.failure
|
|
1146
|
-
};
|
|
1147
|
-
}).pipe(Effect.ensuring(Effect.sync(release)))
|
|
1148
|
-
};
|
|
1149
|
-
return {
|
|
1150
|
-
model: result.model,
|
|
1151
|
-
commands: [...result.commands ?? [], persist]
|
|
1152
|
-
};
|
|
1153
|
-
};
|
|
1154
|
-
/**
|
|
1155
|
-
* A Message's transition, with the facts it returned applied after it. A durable
|
|
1156
|
-
* Message's are not: replay would not apply them, so they stay ordinary Commands.
|
|
1157
|
-
*/
|
|
1158
|
-
const transition = (model, message) => {
|
|
1159
|
-
const result = step(model, message);
|
|
1160
|
-
return durable.has(message._tag) ? result : applyFacts(result);
|
|
1161
|
-
};
|
|
1162
|
-
/** Applies the facts a transition returned, in order, each as the transition after it. */
|
|
1163
|
-
const applyFacts = (result) => {
|
|
1164
|
-
let model = result.model;
|
|
1165
|
-
const kept = [];
|
|
1166
|
-
for (const command of result.commands ?? []) {
|
|
1167
|
-
const found = factOf(command);
|
|
1168
|
-
if (found === void 0) {
|
|
1169
|
-
kept.push(command);
|
|
1170
|
-
continue;
|
|
1171
|
-
}
|
|
1172
|
-
const next = transition(model, found.message);
|
|
1173
|
-
model = next.model;
|
|
1174
|
-
kept.push(...next.commands ?? []);
|
|
1175
|
-
}
|
|
1176
|
-
return {
|
|
1177
|
-
model,
|
|
1178
|
-
commands: kept
|
|
1179
|
-
};
|
|
1180
|
-
};
|
|
1181
|
-
const ports = { inbound: { message: Port.inbound(app.Message) } };
|
|
1182
|
-
const own = Subscription.make()(() => ({
|
|
1183
|
-
message: Port.subscriptionEntry(ports.inbound.message, (message) => ({
|
|
1184
|
-
_tag: DISPATCHED,
|
|
1185
|
-
message
|
|
1186
|
-
})),
|
|
1187
|
-
refresh: Subscription.persistentEntry(replica.statusChanges.pipe(Stream.tap(() => Effect.sync(notifyCommitted)), Stream.mapAccum(() => void 0, (previous, status) => [status, [{
|
|
1188
|
-
_tag: REFRESH,
|
|
1189
|
-
status,
|
|
1190
|
-
changed: sharedChanged(previous, status)
|
|
1191
|
-
}]]))),
|
|
1192
|
-
latest: {
|
|
1193
|
-
dependenciesSchema: Schema.Struct({}),
|
|
1194
|
-
modelToDependencies: (model) => {
|
|
1195
|
-
latest = model;
|
|
1196
|
-
notifyEach(modelListeners, void 0);
|
|
1197
|
-
notifySettled();
|
|
1198
|
-
return {};
|
|
1199
|
-
},
|
|
1200
|
-
dependenciesToStream: () => Stream.never
|
|
1201
|
-
}
|
|
1202
|
-
}));
|
|
1203
|
-
const subscriptions = options.subscriptions === void 0 ? own : Subscription.aggregate()(options.subscriptions, own);
|
|
1204
|
-
const view = (model, h) => options.view(model, h);
|
|
1205
|
-
const common = {
|
|
1206
|
-
Model: app.Model,
|
|
1207
|
-
container: options.container,
|
|
1208
|
-
ports,
|
|
1209
|
-
update,
|
|
1210
|
-
subscriptions,
|
|
1211
|
-
...options.resources === void 0 ? {} : { resources: options.resources },
|
|
1212
|
-
view
|
|
1213
|
-
};
|
|
1214
|
-
const url = options.url;
|
|
1215
|
-
const program = url === void 0 ? Runtime.makeApplication({
|
|
1216
|
-
...common,
|
|
1217
|
-
init: () => ({ model: latest })
|
|
1218
|
-
}) : Runtime.makeApplication({
|
|
1219
|
-
...common,
|
|
1220
|
-
routing: {
|
|
1221
|
-
onUrlChange: (at) => url.onUrlChange(at),
|
|
1222
|
-
onUrlRequest: (request) => url.onUrlRequest === void 0 ? {
|
|
1223
|
-
_tag: NAVIGATE,
|
|
1224
|
-
request
|
|
1225
|
-
} : url.onUrlRequest(request)
|
|
1226
|
-
},
|
|
1227
|
-
init: (at) => {
|
|
1228
|
-
latest = url.init === void 0 ? latest : url.init(latest, at);
|
|
1229
|
-
return { model: latest };
|
|
1230
|
-
}
|
|
1231
|
-
});
|
|
1232
|
-
const handle = Runtime.embed(program);
|
|
1233
|
-
const encodeMessage = Schema.encodeExit(app.Message);
|
|
1234
|
-
return {
|
|
1235
|
-
dispatch: (message) => Exit.match(encodeMessage(message), {
|
|
1236
|
-
onSuccess: (encoded) => {
|
|
1237
|
-
dispatchesOwed++;
|
|
1238
|
-
const sent = handle.ports.message.send(encoded);
|
|
1239
|
-
if (Exit.isFailure(sent)) dispatchesOwed--;
|
|
1240
|
-
return sent;
|
|
1241
|
-
},
|
|
1242
|
-
onFailure: (cause) => Exit.failCause(cause)
|
|
1243
|
-
}),
|
|
1244
|
-
model: () => latest,
|
|
1245
|
-
subscribe: (listener) => {
|
|
1246
|
-
modelListeners.add(listener);
|
|
1247
|
-
return () => modelListeners.delete(listener);
|
|
1248
|
-
},
|
|
1249
|
-
observe: (listener) => {
|
|
1250
|
-
messageListeners.add(listener);
|
|
1251
|
-
return () => messageListeners.delete(listener);
|
|
1252
|
-
},
|
|
1253
|
-
committed: {
|
|
1254
|
-
get: () => Effect.runSync(replica.committed),
|
|
1255
|
-
subscribe: (listener) => {
|
|
1256
|
-
committedListeners.add(listener);
|
|
1257
|
-
return () => committedListeners.delete(listener);
|
|
1258
|
-
}
|
|
1259
|
-
},
|
|
1260
|
-
settled: () => {
|
|
1261
|
-
if (disposed) return Promise.reject(/* @__PURE__ */ new Error("Sync.mount: settled() after dispose"));
|
|
1262
|
-
if (quiet()) return Promise.resolve();
|
|
1263
|
-
return new Promise((resolve, reject) => waiters.add({
|
|
1264
|
-
resolve,
|
|
1265
|
-
reject
|
|
1266
|
-
}));
|
|
1267
|
-
},
|
|
1268
|
-
dispose: async () => {
|
|
1269
|
-
disposed = true;
|
|
1270
|
-
for (const waiter of [...waiters]) {
|
|
1271
|
-
waiters.delete(waiter);
|
|
1272
|
-
waiter.reject(/* @__PURE__ */ new Error("Sync.mount: disposed before it settled"));
|
|
1273
|
-
}
|
|
1274
|
-
await Promise.all([...inFlight]);
|
|
1275
|
-
handle.dispose();
|
|
1276
|
-
}
|
|
1277
|
-
};
|
|
1278
|
-
};
|
|
1279
|
-
// src/presence.ts
|
|
1280
|
-
/**
|
|
1281
|
-
* Tracks ephemeral peers with a time-to-live.
|
|
1282
|
-
*
|
|
1283
|
-
* Nothing here touches the durable log: presence is state a peer refreshes, and
|
|
1284
|
-
* a peer that stops refreshing is dropped, not replayed. Time comes from the
|
|
1285
|
-
* `Clock`, so a `TestClock` drives the TTL deterministically.
|
|
1286
|
-
*/
|
|
1287
|
-
const createPresence = Effect.fn("Presence.create")(function* (options) {
|
|
1288
|
-
const ttl = Duration.toMillis(options.ttl);
|
|
1289
|
-
const throttle = options.throttle === void 0 ? 0 : Duration.toMillis(options.throttle);
|
|
1290
|
-
const scope = yield* Effect.scope;
|
|
1291
|
-
const outbound = yield* SynchronizedRef.make({
|
|
1292
|
-
lastSent: void 0,
|
|
1293
|
-
held: void 0,
|
|
1294
|
-
flusher: void 0
|
|
1295
|
-
});
|
|
1296
|
-
const peers = yield* Ref.make(/* @__PURE__ */ new Map());
|
|
1297
|
-
const closed = yield* Ref.make(false);
|
|
1298
|
-
const signals = yield* PubSub.sliding(1);
|
|
1299
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
1300
|
-
/** A subscriber must never fail an update. */
|
|
1301
|
-
const notify = () => Effect.gen(function* () {
|
|
1302
|
-
for (const listener of [...listeners]) try {
|
|
1303
|
-
listener();
|
|
1304
|
-
} catch {}
|
|
1305
|
-
yield* PubSub.publish(signals, void 0);
|
|
1306
|
-
});
|
|
1307
|
-
const expired = (peer, at) => at - peer.updatedAt > ttl;
|
|
1308
|
-
const put = (id, value, at) => Ref.update(peers, (map) => {
|
|
1309
|
-
const next = new Map(map);
|
|
1310
|
-
next.set(id, {
|
|
1311
|
-
id,
|
|
1312
|
-
value,
|
|
1313
|
-
updatedAt: at
|
|
1314
|
-
});
|
|
1315
|
-
return next;
|
|
1316
|
-
});
|
|
1317
|
-
const remove = (id) => Ref.modify(peers, (map) => {
|
|
1318
|
-
if (!map.has(id)) return [false, map];
|
|
1319
|
-
const next = new Map(map);
|
|
1320
|
-
next.delete(id);
|
|
1321
|
-
return [true, next];
|
|
1322
|
-
});
|
|
1323
|
-
const receive = Effect.fn("Presence.receive")(function* (update) {
|
|
1324
|
-
if (update.id === options.id) return;
|
|
1325
|
-
if (update.value === null) {
|
|
1326
|
-
if (yield* remove(update.id)) yield* notify();
|
|
1327
|
-
return;
|
|
1328
|
-
}
|
|
1329
|
-
let value;
|
|
1330
|
-
try {
|
|
1331
|
-
value = options.decodeValue(update.value);
|
|
1332
|
-
} catch {
|
|
1333
|
-
return;
|
|
1334
|
-
}
|
|
1335
|
-
yield* put(update.id, value, yield* Clock.currentTimeMillis);
|
|
1336
|
-
yield* notify();
|
|
1337
|
-
});
|
|
1338
|
-
const channel = options.channel;
|
|
1339
|
-
const consuming = channel === void 0 ? void 0 : yield* Stream.runForEach(Stream.fromPubSub(channel.updates), receive).pipe(Effect.forkScoped);
|
|
1340
|
-
const publish = (value) => channel.publish({
|
|
1341
|
-
id: options.id,
|
|
1342
|
-
value
|
|
1343
|
-
});
|
|
1344
|
-
/** Drops a value waiting to be sent, so nothing older goes out after what comes next. */
|
|
1345
|
-
const cancelHeld = SynchronizedRef.updateEffect(outbound, (state) => (state.flusher === void 0 ? Effect.void : Fiber.interrupt(state.flusher)).pipe(Effect.as({
|
|
1346
|
-
...state,
|
|
1347
|
-
held: void 0,
|
|
1348
|
-
flusher: void 0
|
|
1349
|
-
})));
|
|
1350
|
-
/** Sends what is held once per interval, until an interval passes with nothing held. */
|
|
1351
|
-
const flush = (wait) => Effect.gen(function* () {
|
|
1352
|
-
for (let delay = wait;; delay = throttle) {
|
|
1353
|
-
yield* Effect.sleep(delay);
|
|
1354
|
-
const now = yield* Clock.currentTimeMillis;
|
|
1355
|
-
const latest = yield* SynchronizedRef.modify(outbound, (state) => state.held === void 0 ? [void 0, {
|
|
1356
|
-
...state,
|
|
1357
|
-
flusher: void 0
|
|
1358
|
-
}] : [state.held, {
|
|
1359
|
-
...state,
|
|
1360
|
-
held: void 0,
|
|
1361
|
-
lastSent: now
|
|
1362
|
-
}]);
|
|
1363
|
-
if (latest === void 0) return;
|
|
1364
|
-
yield* publish(latest.value);
|
|
1365
|
-
}
|
|
1366
|
-
});
|
|
1367
|
-
const broadcast = (value, at) => Effect.gen(function* () {
|
|
1368
|
-
if (yield* SynchronizedRef.modifyEffect(outbound, (state) => Effect.gen(function* () {
|
|
1369
|
-
if (yield* Ref.get(closed)) return [false, state];
|
|
1370
|
-
if (state.flusher !== void 0) return [false, {
|
|
1371
|
-
...state,
|
|
1372
|
-
held: { value }
|
|
1373
|
-
}];
|
|
1374
|
-
const wait = state.lastSent === void 0 ? 0 : Math.min(throttle, state.lastSent + throttle - at);
|
|
1375
|
-
if (wait <= 0) return [true, {
|
|
1376
|
-
...state,
|
|
1377
|
-
lastSent: at
|
|
1378
|
-
}];
|
|
1379
|
-
const flusher = yield* Effect.forkIn(flush(wait), scope);
|
|
1380
|
-
return [false, {
|
|
1381
|
-
...state,
|
|
1382
|
-
held: { value },
|
|
1383
|
-
flusher
|
|
1384
|
-
}];
|
|
1385
|
-
}).pipe(Effect.uninterruptible))) yield* publish(value);
|
|
1386
|
-
});
|
|
1387
|
-
const set = Effect.fn("Presence.set")(function* (value) {
|
|
1388
|
-
if (yield* Ref.get(closed)) return;
|
|
1389
|
-
const at = yield* Clock.currentTimeMillis;
|
|
1390
|
-
yield* put(options.id, value, at);
|
|
1391
|
-
if (channel !== void 0) yield* broadcast(value, at);
|
|
1392
|
-
yield* notify();
|
|
1393
|
-
});
|
|
1394
|
-
const leave = Effect.fn("Presence.leave")(function* () {
|
|
1395
|
-
if (yield* Ref.get(closed)) return;
|
|
1396
|
-
yield* cancelHeld;
|
|
1397
|
-
yield* remove(options.id);
|
|
1398
|
-
if (channel !== void 0) yield* channel.publish({
|
|
1399
|
-
id: options.id,
|
|
1400
|
-
value: null
|
|
1401
|
-
});
|
|
1402
|
-
yield* notify();
|
|
1403
|
-
})();
|
|
1404
|
-
const peerList = Effect.fn("Presence.peers")(function* () {
|
|
1405
|
-
const at = yield* Clock.currentTimeMillis;
|
|
1406
|
-
return [...(yield* Ref.get(peers)).values()].filter((peer) => !expired(peer, at)).map((peer) => ({ ...peer }));
|
|
1407
|
-
})();
|
|
1408
|
-
const prune = Effect.fn("Presence.prune")(function* () {
|
|
1409
|
-
if (yield* Ref.get(closed)) return;
|
|
1410
|
-
const at = yield* Clock.currentTimeMillis;
|
|
1411
|
-
if (yield* Ref.modify(peers, (map) => {
|
|
1412
|
-
let removed = false;
|
|
1413
|
-
const next = new Map(map);
|
|
1414
|
-
for (const [id, peer] of map) if (expired(peer, at)) {
|
|
1415
|
-
next.delete(id);
|
|
1416
|
-
removed = true;
|
|
1417
|
-
}
|
|
1418
|
-
return [removed, next];
|
|
1419
|
-
})) yield* notify();
|
|
1420
|
-
})();
|
|
1421
|
-
const close = Effect.fn("Presence.close")(function* () {
|
|
1422
|
-
if (yield* Ref.get(closed)) return;
|
|
1423
|
-
yield* Ref.set(closed, true);
|
|
1424
|
-
yield* cancelHeld;
|
|
1425
|
-
if (consuming !== void 0) yield* Fiber.interrupt(consuming);
|
|
1426
|
-
yield* Effect.sync(() => listeners.clear());
|
|
1427
|
-
yield* PubSub.shutdown(signals);
|
|
1428
|
-
})();
|
|
1429
|
-
return {
|
|
1430
|
-
set,
|
|
1431
|
-
leave,
|
|
1432
|
-
peers: peerList,
|
|
1433
|
-
prune,
|
|
1434
|
-
subscribe: (listener) => {
|
|
1435
|
-
listeners.add(listener);
|
|
1436
|
-
return () => listeners.delete(listener);
|
|
1437
|
-
},
|
|
1438
|
-
changes: Stream.concat(Stream.fromEffect(peerList), Stream.fromPubSub(signals).pipe(Stream.mapEffect(() => peerList))),
|
|
1439
|
-
close
|
|
1440
|
-
};
|
|
1441
|
-
});
|
|
1442
|
-
/** An in-process channel, for tests and single-process demos. */
|
|
1443
|
-
const loopbackPresenceChannel = Effect.fn("Presence.loopbackChannel")(function* () {
|
|
1444
|
-
const updates = yield* PubSub.unbounded();
|
|
1445
|
-
return {
|
|
1446
|
-
updates,
|
|
1447
|
-
publish: (update) => PubSub.publish(updates, update)
|
|
1448
|
-
};
|
|
1449
|
-
});
|
|
1450
|
-
const createPresenceHub = () => {
|
|
1451
|
-
const peers = /* @__PURE__ */ new Set();
|
|
1452
|
-
return {
|
|
1453
|
-
join: (send) => {
|
|
1454
|
-
peers.add(send);
|
|
1455
|
-
return () => peers.delete(send);
|
|
1456
|
-
},
|
|
1457
|
-
publish: (update) => {
|
|
1458
|
-
for (const send of [...peers]) try {
|
|
1459
|
-
send(update);
|
|
1460
|
-
} catch {}
|
|
1461
|
-
}
|
|
1462
|
-
};
|
|
1463
|
-
};
|
|
1464
|
-
const frameType = "presence";
|
|
1465
|
-
/** Decodes a presence frame, ignoring anything else a socket may carry. */
|
|
1466
|
-
const decodePresence = (data) => {
|
|
1467
|
-
let frame;
|
|
1468
|
-
try {
|
|
1469
|
-
frame = JSON.parse(data);
|
|
1470
|
-
} catch {
|
|
1471
|
-
return;
|
|
1472
|
-
}
|
|
1473
|
-
if (typeof frame !== "object" || frame === null) return void 0;
|
|
1474
|
-
const payload = frame[frameType];
|
|
1475
|
-
if (typeof payload !== "object" || payload === null) return void 0;
|
|
1476
|
-
const { id, value } = payload;
|
|
1477
|
-
return {
|
|
1478
|
-
id: typeof id === "string" ? id : void 0,
|
|
1479
|
-
value: value ?? null
|
|
1480
|
-
};
|
|
1481
|
-
};
|
|
1482
|
-
/**
|
|
1483
|
-
* A presence channel fed by stamped frames from the server, sent back without an
|
|
1484
|
-
* id: the server owns peer identity, so a client cannot assert another's.
|
|
1485
|
-
*/
|
|
1486
|
-
const socketPresenceChannel = (socket) => Effect.gen(function* () {
|
|
1487
|
-
const updates = yield* PubSub.unbounded();
|
|
1488
|
-
yield* Effect.acquireRelease(Effect.sync(() => socket.onMessage((data) => {
|
|
1489
|
-
const frame = decodePresence(data);
|
|
1490
|
-
if (frame === void 0 || frame.id === void 0) return;
|
|
1491
|
-
PubSub.publishUnsafe(updates, {
|
|
1492
|
-
id: frame.id,
|
|
1493
|
-
value: frame.value
|
|
1494
|
-
});
|
|
1495
|
-
})), (off) => Effect.sync(off));
|
|
1496
|
-
return {
|
|
1497
|
-
updates,
|
|
1498
|
-
publish: (update) => Effect.sync(() => socket.send(JSON.stringify({ [frameType]: { value: update.value } })))
|
|
1499
|
-
};
|
|
1500
|
-
});
|
|
1501
|
-
/**
|
|
1502
|
-
* Serves presence frames on an accepted socket, stamping the connection's
|
|
1503
|
-
* identity, until the socket closes or the returned function is called.
|
|
1504
|
-
* With `opens`, the connection joins only once it answers that it may open
|
|
1505
|
-
* the document the presence accompanies: until then, and for good when it
|
|
1506
|
-
* is refused or fails, nothing reaches it and nothing it sends is relayed.
|
|
1507
|
-
*/
|
|
1508
|
-
const servePresence = (socket, hub, options) => {
|
|
1509
|
-
const send = (update) => socket.send(JSON.stringify({ [frameType]: {
|
|
1510
|
-
id: update.id,
|
|
1511
|
-
value: update.value
|
|
1512
|
-
} }));
|
|
1513
|
-
let stopped = false;
|
|
1514
|
-
let leave = () => {};
|
|
1515
|
-
let off = () => {};
|
|
1516
|
-
const join = () => {
|
|
1517
|
-
leave = hub.join(send);
|
|
1518
|
-
off = socket.onMessage((data) => {
|
|
1519
|
-
const frame = decodePresence(data);
|
|
1520
|
-
if (frame === void 0) return;
|
|
1521
|
-
const publish = () => hub.publish({
|
|
1522
|
-
id: options.peerId,
|
|
1523
|
-
value: frame.value
|
|
1524
|
-
});
|
|
1525
|
-
if (options.opens === void 0) return publish();
|
|
1526
|
-
Effect.runPromise(options.opens).then((open) => {
|
|
1527
|
-
if (stopped) return;
|
|
1528
|
-
if (open) publish();
|
|
1529
|
-
else stop();
|
|
1530
|
-
}, () => stop());
|
|
1531
|
-
});
|
|
1532
|
-
};
|
|
1533
|
-
if (options.opens === void 0) join();
|
|
1534
|
-
else Effect.runPromise(options.opens).then((open) => {
|
|
1535
|
-
if (open && !stopped) join();
|
|
1536
|
-
}, () => {});
|
|
1537
|
-
const stop = () => {
|
|
1538
|
-
stopped = true;
|
|
1539
|
-
off();
|
|
1540
|
-
leave();
|
|
1541
|
-
};
|
|
1542
|
-
const stopClose = socket.onClose(stop);
|
|
1543
|
-
return () => {
|
|
1544
|
-
stop();
|
|
1545
|
-
stopClose();
|
|
1546
|
-
};
|
|
1547
|
-
};
|
|
1548
|
-
// src/index.ts
|
|
1549
|
-
/**
|
|
1550
|
-
* `foldkit-sync` — a local-first replica of a shared Foldkit projection.
|
|
1551
|
-
*
|
|
1552
|
-
* The application's Message union and update function stay authoritative: sync
|
|
1553
|
-
* wraps them rather than introducing a second reducer. The replica owns the
|
|
1554
|
-
* local outbox, optimistic projection, and reconciliation; a durable server
|
|
1555
|
-
* journal provides authoritative order.
|
|
1556
|
-
*
|
|
1557
|
-
* `Sync` is the namespace: `Sync.forApplication`, `Sync.mount`,
|
|
1558
|
-
* `Sync.transport.socket`. Ids are branded schemas, so they construct through
|
|
1559
|
-
* `DocumentId.make('todos')`. Every name is also exported on its own.
|
|
1560
|
-
*/
|
|
1561
|
-
/** The package's public surface, grouped. Each entry is the exported function itself. */
|
|
1562
|
-
const Sync = {
|
|
1563
|
-
/** Derives a sync contract from a Foldkit application: `Sync.forApplication(App).make({…})`. */
|
|
1564
|
-
forApplication,
|
|
1565
|
-
/** The protocol primitive, for a client with no Foldkit application to derive from. */
|
|
1566
|
-
define: defineSync,
|
|
1567
|
-
/** Runs a Foldkit application over an open replica with one reducer. */
|
|
1568
|
-
mount,
|
|
1569
|
-
/** A Command whose Message the mount applies within the transition that returned it. */
|
|
1570
|
-
fact,
|
|
1571
|
-
/** Counters and a histogram an application can scrape. */
|
|
1572
|
-
metrics: syncMetrics,
|
|
1573
|
-
/** The only storage adapter: one IndexedDB database per document/replica. */
|
|
1574
|
-
indexedDb,
|
|
1575
|
-
/** The `Transport` service's layers, and the bridges to and from a promise client. */
|
|
1576
|
-
transport: {
|
|
1577
|
-
/** A reconnecting WebSocket client layer. */
|
|
1578
|
-
socket: layerSocket,
|
|
1579
|
-
/** An in-process layer, for tests and single-process demos. */
|
|
1580
|
-
loopback: layerLoopback,
|
|
1581
|
-
/** Wraps the promise-based client the replica already speaks. */
|
|
1582
|
-
fromPromise: layerFromPromise,
|
|
1583
|
-
/** Bridges the service back to that promise client. */
|
|
1584
|
-
toPromise,
|
|
1585
|
-
/** The server side of one accepted socket connection. */
|
|
1586
|
-
serve: serveSocket,
|
|
1587
|
-
/** The accepted end of a Cloudflare `WebSocketPair`, for `serve`. */
|
|
1588
|
-
workerSocket,
|
|
1589
|
-
/** The default socket factory: the platform `WebSocket`. */
|
|
1590
|
-
nativeSocket,
|
|
1591
|
-
/** A socket over a `MessagePort`, closed by `close()` or an abort signal. */
|
|
1592
|
-
portSocket
|
|
1593
|
-
},
|
|
1594
|
-
/** An ephemeral, TTL'd peer registry, deliberately outside the durable log. */
|
|
1595
|
-
presence: {
|
|
1596
|
-
make: createPresence,
|
|
1597
|
-
/** Broadcasts presence updates among connected peers, on the server. */
|
|
1598
|
-
hub: createPresenceHub,
|
|
1599
|
-
/** Serves presence frames on an accepted socket, stamping the connection's identity. */
|
|
1600
|
-
serve: servePresence,
|
|
1601
|
-
socketChannel: socketPresenceChannel,
|
|
1602
|
-
loopbackChannel: loopbackPresenceChannel
|
|
1603
|
-
},
|
|
1604
|
-
/** Last-writer-wins registers (experimental): a per-field merge on logical time. */
|
|
1605
|
-
lww: {
|
|
1606
|
-
register: lwwRegister,
|
|
1607
|
-
/** The durable counter a stamp is allocated from, before dispatch. */
|
|
1608
|
-
openClock: openLwwClock
|
|
1609
|
-
}
|
|
1610
|
-
};
|
|
1611
|
-
export { CheckpointRegressionError, CommittedOrderError, DocumentId, ForeignAcknowledgementError, ForeignRejectionError, InvalidExchangeError, InvalidOutboxError, InvalidReplicaHistoryError, LocalSequence, OpId, ReplayError, ReplicaClosedError, ReplicaId, Sequence, StorageError, Sync, Transport, TransportError, UnsupportedClockVersionError, UnsupportedReplicaVersionError, WrongReplicaStorageError, createPresence, createPresenceHub, defineSync, documentId, fact, forApplication, indexedDb, layerFromPromise, layerLoopback, layerSocket, localSequence, loopbackPresenceChannel, lwwRegister, mount, nativeSocket, opId, openLwwClock, portSocket, replicaId, sequence, servePresence, serveSocket, socketPresenceChannel, syncMetrics, toPromise, workerSocket };
|
|
1612
|
-
|
|
1613
|
-
//# sourceMappingURL=index.mjs.map
|