foldkit-sync 0.14.0 → 0.16.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 (49) hide show
  1. package/README.md +558 -40
  2. package/dist/diagnostics.d.ts +74 -3
  3. package/dist/diagnostics.d.ts.map +1 -1
  4. package/dist/diagnostics.js +60 -4
  5. package/dist/diagnostics.js.map +1 -1
  6. package/dist/do.d.ts +49 -7
  7. package/dist/do.d.ts.map +1 -1
  8. package/dist/do.js +91 -8
  9. package/dist/do.js.map +1 -1
  10. package/dist/errors.d.ts +92 -1
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +87 -1
  13. package/dist/errors.js.map +1 -1
  14. package/dist/index.d.ts +9 -5
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +6 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/journal.d.ts +52 -27
  19. package/dist/journal.d.ts.map +1 -1
  20. package/dist/journal.js +176 -64
  21. package/dist/journal.js.map +1 -1
  22. package/dist/make.d.ts +48 -17
  23. package/dist/make.d.ts.map +1 -1
  24. package/dist/make.js +11 -4
  25. package/dist/make.js.map +1 -1
  26. package/dist/migrations.d.ts +37 -0
  27. package/dist/migrations.d.ts.map +1 -0
  28. package/dist/migrations.js +56 -0
  29. package/dist/migrations.js.map +1 -0
  30. package/dist/mount.d.ts +1 -1
  31. package/dist/mount.d.ts.map +1 -1
  32. package/dist/mount.js +12 -6
  33. package/dist/mount.js.map +1 -1
  34. package/dist/refusal.d.ts +33 -0
  35. package/dist/refusal.d.ts.map +1 -0
  36. package/dist/refusal.js +47 -0
  37. package/dist/refusal.js.map +1 -0
  38. package/dist/serverJournal.d.ts +143 -0
  39. package/dist/serverJournal.d.ts.map +1 -0
  40. package/dist/serverJournal.js +503 -0
  41. package/dist/serverJournal.js.map +1 -0
  42. package/dist/sync.d.ts +132 -11
  43. package/dist/sync.d.ts.map +1 -1
  44. package/dist/sync.js +273 -64
  45. package/dist/sync.js.map +1 -1
  46. package/dist/transport.d.ts +5 -5
  47. package/dist/transport.d.ts.map +1 -1
  48. package/dist/transport.js.map +1 -1
  49. package/package.json +11 -8
@@ -1,4 +1,4 @@
1
- import { Cause, Effect } from "effect";
1
+ import { Cause, Effect, Option } from "effect";
2
2
  import { Diagnostic, ReportDiagnostic } from "foldkit-surface";
3
3
  import { TransportError } from "./transport.js";
4
4
  import { ReplicaError } from "./errors.js";
@@ -19,6 +19,19 @@ export interface HistoryRebuilt extends Diagnostic {
19
19
  readonly documentId: string;
20
20
  readonly replicaId: string;
21
21
  }
22
+ /**
23
+ * The server rejected an operation with a refusal this build cannot read: a
24
+ * newer server's case, or one that does not decode. The rejection stands, and
25
+ * reads with no refusal.
26
+ */
27
+ export interface UnknownRefusal extends Diagnostic {
28
+ readonly _tag: 'UnknownRefusal';
29
+ readonly documentId: string;
30
+ readonly replicaId: string;
31
+ readonly opId: string;
32
+ /** Why it did not decode, cut to 500 characters: the value is the server's, of any size. */
33
+ readonly issue: string;
34
+ }
22
35
  /** Where a document host broke. */
23
36
  export type HostStage =
24
37
  /** Making or accepting the socket pair (`foldkit-sync/do`). */
@@ -34,7 +47,9 @@ export type HostStage =
34
47
  /** Asking `opens` before a commit notice, which failed: the notice was not sent. */
35
48
  'Notice' |
36
49
  /** The journal's stream of commits, which broke: the connection hears of no more commits. */
37
- 'Changes';
50
+ 'Changes' |
51
+ /** A Durable Object's pass of reactions, after an exchange or in `alarm()`, which broke: the alarm comes back later. */
52
+ 'Alarm';
38
53
  /**
39
54
  * A document host broke on its own side: the upgrade was answered 500
40
55
  * "Internal error", the socket closed with 1011, or a notice went unsent. The
@@ -60,10 +75,66 @@ export interface ListenerFailed extends Diagnostic {
60
75
  /** What it threw. */
61
76
  readonly thrown: unknown;
62
77
  }
78
+ /**
79
+ * A replica sent a Message only the server appends: rejected as `Forbidden`.
80
+ * No honest client sends one, so it is worth a look. It names the operation and
81
+ * the replica it claims, never the payload.
82
+ */
83
+ export interface ServerOnlySubmitted extends Diagnostic {
84
+ readonly _tag: 'ServerOnlySubmitted';
85
+ readonly documentId: string;
86
+ readonly opId: string;
87
+ /** The replica id the entry claims: what the sender wrote, not proof of who it is. */
88
+ readonly replicaId: string;
89
+ }
90
+ /**
91
+ * A reaction's run failed, threw or timed out: that reaction waits at the
92
+ * operation, on a backoff, and the others go on.
93
+ */
94
+ export interface ReactionFailed extends Diagnostic {
95
+ readonly _tag: 'ReactionFailed';
96
+ readonly documentId: string;
97
+ readonly reaction: string;
98
+ /** None when the commit itself would not read, so no operation can be named. */
99
+ readonly opId: Option.Option<string>;
100
+ readonly sequence: Option.Option<number>;
101
+ /** Why, cut to 500 characters. */
102
+ readonly cause: string;
103
+ }
104
+ /** A reaction's run was set aside, for a person (`parked`); the reaction went on without it. */
105
+ export interface ReactionParked extends Diagnostic {
106
+ readonly _tag: 'ReactionParked';
107
+ readonly documentId: string;
108
+ readonly reaction: string;
109
+ readonly opId: string;
110
+ readonly sequence: number;
111
+ /** Why, cut to 500 characters. */
112
+ readonly cause: string;
113
+ }
114
+ /**
115
+ * The log was compacted past a reaction's cursor, against `settledThrough`:
116
+ * the commits between were never reacted to, and the reaction resumes at the
117
+ * floor.
118
+ */
119
+ export interface ReactionSkipped extends Diagnostic {
120
+ readonly _tag: 'ReactionSkipped';
121
+ readonly documentId: string;
122
+ readonly reaction: string;
123
+ readonly from: number;
124
+ readonly to: number;
125
+ }
63
126
  /** Every diagnostic Sync reports. */
64
- export type SyncDiagnostic = ExchangeFailed | HistoryRebuilt | HostDefect | ListenerFailed;
127
+ export type SyncDiagnostic = ExchangeFailed | HistoryRebuilt | HostDefect | ListenerFailed | ReactionFailed | ReactionParked | ReactionSkipped | ServerOnlySubmitted | UnknownRefusal;
65
128
  export declare const exchangeFailed: (documentId: string, replicaId: string, error: ReplicaError | TransportError) => ExchangeFailed;
66
129
  export declare const historyRebuilt: (documentId: string, replicaId: string) => HistoryRebuilt;
130
+ export declare const unknownRefusal: (documentId: string, replicaId: string, opId: string, issue: string) => UnknownRefusal;
131
+ export declare const serverOnlySubmitted: (documentId: string, opId: string, replicaId: string) => ServerOnlySubmitted;
132
+ export declare const reactionFailed: (documentId: string, reaction: string, at: Option.Option<{
133
+ readonly opId: string;
134
+ readonly sequence: number;
135
+ }>, cause: string) => ReactionFailed;
136
+ export declare const reactionParked: (documentId: string, reaction: string, opId: string, sequence: number, cause: string) => ReactionParked;
137
+ export declare const reactionSkipped: (documentId: string, reaction: string, from: number, to: number) => ReactionSkipped;
67
138
  export declare const hostDefect: (stage: HostStage, cause: Cause.Cause<unknown>) => HostDefect;
68
139
  export declare const listenerFailed: (site: ListenerSite, thrown: unknown) => ListenerFailed;
69
140
  /** Reports `diagnostic` to `reporter` when a host gave one, else to the reporter in context. */
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics.d.ts","names":[],"sources":["../src/diagnostics.ts"],"mappings":";;;;;iBAgBiB,uBAAuB;WAC7B;WACA;WACA;WACA,OAAO,eAAe;;;;;;;iBAQhB,uBAAuB;WAC7B;WACA;WACA;;;YAIC;;;;;;;;;;;;;;;;;;;;iBAqBK,mBAAmB;WACzB;WACA,OAAO;WACP,OAAO,MAAM;;;YAIZ;;;;;;;;iBASK,uBAAuB;WAC7B;WACA,MAAM;;WAEN;;;YAIC,iBAAiB,iBAAiB,iBAAiB,aAAa;qBAE/D,iBAAc,oBACP,mBACD,OACV,eAAe,mBACrB;qBAUU,iBAAc,oBAAsB,sBAAsB;qBAoB1D,aAAU,OAAW,WAAS,OAAS,MAAM,mBAAiB;qBAe9D,iBAAc,MAAU,cAAY,oBAAoB;;qBAUxD,WAAQ,UACT,8BAA4B,YAC1B,mBACX,OAAO"}
1
+ {"version":3,"file":"diagnostics.d.ts","names":[],"sources":["../src/diagnostics.ts"],"mappings":";;;;;iBAiBiB,uBAAuB;WAC7B;WACA;WACA;WACA,OAAO,eAAe;;;;;;;iBAQhB,uBAAuB;WAC7B;WACA;WACA;;;;;;;iBAQM,uBAAuB;WAC7B;WACA;WACA;WACA;;WAEA;;;YAIC;;;;;;;;;;;;;;;;;;;;;;iBAuBK,mBAAmB;WACzB;WACA,OAAO;WACP,OAAO,MAAM;;;YAIZ;;;;;;;;iBASK,uBAAuB;WAC7B;WACA,MAAM;;WAEN;;;;;;;iBAQM,4BAA4B;WAClC;WACA;WACA;;WAEA;;;;;;iBAOM,uBAAuB;WAC7B;WACA;WACA;;WAEA,MAAM,OAAO;WACb,UAAU,OAAO;;WAEjB;;;iBAIM,uBAAuB;WAC7B;WACA;WACA;WACA;WACA;;WAEA;;;;;;;iBAQM,wBAAwB;WAC9B;WACA;WACA;WACA;WACA;;;YAIC,iBACR,iBACA,iBACA,aACA,iBACA,iBACA,iBACA,kBACA,sBACA;qBAES,iBAAc,oBACP,mBACD,OACV,eAAe,mBACrB;qBAUU,iBAAc,oBAAsB,sBAAsB;qBAS1D,iBAAc,oBACP,mBACD,cACL,kBAEX;qBAWU,sBAAmB,oBACZ,cACN,sBAEX;qBAUU,iBAAc,oBACP,kBACF,IACZ,OAAO;WAAkB;WAAuB;IAAmB,kBAEtE;qBAeU,iBAAc,oBACP,kBACF,cACJ,kBACI,kBAEf;qBAYU,kBAAe,oBACR,kBACF,cACJ,eAEX;qBAuBU,aAAU,OAAW,WAAS,OAAS,MAAM,mBAAiB;qBAe9D,iBAAc,MAAU,cAAY,oBAAoB;;qBAUxD,WAAQ,UACT,8BAA4B,YAC1B,mBACX,OAAO"}
@@ -1,9 +1,10 @@
1
- import { Cause, Effect } from "effect";
1
+ import { Cause, Effect, Option } from "effect";
2
2
  import { Diagnostics } from "foldkit-surface";
3
3
  // src/diagnostics.ts
4
4
  /**
5
5
  * What Sync meets and keeps going past. A replica whose exchange failed (also
6
- * in `status.lastError`), or whose server's history changed under it; a
6
+ * in `status.lastError`), whose server's history changed under it, or whose
7
+ * server refused an operation with a refusal it cannot read; a
7
8
  * document host that answered an upgrade "Internal error" or closed a socket
8
9
  * as one, whose cause neither the replica nor the response carries; and a
9
10
  * listener the application gave that threw. Each is reported through
@@ -27,6 +28,60 @@ const historyRebuilt = (documentId, replicaId) => ({
27
28
  documentId,
28
29
  replicaId
29
30
  });
31
+ const unknownRefusal = (documentId, replicaId, opId, issue) => ({
32
+ _tag: "UnknownRefusal",
33
+ source,
34
+ level: "warning",
35
+ message: `${documentId} (replica ${replicaId}): the server rejected ${opId} with a refusal this build cannot read (${issue}); it reads with none.`,
36
+ documentId,
37
+ replicaId,
38
+ opId,
39
+ issue
40
+ });
41
+ const serverOnlySubmitted = (documentId, opId, replicaId) => ({
42
+ _tag: "ServerOnlySubmitted",
43
+ source,
44
+ level: "warning",
45
+ message: `${documentId}: ${opId}, sent as replica ${replicaId}, carries a Message only the server appends; it was rejected as Forbidden.`,
46
+ documentId,
47
+ opId,
48
+ replicaId
49
+ });
50
+ const reactionFailed = (documentId, reaction, at, cause) => ({
51
+ _tag: "ReactionFailed",
52
+ source,
53
+ level: "warning",
54
+ message: `${documentId}: reaction ${reaction} failed${Option.match(at, {
55
+ onNone: () => " reading the log",
56
+ onSome: ({ opId, sequence }) => ` at ${opId} (${sequence})`
57
+ })} (${cause}); it waits there on a backoff.`,
58
+ documentId,
59
+ reaction,
60
+ opId: Option.map(at, ({ opId }) => opId),
61
+ sequence: Option.map(at, ({ sequence }) => sequence),
62
+ cause
63
+ });
64
+ const reactionParked = (documentId, reaction, opId, sequence, cause) => ({
65
+ _tag: "ReactionParked",
66
+ source,
67
+ level: "error",
68
+ message: `${documentId}: reaction ${reaction} set ${opId} (${sequence}) aside (${cause}); it is in parked, and the reaction went on.`,
69
+ documentId,
70
+ reaction,
71
+ opId,
72
+ sequence,
73
+ cause
74
+ });
75
+ const reactionSkipped = (documentId, reaction, from, to) => ({
76
+ _tag: "ReactionSkipped",
77
+ source,
78
+ level: "error",
79
+ message: `${documentId}: the log was compacted past reaction ${reaction}; commits ${from + 1} to ${to} were never reacted to.`,
80
+ documentId,
81
+ reaction,
82
+ from,
83
+ to
84
+ });
30
85
  const stageText = {
31
86
  Upgrade: "making or accepting the socket broke, and the upgrade was answered \"Internal error\"",
32
87
  Resolve: "building the layer or resolving the principal broke, and the upgrade was answered \"Internal error\"",
@@ -34,7 +89,8 @@ const stageText = {
34
89
  Exchange: "opens or settle threw, and the upgrade was answered \"Internal error\"",
35
90
  Revalidate: "asking the resolver again broke, and the socket was closed with 1011",
36
91
  Notice: "asking opens before a commit notice failed, and the notice was not sent",
37
- Changes: "the journal's stream of commits broke, and this connection hears of no more commits"
92
+ Changes: "the journal's stream of commits broke, and this connection hears of no more commits",
93
+ Alarm: "running the reactions broke, and the alarm was set to run them again later"
38
94
  };
39
95
  const hostDefect = (stage, cause) => ({
40
96
  _tag: "HostDefect",
@@ -62,6 +118,6 @@ const reportTo = (reporter, diagnostic) => {
62
118
  const reported = Diagnostics.report(diagnostic);
63
119
  return reporter === void 0 ? reported : Effect.provideService(reported, Diagnostics.Reporter, reporter);
64
120
  };
65
- export { exchangeFailed, historyRebuilt, hostDefect, listenerFailed, reportTo };
121
+ export { exchangeFailed, historyRebuilt, hostDefect, listenerFailed, reactionFailed, reactionParked, reactionSkipped, reportTo, serverOnlySubmitted, unknownRefusal };
66
122
 
67
123
  //# sourceMappingURL=diagnostics.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics.js","names":[],"sources":["../src/diagnostics.ts"],"sourcesContent":["/**\n * What Sync meets and keeps going past. A replica whose exchange failed (also\n * in `status.lastError`), or whose server's history changed under it; a\n * document host that answered an upgrade \"Internal error\" or closed a socket\n * as one, whose cause neither the replica nor the response carries; and a\n * listener the application gave that threw. Each is reported through\n * `Diagnostics.report`.\n */\nimport { Cause, Effect } from 'effect'\nimport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nimport type { ReplicaError } from './errors.js'\nimport type { TransportError } from './transport.js'\n\nconst source = 'foldkit-sync'\n\n/** An exchange failed; the replica shows it in `status.lastError` and tries again on a backoff. */\nexport interface ExchangeFailed extends Diagnostic {\n readonly _tag: 'ExchangeFailed'\n readonly documentId: string\n readonly replicaId: string\n readonly error: ReplicaError | TransportError\n}\n\n/**\n * The server answered from another epoch: its history is not the one the\n * replica's cursor points into (it was reset), so the committed state was\n * rebuilt from its answer. The outbox is kept.\n */\nexport interface HistoryRebuilt extends Diagnostic {\n readonly _tag: 'HistoryRebuilt'\n readonly documentId: string\n readonly replicaId: string\n}\n\n/** Where a document host broke. */\nexport type HostStage =\n /** Making or accepting the socket pair (`foldkit-sync/do`). */\n | 'Upgrade'\n /** Building `layer`, or `resolvePrincipal` dying or throwing. */\n | 'Resolve'\n /** Opening the journal. */\n | 'Journal'\n /** The application's `opens` or `settle` throwing as the exchange was made. */\n | 'Exchange'\n /** `revalidate` asking the resolver again, which died: the socket closed with 1011. */\n | 'Revalidate'\n /** Asking `opens` before a commit notice, which failed: the notice was not sent. */\n | 'Notice'\n /** The journal's stream of commits, which broke: the connection hears of no more commits. */\n | 'Changes'\n\n/**\n * A document host broke on its own side: the upgrade was answered 500\n * \"Internal error\", the socket closed with 1011, or a notice went unsent. The\n * replica is told nothing of the cause.\n */\nexport interface HostDefect extends Diagnostic {\n readonly _tag: 'HostDefect'\n readonly stage: HostStage\n readonly cause: Cause.Cause<unknown>\n}\n\n/** Where a listener the application gave was called. */\nexport type ListenerSite =\n /** `Presence.subscribe`'s listener, after a peer changed. */\n | 'Presence'\n /** A listener on the socket transport's shared `socket` (`onMessage`), for another protocol's frames. */\n | 'Socket'\n /** `journalChanges`' listener, after a commit: the next commit calls it again. */\n | 'Notice'\n\n/** A listener the application gave threw; the rest still ran, and so did Sync. */\nexport interface ListenerFailed extends Diagnostic {\n readonly _tag: 'ListenerFailed'\n readonly site: ListenerSite\n /** What it threw. */\n readonly thrown: unknown\n}\n\n/** Every diagnostic Sync reports. */\nexport type SyncDiagnostic = ExchangeFailed | HistoryRebuilt | HostDefect | ListenerFailed\n\nexport const exchangeFailed = (\n documentId: string,\n replicaId: string,\n error: ReplicaError | TransportError,\n): ExchangeFailed => ({\n _tag: 'ExchangeFailed',\n source,\n level: 'warning',\n message: `${documentId} (replica ${replicaId}) failed an exchange (${error._tag}: ${error.message}); it is in status.lastError and tried again on a backoff.`,\n documentId,\n replicaId,\n error,\n})\n\nexport const historyRebuilt = (documentId: string, replicaId: string): HistoryRebuilt => ({\n _tag: 'HistoryRebuilt',\n source,\n level: 'warning',\n message: `${documentId} (replica ${replicaId}): the server's history changed (another epoch), so the committed state was rebuilt from it; unsent edits were kept.`,\n documentId,\n replicaId,\n})\n\nconst stageText: Record<HostStage, string> = {\n Upgrade: 'making or accepting the socket broke, and the upgrade was answered \"Internal error\"',\n Resolve:\n 'building the layer or resolving the principal broke, and the upgrade was answered \"Internal error\"',\n Journal: 'opening the journal failed, and the upgrade was answered \"Internal error\"',\n Exchange: 'opens or settle threw, and the upgrade was answered \"Internal error\"',\n Revalidate: 'asking the resolver again broke, and the socket was closed with 1011',\n Notice: 'asking opens before a commit notice failed, and the notice was not sent',\n Changes: \"the journal's stream of commits broke, and this connection hears of no more commits\",\n}\n\nexport const hostDefect = (stage: HostStage, cause: Cause.Cause<unknown>): HostDefect => ({\n _tag: 'HostDefect',\n source,\n level: 'error',\n message: `a document host broke: ${stageText[stage]}\\n${Cause.pretty(cause)}`,\n stage,\n cause,\n})\n\nconst siteText: Record<ListenerSite, string> = {\n Presence: 'a presence listener',\n Socket: \"a listener on the replica's socket\",\n Notice: 'the listener woken by a commit',\n}\n\nexport const listenerFailed = (site: ListenerSite, thrown: unknown): ListenerFailed => ({\n _tag: 'ListenerFailed',\n source,\n level: 'error',\n message: `${siteText[site]} threw (${String(thrown)}); the other listeners ran.`,\n site,\n thrown,\n})\n\n/** Reports `diagnostic` to `reporter` when a host gave one, else to the reporter in context. */\nexport const reportTo = (\n reporter: ReportDiagnostic | undefined,\n diagnostic: SyncDiagnostic,\n): Effect.Effect<void> => {\n const reported = Diagnostics.report(diagnostic)\n return reporter === undefined\n ? reported\n : Effect.provideService(reported, Diagnostics.Reporter, reporter)\n}\n"],"mappings":";;;;;;;;;;;AAaA,MAAM,SAAS;AAqEf,MAAa,kBACX,YACA,WACA,WACoB;CACpB,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,WAAW,YAAY,UAAU,wBAAwB,MAAM,KAAK,IAAI,MAAM,QAAQ;CAClG;CACA;CACA;AACF;AAEA,MAAa,kBAAkB,YAAoB,eAAuC;CACxF,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,WAAW,YAAY,UAAU;CAC7C;CACA;AACF;AAEA,MAAM,YAAuC;CAC3C,SAAS;CACT,SACE;CACF,SAAS;CACT,UAAU;CACV,YAAY;CACZ,QAAQ;CACR,SAAS;AACX;AAEA,MAAa,cAAc,OAAkB,WAA6C;CACxF,MAAM;CACN;CACA,OAAO;CACP,SAAS,0BAA0B,UAAU,OAAO,IAAI,MAAM,OAAO,KAAK;CAC1E;CACA;AACF;AAEA,MAAM,WAAyC;CAC7C,UAAU;CACV,QAAQ;CACR,QAAQ;AACV;AAEA,MAAa,kBAAkB,MAAoB,YAAqC;CACtF,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,SAAS,MAAM,UAAU,OAAO,MAAM,EAAE;CACpD;CACA;AACF;;AAGA,MAAa,YACX,UACA,eACwB;CACxB,MAAM,WAAW,YAAY,OAAO,UAAU;CAC9C,OAAO,aAAa,KAAA,IAChB,WACA,OAAO,eAAe,UAAU,YAAY,UAAU,QAAQ;AACpE"}
1
+ {"version":3,"file":"diagnostics.js","names":[],"sources":["../src/diagnostics.ts"],"sourcesContent":["/**\n * What Sync meets and keeps going past. A replica whose exchange failed (also\n * in `status.lastError`), whose server's history changed under it, or whose\n * server refused an operation with a refusal it cannot read; a\n * document host that answered an upgrade \"Internal error\" or closed a socket\n * as one, whose cause neither the replica nor the response carries; and a\n * listener the application gave that threw. Each is reported through\n * `Diagnostics.report`.\n */\nimport { Cause, Effect, Option } from 'effect'\nimport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nimport type { ReplicaError } from './errors.js'\nimport type { TransportError } from './transport.js'\n\nconst source = 'foldkit-sync'\n\n/** An exchange failed; the replica shows it in `status.lastError` and tries again on a backoff. */\nexport interface ExchangeFailed extends Diagnostic {\n readonly _tag: 'ExchangeFailed'\n readonly documentId: string\n readonly replicaId: string\n readonly error: ReplicaError | TransportError\n}\n\n/**\n * The server answered from another epoch: its history is not the one the\n * replica's cursor points into (it was reset), so the committed state was\n * rebuilt from its answer. The outbox is kept.\n */\nexport interface HistoryRebuilt extends Diagnostic {\n readonly _tag: 'HistoryRebuilt'\n readonly documentId: string\n readonly replicaId: string\n}\n\n/**\n * The server rejected an operation with a refusal this build cannot read: a\n * newer server's case, or one that does not decode. The rejection stands, and\n * reads with no refusal.\n */\nexport interface UnknownRefusal extends Diagnostic {\n readonly _tag: 'UnknownRefusal'\n readonly documentId: string\n readonly replicaId: string\n readonly opId: string\n /** Why it did not decode, cut to 500 characters: the value is the server's, of any size. */\n readonly issue: string\n}\n\n/** Where a document host broke. */\nexport type HostStage =\n /** Making or accepting the socket pair (`foldkit-sync/do`). */\n | 'Upgrade'\n /** Building `layer`, or `resolvePrincipal` dying or throwing. */\n | 'Resolve'\n /** Opening the journal. */\n | 'Journal'\n /** The application's `opens` or `settle` throwing as the exchange was made. */\n | 'Exchange'\n /** `revalidate` asking the resolver again, which died: the socket closed with 1011. */\n | 'Revalidate'\n /** Asking `opens` before a commit notice, which failed: the notice was not sent. */\n | 'Notice'\n /** The journal's stream of commits, which broke: the connection hears of no more commits. */\n | 'Changes'\n /** A Durable Object's pass of reactions, after an exchange or in `alarm()`, which broke: the alarm comes back later. */\n | 'Alarm'\n\n/**\n * A document host broke on its own side: the upgrade was answered 500\n * \"Internal error\", the socket closed with 1011, or a notice went unsent. The\n * replica is told nothing of the cause.\n */\nexport interface HostDefect extends Diagnostic {\n readonly _tag: 'HostDefect'\n readonly stage: HostStage\n readonly cause: Cause.Cause<unknown>\n}\n\n/** Where a listener the application gave was called. */\nexport type ListenerSite =\n /** `Presence.subscribe`'s listener, after a peer changed. */\n | 'Presence'\n /** A listener on the socket transport's shared `socket` (`onMessage`), for another protocol's frames. */\n | 'Socket'\n /** `journalChanges`' listener, after a commit: the next commit calls it again. */\n | 'Notice'\n\n/** A listener the application gave threw; the rest still ran, and so did Sync. */\nexport interface ListenerFailed extends Diagnostic {\n readonly _tag: 'ListenerFailed'\n readonly site: ListenerSite\n /** What it threw. */\n readonly thrown: unknown\n}\n\n/**\n * A replica sent a Message only the server appends: rejected as `Forbidden`.\n * No honest client sends one, so it is worth a look. It names the operation and\n * the replica it claims, never the payload.\n */\nexport interface ServerOnlySubmitted extends Diagnostic {\n readonly _tag: 'ServerOnlySubmitted'\n readonly documentId: string\n readonly opId: string\n /** The replica id the entry claims: what the sender wrote, not proof of who it is. */\n readonly replicaId: string\n}\n\n/**\n * A reaction's run failed, threw or timed out: that reaction waits at the\n * operation, on a backoff, and the others go on.\n */\nexport interface ReactionFailed extends Diagnostic {\n readonly _tag: 'ReactionFailed'\n readonly documentId: string\n readonly reaction: string\n /** None when the commit itself would not read, so no operation can be named. */\n readonly opId: Option.Option<string>\n readonly sequence: Option.Option<number>\n /** Why, cut to 500 characters. */\n readonly cause: string\n}\n\n/** A reaction's run was set aside, for a person (`parked`); the reaction went on without it. */\nexport interface ReactionParked extends Diagnostic {\n readonly _tag: 'ReactionParked'\n readonly documentId: string\n readonly reaction: string\n readonly opId: string\n readonly sequence: number\n /** Why, cut to 500 characters. */\n readonly cause: string\n}\n\n/**\n * The log was compacted past a reaction's cursor, against `settledThrough`:\n * the commits between were never reacted to, and the reaction resumes at the\n * floor.\n */\nexport interface ReactionSkipped extends Diagnostic {\n readonly _tag: 'ReactionSkipped'\n readonly documentId: string\n readonly reaction: string\n readonly from: number\n readonly to: number\n}\n\n/** Every diagnostic Sync reports. */\nexport type SyncDiagnostic =\n | ExchangeFailed\n | HistoryRebuilt\n | HostDefect\n | ListenerFailed\n | ReactionFailed\n | ReactionParked\n | ReactionSkipped\n | ServerOnlySubmitted\n | UnknownRefusal\n\nexport const exchangeFailed = (\n documentId: string,\n replicaId: string,\n error: ReplicaError | TransportError,\n): ExchangeFailed => ({\n _tag: 'ExchangeFailed',\n source,\n level: 'warning',\n message: `${documentId} (replica ${replicaId}) failed an exchange (${error._tag}: ${error.message}); it is in status.lastError and tried again on a backoff.`,\n documentId,\n replicaId,\n error,\n})\n\nexport const historyRebuilt = (documentId: string, replicaId: string): HistoryRebuilt => ({\n _tag: 'HistoryRebuilt',\n source,\n level: 'warning',\n message: `${documentId} (replica ${replicaId}): the server's history changed (another epoch), so the committed state was rebuilt from it; unsent edits were kept.`,\n documentId,\n replicaId,\n})\n\nexport const unknownRefusal = (\n documentId: string,\n replicaId: string,\n opId: string,\n issue: string,\n): UnknownRefusal => ({\n _tag: 'UnknownRefusal',\n source,\n level: 'warning',\n message: `${documentId} (replica ${replicaId}): the server rejected ${opId} with a refusal this build cannot read (${issue}); it reads with none.`,\n documentId,\n replicaId,\n opId,\n issue,\n})\n\nexport const serverOnlySubmitted = (\n documentId: string,\n opId: string,\n replicaId: string,\n): ServerOnlySubmitted => ({\n _tag: 'ServerOnlySubmitted',\n source,\n level: 'warning',\n message: `${documentId}: ${opId}, sent as replica ${replicaId}, carries a Message only the server appends; it was rejected as Forbidden.`,\n documentId,\n opId,\n replicaId,\n})\n\nexport const reactionFailed = (\n documentId: string,\n reaction: string,\n at: Option.Option<{ readonly opId: string; readonly sequence: number }>,\n cause: string,\n): ReactionFailed => ({\n _tag: 'ReactionFailed',\n source,\n level: 'warning',\n message: `${documentId}: reaction ${reaction} failed${Option.match(at, {\n onNone: () => ' reading the log',\n onSome: ({ opId, sequence }) => ` at ${opId} (${sequence})`,\n })} (${cause}); it waits there on a backoff.`,\n documentId,\n reaction,\n opId: Option.map(at, ({ opId }) => opId),\n sequence: Option.map(at, ({ sequence }) => sequence),\n cause,\n})\n\nexport const reactionParked = (\n documentId: string,\n reaction: string,\n opId: string,\n sequence: number,\n cause: string,\n): ReactionParked => ({\n _tag: 'ReactionParked',\n source,\n level: 'error',\n message: `${documentId}: reaction ${reaction} set ${opId} (${sequence}) aside (${cause}); it is in parked, and the reaction went on.`,\n documentId,\n reaction,\n opId,\n sequence,\n cause,\n})\n\nexport const reactionSkipped = (\n documentId: string,\n reaction: string,\n from: number,\n to: number,\n): ReactionSkipped => ({\n _tag: 'ReactionSkipped',\n source,\n level: 'error',\n message: `${documentId}: the log was compacted past reaction ${reaction}; commits ${from + 1} to ${to} were never reacted to.`,\n documentId,\n reaction,\n from,\n to,\n})\n\nconst stageText: Record<HostStage, string> = {\n Upgrade: 'making or accepting the socket broke, and the upgrade was answered \"Internal error\"',\n Resolve:\n 'building the layer or resolving the principal broke, and the upgrade was answered \"Internal error\"',\n Journal: 'opening the journal failed, and the upgrade was answered \"Internal error\"',\n Exchange: 'opens or settle threw, and the upgrade was answered \"Internal error\"',\n Revalidate: 'asking the resolver again broke, and the socket was closed with 1011',\n Notice: 'asking opens before a commit notice failed, and the notice was not sent',\n Changes: \"the journal's stream of commits broke, and this connection hears of no more commits\",\n Alarm: 'running the reactions broke, and the alarm was set to run them again later',\n}\n\nexport const hostDefect = (stage: HostStage, cause: Cause.Cause<unknown>): HostDefect => ({\n _tag: 'HostDefect',\n source,\n level: 'error',\n message: `a document host broke: ${stageText[stage]}\\n${Cause.pretty(cause)}`,\n stage,\n cause,\n})\n\nconst siteText: Record<ListenerSite, string> = {\n Presence: 'a presence listener',\n Socket: \"a listener on the replica's socket\",\n Notice: 'the listener woken by a commit',\n}\n\nexport const listenerFailed = (site: ListenerSite, thrown: unknown): ListenerFailed => ({\n _tag: 'ListenerFailed',\n source,\n level: 'error',\n message: `${siteText[site]} threw (${String(thrown)}); the other listeners ran.`,\n site,\n thrown,\n})\n\n/** Reports `diagnostic` to `reporter` when a host gave one, else to the reporter in context. */\nexport const reportTo = (\n reporter: ReportDiagnostic | undefined,\n diagnostic: SyncDiagnostic,\n): Effect.Effect<void> => {\n const reported = Diagnostics.report(diagnostic)\n return reporter === undefined\n ? reported\n : Effect.provideService(reported, Diagnostics.Reporter, reporter)\n}\n"],"mappings":";;;;;;;;;;;;AAcA,MAAM,SAAS;AAkJf,MAAa,kBACX,YACA,WACA,WACoB;CACpB,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,WAAW,YAAY,UAAU,wBAAwB,MAAM,KAAK,IAAI,MAAM,QAAQ;CAClG;CACA;CACA;AACF;AAEA,MAAa,kBAAkB,YAAoB,eAAuC;CACxF,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,WAAW,YAAY,UAAU;CAC7C;CACA;AACF;AAEA,MAAa,kBACX,YACA,WACA,MACA,WACoB;CACpB,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,WAAW,YAAY,UAAU,yBAAyB,KAAK,0CAA0C,MAAM;CAC3H;CACA;CACA;CACA;AACF;AAEA,MAAa,uBACX,YACA,MACA,eACyB;CACzB,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,WAAW,IAAI,KAAK,oBAAoB,UAAU;CAC9D;CACA;CACA;AACF;AAEA,MAAa,kBACX,YACA,UACA,IACA,WACoB;CACpB,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,WAAW,aAAa,SAAS,SAAS,OAAO,MAAM,IAAI;EACrE,cAAc;EACd,SAAS,EAAE,MAAM,eAAe,OAAO,KAAK,IAAI,SAAS;CAC3D,CAAC,EAAE,IAAI,MAAM;CACb;CACA;CACA,MAAM,OAAO,IAAI,KAAK,EAAE,WAAW,IAAI;CACvC,UAAU,OAAO,IAAI,KAAK,EAAE,eAAe,QAAQ;CACnD;AACF;AAEA,MAAa,kBACX,YACA,UACA,MACA,UACA,WACoB;CACpB,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,WAAW,aAAa,SAAS,OAAO,KAAK,IAAI,SAAS,WAAW,MAAM;CACvF;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,mBACX,YACA,UACA,MACA,QACqB;CACrB,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,WAAW,wCAAwC,SAAS,YAAY,OAAO,EAAE,MAAM,GAAG;CACtG;CACA;CACA;CACA;AACF;AAEA,MAAM,YAAuC;CAC3C,SAAS;CACT,SACE;CACF,SAAS;CACT,UAAU;CACV,YAAY;CACZ,QAAQ;CACR,SAAS;CACT,OAAO;AACT;AAEA,MAAa,cAAc,OAAkB,WAA6C;CACxF,MAAM;CACN;CACA,OAAO;CACP,SAAS,0BAA0B,UAAU,OAAO,IAAI,MAAM,OAAO,KAAK;CAC1E;CACA;AACF;AAEA,MAAM,WAAyC;CAC7C,UAAU;CACV,QAAQ;CACR,QAAQ;AACV;AAEA,MAAa,kBAAkB,MAAoB,YAAqC;CACtF,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,SAAS,MAAM,UAAU,OAAO,MAAM,EAAE;CACpD;CACA;AACF;;AAGA,MAAa,YACX,UACA,eACwB;CACxB,MAAM,WAAW,YAAY,OAAO,UAAU;CAC9C,OAAO,aAAa,KAAA,IAChB,WACA,OAAO,eAAe,UAAU,YAAY,UAAU,QAAQ;AACpE"}
package/dist/do.d.ts CHANGED
@@ -1,13 +1,41 @@
1
1
  import { Duration, Effect, Layer } from "effect";
2
2
  import { Diagnostic } from "foldkit-surface";
3
- import { AuthorizeDecision } from "./make.js";
4
- import { Operation, Sync } from "./sync.js";
5
3
  import { Journal } from "foldkit-durable/core";
4
+ import { Reaction } from "./serverJournal.js";
5
+ import { AuthorizeDecision } from "./make.js";
6
+ import { Operation, Sync, WrittenOperation } from "./sync.js";
6
7
  import { RemoteUnauthenticated } from "foldkit-remote";
7
- /** The sliver of a Durable Object the host uses: state for the journal to open with. */
8
+ /** The alarm a Durable Object's storage keeps: one per object. */
9
+ export interface AlarmStorage {
10
+ getAlarm(): Promise<number | null>;
11
+ setAlarm(scheduledTime: number): Promise<void>;
12
+ }
13
+ /**
14
+ * Brings a Durable Object's alarm to `at` (ms since the Unix epoch) unless it
15
+ * is already sooner: what an application's own `alarm()` uses beside the
16
+ * host's, which shares the object's one alarm. Inside `alarm()` the runtime
17
+ * may still answer the alarm being run, so a time already past counts as no
18
+ * alarm.
19
+ */
20
+ export declare const armAlarm: (storage: AlarmStorage, at: number) => Promise<void>;
21
+ /**
22
+ * The sliver of a Durable Object the host uses: state for the journal to
23
+ * open with, and, with `server`, the storage's alarm (`getAlarm`,
24
+ * `setAlarm`). Left `unknown` so `openJournal` can read the rest of it (the
25
+ * object's SQLite) as its own type.
26
+ */
8
27
  export interface DocumentHostContext {
9
28
  readonly storage?: unknown;
10
29
  }
30
+ /** The server's own side of the document, for `defineDocumentHost`'s `server`. */
31
+ export interface DocumentHostServer<Principal, Env> {
32
+ /** Who the server commits as. Never resolved from a request, and never changed. */
33
+ readonly principal: Principal;
34
+ /** The document's reactions, made from the environment (a mailer's key, a binding). */
35
+ readonly reactions: (env: Env) => ReadonlyArray<Reaction<unknown, never>>;
36
+ /** The most runs one pass starts. */
37
+ readonly runsPerPass?: number | undefined;
38
+ }
11
39
  /** What `defineDocumentHost` needs of the application, per document. */
12
40
  export interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never> {
13
41
  /** The document's contract: its codecs and journal shape. */
@@ -19,7 +47,7 @@ export interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never>
19
47
  * unwrap; a rejection answers the upgrade with a 500, and the next upgrade
20
48
  * tries again.
21
49
  */
22
- readonly openJournal: (ctx: DocumentHostContext, env: Env) => Promise<Journal<Operation, Shared, Principal, Operation>>;
50
+ readonly openJournal: (ctx: DocumentHostContext, env: Env) => Promise<Journal<Operation, Shared, Principal, WrittenOperation>>;
23
51
  /**
24
52
  * Who is opening this socket, from the upgrade request. Fails with a
25
53
  * `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated()`
@@ -34,7 +62,7 @@ export interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never>
34
62
  * environment — a D1 binding, say — and the journal, because both live
35
63
  * outside the exchange. See `serveJournal`.
36
64
  */
37
- readonly settle?: ((env: Env, journal: Journal<Operation, Shared, Principal, Operation>) => Effect.Effect<void, unknown>) | undefined;
65
+ readonly settle?: ((env: Env, journal: Journal<Operation, Shared, Principal, WrittenOperation>) => Effect.Effect<void, unknown>) | undefined;
38
66
  /**
39
67
  * Asks `resolvePrincipal` again, of the upgrade request, every `every`
40
68
  * while the socket is open: a refusal closes it with 4401, and a principal
@@ -55,6 +83,18 @@ export interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never>
55
83
  * sees it. See `journalExchange`'s `admit`.
56
84
  */
57
85
  readonly admit?: ((principal: Principal, operation: Operation) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>) | undefined;
86
+ /**
87
+ * The server's own side: who it commits as, and the document's reactions
88
+ * (`foldkit-sync/journal`'s `reaction`), for a contract from
89
+ * `Sync.forApplication(App).make`. The host registers them when it opens
90
+ * the journal, before the first socket is served. After an exchange that
91
+ * committed, it sets the object's alarm and then runs them without holding
92
+ * the reply; `alarm()` runs them and sets the alarm again from what they
93
+ * answer. A run eviction cut off is resumed by the alarm, never by the
94
+ * runtime's retries of a throwing `alarm()`. The object has one alarm:
95
+ * the host only ever brings it earlier.
96
+ */
97
+ readonly server?: DocumentHostServer<Principal, Env> | undefined;
58
98
  /**
59
99
  * Makes the socket pair for an upgrade: the server end is accepted before
60
100
  * serving. Defaults to the `WebSocketPair` global where one exists (a
@@ -65,8 +105,9 @@ export interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never>
65
105
  * Where each upgrade's diagnostics go, with its request: a `HostDefect`
66
106
  * for every failure answered "Internal error" (making the socket pair,
67
107
  * the resolver, the journal, the exchange) and the rest `documentHost`
68
- * reports. The reporter in the Effect context when not given, by default
69
- * the log.
108
+ * reports. A pass of reactions that broke has no request of its own: it is
109
+ * reported with one for `https://durable-object/alarm`. The reporter in the
110
+ * Effect context when not given, by default the log.
70
111
  */
71
112
  readonly diagnostics?: ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>) | undefined;
72
113
  }
@@ -96,5 +137,6 @@ export interface AcceptingWebSocket extends WebSocket {
96
137
  */
97
138
  export declare const defineDocumentHost: <Message, Shared, Principal, Env, RP = never>(Base: new (ctx: DocumentHostContext, env: Env) => object, config: DocumentHostConfig<Message, Shared, Principal, Env, RP> & DocumentHostLayer<Env, RP>) => new (ctx: DocumentHostContext, env: Env) => {
98
139
  fetch(request: Request): Promise<Response>;
140
+ alarm(...info: Array<unknown>): Promise<void>;
99
141
  };
100
142
  //# sourceMappingURL=do.d.ts.map
package/dist/do.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"do.d.ts","names":[],"sources":["../src/do.ts"],"mappings":";;;;;;;iBA2CiB;WACN;;;iBAIM,mBAAmB,SAAS,QAAQ,WAAW,KAAK;;WAE1D,MAAM,KAAK,SAAS;;;;;;;;WAQpB,cACP,KAAK,qBACL,KAAK,QACF,QAAQ,QAAQ,WAAW,QAAQ,WAAW;;;;;;;;WAQ1C,mBACP,SAAS,SACT,KAAK,QACF,OAAO,OAAO,WAAW,uBAAuB;;;;;;;WAO5C,WAEH,KAAK,KACL,SAAS,QAAQ,WAAW,QAAQ,WAAW,eAC5C,OAAO;;;;;;;;;;WAWP;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,UAAU,WAAW,cAAc,OAAO;;;;;WAK1C,UAEH,WAAW,WACX,WAAW,cACR,oBAAoB,OAAO,OAAO;;;;;;WAOlC,wBAAwB,QAAQ,WAAW,QAAQ;;;;;;;;WAQnD,gBACH,YAAY,YAAY,SAAS,YAAY,OAAO;;;;;;;;YAUhD,kBAAkB,KAAK,OAAO;WAC3B;;WACA,QAAQ,KAAK,QAAQ,MAAM,MAAM;;;;;;iBAM/B,2BAA2B;EAC1C;;;;;;;;qBAuCW,qBAAsB,SAAS,QAAQ,WAAW,KAAK,YAAU,WACjE,KAAK,qBAAqB,KAAK,gBAAc,QAChD,mBAAmB,SAAS,QAAQ,WAAW,KAAK,MAAM,kBA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M,iBAAiB"}
package/dist/do.js CHANGED
@@ -1,8 +1,10 @@
1
- import { Cause, Effect, Result } from "effect";
1
+ import { Cause, Duration, Effect, Exit, Option, Result } from "effect";
2
+ import { DocumentId } from "foldkit-durable/core";
2
3
  import { documentHost } from "./journal.js";
3
4
  import { checkRevalidate } from "./revalidate.js";
4
5
  import { hostDefect, reportTo } from "./diagnostics.js";
5
6
  import { workerSocket } from "./transport.js";
7
+ import { serverJournal } from "./serverJournal.js";
6
8
  // src/do.ts
7
9
  /**
8
10
  * `foldkit-sync/do`: serve one document's Sync exchange from a Cloudflare
@@ -30,6 +32,22 @@ import { workerSocket } from "./transport.js";
30
32
  * .documentId)`); its in-memory cache and change stream are then exact
31
33
  * because nothing else writes.
32
34
  */
35
+ /** How long after a commit the alarm is set for: what resumes a run eviction cut off. */
36
+ const ALARM_AFTER_COMMIT = Duration.seconds(1);
37
+ /** When the alarm comes back after a pass that broke: never left to the runtime's retries. */
38
+ const ALARM_AFTER_DEFECT = Duration.seconds(30);
39
+ /**
40
+ * Brings a Durable Object's alarm to `at` (ms since the Unix epoch) unless it
41
+ * is already sooner: what an application's own `alarm()` uses beside the
42
+ * host's, which shares the object's one alarm. Inside `alarm()` the runtime
43
+ * may still answer the alarm being run, so a time already past counts as no
44
+ * alarm.
45
+ */
46
+ const armAlarm = async (storage, at) => {
47
+ const current = await storage.getAlarm();
48
+ if (current === null || current <= Date.now() || current > at) await storage.setAlarm(at);
49
+ };
50
+ const alarmsOf = (storage) => typeof storage === "object" && storage !== null && typeof storage.getAlarm === "function" && typeof storage.setAlarm === "function" ? Option.some(storage) : Option.none();
33
51
  /**
34
52
  * Closes a socket with `code`, and `reason` when the platform takes it: a
35
53
  * reason past 123 bytes, or a socket already gone, still closes or is closed.
@@ -57,27 +75,92 @@ const defaultPair = () => {
57
75
  */
58
76
  const defineDocumentHost = (Base, config) => {
59
77
  checkRevalidate(config.revalidate, "defineDocumentHost");
78
+ const baseAlarm = Base.prototype.alarm;
60
79
  return class extends Base {
61
80
  host;
81
+ react;
62
82
  constructor(ctx, env) {
63
83
  super(ctx, env);
64
84
  let ready;
65
- const { layer, settle } = config;
85
+ const { layer, settle, server } = config;
86
+ const alarms = Option.flatMap(Option.fromUndefinedOr(server), () => alarmsOf(ctx.storage));
87
+ if (server !== void 0 && Option.isNone(alarms)) throw new Error("defineDocumentHost: `server` needs the object’s storage alarm");
88
+ const reactions = server === void 0 ? [] : server.reactions(env);
89
+ for (const each of reactions) if (each.sync !== config.sync) throw new Error(`defineDocumentHost: reaction ${each.name} was declared for another contract`);
90
+ /** Reports a pass that broke; a reporter that fails itself is not let out of `alarm()`. */
91
+ const report = (stage, cause) => Effect.runPromise(reportTo(config.diagnostics === void 0 ? void 0 : (diagnostic) => config.diagnostics(diagnostic, new Request("https://durable-object/alarm")), hostDefect(stage, cause))).catch(() => void 0);
92
+ const arm = (after) => armAlarm(Option.getOrThrow(alarms), Date.now() + Duration.toMillis(after));
93
+ const open = () => (ready ??= config.openJournal(ctx, env).then(async (journal) => ({
94
+ journal,
95
+ server: server === void 0 ? Option.none() : Option.some(await Effect.runPromise(serverJournal({
96
+ sync: config.sync,
97
+ journal,
98
+ server: server.principal,
99
+ reactions,
100
+ runsPerPass: server.runsPerPass
101
+ })))
102
+ }))).catch((error) => {
103
+ ready = void 0;
104
+ throw error;
105
+ });
106
+ /**
107
+ * One pass, then the alarm from its answer. Never rejects: a pass that
108
+ * broke (the journal would not open, a reaction was never registered)
109
+ * is reported and brings the alarm back later.
110
+ */
111
+ const runPass = async () => {
112
+ if (server === void 0) return;
113
+ const exit = await Effect.runPromiseExit(Effect.gen(function* () {
114
+ const { server: running } = yield* Effect.promise(open);
115
+ if (Option.isNone(running)) return;
116
+ const next = yield* running.value.react;
117
+ if (Option.isSome(next)) yield* Effect.promise(() => arm(next.value));
118
+ }));
119
+ if (Exit.isSuccess(exit)) return;
120
+ await report("Alarm", exit.cause);
121
+ await arm(ALARM_AFTER_DEFECT).catch(() => void 0);
122
+ };
123
+ const pass = runPass;
124
+ this.react = pass;
125
+ let seen = -1;
126
+ const afterExchange = (journal) => Effect.gen(function* () {
127
+ const at = yield* journal.cursor(DocumentId.make(config.sync.documentId));
128
+ if (at === seen) return;
129
+ if (yield* Effect.promise(() => arm(ALARM_AFTER_COMMIT).then(() => true, async (error) => {
130
+ await report("Alarm", Cause.die(error));
131
+ return false;
132
+ }))) seen = at;
133
+ pass();
134
+ });
66
135
  this.host = documentHost({
67
136
  sync: config.sync,
68
- journal: () => (ready ??= config.openJournal(ctx, env)).catch((error) => {
69
- ready = void 0;
70
- throw error;
71
- }),
137
+ journal: () => open().then((opened) => opened.journal),
72
138
  resolvePrincipal: (request) => config.resolvePrincipal(request, env),
73
139
  layer: layer === void 0 ? void 0 : () => layer(env),
74
140
  revalidate: config.revalidate,
75
- settle: settle === void 0 ? void 0 : (journal) => settle(env, journal),
141
+ settle: settle === void 0 && server === void 0 ? void 0 : (journal) => Effect.gen(function* () {
142
+ if (server !== void 0) yield* afterExchange(journal);
143
+ if (settle !== void 0) yield* settle(env, journal);
144
+ }),
76
145
  opens: config.opens,
77
146
  admit: config.admit,
78
147
  diagnostics: config.diagnostics
79
148
  });
80
149
  }
150
+ /**
151
+ * The object's alarm: runs the reactions and sets the alarm again from
152
+ * what they answer, then the base class's own `alarm()`, if it has one,
153
+ * with what the runtime passed. The reactions' part never throws, so the
154
+ * runtime's few retries of a throwing alarm are never what a run depends
155
+ * on. The object has one alarm, shared: the base runs on every wake, so
156
+ * it decides itself what is due, and sets its next with `armAlarm`, which
157
+ * only brings the alarm earlier. A subclass that overrides `alarm()` calls
158
+ * `super.alarm()`, or the reactions stop being resumed.
159
+ */
160
+ async alarm(...info) {
161
+ await this.react();
162
+ if (typeof baseAlarm === "function") await baseAlarm.apply(this, info);
163
+ }
81
164
  async fetch(request) {
82
165
  if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return Response.json({ error: "not found" }, { status: 404 });
83
166
  const broke = async (error) => {
@@ -112,6 +195,6 @@ const defineDocumentHost = (Base, config) => {
112
195
  }
113
196
  };
114
197
  };
115
- export { defineDocumentHost };
198
+ export { armAlarm, defineDocumentHost };
116
199
 
117
200
  //# sourceMappingURL=do.js.map
package/dist/do.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"do.js","names":[],"sources":["../src/do.ts"],"sourcesContent":["/**\n * `foldkit-sync/do`: serve one document's Sync exchange from a Cloudflare\n * Durable Object, the single writer its journal wants. Each socket the\n * object accepts exchanges against the same journal through `serveJournal`;\n * the replica side already exists as `Sync.transport.socket` over the\n * object's `wss://…` URL, which hears other writers' commits as notices.\n *\n * The class takes its `DurableObject` base as a parameter, so this module\n * imports no worker runtime and loads anywhere:\n *\n * ```ts\n * import { DurableObject } from 'cloudflare:workers'\n *\n * export class SyncHost extends defineDocumentHost(DurableObject, {\n * sync: Todos,\n * openJournal: (_ctx, env) => openTodosJournal(env.DB),\n * resolvePrincipal: request =>\n * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * }) {}\n * ```\n *\n * Open the journal once per object: on the first upgrade, so probes never\n * provision storage. Route one object per document (`idFromName(sync\n * .documentId)`); its in-memory cache and change stream are then exact\n * because nothing else writes.\n */\nimport { Cause, type Duration, Effect, type Layer, Result } from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport type { Diagnostic } from 'foldkit-surface'\nimport type { Journal } from 'foldkit-durable/core'\nimport {\n documentHost,\n type Accepted,\n type DocumentHostOptions,\n type DocumentHostOptionsLayer,\n} from './journal.js'\nimport { checkRevalidate } from './revalidate.js'\nimport { hostDefect, reportTo } from './diagnostics.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync } from './sync.js'\nimport { workerSocket } from './transport.js'\n\n/** The sliver of a Durable Object the host uses: state for the journal to open with. */\nexport interface DocumentHostContext {\n readonly storage?: unknown\n}\n\n/** What `defineDocumentHost` needs of the application, per document. */\nexport interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never> {\n /** The document's contract: its codecs and journal shape. */\n readonly sync: Sync<Message, Shared>\n /**\n * Opens the document's journal, once: on the first upgrade, not on\n * construction, so probes never provision storage. Over D1 (`d1: true`),\n * or the object's SQLite storage through `ctx`. May build with Effect and\n * unwrap; a rejection answers the upgrade with a 500, and the next upgrade\n * tries again.\n */\n readonly openJournal: (\n ctx: DocumentHostContext,\n env: Env,\n ) => Promise<Journal<Operation, Shared, Principal, Operation>>\n /**\n * Who is opening this socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated()`\n * makes one) to refuse it: a 401 carrying its message. A defect is a 500\n * that says nothing of it. What it needs (a session store) comes from\n * `layer`.\n */\n readonly resolvePrincipal: (\n request: Request,\n env: Env,\n ) => Effect.Effect<Principal, RemoteUnauthenticated, RP>\n /**\n * Runs after each exchange's appends and before the reply is read: apply\n * what committed to another store, through `journal.recover`. Takes the\n * environment — a D1 binding, say — and the journal, because both live\n * outside the exchange. See `serveJournal`.\n */\n readonly settle?:\n | ((\n env: Env,\n journal: Journal<Operation, Shared, Principal, Operation>,\n ) => Effect.Effect<void, unknown>)\n | undefined\n /**\n * Asks `resolvePrincipal` again, of the upgrade request, every `every`\n * while the socket is open: a refusal closes it with 4401, and a principal\n * whose `key` differs from the one it opened with (`Policy.keyOf`) closes\n * it with 1012, which the replica reconnects after, as the new principal;\n * without `key` only a refusal closes it. Without it a socket\n * serves the principal it opened with until it closes, a revoked session\n * included.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: Principal) => unknown) | undefined\n }\n | undefined\n /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */\n readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined\n /**\n * Whether an operation from `principal` may be appended, before the journal\n * sees it. See `journalExchange`'s `admit`.\n */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /**\n * Makes the socket pair for an upgrade: the server end is accepted before\n * serving. Defaults to the `WebSocketPair` global where one exists (a\n * worker, miniflare); pass one in tests.\n */\n readonly pair?: (() => readonly [client: WebSocket, server: AcceptingWebSocket]) | undefined\n /**\n * Where each upgrade's diagnostics go, with its request: a `HostDefect`\n * for every failure answered \"Internal error\" (making the socket pair,\n * the resolver, the journal, the exchange) and the rest `documentHost`\n * reports. The reporter in the Effect context when not given, by default\n * the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | undefined\n}\n\n/**\n * What the resolver needs, from the environment: required exactly when it\n * needs something. Built per upgrade and kept until the socket closes, since\n * `revalidate` asks the resolver again while it is open; an upgrade that is\n * refused closes it at once.\n */\nexport type DocumentHostLayer<Env, RP> = [RP] extends [never]\n ? { readonly layer?: undefined }\n : { readonly layer: (env: Env) => Layer.Layer<RP> }\n\n/**\n * A server `WebSocket`: accepted once it serves. The `accept` member is a\n * worker-runtime extension the DOM type does not declare.\n */\nexport interface AcceptingWebSocket extends WebSocket {\n accept(): void\n}\n\n/**\n * Closes a socket with `code`, and `reason` when the platform takes it: a\n * reason past 123 bytes, or a socket already gone, still closes or is closed.\n */\nconst closeWith = (socket: WebSocket, code: number, reason: string): void => {\n try {\n socket.close(code, reason)\n } catch {\n try {\n socket.close(code)\n } catch {\n // Already closed.\n }\n }\n}\n\nconst defaultPair = (): readonly [client: WebSocket, server: AcceptingWebSocket] => {\n const maker = (\n globalThis as {\n readonly WebSocketPair?:\n | (new () => { readonly 0: WebSocket; readonly 1: AcceptingWebSocket })\n | undefined\n }\n ).WebSocketPair\n if (maker === undefined)\n throw new Error('DocumentHost: no WebSocketPair global; pass `pair` explicitly')\n const pair = new maker()\n return [pair[0], pair[1]] as const\n}\n\n/**\n * Defines the Durable Object class serving one document's Sync exchange.\n * Non-upgrades are 404s that open nothing; a refused principal is a 401; a\n * resolver that breaks, or a journal that never opened, a 500 that says\n * nothing of it.\n */\nexport const defineDocumentHost = <Message, Shared, Principal, Env, RP = never>(\n Base: new (ctx: DocumentHostContext, env: Env) => object,\n config: DocumentHostConfig<Message, Shared, Principal, Env, RP> & DocumentHostLayer<Env, RP>,\n): new (ctx: DocumentHostContext, env: Env) => { fetch(request: Request): Promise<Response> } => {\n checkRevalidate(config.revalidate, 'defineDocumentHost')\n return class extends Base {\n private readonly host: (request: Request) => Promise<Result.Result<Accepted, Response>>\n\n constructor(ctx: DocumentHostContext, env: Env) {\n super(ctx, env)\n let ready: Promise<Journal<Operation, Shared, Principal, Operation>> | undefined\n const { layer, settle } = config\n this.host = documentHost<Message, Shared, Principal, RP>({\n sync: config.sync,\n // Opened on the first upgrade a principal passes, so probes never\n // provision storage; a failed open is tried again on the next.\n journal: () =>\n (ready ??= config.openJournal(ctx, env)).catch((error: unknown) => {\n ready = undefined\n throw error\n }),\n resolvePrincipal: request => config.resolvePrincipal(request, env),\n layer: layer === undefined ? undefined : () => layer(env),\n revalidate: config.revalidate,\n settle: settle === undefined ? undefined : journal => settle(env, journal),\n opens: config.opens,\n admit: config.admit,\n diagnostics: config.diagnostics,\n // `DocumentHostLayer` already tied `layer` to `RP` on the config; the\n // conditional cannot be resolved for an `RP` still generic here.\n } as DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>)\n }\n\n async fetch(request: Request): Promise<Response> {\n if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket')\n return Response.json({ error: 'not found' }, { status: 404 })\n // The replica learns nothing of it; whoever runs the host must.\n const broke = async (error: unknown): Promise<Response> => {\n const { diagnostics } = config\n await Effect.runPromise(\n reportTo(\n diagnostics === undefined ? undefined : diagnostic => diagnostics(diagnostic, request),\n hostDefect('Upgrade', Cause.die(error)),\n ),\n )\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n // Made first: a runtime without WebSocketPair is a 500 that resolves no one.\n let pair: readonly [client: WebSocket, server: AcceptingWebSocket]\n try {\n pair = (config.pair ?? defaultPair)()\n } catch (error) {\n return broke(error)\n }\n const [client, server] = pair\n const answered = await this.host(request)\n if (Result.isFailure(answered)) return answered.failure\n const { serve, abandon } = answered.success\n try {\n server.accept()\n serve({\n ...workerSocket(server),\n closeWith: (code, reason) => closeWith(server, code, reason),\n })\n return new Response(null, {\n status: 101,\n // The worker runtime reads the client out of the upgrade response;\n // the DOM's `ResponseInit` has no such member.\n webSocket: client,\n } as ResponseInit)\n } catch (error) {\n abandon()\n return broke(error)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwJA,MAAM,aAAa,QAAmB,MAAc,WAAyB;CAC3E,IAAI;EACF,OAAO,MAAM,MAAM,MAAM;CAC3B,QAAQ;EACN,IAAI;GACF,OAAO,MAAM,IAAI;EACnB,QAAQ,CAER;CACF;AACF;AAEA,MAAM,oBAA8E;CAClF,MAAM,QACJ,WAKA;CACF,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,+DAA+D;CACjF,MAAM,OAAO,IAAI,MAAM;CACvB,OAAO,CAAC,KAAK,IAAI,KAAK,EAAE;AAC1B;;;;;;;AAQA,MAAa,sBACX,MACA,WAC+F;CAC/F,gBAAgB,OAAO,YAAY,oBAAoB;CACvD,OAAO,cAAc,KAAK;EACxB;EAEA,YAAY,KAA0B,KAAU;GAC9C,MAAM,KAAK,GAAG;GACd,IAAI;GACJ,MAAM,EAAE,OAAO,WAAW;GAC1B,KAAK,OAAO,aAA6C;IACvD,MAAM,OAAO;IAGb,gBACG,UAAU,OAAO,YAAY,KAAK,GAAG,EAAA,CAAG,OAAO,UAAmB;KACjE,QAAQ,KAAA;KACR,MAAM;IACR,CAAC;IACH,mBAAkB,YAAW,OAAO,iBAAiB,SAAS,GAAG;IACjE,OAAO,UAAU,KAAA,IAAY,KAAA,UAAkB,MAAM,GAAG;IACxD,YAAY,OAAO;IACnB,QAAQ,WAAW,KAAA,IAAY,KAAA,KAAY,YAAW,OAAO,KAAK,OAAO;IACzE,OAAO,OAAO;IACd,OAAO,OAAO;IACd,aAAa,OAAO;GAGtB,CAAuF;EACzF;EAEA,MAAM,MAAM,SAAqC;GAC/C,IAAI,QAAQ,QAAQ,IAAI,SAAS,CAAC,EAAE,YAAY,MAAM,aACpD,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;GAE9D,MAAM,QAAQ,OAAO,UAAsC;IACzD,MAAM,EAAE,gBAAgB;IACxB,MAAM,OAAO,WACX,SACE,gBAAgB,KAAA,IAAY,KAAA,KAAY,eAAc,YAAY,YAAY,OAAO,GACrF,WAAW,WAAW,MAAM,IAAI,KAAK,CAAC,CACxC,CACF;IACA,OAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;GACnE;GAEA,IAAI;GACJ,IAAI;IACF,QAAQ,OAAO,QAAQ,YAAA,CAAa;GACtC,SAAS,OAAO;IACd,OAAO,MAAM,KAAK;GACpB;GACA,MAAM,CAAC,QAAQ,UAAU;GACzB,MAAM,WAAW,MAAM,KAAK,KAAK,OAAO;GACxC,IAAI,OAAO,UAAU,QAAQ,GAAG,OAAO,SAAS;GAChD,MAAM,EAAE,OAAO,YAAY,SAAS;GACpC,IAAI;IACF,OAAO,OAAO;IACd,MAAM;KACJ,GAAG,aAAa,MAAM;KACtB,YAAY,MAAM,WAAW,UAAU,QAAQ,MAAM,MAAM;IAC7D,CAAC;IACD,OAAO,IAAI,SAAS,MAAM;KACxB,QAAQ;KAGR,WAAW;IACb,CAAiB;GACnB,SAAS,OAAO;IACd,QAAQ;IACR,OAAO,MAAM,KAAK;GACpB;EACF;CACF;AACF"}
1
+ {"version":3,"file":"do.js","names":["JournalDocumentId"],"sources":["../src/do.ts"],"sourcesContent":["/**\n * `foldkit-sync/do`: serve one document's Sync exchange from a Cloudflare\n * Durable Object, the single writer its journal wants. Each socket the\n * object accepts exchanges against the same journal through `serveJournal`;\n * the replica side already exists as `Sync.transport.socket` over the\n * object's `wss://…` URL, which hears other writers' commits as notices.\n *\n * The class takes its `DurableObject` base as a parameter, so this module\n * imports no worker runtime and loads anywhere:\n *\n * ```ts\n * import { DurableObject } from 'cloudflare:workers'\n *\n * export class SyncHost extends defineDocumentHost(DurableObject, {\n * sync: Todos,\n * openJournal: (_ctx, env) => openTodosJournal(env.DB),\n * resolvePrincipal: request =>\n * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * }) {}\n * ```\n *\n * Open the journal once per object: on the first upgrade, so probes never\n * provision storage. Route one object per document (`idFromName(sync\n * .documentId)`); its in-memory cache and change stream are then exact\n * because nothing else writes.\n */\nimport { Cause, Duration, Effect, Exit, type Layer, Option, Result } from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport type { Diagnostic } from 'foldkit-surface'\nimport { DocumentId as JournalDocumentId, type Journal } from 'foldkit-durable/core'\nimport {\n documentHost,\n type Accepted,\n type DocumentHostOptions,\n type DocumentHostOptionsLayer,\n} from './journal.js'\nimport { checkRevalidate } from './revalidate.js'\nimport { hostDefect, reportTo } from './diagnostics.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync, WrittenOperation } from './sync.js'\nimport { workerSocket } from './transport.js'\nimport { serverJournal, type Reaction, type ServerJournal } from './serverJournal.js'\n\n/** How long after a commit the alarm is set for: what resumes a run eviction cut off. */\nconst ALARM_AFTER_COMMIT = Duration.seconds(1)\n/** When the alarm comes back after a pass that broke: never left to the runtime's retries. */\nconst ALARM_AFTER_DEFECT = Duration.seconds(30)\n\n/** The alarm a Durable Object's storage keeps: one per object. */\nexport interface AlarmStorage {\n getAlarm(): Promise<number | null>\n setAlarm(scheduledTime: number): Promise<void>\n}\n\n/**\n * Brings a Durable Object's alarm to `at` (ms since the Unix epoch) unless it\n * is already sooner: what an application's own `alarm()` uses beside the\n * host's, which shares the object's one alarm. Inside `alarm()` the runtime\n * may still answer the alarm being run, so a time already past counts as no\n * alarm.\n */\nexport const armAlarm = async (storage: AlarmStorage, at: number): Promise<void> => {\n const current = await storage.getAlarm()\n if (current === null || current <= Date.now() || current > at) await storage.setAlarm(at)\n}\n\nconst alarmsOf = (storage: unknown): Option.Option<AlarmStorage> =>\n typeof storage === 'object' &&\n storage !== null &&\n typeof (storage as Partial<AlarmStorage>).getAlarm === 'function' &&\n typeof (storage as Partial<AlarmStorage>).setAlarm === 'function'\n ? Option.some(storage as AlarmStorage)\n : Option.none()\n\n/**\n * The sliver of a Durable Object the host uses: state for the journal to\n * open with, and, with `server`, the storage's alarm (`getAlarm`,\n * `setAlarm`). Left `unknown` so `openJournal` can read the rest of it (the\n * object's SQLite) as its own type.\n */\nexport interface DocumentHostContext {\n readonly storage?: unknown\n}\n\n/** The server's own side of the document, for `defineDocumentHost`'s `server`. */\nexport interface DocumentHostServer<Principal, Env> {\n /** Who the server commits as. Never resolved from a request, and never changed. */\n readonly principal: Principal\n /** The document's reactions, made from the environment (a mailer's key, a binding). */\n readonly reactions: (env: Env) => ReadonlyArray<Reaction<unknown, never>>\n /** The most runs one pass starts. */\n readonly runsPerPass?: number | undefined\n}\n\n/** What `defineDocumentHost` needs of the application, per document. */\nexport interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never> {\n /** The document's contract: its codecs and journal shape. */\n readonly sync: Sync<Message, Shared>\n /**\n * Opens the document's journal, once: on the first upgrade, not on\n * construction, so probes never provision storage. Over D1 (`d1: true`),\n * or the object's SQLite storage through `ctx`. May build with Effect and\n * unwrap; a rejection answers the upgrade with a 500, and the next upgrade\n * tries again.\n */\n readonly openJournal: (\n ctx: DocumentHostContext,\n env: Env,\n ) => Promise<Journal<Operation, Shared, Principal, WrittenOperation>>\n /**\n * Who is opening this socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated()`\n * makes one) to refuse it: a 401 carrying its message. A defect is a 500\n * that says nothing of it. What it needs (a session store) comes from\n * `layer`.\n */\n readonly resolvePrincipal: (\n request: Request,\n env: Env,\n ) => Effect.Effect<Principal, RemoteUnauthenticated, RP>\n /**\n * Runs after each exchange's appends and before the reply is read: apply\n * what committed to another store, through `journal.recover`. Takes the\n * environment — a D1 binding, say — and the journal, because both live\n * outside the exchange. See `serveJournal`.\n */\n readonly settle?:\n | ((\n env: Env,\n journal: Journal<Operation, Shared, Principal, WrittenOperation>,\n ) => Effect.Effect<void, unknown>)\n | undefined\n /**\n * Asks `resolvePrincipal` again, of the upgrade request, every `every`\n * while the socket is open: a refusal closes it with 4401, and a principal\n * whose `key` differs from the one it opened with (`Policy.keyOf`) closes\n * it with 1012, which the replica reconnects after, as the new principal;\n * without `key` only a refusal closes it. Without it a socket\n * serves the principal it opened with until it closes, a revoked session\n * included.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: Principal) => unknown) | undefined\n }\n | undefined\n /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */\n readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined\n /**\n * Whether an operation from `principal` may be appended, before the journal\n * sees it. See `journalExchange`'s `admit`.\n */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /**\n * The server's own side: who it commits as, and the document's reactions\n * (`foldkit-sync/journal`'s `reaction`), for a contract from\n * `Sync.forApplication(App).make`. The host registers them when it opens\n * the journal, before the first socket is served. After an exchange that\n * committed, it sets the object's alarm and then runs them without holding\n * the reply; `alarm()` runs them and sets the alarm again from what they\n * answer. A run eviction cut off is resumed by the alarm, never by the\n * runtime's retries of a throwing `alarm()`. The object has one alarm:\n * the host only ever brings it earlier.\n */\n readonly server?: DocumentHostServer<Principal, Env> | undefined\n /**\n * Makes the socket pair for an upgrade: the server end is accepted before\n * serving. Defaults to the `WebSocketPair` global where one exists (a\n * worker, miniflare); pass one in tests.\n */\n readonly pair?: (() => readonly [client: WebSocket, server: AcceptingWebSocket]) | undefined\n /**\n * Where each upgrade's diagnostics go, with its request: a `HostDefect`\n * for every failure answered \"Internal error\" (making the socket pair,\n * the resolver, the journal, the exchange) and the rest `documentHost`\n * reports. A pass of reactions that broke has no request of its own: it is\n * reported with one for `https://durable-object/alarm`. The reporter in the\n * Effect context when not given, by default the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | undefined\n}\n\n/**\n * What the resolver needs, from the environment: required exactly when it\n * needs something. Built per upgrade and kept until the socket closes, since\n * `revalidate` asks the resolver again while it is open; an upgrade that is\n * refused closes it at once.\n */\nexport type DocumentHostLayer<Env, RP> = [RP] extends [never]\n ? { readonly layer?: undefined }\n : { readonly layer: (env: Env) => Layer.Layer<RP> }\n\n/**\n * A server `WebSocket`: accepted once it serves. The `accept` member is a\n * worker-runtime extension the DOM type does not declare.\n */\nexport interface AcceptingWebSocket extends WebSocket {\n accept(): void\n}\n\n/**\n * Closes a socket with `code`, and `reason` when the platform takes it: a\n * reason past 123 bytes, or a socket already gone, still closes or is closed.\n */\nconst closeWith = (socket: WebSocket, code: number, reason: string): void => {\n try {\n socket.close(code, reason)\n } catch {\n try {\n socket.close(code)\n } catch {\n // Already closed.\n }\n }\n}\n\nconst defaultPair = (): readonly [client: WebSocket, server: AcceptingWebSocket] => {\n const maker = (\n globalThis as {\n readonly WebSocketPair?:\n | (new () => { readonly 0: WebSocket; readonly 1: AcceptingWebSocket })\n | undefined\n }\n ).WebSocketPair\n if (maker === undefined)\n throw new Error('DocumentHost: no WebSocketPair global; pass `pair` explicitly')\n const pair = new maker()\n return [pair[0], pair[1]] as const\n}\n\n/**\n * Defines the Durable Object class serving one document's Sync exchange.\n * Non-upgrades are 404s that open nothing; a refused principal is a 401; a\n * resolver that breaks, or a journal that never opened, a 500 that says\n * nothing of it.\n */\nexport const defineDocumentHost = <Message, Shared, Principal, Env, RP = never>(\n Base: new (ctx: DocumentHostContext, env: Env) => object,\n config: DocumentHostConfig<Message, Shared, Principal, Env, RP> & DocumentHostLayer<Env, RP>,\n): new (\n ctx: DocumentHostContext,\n env: Env,\n) => {\n fetch(request: Request): Promise<Response>\n alarm(...info: Array<unknown>): Promise<void>\n} => {\n checkRevalidate(config.revalidate, 'defineDocumentHost')\n // The application's own alarm, if its base has one: run after the reactions'.\n const baseAlarm = (Base.prototype as { readonly alarm?: unknown }).alarm\n return class extends Base {\n private readonly host: (request: Request) => Promise<Result.Result<Accepted, Response>>\n private readonly react: () => Promise<void>\n\n constructor(ctx: DocumentHostContext, env: Env) {\n super(ctx, env)\n interface Opened {\n readonly journal: Journal<Operation, Shared, Principal, WrittenOperation>\n readonly server: Option.Option<ServerJournal<unknown, never>>\n }\n let ready: Promise<Opened> | undefined\n const { layer, settle, server } = config\n const alarms = Option.flatMap(Option.fromUndefinedOr(server), () => alarmsOf(ctx.storage))\n if (server !== undefined && Option.isNone(alarms))\n throw new Error('defineDocumentHost: `server` needs the object’s storage alarm')\n // Made now, so one declared for another contract fails here and not at\n // the first upgrade; `serverJournal` checks the rest when it opens.\n const reactions = server === undefined ? [] : server.reactions(env)\n for (const each of reactions)\n if (each.sync !== config.sync)\n throw new Error(\n `defineDocumentHost: reaction ${each.name} was declared for another contract`,\n )\n /** Reports a pass that broke; a reporter that fails itself is not let out of `alarm()`. */\n const report = (stage: 'Alarm', cause: Cause.Cause<unknown>): Promise<void> =>\n Effect.runPromise(\n reportTo(\n config.diagnostics === undefined\n ? undefined\n : diagnostic =>\n config.diagnostics!(diagnostic, new Request('https://durable-object/alarm')),\n hostDefect(stage, cause),\n ),\n ).catch(() => undefined)\n const arm = (after: Duration.Duration): Promise<void> =>\n armAlarm(Option.getOrThrow(alarms), Date.now() + Duration.toMillis(after))\n // The journal and the reactions' registration in one, once per object:\n // registered before any socket is served, so no commit is missed.\n const open = (): Promise<Opened> =>\n (ready ??= config.openJournal(ctx, env).then(async journal => ({\n journal,\n server:\n server === undefined\n ? Option.none()\n : Option.some(\n await Effect.runPromise(\n // The contract's own type is not kept here: `serverJournal`\n // refuses a reaction declared for another at run time.\n serverJournal({\n sync: config.sync,\n journal,\n server: server.principal,\n reactions,\n runsPerPass: server.runsPerPass,\n } as never) as Effect.Effect<ServerJournal<unknown, never>>,\n ),\n ),\n }))).catch((error: unknown) => {\n ready = undefined\n throw error\n })\n /**\n * One pass, then the alarm from its answer. Never rejects: a pass that\n * broke (the journal would not open, a reaction was never registered)\n * is reported and brings the alarm back later.\n */\n const runPass = async (): Promise<void> => {\n if (server === undefined) return\n const exit = await Effect.runPromiseExit(\n Effect.gen(function* () {\n const { server: running } = yield* Effect.promise(open)\n if (Option.isNone(running)) return\n const next = yield* running.value.react\n if (Option.isSome(next)) yield* Effect.promise(() => arm(next.value))\n }),\n )\n if (Exit.isSuccess(exit)) return\n await report('Alarm', exit.cause)\n await arm(ALARM_AFTER_DEFECT).catch(() => undefined)\n }\n // `serverJournal` runs one pass at a time itself.\n const pass = runPass\n this.react = pass\n // What the host knows was committed, so only an exchange that moved it arms the alarm.\n let seen = -1\n const afterExchange = (journal: Journal<Operation, Shared, Principal, WrittenOperation>) =>\n Effect.gen(function* () {\n const at = yield* journal.cursor(JournalDocumentId.make(config.sync.documentId))\n if (at === seen) return\n // Before the reply, so a run cut off by eviction is resumed. One that\n // fails is reported, and `seen` stays, so the next exchange arms again.\n const armed = yield* Effect.promise(() =>\n arm(ALARM_AFTER_COMMIT).then(\n () => true,\n async (error: unknown) => {\n await report('Alarm', Cause.die(error))\n return false\n },\n ),\n )\n if (armed) seen = at\n // Not awaited: the reply does not wait on a provider.\n void pass()\n })\n this.host = documentHost<Message, Shared, Principal, RP>({\n sync: config.sync,\n // Opened on the first upgrade a principal passes, so probes never\n // provision storage; a failed open is tried again on the next.\n journal: () => open().then(opened => opened.journal),\n resolvePrincipal: request => config.resolvePrincipal(request, env),\n layer: layer === undefined ? undefined : () => layer(env),\n revalidate: config.revalidate,\n settle:\n settle === undefined && server === undefined\n ? undefined\n : journal =>\n Effect.gen(function* () {\n // First: a settle that fails still leaves what committed to be reacted to.\n if (server !== undefined) yield* afterExchange(journal)\n if (settle !== undefined) yield* settle(env, journal)\n }),\n opens: config.opens,\n admit: config.admit,\n diagnostics: config.diagnostics,\n // `DocumentHostLayer` already tied `layer` to `RP` on the config; the\n // conditional cannot be resolved for an `RP` still generic here.\n } as DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>)\n }\n\n /**\n * The object's alarm: runs the reactions and sets the alarm again from\n * what they answer, then the base class's own `alarm()`, if it has one,\n * with what the runtime passed. The reactions' part never throws, so the\n * runtime's few retries of a throwing alarm are never what a run depends\n * on. The object has one alarm, shared: the base runs on every wake, so\n * it decides itself what is due, and sets its next with `armAlarm`, which\n * only brings the alarm earlier. A subclass that overrides `alarm()` calls\n * `super.alarm()`, or the reactions stop being resumed.\n */\n async alarm(...info: Array<unknown>): Promise<void> {\n await this.react()\n if (typeof baseAlarm === 'function')\n await (baseAlarm as (...info: Array<unknown>) => Promise<void>).apply(this, info)\n }\n\n async fetch(request: Request): Promise<Response> {\n if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket')\n return Response.json({ error: 'not found' }, { status: 404 })\n // The replica learns nothing of it; whoever runs the host must.\n const broke = async (error: unknown): Promise<Response> => {\n const { diagnostics } = config\n await Effect.runPromise(\n reportTo(\n diagnostics === undefined ? undefined : diagnostic => diagnostics(diagnostic, request),\n hostDefect('Upgrade', Cause.die(error)),\n ),\n )\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n // Made first: a runtime without WebSocketPair is a 500 that resolves no one.\n let pair: readonly [client: WebSocket, server: AcceptingWebSocket]\n try {\n pair = (config.pair ?? defaultPair)()\n } catch (error) {\n return broke(error)\n }\n const [client, server] = pair\n const answered = await this.host(request)\n if (Result.isFailure(answered)) return answered.failure\n const { serve, abandon } = answered.success\n try {\n server.accept()\n serve({\n ...workerSocket(server),\n closeWith: (code, reason) => closeWith(server, code, reason),\n })\n return new Response(null, {\n status: 101,\n // The worker runtime reads the client out of the upgrade response;\n // the DO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