cojson 0.0.1 → 0.0.3

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/src/sync.ts ADDED
@@ -0,0 +1,493 @@
1
+ import { Hash, Signature } from "./crypto";
2
+ import { CoValueHeader, Transaction } from "./coValue";
3
+ import { CoValue } from "./coValue";
4
+ import { LocalNode } from "./node";
5
+ import { newLoadingState } from "./node";
6
+ import { ReadableStream, WritableStream, WritableStreamDefaultWriter } from "isomorphic-streams";
7
+ import { RawCoValueID, SessionID } from "./ids";
8
+
9
+ export type CoValueKnownState = {
10
+ coValueID: RawCoValueID;
11
+ header: boolean;
12
+ sessions: { [sessionID: SessionID]: number };
13
+ };
14
+
15
+ export function emptyKnownState(coValueID: RawCoValueID): CoValueKnownState {
16
+ return {
17
+ coValueID,
18
+ header: false,
19
+ sessions: {},
20
+ };
21
+ }
22
+
23
+ export type SyncMessage =
24
+ | SubscribeMessage
25
+ | TellKnownStateMessage
26
+ | NewContentMessage
27
+ | WrongAssumedKnownStateMessage
28
+ | UnsubscribeMessage;
29
+
30
+ export type SubscribeMessage = {
31
+ action: "subscribe";
32
+ } & CoValueKnownState;
33
+
34
+ export type TellKnownStateMessage = {
35
+ action: "tellKnownState";
36
+ asDependencyOf?: RawCoValueID;
37
+ } & CoValueKnownState;
38
+
39
+ export type NewContentMessage = {
40
+ action: "newContent";
41
+ coValueID: RawCoValueID;
42
+ header?: CoValueHeader;
43
+ newContent: {
44
+ [sessionID: SessionID]: SessionNewContent;
45
+ };
46
+ };
47
+
48
+ export type SessionNewContent = {
49
+ after: number;
50
+ newTransactions: Transaction[];
51
+ // TODO: is lastHash needed here?
52
+ lastHash: Hash;
53
+ lastSignature: Signature;
54
+ };
55
+
56
+ export type WrongAssumedKnownStateMessage = {
57
+ action: "wrongAssumedKnownState";
58
+ } & CoValueKnownState;
59
+
60
+ export type UnsubscribeMessage = {
61
+ action: "unsubscribe";
62
+ coValueID: RawCoValueID;
63
+ };
64
+
65
+ export type PeerID = string;
66
+
67
+ export interface Peer {
68
+ id: PeerID;
69
+ incoming: ReadableStream<SyncMessage>;
70
+ outgoing: WritableStream<SyncMessage>;
71
+ role: "peer" | "server" | "client";
72
+ }
73
+
74
+ export interface PeerState {
75
+ id: PeerID;
76
+ optimisticKnownStates: { [coValueID: RawCoValueID]: CoValueKnownState };
77
+ toldKnownState: Set<RawCoValueID>;
78
+ incoming: ReadableStream<SyncMessage>;
79
+ outgoing: WritableStreamDefaultWriter<SyncMessage>;
80
+ role: "peer" | "server" | "client";
81
+ }
82
+
83
+ export function combinedKnownStates(
84
+ stateA: CoValueKnownState,
85
+ stateB: CoValueKnownState
86
+ ): CoValueKnownState {
87
+ const sessionStates: CoValueKnownState["sessions"] = {};
88
+
89
+ const allSessions = new Set([
90
+ ...Object.keys(stateA.sessions),
91
+ ...Object.keys(stateB.sessions),
92
+ ] as SessionID[]);
93
+
94
+ for (const sessionID of allSessions) {
95
+ const stateAValue = stateA.sessions[sessionID];
96
+ const stateBValue = stateB.sessions[sessionID];
97
+
98
+ sessionStates[sessionID] = Math.max(stateAValue || 0, stateBValue || 0);
99
+ }
100
+
101
+ return {
102
+ coValueID: stateA.coValueID,
103
+ header: stateA.header || stateB.header,
104
+ sessions: sessionStates,
105
+ };
106
+ }
107
+
108
+ export class SyncManager {
109
+ peers: { [key: PeerID]: PeerState } = {};
110
+ local: LocalNode;
111
+
112
+ constructor(local: LocalNode) {
113
+ this.local = local;
114
+ }
115
+
116
+ loadFromPeers(id: RawCoValueID) {
117
+ for (const peer of Object.values(this.peers)) {
118
+ peer.outgoing
119
+ .write({
120
+ action: "subscribe",
121
+ coValueID: id,
122
+ header: false,
123
+ sessions: {},
124
+ })
125
+ .catch((e) => {
126
+ console.error("Error writing to peer", e);
127
+ });
128
+ }
129
+ }
130
+
131
+ async handleSyncMessage(msg: SyncMessage, peer: PeerState) {
132
+ // TODO: validate
133
+ switch (msg.action) {
134
+ case "subscribe":
135
+ return await this.handleSubscribe(msg, peer);
136
+ case "tellKnownState":
137
+ return await this.handleTellKnownState(msg, peer);
138
+ case "newContent":
139
+ return await this.handleNewContent(msg, peer);
140
+ case "wrongAssumedKnownState":
141
+ return await this.handleWrongAssumedKnownState(msg, peer);
142
+ case "unsubscribe":
143
+ return await this.handleUnsubscribe(msg);
144
+ default:
145
+ throw new Error(
146
+ `Unknown message type ${
147
+ (msg as { action: "string" }).action
148
+ }`
149
+ );
150
+ }
151
+ }
152
+
153
+ async subscribeToIncludingDependencies(
154
+ coValueID: RawCoValueID,
155
+ peer: PeerState
156
+ ) {
157
+ const coValue = this.local.expectCoValueLoaded(coValueID);
158
+
159
+ for (const coValueID of coValue.getDependedOnCoValues()) {
160
+ await this.subscribeToIncludingDependencies(coValueID, peer);
161
+ }
162
+
163
+ if (!peer.toldKnownState.has(coValueID)) {
164
+ peer.toldKnownState.add(coValueID);
165
+ await peer.outgoing.write({
166
+ action: "subscribe",
167
+ ...coValue.knownState(),
168
+ });
169
+ }
170
+ }
171
+
172
+ async tellUntoldKnownStateIncludingDependencies(
173
+ coValueID: RawCoValueID,
174
+ peer: PeerState,
175
+ asDependencyOf?: RawCoValueID
176
+ ) {
177
+ const coValue = this.local.expectCoValueLoaded(coValueID);
178
+
179
+ for (const dependentCoValueID of coValue.getDependedOnCoValues()) {
180
+ await this.tellUntoldKnownStateIncludingDependencies(
181
+ dependentCoValueID,
182
+ peer,
183
+ asDependencyOf || coValueID
184
+ );
185
+ }
186
+
187
+ if (!peer.toldKnownState.has(coValueID)) {
188
+ await peer.outgoing.write({
189
+ action: "tellKnownState",
190
+ asDependencyOf,
191
+ ...coValue.knownState(),
192
+ });
193
+
194
+ peer.toldKnownState.add(coValueID);
195
+ }
196
+ }
197
+
198
+ async sendNewContentIncludingDependencies(
199
+ coValueID: RawCoValueID,
200
+ peer: PeerState
201
+ ) {
202
+ const coValue = this.local.expectCoValueLoaded(coValueID);
203
+
204
+ for (const coValueID of coValue.getDependedOnCoValues()) {
205
+ await this.sendNewContentIncludingDependencies(coValueID, peer);
206
+ }
207
+
208
+ const newContent = coValue.newContentSince(
209
+ peer.optimisticKnownStates[coValueID]
210
+ );
211
+
212
+ if (newContent) {
213
+ await peer.outgoing.write(newContent);
214
+ peer.optimisticKnownStates[coValueID] = combinedKnownStates(
215
+ peer.optimisticKnownStates[coValueID] ||
216
+ emptyKnownState(coValueID),
217
+ coValue.knownState()
218
+ );
219
+ }
220
+ }
221
+
222
+ addPeer(peer: Peer) {
223
+ const peerState: PeerState = {
224
+ id: peer.id,
225
+ optimisticKnownStates: {},
226
+ incoming: peer.incoming,
227
+ outgoing: peer.outgoing.getWriter(),
228
+ toldKnownState: new Set(),
229
+ role: peer.role,
230
+ };
231
+ this.peers[peer.id] = peerState;
232
+
233
+ if (peer.role === "server") {
234
+ const initialSync = async () => {
235
+ for (const entry of Object.values(this.local.coValues)) {
236
+ if (entry.state === "loading") {
237
+ continue;
238
+ }
239
+
240
+ await this.subscribeToIncludingDependencies(
241
+ entry.coValue.id,
242
+ peerState
243
+ );
244
+
245
+ peerState.optimisticKnownStates[entry.coValue.id] = {
246
+ coValueID: entry.coValue.id,
247
+ header: false,
248
+ sessions: {},
249
+ };
250
+ }
251
+ };
252
+ void initialSync();
253
+ }
254
+
255
+ const readIncoming = async () => {
256
+ for await (const msg of peerState.incoming) {
257
+ try {
258
+ await this.handleSyncMessage(msg, peerState);
259
+ } catch (e) {
260
+ console.error(
261
+ `Error reading from peer ${peer.id}`,
262
+ JSON.stringify(msg),
263
+ e
264
+ );
265
+ }
266
+ }
267
+ };
268
+
269
+ void readIncoming();
270
+ }
271
+
272
+ async handleSubscribe(msg: SubscribeMessage, peer: PeerState) {
273
+ const entry = this.local.coValues[msg.coValueID];
274
+
275
+ if (!entry || entry.state === "loading") {
276
+ if (!entry) {
277
+ this.local.coValues[msg.coValueID] = newLoadingState();
278
+ }
279
+
280
+ peer.optimisticKnownStates[msg.coValueID] = knownStateIn(msg);
281
+ peer.toldKnownState.add(msg.coValueID);
282
+
283
+ await peer.outgoing.write({
284
+ action: "tellKnownState",
285
+ coValueID: msg.coValueID,
286
+ header: false,
287
+ sessions: {},
288
+ });
289
+
290
+ return;
291
+ }
292
+
293
+ peer.optimisticKnownStates[msg.coValueID] = knownStateIn(msg);
294
+
295
+ await this.tellUntoldKnownStateIncludingDependencies(
296
+ msg.coValueID,
297
+ peer
298
+ );
299
+
300
+ await this.sendNewContentIncludingDependencies(msg.coValueID, peer);
301
+ }
302
+
303
+ async handleTellKnownState(msg: TellKnownStateMessage, peer: PeerState) {
304
+ let entry = this.local.coValues[msg.coValueID];
305
+
306
+ peer.optimisticKnownStates[msg.coValueID] = combinedKnownStates(
307
+ peer.optimisticKnownStates[msg.coValueID] || emptyKnownState(msg.coValueID),
308
+ knownStateIn(msg)
309
+ );
310
+
311
+ if (!entry) {
312
+ if (msg.asDependencyOf) {
313
+ if (this.local.coValues[msg.asDependencyOf]) {
314
+ entry = newLoadingState();
315
+
316
+ this.local.coValues[msg.coValueID] = entry;
317
+ } else {
318
+ throw new Error(
319
+ "Expected coValue dependency entry to be created, missing subscribe?"
320
+ );
321
+ }
322
+ } else {
323
+ throw new Error(
324
+ "Expected coValue entry to be created, missing subscribe?"
325
+ );
326
+ }
327
+ }
328
+
329
+ if (entry.state === "loading") {
330
+ return [];
331
+ }
332
+
333
+ await this.tellUntoldKnownStateIncludingDependencies(
334
+ msg.coValueID,
335
+ peer
336
+ );
337
+ await this.sendNewContentIncludingDependencies(msg.coValueID, peer);
338
+ }
339
+
340
+ async handleNewContent(msg: NewContentMessage, peer: PeerState) {
341
+ let entry = this.local.coValues[msg.coValueID];
342
+
343
+ if (!entry) {
344
+ throw new Error(
345
+ "Expected coValue entry to be created, missing subscribe?"
346
+ );
347
+ }
348
+
349
+ let resolveAfterDone: ((coValue: CoValue) => void) | undefined;
350
+
351
+ const peerOptimisticKnownState =
352
+ peer.optimisticKnownStates[msg.coValueID];
353
+
354
+ if (!peerOptimisticKnownState) {
355
+ throw new Error(
356
+ "Expected optimisticKnownState to be set for coValue we receive new content for"
357
+ );
358
+ }
359
+
360
+ if (entry.state === "loading") {
361
+ if (!msg.header) {
362
+ throw new Error("Expected header to be sent in first message");
363
+ }
364
+
365
+ peerOptimisticKnownState.header = true;
366
+
367
+ const coValue = new CoValue(msg.header, this.local);
368
+
369
+ resolveAfterDone = entry.resolve;
370
+
371
+ entry = {
372
+ state: "loaded",
373
+ coValue: coValue,
374
+ };
375
+
376
+ this.local.coValues[msg.coValueID] = entry;
377
+ }
378
+
379
+ const coValue = entry.coValue;
380
+
381
+ let invalidStateAssumed = false;
382
+
383
+ for (const [sessionID, newContentForSession] of Object.entries(
384
+ msg.newContent
385
+ ) as [SessionID, SessionNewContent][]) {
386
+ const ourKnownTxIdx =
387
+ coValue.sessions[sessionID]?.transactions.length;
388
+ const theirFirstNewTxIdx = newContentForSession.after;
389
+
390
+ if ((ourKnownTxIdx || 0) < theirFirstNewTxIdx) {
391
+ invalidStateAssumed = true;
392
+ continue;
393
+ }
394
+
395
+ const alreadyKnownOffset = ourKnownTxIdx
396
+ ? ourKnownTxIdx - theirFirstNewTxIdx
397
+ : 0;
398
+
399
+ const newTransactions =
400
+ newContentForSession.newTransactions.slice(alreadyKnownOffset);
401
+
402
+ const success = coValue.tryAddTransactions(
403
+ sessionID,
404
+ newTransactions,
405
+ newContentForSession.lastHash,
406
+ newContentForSession.lastSignature
407
+ );
408
+
409
+ if (!success) {
410
+ console.error("Failed to add transactions", newTransactions);
411
+ continue;
412
+ }
413
+
414
+ peerOptimisticKnownState.sessions[sessionID] =
415
+ newContentForSession.after +
416
+ newContentForSession.newTransactions.length;
417
+ }
418
+
419
+ if (resolveAfterDone) {
420
+ resolveAfterDone(coValue);
421
+ }
422
+
423
+ await this.syncCoValue(coValue);
424
+
425
+ if (invalidStateAssumed) {
426
+ await peer.outgoing.write({
427
+ action: "wrongAssumedKnownState",
428
+ ...coValue.knownState(),
429
+ });
430
+ }
431
+ }
432
+
433
+ async handleWrongAssumedKnownState(
434
+ msg: WrongAssumedKnownStateMessage,
435
+ peer: PeerState
436
+ ) {
437
+ const coValue = this.local.expectCoValueLoaded(msg.coValueID);
438
+
439
+ peer.optimisticKnownStates[msg.coValueID] = combinedKnownStates(
440
+ msg,
441
+ coValue.knownState()
442
+ );
443
+
444
+ const newContent = coValue.newContentSince(msg);
445
+
446
+ if (newContent) {
447
+ await peer.outgoing.write(newContent);
448
+ }
449
+ }
450
+
451
+ handleUnsubscribe(_msg: UnsubscribeMessage) {
452
+ throw new Error("Method not implemented.");
453
+ }
454
+
455
+ async syncCoValue(coValue: CoValue) {
456
+ for (const peer of Object.values(this.peers)) {
457
+ const optimisticKnownState = peer.optimisticKnownStates[coValue.id];
458
+
459
+ if (optimisticKnownState) {
460
+ await this.tellUntoldKnownStateIncludingDependencies(
461
+ coValue.id,
462
+ peer
463
+ );
464
+ await this.sendNewContentIncludingDependencies(
465
+ coValue.id,
466
+ peer
467
+ );
468
+ } else if (peer.role === "server") {
469
+ await this.subscribeToIncludingDependencies(
470
+ coValue.id,
471
+ peer
472
+ );
473
+ await this.sendNewContentIncludingDependencies(
474
+ coValue.id,
475
+ peer
476
+ );
477
+ }
478
+ }
479
+ }
480
+ }
481
+
482
+ function knownStateIn(
483
+ msg:
484
+ | SubscribeMessage
485
+ | TellKnownStateMessage
486
+ | WrongAssumedKnownStateMessage
487
+ ) {
488
+ return {
489
+ coValueID: msg.coValueID,
490
+ header: msg.header,
491
+ sessions: msg.sessions,
492
+ };
493
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "lib": ["ESNext"],
4
+ "module": "esnext",
5
+ "target": "esnext",
6
+ "moduleResolution": "bundler",
7
+ "moduleDetection": "force",
8
+ "allowImportingTsExtensions": true,
9
+ "strict": true,
10
+ "downlevelIteration": true,
11
+ "skipLibCheck": true,
12
+ "jsx": "preserve",
13
+ "allowSyntheticDefaultImports": true,
14
+ "forceConsistentCasingInFileNames": true,
15
+ "allowJs": true,
16
+ "noEmit": true,
17
+ "noUncheckedIndexedAccess": true,
18
+ "esModuleInterop": true,
19
+ },
20
+ "include": ["./src/**/*"],
21
+ }