foldkit-sync 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +160 -27
  2. package/dist/diagnostics.d.ts +29 -2
  3. package/dist/diagnostics.d.ts.map +1 -1
  4. package/dist/diagnostics.js +33 -4
  5. package/dist/diagnostics.js.map +1 -1
  6. package/dist/do.d.ts +11 -8
  7. package/dist/do.d.ts.map +1 -1
  8. package/dist/do.js +3 -4
  9. package/dist/do.js.map +1 -1
  10. package/dist/errors.d.ts +16 -3
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +15 -3
  13. package/dist/errors.js.map +1 -1
  14. package/dist/index.d.ts +9 -7
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +6 -4
  17. package/dist/index.js.map +1 -1
  18. package/dist/journal.d.ts +15 -9
  19. package/dist/journal.d.ts.map +1 -1
  20. package/dist/journal.js +48 -19
  21. package/dist/journal.js.map +1 -1
  22. package/dist/make.d.ts +40 -6
  23. package/dist/make.d.ts.map +1 -1
  24. package/dist/make.js +35 -3
  25. package/dist/make.js.map +1 -1
  26. package/dist/mount.d.ts.map +1 -1
  27. package/dist/mount.js +27 -2
  28. package/dist/mount.js.map +1 -1
  29. package/dist/refusal.d.ts +10 -2
  30. package/dist/refusal.d.ts.map +1 -1
  31. package/dist/refusal.js +10 -4
  32. package/dist/refusal.js.map +1 -1
  33. package/dist/serverJournal.d.ts +6 -1
  34. package/dist/serverJournal.d.ts.map +1 -1
  35. package/dist/serverJournal.js +1 -1
  36. package/dist/serverJournal.js.map +1 -1
  37. package/dist/sync.d.ts +48 -7
  38. package/dist/sync.d.ts.map +1 -1
  39. package/dist/sync.js +28 -8
  40. package/dist/sync.js.map +1 -1
  41. package/dist/transport.d.ts +35 -8
  42. package/dist/transport.d.ts.map +1 -1
  43. package/dist/transport.js +41 -8
  44. package/dist/transport.js.map +1 -1
  45. package/package.json +12 -12
@@ -1,7 +1,10 @@
1
1
  import { Context, Duration, Effect, Layer, Schema, Stream } from "effect";
2
- import { TransportClient, WrittenOperation } from "./sync.js";
2
+ import { ReportDiagnostic } from "foldkit-surface";
3
+ import { TransportClient } from "./sync.js";
3
4
  declare const TransportError_base: Schema.Class<TransportError, Schema.TaggedStruct<"SyncTransportError", {
4
5
  readonly message: Schema.String;
6
+ /** The id a server reported its own failure under (`ExchangeDefect`), when it answered with one. */
7
+ readonly incident: Schema.optional<Schema.String>;
5
8
  }>, import("effect/Cause").YieldableError>;
6
9
  /** The wire failure of a transport. A refusal is a result, not an error. */
7
10
  export declare class TransportError extends TransportError_base {}
@@ -9,13 +12,24 @@ export declare class TransportError extends TransportError_base {}
9
12
  export interface ExchangeFrame {
10
13
  readonly id: string;
11
14
  readonly cursor: number;
12
- readonly pending: ReadonlyArray<WrittenOperation>;
15
+ readonly pending: ReadonlyArray<unknown>;
13
16
  readonly epoch?: string | undefined;
14
17
  }
18
+ declare const ExchangeRefused_base: Schema.Class<ExchangeRefused, Schema.TaggedStruct<"SyncExchangeRefused", {
19
+ readonly message: Schema.String;
20
+ }>, import("effect/Cause").YieldableError>;
21
+ /**
22
+ * A failed exchange in words written for the replica: throw it from a served
23
+ * exchange (`serveSocket`) and its `message` is sent as it is. Anything else a
24
+ * handler throws is the server's own, and is answered "Exchange failed".
25
+ */
26
+ export declare class ExchangeRefused extends ExchangeRefused_base {}
15
27
  export interface ExchangeReply {
16
28
  readonly id: string;
17
29
  readonly result?: unknown;
18
30
  readonly error?: string;
31
+ /** Beside `error`, when the server failed on its own side: the id it reported the cause under. */
32
+ readonly incident?: string;
19
33
  }
20
34
  /**
21
35
  * Sent by a server, unasked, when the document may have changed. It carries no
@@ -26,8 +40,12 @@ export interface NotifyFrame {
26
40
  readonly notify: true;
27
41
  }
28
42
  export interface TransportShape {
29
- /** `epoch` is the server history the replica's cursor points into, when it knows one. */
30
- readonly exchange: (cursor: number, pending: ReadonlyArray<WrittenOperation>, epoch?: string | undefined) => Effect.Effect<unknown, TransportError>;
43
+ /**
44
+ * `epoch` is the server history the replica's cursor points into, when it
45
+ * knows one. `pending` is unread: whoever answers reads each entry with
46
+ * `codec.writtenFrom` before appending it.
47
+ */
48
+ readonly exchange: (cursor: number, pending: ReadonlyArray<unknown>, epoch?: string | undefined) => Effect.Effect<unknown, TransportError>;
31
49
  /**
32
50
  * Emits when the server may have something new, for a transport that can hear
33
51
  * it: `Replica.start` exchanges on each. A wake-up, not data.
@@ -53,7 +71,7 @@ declare const TransportSocket_base: Context.ServiceClass<TransportSocket, "foldk
53
71
  */
54
72
  export declare class TransportSocket extends TransportSocket_base {}
55
73
  /** A transport backed by an in-process handler, for tests and single-process demos. */
56
- export declare const layerLoopback: (handler: (cursor: number, pending: ReadonlyArray<WrittenOperation>, epoch?: string | undefined) => unknown | Promise<unknown>) => Layer.Layer<Transport>;
74
+ export declare const layerLoopback: (handler: (cursor: number, pending: ReadonlyArray<unknown>, epoch?: string | undefined) => unknown | Promise<unknown>) => Layer.Layer<Transport>;
57
75
  /** Wraps the promise-based client the replica already speaks. */
58
76
  export declare const layerFromPromise: (transport: TransportClient) => Layer.Layer<Transport>;
59
77
  /** Bridges the service back to the promise client the replica consumes. */
@@ -61,16 +79,25 @@ export declare const toPromise: (transport: TransportShape) => TransportClient;
61
79
  /**
62
80
  * Serves one accepted socket, answering each exchange frame.
63
81
  *
64
- * The counterpart to `layerSocket`: the handler returns the exchange result, or
65
- * throws and the failure is written back as an error frame. With `changes`, a
82
+ * The counterpart to `layerSocket`: the handler returns the exchange result,
83
+ * or throws. An `ExchangeRefused`, and a replica newer than this server
84
+ * (`UnsupportedMessageVersionError`), are words for the replica, sent as they
85
+ * are. Anything else thrown is this side's (a journal's failure, a driver's
86
+ * words): it is reported as an `ExchangeDefect`, and the error frame says only
87
+ * "Exchange failed" and the incident it was reported under; a stored
88
+ * operation no build reads (`UnreadableHistoryError`) is reported so too, and
89
+ * its frame carries the journal's sentence for it, which names no operation.
90
+ * With `changes`, a
66
91
  * subscription to the document's commits, the socket is also sent a
67
92
  * `NotifyFrame` after each, so a client hears of others' edits without polling.
68
93
  * Returns a function that stops serving.
69
94
  */
70
95
  export declare const serveSocket: (socket: SocketLike, options: {
71
- readonly exchange: (cursor: number, pending: ReadonlyArray<WrittenOperation>, epoch?: string | undefined) => unknown | Promise<unknown>;
96
+ readonly exchange: (cursor: number, pending: ReadonlyArray<unknown>, epoch?: string | undefined) => unknown | Promise<unknown>;
72
97
  /** Subscribes to the document's commits; returns the unsubscribe. */
73
98
  readonly changes?: ((listener: () => void) => () => void) | undefined;
99
+ /** Where an exchange that threw is reported; the default reporter when not given, since this runs outside any context. */
100
+ readonly diagnostics?: ReportDiagnostic | undefined;
74
101
  }) => (() => void);
75
102
  /** The minimal socket the layer needs; the global `WebSocket` satisfies it. */
76
103
  export interface SocketLike {
@@ -1 +1 @@
1
- {"version":3,"file":"transport.d.ts","names":[],"sources":["../src/transport.ts"],"mappings":";;;;;;qBAOa,uBAAuB;;iBAKnB;WACN;WACA;WACA,SAAS,cAAc;WACvB;;iBAGM;WACN;WACA;WACA;;;;;;;iBAQM;WACN;;iBAGM;;WAEN,WACP,gBACA,SAAS,cAAc,mBACvB,+BACG,OAAO,gBAAgB;;;;;WAKnB,UAAU,OAAO;;;;;;;;;;qBAUf,kBAAkB;;;;;;;;;qBAWlB,wBAAwB;;qBAQxB,gBAAa,UAEtB,gBACA,SAAS,cAAc,mBACvB,yCACa,qBACd,MAAM,MAAM;;qBAUF,mBAAgB,WAAe,oBAAkB,MAAM,MAAM;;qBAU7D,YAAS,WAAe,mBAAiB;;;;;;;;;;qBAczC,cAAW,QACd,YAAU;WAEP,WACP,gBACA,SAAS,cAAc,mBACvB,yCACa;;WAEN,YAAY;;;iBAgER;EACf,KAAK;EACL;EACA,UAAU,WAAW;EACrB,QAAQ;;;;;EAKR,QAAQ;;;;;;;YAQE,gBAAgB;WAEX;WAAsB;;WACtB,kBAAkB;WAAqB;;UAG9C;;;;;;WAMC;;WAEA,YAAY,SAAS;;WAErB,gBAAgB,SAAS;;WAEzB;;;qBAIE,eAAY,gBAAkB;;;;;;;;qBAiC9B,aAAU,MACf,aAAW;WACG,SAAS;MAC5B;;;;;;;;qBAwCU,eAAY,QAAY,cAAY;;;;;;;;;;;;;;;;;qBAuEpC,cAAW,SACb,kBACR,MAAM,MAAM,YAAY,iBAAiB"}
1
+ {"version":3,"file":"transport.d.ts","names":[],"sources":["../src/transport.ts"],"mappings":";;;;;;;;;qBAQa,uBAAuB;;iBAOnB;WACN;WACA;WACA,SAAS;WACT;;;;;;;;;;qBAQE,wBAAwB;iBAIpB;WACN;WACA;WACA;;WAEA;;;;;;;iBAWM;WACN;;iBAGM;;;;;;WAMN,WACP,gBACA,SAAS,wBACT,+BACG,OAAO,gBAAgB;;;;;WAKnB,UAAU,OAAO;;;;;;;;;;qBAUf,kBAAkB;;;;;;;;;qBAWlB,wBAAwB;;qBAQxB,gBAAa,UAEtB,gBACA,SAAS,wBACT,yCACa,qBACd,MAAM,MAAM;;qBAUF,mBAAgB,WAAe,oBAAkB,MAAM,MAAM;;qBAU7D,YAAS,WAAe,mBAAiB;;;;;;;;;;;;;;;;;qBAqBzC,cAAW,QACd,YAAU;WAEP,WACP,gBACA,SAAS,wBACT,yCACa;;WAEN,YAAY;;WAEZ,cAAc;;;iBA4EV;EACf,KAAK;EACL;EACA,UAAU,WAAW;EACrB,QAAQ;;;;;EAKR,QAAQ;;;;;;;YAQE,gBAAgB;WAEX;WAAsB;;WACtB,kBAAkB;WAAqB;;UAG9C;;;;;;WAMC;;WAEA,YAAY,SAAS;;WAErB,gBAAgB,SAAS;;WAEzB;;;qBAIE,eAAY,gBAAkB;;;;;;;;qBAiC9B,aAAU,MACf,aAAW;WACG,SAAS;MAC5B;;;;;;;;qBAwCU,eAAY,QAAY,cAAY;;;;;;;;;;;;;;;;;qBAuEpC,cAAW,SACb,kBACR,MAAM,MAAM,YAAY,iBAAiB"}
package/dist/transport.js CHANGED
@@ -1,10 +1,23 @@
1
1
  import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from "effect";
2
2
  import { Diagnostics } from "foldkit-surface";
3
- import { listenerFailed } from "./diagnostics.js";
3
+ import { exchangeDefect, listenerFailed, mintIncident, reportTo } from "./diagnostics.js";
4
4
  import { sequence } from "./ids.js";
5
+ import { UnreadableHistoryError, UnsupportedMessageVersionError } from "./errors.js";
5
6
  // src/transport.ts
6
7
  /** The wire failure of a transport. A refusal is a result, not an error. */
7
- var TransportError = class extends Schema.TaggedError()("SyncTransportError", { message: Schema.String }) {};
8
+ var TransportError = class extends Schema.TaggedError()("SyncTransportError", {
9
+ message: Schema.String,
10
+ /** The id a server reported its own failure under (`ExchangeDefect`), when it answered with one. */
11
+ incident: Schema.optional(Schema.String)
12
+ }) {};
13
+ /**
14
+ * A failed exchange in words written for the replica: throw it from a served
15
+ * exchange (`serveSocket`) and its `message` is sent as it is. Anything else a
16
+ * handler throws is the server's own, and is answered "Exchange failed".
17
+ */
18
+ var ExchangeRefused = class extends Schema.TaggedError()("SyncExchangeRefused", { message: Schema.String }) {};
19
+ /** What a replica reads of an exchange that threw on the server's side, whatever was thrown. */
20
+ const EXCHANGE_FAILED = "Exchange failed";
8
21
  /**
9
22
  * The seam the replica syncs through.
10
23
  *
@@ -37,8 +50,15 @@ const toPromise = (transport) => ({ exchange: (cursor, pending, epoch) => Effect
37
50
  /**
38
51
  * Serves one accepted socket, answering each exchange frame.
39
52
  *
40
- * The counterpart to `layerSocket`: the handler returns the exchange result, or
41
- * throws and the failure is written back as an error frame. With `changes`, a
53
+ * The counterpart to `layerSocket`: the handler returns the exchange result,
54
+ * or throws. An `ExchangeRefused`, and a replica newer than this server
55
+ * (`UnsupportedMessageVersionError`), are words for the replica, sent as they
56
+ * are. Anything else thrown is this side's (a journal's failure, a driver's
57
+ * words): it is reported as an `ExchangeDefect`, and the error frame says only
58
+ * "Exchange failed" and the incident it was reported under; a stored
59
+ * operation no build reads (`UnreadableHistoryError`) is reported so too, and
60
+ * its frame carries the journal's sentence for it, which names no operation.
61
+ * With `changes`, a
42
62
  * subscription to the document's commits, the socket is also sent a
43
63
  * `NotifyFrame` after each, so a client hears of others' edits without polling.
44
64
  * Returns a function that stops serving.
@@ -79,10 +99,20 @@ const serveSocket = (socket, options) => {
79
99
  id: frame.id,
80
100
  result
81
101
  });
82
- } catch (error) {
102
+ } catch (thrown) {
103
+ if (thrown instanceof ExchangeRefused || thrown instanceof UnsupportedMessageVersionError) {
104
+ send({
105
+ id: frame.id,
106
+ error: thrown.message
107
+ });
108
+ return;
109
+ }
110
+ const incident = mintIncident();
111
+ await Effect.runPromise(reportTo(options.diagnostics, exchangeDefect(incident, thrown)));
83
112
  send({
84
113
  id: frame.id,
85
- error: error instanceof Error ? error.message : String(error)
114
+ error: thrown instanceof UnreadableHistoryError ? thrown.message : EXCHANGE_FAILED,
115
+ incident
86
116
  });
87
117
  }
88
118
  })();
@@ -326,7 +356,10 @@ const layerSocket = (options) => Layer.effectContext(Effect.fn("Transport.layerS
326
356
  if (entry === void 0) return;
327
357
  healthy();
328
358
  inFlight.delete(reply.id);
329
- entry.resume(reply.error === void 0 ? Effect.succeed(reply.result) : Effect.fail(new TransportError({ message: reply.error })));
359
+ entry.resume(reply.error === void 0 ? Effect.succeed(reply.result) : Effect.fail(new TransportError({
360
+ message: reply.error,
361
+ ...typeof reply.incident === "string" ? { incident: reply.incident } : {}
362
+ })));
330
363
  });
331
364
  const offClose = next.onClose(() => {
332
365
  offOpen?.();
@@ -395,6 +428,6 @@ const layerSocket = (options) => Layer.effectContext(Effect.fn("Transport.layerS
395
428
  });
396
429
  return Context.make(Transport, transport).pipe(Context.add(TransportSocket, shared));
397
430
  })());
398
- export { Transport, TransportError, TransportSocket, layerFromPromise, layerLoopback, layerSocket, nativeSocket, portSocket, serveSocket, toPromise, workerSocket };
431
+ export { ExchangeRefused, Transport, TransportError, TransportSocket, layerFromPromise, layerLoopback, layerSocket, nativeSocket, portSocket, serveSocket, toPromise, workerSocket };
399
432
 
400
433
  //# sourceMappingURL=transport.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","names":[],"sources":["../src/transport.ts"],"sourcesContent":["import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { TransportClient, WrittenOperation } from './sync.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { listenerFailed } from './diagnostics.js'\n\n/** The wire failure of a transport. A refusal is a result, not an error. */\nexport class TransportError extends Schema.TaggedError<TransportError>()('SyncTransportError', {\n message: Schema.String,\n}) {}\n\n/** One request/response frame, as it crosses a wire. */\nexport interface ExchangeFrame {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<WrittenOperation>\n readonly epoch?: string | undefined\n}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\n/**\n * Sent by a server, unasked, when the document may have changed. It carries no\n * data: the replica exchanges from its own cursor, so a notice that is lost,\n * late, or one of many is harmless.\n */\nexport interface NotifyFrame {\n readonly notify: true\n}\n\nexport interface TransportShape {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<WrittenOperation>,\n epoch?: string | undefined,\n ) => Effect.Effect<unknown, TransportError>\n /**\n * Emits when the server may have something new, for a transport that can hear\n * it: `Replica.start` exchanges on each. A wake-up, not data.\n */\n readonly changes?: Stream.Stream<void> | undefined\n}\n\n/**\n * The seam the replica syncs through.\n *\n * A service, not a concrete client, so an application substitutes an in-process\n * transport, a socket, or a test double without the replica knowing. A refusal\n * arrives in the exchange result; only a wire failure is a `TransportError`.\n */\nexport class Transport extends Context.Service<Transport, TransportShape>()(\n 'foldkit-sync/Transport',\n) {}\n\n/**\n * The connection `layerSocket` keeps, for another protocol to share, such as\n * presence: a send goes to the socket open now and is dropped while none is,\n * and messages from every socket the transport opens arrive here. It is the\n * transport's to close. Only a socket transport provides it, so a layer that\n * has one says so in its type.\n */\nexport class TransportSocket extends Context.Service<TransportSocket, SocketLike>()(\n 'foldkit-sync/TransportSocket',\n) {}\n\nconst failure = (error: unknown): TransportError =>\n new TransportError({ message: error instanceof Error ? error.message : String(error) })\n\n/** A transport backed by an in-process handler, for tests and single-process demos. */\nexport const layerLoopback = (\n handler: (\n cursor: number,\n pending: ReadonlyArray<WrittenOperation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => Promise.resolve(handler(cursor, pending, epoch)),\n catch: failure,\n }),\n })\n\n/** Wraps the promise-based client the replica already speaks. */\nexport const layerFromPromise = (transport: TransportClient): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending, epoch),\n catch: failure,\n }),\n })\n\n/** Bridges the service back to the promise client the replica consumes. */\nexport const toPromise = (transport: TransportShape): TransportClient => ({\n exchange: (cursor, pending, epoch) =>\n Effect.runPromise(transport.exchange(cursor, pending, epoch)),\n})\n\n/**\n * Serves one accepted socket, answering each exchange frame.\n *\n * The counterpart to `layerSocket`: the handler returns the exchange result, or\n * throws and the failure is written back as an error frame. With `changes`, a\n * subscription to the document's commits, the socket is also sent a\n * `NotifyFrame` after each, so a client hears of others' edits without polling.\n * Returns a function that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<WrittenOperation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>\n /** Subscribes to the document's commits; returns the unsubscribe. */\n readonly changes?: ((listener: () => void) => () => void) | undefined\n },\n): (() => void) => {\n const send = (reply: ExchangeReply | NotifyFrame): void => {\n try {\n socket.send(JSON.stringify(reply))\n } catch {\n // The socket may have closed while the handler was running.\n }\n }\n const stopMessage = socket.onMessage(data => {\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch {\n return\n }\n if (typeof parsed !== 'object' || parsed === null) return\n const { id, cursor, pending, epoch } = parsed as {\n id?: unknown\n cursor?: unknown\n pending?: unknown\n epoch?: unknown\n }\n // Without an id there is nobody to answer, so drop the frame.\n if (typeof id !== 'string') return\n if (\n typeof cursor !== 'number' ||\n !Number.isSafeInteger(cursor) ||\n cursor < 0 ||\n !Array.isArray(pending) ||\n (epoch !== undefined && typeof epoch !== 'string')\n ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = {\n id,\n cursor,\n pending: pending as ReadonlyArray<WrittenOperation>,\n epoch: typeof epoch === 'string' ? epoch : undefined,\n }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending, frame.epoch)\n send({ id: frame.id, result })\n } catch (error) {\n send({ id: frame.id, error: error instanceof Error ? error.message : String(error) })\n }\n })()\n })\n const stopChanges = options.changes?.(() => send({ notify: true }))\n const stop = (): void => {\n stopMessage()\n stopChanges?.()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\n stopClose()\n }\n}\n\n/** The minimal socket the layer needs; the global `WebSocket` satisfies it. */\nexport interface SocketLike {\n send(data: string): void\n close(): void\n onMessage(listener: (data: string) => void): () => void\n onClose(listener: () => void): () => void\n /**\n * Optional. When provided, exchanges wait for it before sending, so a\n * transport can connect asynchronously. Absent means already connected.\n */\n onOpen?(listener: () => void): () => void\n}\n\n/**\n * Where `layerSocket` connects: a `url` for the platform `WebSocket`, or a\n * `makeSocket` that opens any other `SocketLike` (a port, a test socket), called\n * again on every reconnect.\n */\nexport type SocketOptions = SocketTuning &\n (\n | { readonly url: string; readonly makeSocket?: undefined }\n | { readonly makeSocket: () => SocketLike; readonly url?: undefined }\n )\n\ninterface SocketTuning {\n /**\n * Consecutive failed connections after which queued work fails and new\n * exchanges fail fast until a connection is healthy again. Reconnecting goes\n * on regardless. Default 5.\n */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: Duration.Input | undefined\n /** Longest wait between reconnect attempts. Default `5 seconds`. */\n readonly maxRetryDelay?: Duration.Input | undefined\n /** Exchanges queued or in flight before new ones fail. Default 64. */\n readonly maxQueue?: number | undefined\n}\n\n/** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */\nexport const nativeSocket = (url: string): SocketLike => {\n const socket = new WebSocket(url)\n return {\n send: data => socket.send(data),\n close: () => socket.close(),\n onOpen: listener => {\n if (socket.readyState === WebSocket.OPEN) {\n listener()\n return () => {}\n }\n socket.addEventListener('open', listener)\n return () => socket.removeEventListener('open', listener)\n },\n onMessage: listener => {\n const handler = (event: MessageEvent): void => listener(String(event.data))\n socket.addEventListener('message', handler)\n return () => socket.removeEventListener('message', handler)\n },\n onClose: listener => {\n const handler = (): void => listener()\n socket.addEventListener('close', handler)\n return () => socket.removeEventListener('close', handler)\n },\n }\n}\n\n/**\n * A socket over a `MessagePort`, for either end: its frames are the port's\n * string messages, and anything else on the port is ignored. A port tells\n * neither end when the other goes, so `onClose` fires once, on `close()` or\n * when `signal` aborts; a host that serves a pane aborts it when the pane is\n * gone, which stops `serveSocket` and anything else listening.\n */\nexport const portSocket = (\n port: MessagePort,\n options: { readonly signal?: AbortSignal | undefined } = {},\n): SocketLike => {\n const closeListeners = new Set<() => void>()\n let closed = false\n const close = (): void => {\n closed = true\n port.close()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n options.signal?.addEventListener('abort', close, { once: true })\n if (options.signal?.aborted === true) close()\n port.start()\n return {\n send: data => port.postMessage(data),\n close,\n onMessage: listener => {\n const handler = (event: MessageEvent): void => {\n if (typeof event.data === 'string') listener(event.data)\n }\n port.addEventListener('message', handler)\n return () => port.removeEventListener('message', handler)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\n/**\n * A socket over an existing `WebSocket`: the accepted end of a Cloudflare\n * `WebSocketPair`, or any other socket the platform hands over. Unlike\n * `nativeSocket` it opens nothing — accept the pair first — and unlike\n * `portSocket` there is no signal: the socket closing, erroring, or being\n * closed fires `onClose` once, which is how a host stops serving it.\n */\nexport const workerSocket = (socket: WebSocket): SocketLike => {\n const messageListeners = new Set<(data: string) => void>()\n const closeListeners = new Set<() => void>()\n let closed = false\n const forget = (): void => {\n socket.removeEventListener('message', onMessageEvent)\n socket.removeEventListener('close', onClosedEvent)\n socket.removeEventListener('error', onClosedEvent)\n }\n const fireClose = (): void => {\n closed = true\n forget()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n const onMessageEvent = (event: MessageEvent): void => {\n for (const listener of [...messageListeners]) listener(String(event.data))\n }\n const onClosedEvent = (): void => {\n fireClose()\n }\n socket.addEventListener('message', onMessageEvent)\n socket.addEventListener('close', onClosedEvent)\n socket.addEventListener('error', onClosedEvent)\n return {\n send: data => socket.send(data),\n close: () => {\n try {\n socket.close()\n } catch {\n // Already gone: still report the close.\n }\n fireClose()\n },\n onMessage: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\nconst connector = (options: SocketOptions): (() => SocketLike) => {\n if (options.makeSocket !== undefined) return options.makeSocket\n const { url } = options\n return () => nativeSocket(url)\n}\n\n/**\n * A WebSocket client transport.\n *\n * One connection is live at a time. While it is connecting, exchanges queue; if\n * it closes, the transport reconnects on an exponential, jittered backoff and\n * re-sends every queued and in-flight frame with its original id, so a lost\n * reply is answered rather than dropped and a late reply cannot resolve a newer\n * frame. It never stops reconnecting: after `maxRetries` consecutive failures\n * queued work fails with a `TransportError`, and exchanges fail fast while no\n * socket is up, until a socket opens. The count resets only when a connection\n * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:\n * a server that accepts a socket and drops it at once is backed off like one\n * that refuses it. A queue over `maxQueue` fails new\n * exchanges with backpressure. The socket is released when the layer's scope\n * ends.\n */\nexport const layerSocket = (\n options: SocketOptions,\n): Layer.Layer<Transport | TransportSocket, TransportError> =>\n Layer.effectContext(\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = connector(options)\n const maxQueue = options.maxQueue ?? 64\n const maxRetries = options.maxRetries ?? 5\n const retryBase = Duration.toMillis(\n Duration.fromInputUnsafe(options.retryBase ?? '50 millis'),\n )\n const maxRetryDelay = Duration.toMillis(\n Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'),\n )\n const clock = yield* Clock.Clock\n // Listeners run in a socket's callback, outside any Effect: their\n // failures go to the reporter this layer was built with.\n const reporter = yield* Effect.service(Diagnostics.Reporter)\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<WrittenOperation>\n readonly epoch: string | undefined\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\n }\n const notices = yield* PubSub.sliding<void>(1)\n const listeners = new Set<(data: string) => void>()\n const shared: SocketLike = {\n send: data => {\n if (ready) socket?.send(data)\n },\n close: () => {},\n onMessage: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n onClose: () => () => {},\n }\n const queued: Array<Entry> = []\n const inFlight = new Map<string, Entry>()\n let socket: SocketLike | undefined\n let ready = false\n let nextId = 0\n let disposed = false\n // Closes since a connection last proved healthy. Past `maxRetries` the\n // transport is offline: nothing waits for a socket that may be minutes away.\n let failures = 0\n const healthy = (): void => {\n failures = 0\n }\n\n const send = (entry: Entry): void => {\n inFlight.set(entry.id, entry)\n socket?.send(\n JSON.stringify({\n id: entry.id,\n cursor: entry.cursor,\n pending: entry.pending,\n ...(entry.epoch === undefined ? {} : { epoch: entry.epoch }),\n } satisfies ExchangeFrame),\n )\n }\n const flush = (): void => {\n if (socket === undefined || !ready) return\n for (const entry of queued.splice(0)) send(entry)\n }\n const requeue = (): void => {\n queued.unshift(...inFlight.values())\n inFlight.clear()\n }\n const failAll = (message: string): void => {\n const entries = [...queued.splice(0), ...inFlight.values()]\n inFlight.clear()\n for (const entry of entries) entry.resume(Effect.fail(new TransportError({ message })))\n }\n\n const connect = Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n const next = makeSocket()\n socket = next\n ready = next.onOpen === undefined\n let openedAt = ready ? clock.currentTimeMillisUnsafe() : undefined\n // A socket that just (re)connected may have missed notices, so opening is one.\n const opened = (): void => {\n PubSub.publishUnsafe(notices, undefined)\n }\n const offOpen = next.onOpen?.(() => {\n ready = true\n openedAt = clock.currentTimeMillisUnsafe()\n opened()\n flush()\n })\n const offMessage = next.onMessage(data => {\n // Another protocol's listener must not cost an exchange its reply.\n for (const listener of [...listeners]) {\n try {\n listener(data)\n } catch (thrown) {\n Effect.runFork(\n Diagnostics.report(listenerFailed('Socket', thrown)).pipe(\n Effect.provideService(Diagnostics.Reporter, reporter),\n ),\n )\n }\n }\n let reply: ExchangeReply | NotifyFrame\n try {\n reply = JSON.parse(data) as ExchangeReply | NotifyFrame\n } catch {\n return\n }\n if (typeof reply !== 'object' || reply === null) return\n if ('notify' in reply) {\n if (reply.notify === true) PubSub.publishUnsafe(notices, undefined)\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\n healthy()\n inFlight.delete(reply.id)\n entry.resume(\n reply.error === undefined\n ? Effect.succeed(reply.result)\n : Effect.fail(new TransportError({ message: reply.error })),\n )\n })\n const offClose = next.onClose(() => {\n offOpen?.()\n offMessage()\n offClose()\n socket = undefined\n ready = false\n if (\n openedAt !== undefined &&\n clock.currentTimeMillisUnsafe() - openedAt >= maxRetryDelay\n )\n healthy()\n // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) {\n opened()\n flush()\n }\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n Effect.gen(function* () {\n while (!disposed) {\n yield* Effect.exit(connect)\n if (disposed) return\n failures += 1\n if (failures > maxRetries) failAll('transport closed')\n const backoff = Math.min(maxRetryDelay, retryBase * 2 ** Math.min(failures - 1, 30))\n yield* Effect.sleep(backoff * (0.8 + Math.random() * 0.4))\n }\n }),\n )\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n disposed = true\n ready = false\n socket?.close()\n socket = undefined\n failAll('transport closed')\n }),\n )\n\n const transport = Transport.of({\n changes: Stream.fromPubSub(notices),\n exchange: (cursor, pending, epoch) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (failures > maxRetries && !ready) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (queued.length + inFlight.size >= maxQueue) {\n resume(Effect.fail(new TransportError({ message: 'transport queue full' })))\n return\n }\n const entry: Entry = { id: String(nextId++), cursor, pending, epoch, resume }\n if (ready) send(entry)\n else queued.push(entry)\n // A caller interrupted before a reply must release its slot, or a\n // socket that never replies can exhaust the queue with abandoned\n // work. The frame may already be on the wire; only the local waiter\n // is forgotten, and a late reply for it is ignored.\n return Effect.sync(() => {\n const queuedIndex = queued.indexOf(entry)\n if (queuedIndex >= 0) queued.splice(queuedIndex, 1)\n if (inFlight.get(entry.id) === entry) inFlight.delete(entry.id)\n })\n }),\n })\n return Context.make(Transport, transport).pipe(Context.add(TransportSocket, shared))\n })(),\n )\n"],"mappings":";;;;;;AAOA,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CAAC,sBAAsB,EAC7F,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;;;;;;;;AA8CJ,IAAa,YAAb,cAA+B,QAAQ,QAAmC,CAAC,CACzE,wBACF,CAAC,CAAC,CAAC;;;;;;;;AASH,IAAa,kBAAb,cAAqC,QAAQ,QAAqC,CAAC,CACjF,8BACF,CAAC,CAAC,CAAC;AAEH,MAAM,WAAW,UACf,IAAI,eAAe,EAAE,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KA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O,WAAW;EAChB,WAAW;EACX,QAAQ;EACR,QAAQ,MAAM;EACd,SAAS,KAAA;EACT,QAAQ,kBAAkB;CAC5B,CAAC,CACH;CAEA,MAAM,YAAY,UAAU,GAAG;EAC7B,SAAS,OAAO,WAAW,OAAO;EAClC,WAAW,QAAQ,SAAS,UAC1B,OAAO,UAAkC,WAAU;GACjD,IAAI,UAAU;IACZ,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,mBAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,WAAW,cAAc,CAAC,OAAO;IACnC,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,mBAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,OAAO,SAAS,SAAS,QAAQ,UAAU;IAC7C,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,uBAAuB,CAAC,CAAC,CAAC;IAC3E;GACF;GACA,MAAM,QAAe;IAAE,IAAI,OAAO,QAAQ;IAAG;IAAQ;IAAS;IAAO;GAAO;GAC5E,IAAI,OAAO,KAAK,KAAK;QAChB,OAAO,KAAK,KAAK;GAKtB,OAAO,OAAO,WAAW;IACvB,MAAM,cAAc,OAAO,QAAQ,KAAK;IACxC,IAAI,eAAe,GAAG,OAAO,OAAO,aAAa,CAAC;IAClD,IAAI,SAAS,IAAI,MAAM,EAAE,MAAM,OAAO,SAAS,OAAO,MAAM,EAAE;GAChE,CAAC;EACH,CAAC;CACL,CAAC;CACD,OAAO,QAAQ,KAAK,WAAW,SAAS,CAAC,CAAC,KAAK,QAAQ,IAAI,iBAAiB,MAAM,CAAC;AACrF,CAAC,CAAC,CAAC,CACL"}
1
+ {"version":3,"file":"transport.js","names":[],"sources":["../src/transport.ts"],"sourcesContent":["import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { TransportClient } from './sync.js'\nimport { Diagnostics, type ReportDiagnostic } from 'foldkit-surface'\nimport { exchangeDefect, listenerFailed, mintIncident, reportTo } from './diagnostics.js'\nimport { UnreadableHistoryError, UnsupportedMessageVersionError } from './errors.js'\n\n/** The wire failure of a transport. A refusal is a result, not an error. */\nexport class TransportError extends Schema.TaggedError<TransportError>()('SyncTransportError', {\n message: Schema.String,\n /** The id a server reported its own failure under (`ExchangeDefect`), when it answered with one. */\n incident: Schema.optional(Schema.String),\n}) {}\n\n/** One request/response frame, as it crosses a wire. */\nexport interface ExchangeFrame {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<unknown>\n readonly epoch?: string | undefined\n}\n\n/**\n * A failed exchange in words written for the replica: throw it from a served\n * exchange (`serveSocket`) and its `message` is sent as it is. Anything else a\n * handler throws is the server's own, and is answered \"Exchange failed\".\n */\nexport class ExchangeRefused extends Schema.TaggedError<ExchangeRefused>()('SyncExchangeRefused', {\n message: Schema.String,\n}) {}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n /** Beside `error`, when the server failed on its own side: the id it reported the cause under. */\n readonly incident?: string\n}\n\n/** What a replica reads of an exchange that threw on the server's side, whatever was thrown. */\nconst EXCHANGE_FAILED = 'Exchange failed'\n\n/**\n * Sent by a server, unasked, when the document may have changed. It carries no\n * data: the replica exchanges from its own cursor, so a notice that is lost,\n * late, or one of many is harmless.\n */\nexport interface NotifyFrame {\n readonly notify: true\n}\n\nexport interface TransportShape {\n /**\n * `epoch` is the server history the replica's cursor points into, when it\n * knows one. `pending` is unread: whoever answers reads each entry with\n * `codec.writtenFrom` before appending it.\n */\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<unknown>,\n epoch?: string | undefined,\n ) => Effect.Effect<unknown, TransportError>\n /**\n * Emits when the server may have something new, for a transport that can hear\n * it: `Replica.start` exchanges on each. A wake-up, not data.\n */\n readonly changes?: Stream.Stream<void> | undefined\n}\n\n/**\n * The seam the replica syncs through.\n *\n * A service, not a concrete client, so an application substitutes an in-process\n * transport, a socket, or a test double without the replica knowing. A refusal\n * arrives in the exchange result; only a wire failure is a `TransportError`.\n */\nexport class Transport extends Context.Service<Transport, TransportShape>()(\n 'foldkit-sync/Transport',\n) {}\n\n/**\n * The connection `layerSocket` keeps, for another protocol to share, such as\n * presence: a send goes to the socket open now and is dropped while none is,\n * and messages from every socket the transport opens arrive here. It is the\n * transport's to close. Only a socket transport provides it, so a layer that\n * has one says so in its type.\n */\nexport class TransportSocket extends Context.Service<TransportSocket, SocketLike>()(\n 'foldkit-sync/TransportSocket',\n) {}\n\nconst failure = (error: unknown): TransportError =>\n new TransportError({ message: error instanceof Error ? error.message : String(error) })\n\n/** A transport backed by an in-process handler, for tests and single-process demos. */\nexport const layerLoopback = (\n handler: (\n cursor: number,\n pending: ReadonlyArray<unknown>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => Promise.resolve(handler(cursor, pending, epoch)),\n catch: failure,\n }),\n })\n\n/** Wraps the promise-based client the replica already speaks. */\nexport const layerFromPromise = (transport: TransportClient): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending, epoch),\n catch: failure,\n }),\n })\n\n/** Bridges the service back to the promise client the replica consumes. */\nexport const toPromise = (transport: TransportShape): TransportClient => ({\n exchange: (cursor, pending, epoch) =>\n Effect.runPromise(transport.exchange(cursor, pending, epoch)),\n})\n\n/**\n * Serves one accepted socket, answering each exchange frame.\n *\n * The counterpart to `layerSocket`: the handler returns the exchange result,\n * or throws. An `ExchangeRefused`, and a replica newer than this server\n * (`UnsupportedMessageVersionError`), are words for the replica, sent as they\n * are. Anything else thrown is this side's (a journal's failure, a driver's\n * words): it is reported as an `ExchangeDefect`, and the error frame says only\n * \"Exchange failed\" and the incident it was reported under; a stored\n * operation no build reads (`UnreadableHistoryError`) is reported so too, and\n * its frame carries the journal's sentence for it, which names no operation.\n * With `changes`, a\n * subscription to the document's commits, the socket is also sent a\n * `NotifyFrame` after each, so a client hears of others' edits without polling.\n * Returns a function that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<unknown>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>\n /** Subscribes to the document's commits; returns the unsubscribe. */\n readonly changes?: ((listener: () => void) => () => void) | undefined\n /** Where an exchange that threw is reported; the default reporter when not given, since this runs outside any context. */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n): (() => void) => {\n const send = (reply: ExchangeReply | NotifyFrame): void => {\n try {\n socket.send(JSON.stringify(reply))\n } catch {\n // The socket may have closed while the handler was running.\n }\n }\n const stopMessage = socket.onMessage(data => {\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch {\n return\n }\n if (typeof parsed !== 'object' || parsed === null) return\n const { id, cursor, pending, epoch } = parsed as {\n id?: unknown\n cursor?: unknown\n pending?: unknown\n epoch?: unknown\n }\n // Without an id there is nobody to answer, so drop the frame.\n if (typeof id !== 'string') return\n if (\n typeof cursor !== 'number' ||\n !Number.isSafeInteger(cursor) ||\n cursor < 0 ||\n !Array.isArray(pending) ||\n (epoch !== undefined && typeof epoch !== 'string')\n ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = {\n id,\n cursor,\n pending,\n epoch: typeof epoch === 'string' ? epoch : undefined,\n }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending, frame.epoch)\n send({ id: frame.id, result })\n } catch (thrown) {\n if (thrown instanceof ExchangeRefused || thrown instanceof UnsupportedMessageVersionError) {\n send({ id: frame.id, error: thrown.message })\n return\n }\n const incident = mintIncident()\n // `Diagnostics.report` answers a reporter that breaks itself, so this cannot reject.\n await Effect.runPromise(reportTo(options.diagnostics, exchangeDefect(incident, thrown)))\n send({\n id: frame.id,\n // The journal's own sentence; whose operation it is stays on the report.\n error: thrown instanceof UnreadableHistoryError ? thrown.message : EXCHANGE_FAILED,\n incident,\n })\n }\n })()\n })\n const stopChanges = options.changes?.(() => send({ notify: true }))\n const stop = (): void => {\n stopMessage()\n stopChanges?.()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\n stopClose()\n }\n}\n\n/** The minimal socket the layer needs; the global `WebSocket` satisfies it. */\nexport interface SocketLike {\n send(data: string): void\n close(): void\n onMessage(listener: (data: string) => void): () => void\n onClose(listener: () => void): () => void\n /**\n * Optional. When provided, exchanges wait for it before sending, so a\n * transport can connect asynchronously. Absent means already connected.\n */\n onOpen?(listener: () => void): () => void\n}\n\n/**\n * Where `layerSocket` connects: a `url` for the platform `WebSocket`, or a\n * `makeSocket` that opens any other `SocketLike` (a port, a test socket), called\n * again on every reconnect.\n */\nexport type SocketOptions = SocketTuning &\n (\n | { readonly url: string; readonly makeSocket?: undefined }\n | { readonly makeSocket: () => SocketLike; readonly url?: undefined }\n )\n\ninterface SocketTuning {\n /**\n * Consecutive failed connections after which queued work fails and new\n * exchanges fail fast until a connection is healthy again. Reconnecting goes\n * on regardless. Default 5.\n */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: Duration.Input | undefined\n /** Longest wait between reconnect attempts. Default `5 seconds`. */\n readonly maxRetryDelay?: Duration.Input | undefined\n /** Exchanges queued or in flight before new ones fail. Default 64. */\n readonly maxQueue?: number | undefined\n}\n\n/** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */\nexport const nativeSocket = (url: string): SocketLike => {\n const socket = new WebSocket(url)\n return {\n send: data => socket.send(data),\n close: () => socket.close(),\n onOpen: listener => {\n if (socket.readyState === WebSocket.OPEN) {\n listener()\n return () => {}\n }\n socket.addEventListener('open', listener)\n return () => socket.removeEventListener('open', listener)\n },\n onMessage: listener => {\n const handler = (event: MessageEvent): void => listener(String(event.data))\n socket.addEventListener('message', handler)\n return () => socket.removeEventListener('message', handler)\n },\n onClose: listener => {\n const handler = (): void => listener()\n socket.addEventListener('close', handler)\n return () => socket.removeEventListener('close', handler)\n },\n }\n}\n\n/**\n * A socket over a `MessagePort`, for either end: its frames are the port's\n * string messages, and anything else on the port is ignored. A port tells\n * neither end when the other goes, so `onClose` fires once, on `close()` or\n * when `signal` aborts; a host that serves a pane aborts it when the pane is\n * gone, which stops `serveSocket` and anything else listening.\n */\nexport const portSocket = (\n port: MessagePort,\n options: { readonly signal?: AbortSignal | undefined } = {},\n): SocketLike => {\n const closeListeners = new Set<() => void>()\n let closed = false\n const close = (): void => {\n closed = true\n port.close()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n options.signal?.addEventListener('abort', close, { once: true })\n if (options.signal?.aborted === true) close()\n port.start()\n return {\n send: data => port.postMessage(data),\n close,\n onMessage: listener => {\n const handler = (event: MessageEvent): void => {\n if (typeof event.data === 'string') listener(event.data)\n }\n port.addEventListener('message', handler)\n return () => port.removeEventListener('message', handler)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\n/**\n * A socket over an existing `WebSocket`: the accepted end of a Cloudflare\n * `WebSocketPair`, or any other socket the platform hands over. Unlike\n * `nativeSocket` it opens nothing — accept the pair first — and unlike\n * `portSocket` there is no signal: the socket closing, erroring, or being\n * closed fires `onClose` once, which is how a host stops serving it.\n */\nexport const workerSocket = (socket: WebSocket): SocketLike => {\n const messageListeners = new Set<(data: string) => void>()\n const closeListeners = new Set<() => void>()\n let closed = false\n const forget = (): void => {\n socket.removeEventListener('message', onMessageEvent)\n socket.removeEventListener('close', onClosedEvent)\n socket.removeEventListener('error', onClosedEvent)\n }\n const fireClose = (): void => {\n closed = true\n forget()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n const onMessageEvent = (event: MessageEvent): void => {\n for (const listener of [...messageListeners]) listener(String(event.data))\n }\n const onClosedEvent = (): void => {\n fireClose()\n }\n socket.addEventListener('message', onMessageEvent)\n socket.addEventListener('close', onClosedEvent)\n socket.addEventListener('error', onClosedEvent)\n return {\n send: data => socket.send(data),\n close: () => {\n try {\n socket.close()\n } catch {\n // Already gone: still report the close.\n }\n fireClose()\n },\n onMessage: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\nconst connector = (options: SocketOptions): (() => SocketLike) => {\n if (options.makeSocket !== undefined) return options.makeSocket\n const { url } = options\n return () => nativeSocket(url)\n}\n\n/**\n * A WebSocket client transport.\n *\n * One connection is live at a time. While it is connecting, exchanges queue; if\n * it closes, the transport reconnects on an exponential, jittered backoff and\n * re-sends every queued and in-flight frame with its original id, so a lost\n * reply is answered rather than dropped and a late reply cannot resolve a newer\n * frame. It never stops reconnecting: after `maxRetries` consecutive failures\n * queued work fails with a `TransportError`, and exchanges fail fast while no\n * socket is up, until a socket opens. The count resets only when a connection\n * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:\n * a server that accepts a socket and drops it at once is backed off like one\n * that refuses it. A queue over `maxQueue` fails new\n * exchanges with backpressure. The socket is released when the layer's scope\n * ends.\n */\nexport const layerSocket = (\n options: SocketOptions,\n): Layer.Layer<Transport | TransportSocket, TransportError> =>\n Layer.effectContext(\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = connector(options)\n const maxQueue = options.maxQueue ?? 64\n const maxRetries = options.maxRetries ?? 5\n const retryBase = Duration.toMillis(\n Duration.fromInputUnsafe(options.retryBase ?? '50 millis'),\n )\n const maxRetryDelay = Duration.toMillis(\n Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'),\n )\n const clock = yield* Clock.Clock\n // Listeners run in a socket's callback, outside any Effect: their\n // failures go to the reporter this layer was built with.\n const reporter = yield* Effect.service(Diagnostics.Reporter)\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<unknown>\n readonly epoch: string | undefined\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\n }\n const notices = yield* PubSub.sliding<void>(1)\n const listeners = new Set<(data: string) => void>()\n const shared: SocketLike = {\n send: data => {\n if (ready) socket?.send(data)\n },\n close: () => {},\n onMessage: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n onClose: () => () => {},\n }\n const queued: Array<Entry> = []\n const inFlight = new Map<string, Entry>()\n let socket: SocketLike | undefined\n let ready = false\n let nextId = 0\n let disposed = false\n // Closes since a connection last proved healthy. Past `maxRetries` the\n // transport is offline: nothing waits for a socket that may be minutes away.\n let failures = 0\n const healthy = (): void => {\n failures = 0\n }\n\n const send = (entry: Entry): void => {\n inFlight.set(entry.id, entry)\n socket?.send(\n JSON.stringify({\n id: entry.id,\n cursor: entry.cursor,\n pending: entry.pending,\n ...(entry.epoch === undefined ? {} : { epoch: entry.epoch }),\n } satisfies ExchangeFrame),\n )\n }\n const flush = (): void => {\n if (socket === undefined || !ready) return\n for (const entry of queued.splice(0)) send(entry)\n }\n const requeue = (): void => {\n queued.unshift(...inFlight.values())\n inFlight.clear()\n }\n const failAll = (message: string): void => {\n const entries = [...queued.splice(0), ...inFlight.values()]\n inFlight.clear()\n for (const entry of entries) entry.resume(Effect.fail(new TransportError({ message })))\n }\n\n const connect = Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n const next = makeSocket()\n socket = next\n ready = next.onOpen === undefined\n let openedAt = ready ? clock.currentTimeMillisUnsafe() : undefined\n // A socket that just (re)connected may have missed notices, so opening is one.\n const opened = (): void => {\n PubSub.publishUnsafe(notices, undefined)\n }\n const offOpen = next.onOpen?.(() => {\n ready = true\n openedAt = clock.currentTimeMillisUnsafe()\n opened()\n flush()\n })\n const offMessage = next.onMessage(data => {\n // Another protocol's listener must not cost an exchange its reply.\n for (const listener of [...listeners]) {\n try {\n listener(data)\n } catch (thrown) {\n Effect.runFork(\n Diagnostics.report(listenerFailed('Socket', thrown)).pipe(\n Effect.provideService(Diagnostics.Reporter, reporter),\n ),\n )\n }\n }\n let reply: ExchangeReply | NotifyFrame\n try {\n reply = JSON.parse(data) as ExchangeReply | NotifyFrame\n } catch {\n return\n }\n if (typeof reply !== 'object' || reply === null) return\n if ('notify' in reply) {\n if (reply.notify === true) PubSub.publishUnsafe(notices, undefined)\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\n healthy()\n inFlight.delete(reply.id)\n entry.resume(\n reply.error === undefined\n ? Effect.succeed(reply.result)\n : Effect.fail(\n new TransportError({\n message: reply.error,\n ...(typeof reply.incident === 'string' ? { incident: reply.incident } : {}),\n }),\n ),\n )\n })\n const offClose = next.onClose(() => {\n offOpen?.()\n offMessage()\n offClose()\n socket = undefined\n ready = false\n if (\n openedAt !== undefined &&\n clock.currentTimeMillisUnsafe() - openedAt >= maxRetryDelay\n )\n healthy()\n // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) {\n opened()\n flush()\n }\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n Effect.gen(function* () {\n while (!disposed) {\n yield* Effect.exit(connect)\n if (disposed) return\n failures += 1\n if (failures > maxRetries) failAll('transport closed')\n const backoff = Math.min(maxRetryDelay, retryBase * 2 ** Math.min(failures - 1, 30))\n yield* Effect.sleep(backoff * (0.8 + Math.random() * 0.4))\n }\n }),\n )\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n disposed = true\n ready = false\n socket?.close()\n socket = undefined\n failAll('transport closed')\n }),\n )\n\n const transport = Transport.of({\n changes: Stream.fromPubSub(notices),\n exchange: (cursor, pending, epoch) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (failures > maxRetries && !ready) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (queued.length + inFlight.size >= maxQueue) {\n resume(Effect.fail(new TransportError({ message: 'transport queue full' })))\n return\n }\n const entry: Entry = { id: String(nextId++), cursor, pending, epoch, resume }\n if (ready) send(entry)\n else queued.push(entry)\n // A caller interrupted before a reply must release its slot, or a\n // socket that never replies can exhaust the queue with abandoned\n // work. The frame may already be on the wire; only the local waiter\n // is forgotten, and a late reply for it is ignored.\n return Effect.sync(() => {\n const queuedIndex = queued.indexOf(entry)\n if (queuedIndex >= 0) queued.splice(queuedIndex, 1)\n if (inFlight.get(entry.id) === entry) inFlight.delete(entry.id)\n })\n }),\n })\n return Context.make(Transport, transport).pipe(Context.add(TransportSocket, shared))\n })(),\n )\n"],"mappings":";;;;;;;AAQA,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CAAC,sBAAsB;CAC7F,SAAS,OAAO;;CAEhB,UAAU,OAAO,SAAS,OAAO,MAAM;AACzC,CAAC,CAAC,CAAC,CAAC;;;;;;AAeJ,IAAa,kBAAb,cAAqC,OAAO,YAA6B,CAAC,CAAC,uBAAuB,EAChG,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;;AAWJ,MAAM,kBAAkB;;;;;;;;AAoCxB,IAAa,YAAb,cAA+B,QAAQ,QAAmC,CAAC,CACzE,wBACF,CAAC,CAAC,CAAC;;;;;;;;AASH,IAAa,kBAAb,cAAqC,QAAQ,QAAqC,CAAC,CACjF,8BACF,CAAC,CAAC,CAAC;AAEH,MAAM,WAAW,UACf,IAAI,eAAe,EAAE,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;;AAGxF,MAAa,iBACX,YAMA,MAAM,QAAQ,WAAW,EACvB,WAAW,QAAQ,SAAS,UAC1B,OAAO,WAAW;CAChB,WAAW,QAAQ,QAAQ,QAAQ,QAAQ,SAAS,KAAK,CAAC;CAC1D,OAAO;AACT,CAAC,EACL,CAAC;;AAGH,MAAa,oBAAoB,cAC/B,MAAM,QAAQ,WAAW,EACvB,WAAW,QAAQ,SA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,OAAO,mBACZ,OAAO,WAAW;EAChB,WAAW;EACX,QAAQ;EACR,QAAQ,MAAM;EACd,SAAS,KAAA;EACT,QAAQ,kBAAkB;CAC5B,CAAC,CACH;CAEA,MAAM,YAAY,UAAU,GAAG;EAC7B,SAAS,OAAO,WAAW,OAAO;EAClC,WAAW,QAAQ,SAAS,UAC1B,OAAO,UAAkC,WAAU;GACjD,IAAI,UAAU;IACZ,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,mBAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,WAAW,cAAc,CAAC,OAAO;IACnC,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,mBAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,OAAO,SAAS,SAAS,QAAQ,UAAU;IAC7C,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,uBAAuB,CAAC,CAAC,CAAC;IAC3E;GACF;GACA,MAAM,QAAe;IAAE,IAAI,OAAO,QAAQ;IAAG;IAAQ;IAAS;IAAO;GAAO;GAC5E,IAAI,OAAO,KAAK,KAAK;QAChB,OAAO,KAAK,KAAK;GAKtB,OAAO,OAAO,WAAW;IACvB,MAAM,cAAc,OAAO,QAAQ,KAAK;IACxC,IAAI,eAAe,GAAG,OAAO,OAAO,aAAa,CAAC;IAClD,IAAI,SAAS,IAAI,MAAM,EAAE,MAAM,OAAO,SAAS,OAAO,MAAM,EAAE;GAChE,CAAC;EACH,CAAC;CACL,CAAC;CACD,OAAO,QAAQ,KAAK,WAAW,SAAS,CAAC,CAAC,KAAK,QAAQ,IAAI,iBAAiB,MAAM,CAAC;AACrF,CAAC,CAAC,CAAC,CACL"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-sync",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "description": "A local-first replica of a shared Foldkit projection: offline outbox, optimistic updates, and reconciliation.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -59,13 +59,13 @@
59
59
  "LICENSE"
60
60
  ],
61
61
  "dependencies": {
62
- "foldkit-surface": "0.14.0"
62
+ "foldkit-surface": "0.15.0"
63
63
  },
64
64
  "peerDependencies": {
65
65
  "effect": "^4.1.0",
66
66
  "foldkit": "^0.170.0",
67
- "foldkit-durable": "0.13.0",
68
- "foldkit-remote": "0.25.0"
67
+ "foldkit-durable": "0.15.0",
68
+ "foldkit-remote": "0.27.0"
69
69
  },
70
70
  "peerDependenciesMeta": {
71
71
  "foldkit-durable": {
@@ -76,11 +76,11 @@
76
76
  }
77
77
  },
78
78
  "devDependencies": {
79
- "@cloudflare/workers-types": "5.20261022.1",
80
- "@effect/platform-browser": "^4.1.1",
81
- "@effect/sql-d1": "^4.1.1",
79
+ "@cloudflare/workers-types": "5.20261112.1",
80
+ "@effect/platform-browser": "4.1.4",
81
+ "@effect/sql-d1": "^4.1.4",
82
82
  "@types/ws": "^8.18.2",
83
- "effect": "^4.1.1",
83
+ "effect": "4.1.4",
84
84
  "esbuild": "0.28.2",
85
85
  "fake-indexeddb": "6.2.6",
86
86
  "foldkit": "0.170.0",
@@ -89,10 +89,10 @@
89
89
  "tsdown": "^0.23.1",
90
90
  "typescript": "7.0.2",
91
91
  "ws": "^8.22.0",
92
- "foldkit-agent": "0.12.0",
93
- "foldkit-durable": "0.13.0",
94
- "foldkit-entity": "0.17.0",
95
- "foldkit-remote": "0.25.0"
92
+ "foldkit-agent": "0.13.0",
93
+ "foldkit-entity": "0.18.0",
94
+ "foldkit-durable": "0.15.0",
95
+ "foldkit-remote": "0.27.0"
96
96
  },
97
97
  "scripts": {
98
98
  "build": "node ../../scripts/declarations.mjs . && tsdown && node ../../scripts/declared-any.mjs .",