foldkit-sync 0.17.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.
package/README.md CHANGED
@@ -36,7 +36,7 @@ CRDT; every peer accepting writes without a server is a different design.
36
36
  ## The model in one equation
37
37
 
38
38
  ```text
39
- what the user sees = committed snapshot + pending local edits, replayed
39
+ visible = committed snapshot + pending edits, replayed
40
40
  ```
41
41
 
42
42
  The server has committed `A B C`; this device has typed `D E` since:
@@ -338,19 +338,28 @@ Sync.transport.socket({ url: 'wss://example.com/sync' })
338
338
  [the durable D1 guide](../durable/README.md#on-cloudflare-d1-d1-true)), or
339
339
  the object's SQLite storage through `ctx`.
340
340
  - Each upgrade resolves its own principal, an Effect that refuses the caller
341
- by failing with a `RemoteUnauthenticated` (`RemoteServer.unauthenticated()`
342
- makes one): a 401 carrying its message. Non-upgrades are 404s that open
343
- nothing. A resolver that breaks, a `layer` that fails to build, or a
344
- journal that never opened, is a 500 that says nothing of it to the caller;
345
- the cause is reported as a `HostDefect` (see [Diagnostics](#diagnostics)).
341
+ by failing with a `RemoteUnauthenticated`
342
+ (`RemoteServer.unauthenticated(reason?)` makes one): a 401 that says
343
+ `Unauthenticated`, or the refusal's `reason`, the words written for the
344
+ caller, when it has one. Its `message` is never sent. Non-upgrades are 404s
345
+ that open nothing. A resolver that breaks (it dies, throws, or fails with
346
+ anything but a `RemoteUnauthenticated`), a `layer` that fails to build, or
347
+ a journal that never opened, is a 500 that says `Internal error` and an
348
+ `incident`, and nothing of the cause, which is reported as a `HostDefect`
349
+ under that incident (see [Diagnostics](#diagnostics)). A session store that
350
+ is down is no refusal: let it die (`Effect.orDie`), so the caller is not
351
+ told to sign in again.
346
352
  - A resolver that reads a service (a session store) takes it from
347
353
  `layer: env => Layer`, required exactly when the resolver needs one. It is
348
354
  built per upgrade and kept until the socket closes, so `revalidate` reads
349
355
  an open store; a refused upgrade closes it at once.
350
356
  - `revalidate: { every, key? }` asks the resolver again, of the upgrade
351
- request, while the socket is open: a refusal closes it with 4401, and a
352
- principal whose `key` (`Policy.keyOf`) changed with 1012, which the
353
- replica reconnects after. Without it a socket serves its first principal until it closes.
357
+ request, while the socket is open: a refusal closes it with 4401 and the
358
+ reason `Unauthenticated`, or the refusal's `reason` when it has one (cut to
359
+ the 123 bytes a close reason carries), and a principal whose `key`
360
+ (`Policy.keyOf`) changed with 1012, which the replica reconnects after. A
361
+ resolver that breaks closes it with 1011 `Internal error`. Without it a
362
+ socket serves its first principal until it closes.
354
363
  - `server: { principal, reactions: env => [...], runsPerPass? }` gives the
355
364
  object its [reactions](#work-after-a-commit-reactions): registered when the
356
365
  journal opens, before any socket is served; the alarm set before the reply
@@ -403,6 +412,20 @@ from `update` and refuses a durable Message whose transition:
403
412
  A refused Message fails `submit` with `ReplayError` and writes nothing, so a
404
413
  mistake shows on the first edit instead of as diverging replicas later.
405
414
 
415
+ Replay also reads nothing but the slice. A durable Message whose `update` reads
416
+ a local field (a `filter` that decides which todos to clear) shows one slice on
417
+ this page and replays to another everywhere else, the server included.
418
+ `Sync.mount` catches it as the Message is dispatched: it runs `update` again
419
+ with every local field that is not at its `initial` value reset, and when the
420
+ two slices differ it does not apply the Message and does not submit it. The
421
+ failure reaches `onPersistenceFailure` as a `ReplayError` that names the
422
+ fields: `durable "ClearedShown" reads Model fields outside the shared
423
+ projection: filter`. A Message that reads a local field and still produces an
424
+ equal slice is accepted, and so is one over a slice that holds pending edits.
425
+ The check costs one more `update` per durable dispatch, and none while every
426
+ local field is still at its `initial` value. `replica.submit` has no Model and
427
+ cannot make it; a replica used without `mount` is not checked.
428
+
406
429
  The consequence is a pattern you will use everywhere: **an intent mints, a fact
407
430
  records**.
408
431
 
@@ -471,13 +494,15 @@ handles both with one function:
471
494
  replica belongs to another actor. `reason` is the rule's own words when it
472
495
  gave some (a plain `false` gives none), cut to 500 characters. Remote's
473
496
  `Denied.Forbidden` has the same shape.
474
- - `Invalid { message, entity, rule, path }`: the operation failed, with a fixed
475
- sentence as `message`. "Not a valid operation" when `validate` refused or
476
- threw, `authorize` threw, or the reducer could not apply it; "Not an
477
- operation this server accepts" when it did not decode or named another
478
- document; "Its id was already used for another" for a reused id.
479
- `journalExchange` names no Entity, so `entity`, `rule` and `path` are empty;
480
- the shape is Remote's `Refusal.invalid`.
497
+ - `Invalid { message, entity, rule, path }`: the operation failed. When it
498
+ breaks one of the contract's [laws](#laws-what-every-snapshot-keeps), `rule`
499
+ is the law's id and `message` and `path` are the law's own. Otherwise `rule`
500
+ and `path` are empty and `message` is a fixed sentence: "Not a valid
501
+ operation" when `validate` refused or threw, `authorize` or a law threw, or
502
+ the reducer could not apply it; "Not an operation this server accepts" when
503
+ it did not decode or named another document; "Its id was already used for
504
+ another" for a reused id. `journalExchange` names no Entity, so `entity` is
505
+ empty; the shape is Remote's `Refusal.invalid`.
481
506
  - `Unreadable { version }`: written at an older Message version that no step
482
507
  of the server's history reads. The replica keeps such an operation in
483
508
  `status.refused` as well, with its payload (see
@@ -608,6 +633,72 @@ that is not a durable variant is a type error. The rules ride in
608
633
  An edit the policy refuses still shows at once on the client, then comes back
609
634
  as a rejection, as [above](#what-to-show-the-user).
610
635
 
636
+ ### Laws: what every snapshot keeps
637
+
638
+ `authorize` decides who may make a change. What the document must always be,
639
+ whoever changes it and whichever Message does, is a **law**: a predicate over
640
+ the snapshot an operation leaves.
641
+
642
+ ```ts
643
+ const CappedBoard = AppSync.make({
644
+ documentId: DocumentId.make('capped-board'),
645
+ ...AppSync.compose(Todos, Members),
646
+ laws: {
647
+ atMost100Todos: {
648
+ holds: ({ after }) => after.todos.length <= 100,
649
+ message: 'A board holds 100 todos',
650
+ path: ['todos'],
651
+ },
652
+ },
653
+ })
654
+ ```
655
+
656
+ ```text
657
+ operation -> validate -> authorize -> reduce -> laws(before, after) -> written
658
+ ```
659
+
660
+ - **Where it is judged.** The contract's `journalContract()` carries a
661
+ `judge` built from the laws, which the journal runs inside the commit after
662
+ `reduce`, over the snapshot before and the one the operation leaves. The
663
+ first law that does not answer `true`, in the record's order, refuses the
664
+ operation: `journalExchange` sends it as `Invalid` with the law's id as
665
+ `rule`, its `message`, and its `path`. On D1 a commit that lost a race is
666
+ reduced and judged again over the snapshot it then lands on.
667
+ - **What it sees.** `holds` gets `{ before, after }`, typed over the shared
668
+ fields alone, so a law that reads a local field does not compile. It sees no
669
+ principal and no Message: a rule about who belongs in `authorize`.
670
+ - **In the Module graph.** The contract declares its law ids
671
+ (`contract.laws.model`), and `Graph.of` draws a law per declared law
672
+ (`sync:<name>.<id>`), read as reading the whole shared slice since `holds`
673
+ is a function, and a transition per durable and server-only tag
674
+ (`durable:<tag>`), each writing it. So `Graph.validate(module, { evidence })`
675
+ reports each durable Message as `law-unwitnessed` against each law until a
676
+ walk or a scenario (`Scenario.runMessages`) issues its evidence, or an
677
+ `Evidence.runtimeOnly` line says only the journal's judge refuses it: a
678
+ durable Message added later is reported until something draws it.
679
+ - **Matching the refusal.** `CappedBoard.laws.atMost100Todos` is the declared
680
+ law (`{ id, message, path }`), and
681
+ `Sync.isInvalidBy(refusal, CappedBoard.laws.atMost100Todos)` tells its
682
+ refusal from any other.
683
+ - **On the replica.** `submit` judges the Message's optimistic result before
684
+ writing the outbox, and fails with `LawBrokenError` (`rule`, `message`,
685
+ `path`) when it breaks a law, so nothing is sent; `Sync.mount` reverts the
686
+ edit it showed and hands the error to `onPersistenceFailure`. It is a hint: the
687
+ optimistic snapshot holds pending edits the server may still refuse, and the
688
+ server judges again where it commits.
689
+ - **Strict.** A law judges `after`, whatever `before` held. A document that
690
+ already breaks one, because the law was added after the fact, refuses every
691
+ operation that leaves it broken until one repairs it. To let such documents
692
+ shrink toward a new cap, write the law over `before` too
693
+ (`after.todos.length <= Math.max(100, before.todos.length)`), and run
694
+ `CappedBoard.judge(snapshot, snapshot)` over the stored snapshots before the
695
+ deploy to find the ones it would refuse.
696
+ - **The server's own appends** go through the same commit, so
697
+ `appendAsServer` and a reaction's appends are judged too.
698
+
699
+ `make` throws for a law whose id or message is over 500 characters, or whose
700
+ `path` names more than 16 fields: its refusal could not be sent.
701
+
611
702
  ### Stamp what only the commit decides
612
703
 
613
704
  A fact carries its own nondeterminism, but a client cannot know where its
@@ -760,8 +851,8 @@ const serving = Effect.gen(function* () {
760
851
  redelivered webhook is harmless; the same key with another Message fails
761
852
  with `ServerKeyReusedError`, and the first fact stands. A key is a
762
853
  non-empty string of at most 200 characters.
763
- - **It goes through the journal's `append`**, so `validate` and `authorize`
764
- judge it like any operation.
854
+ - **It goes through the journal's `append`**, so `validate`, `authorize` and
855
+ the laws judge it like any operation.
765
856
  - **Keep the server's `actorId`.** The journal binds each replica id to the
766
857
  first actor that commits from it, so after a change of `actorId` a
767
858
  redelivered key is an `IdentityConflictError`: that fact was the first
@@ -769,7 +860,7 @@ const serving = Effect.gen(function* () {
769
860
  new actor.
770
861
  - **A refused append frees its key.** The key is recorded before the append,
771
862
  so a redelivery after a deploy appends the bytes first written; when the
772
- journal refuses the append (`validate`, `authorize`), nothing committed and
863
+ journal refuses the append (`validate`, `authorize`, a law), nothing committed and
773
864
  the record is cleared, so the key can name a Message the rules take. A
774
865
  redelivery after a refusal is judged afresh: refused again with the same
775
866
  error, or committed if the rules now take it, never `ServerKeyReusedError`.
@@ -843,12 +934,15 @@ commit -> react: read after the stored cursor -> run (answer recorded)
843
934
  defect and a timeout (`timeout`, 10 s by default) are failures like any
844
935
  other.
845
936
  - **A run that can never succeed is parked**: the journal refused its append
846
- (`validate`, `authorize`), or its answer holds a Message `appends` does not
937
+ (`validate`, `authorize`, a law), or its answer holds a Message `appends` does not
847
938
  name, more than 16, or one that will not encode. So is one that has failed
848
939
  `attempts` times (8) *and* for at least `parkAfter` (an hour), so an outage
849
940
  parks nothing. The journal itself failing counts toward neither. A parked
850
941
  run is reported as `ReactionParked` and set aside with its trigger; the
851
- reaction goes on. `parked` lists them, `retry` runs one again out of order
942
+ reaction goes on. Why it failed, on `parked`'s `error` and the report's
943
+ `cause`, is the failure's own text (a provider's, a driver's), kept beside
944
+ the journal for whoever runs the server: no exchange sends it, and a page
945
+ for the document's readers should not show it. `parked` lists them, `retry` runs one again out of order
852
946
  (a recorded answer is reused, so no second call), and `dismiss` gives one
853
947
  up. After a `reset` a parked run is `stale`: it can be dismissed, not
854
948
  retried.
@@ -1003,8 +1097,9 @@ When something will not read:
1003
1097
  or load that rebuilds the document from that snapshot. A replica past the
1004
1098
  row is served, and other documents are not affected. Only a build with a
1005
1099
  step that reads it recovers it. The replica is told only "This server
1006
- cannot read the history of this document"; the operation's id and
1007
- version stay on the error, for the server's logs.
1100
+ cannot read the history of this document" and an incident; the
1101
+ operation's id and version stay on the error, which a served socket
1102
+ reports as an `ExchangeDefect` under that incident.
1008
1103
  - **A newer version** (a rollback, or an old client): the replica refuses to
1009
1104
  open on one in its outbox (`UnsupportedMessageVersionError`, nothing
1010
1105
  removed), and an exchange that receives one fails with it, recorded in
@@ -1239,8 +1334,9 @@ Effect's log: the console in a browser, `wrangler tail` on a Worker.
1239
1334
  | `_tag` | `level` | When |
1240
1335
  | --- | --- | --- |
1241
1336
  | `ExchangeFailed` | `warning` | An exchange failed; it is in `status.lastError` and retried on a backoff. Carries the `error`. |
1337
+ | `ExchangeDefect` | `error` | On the server: an exchange `Sync.transport.serve` answered threw something not written for the replica (a journal's failure, a driver's words). The replica was answered `Exchange failed` and the `incident` this carries, with `thrown`. |
1242
1338
  | `HistoryRebuilt` | `warning` | The server answered from another epoch, so the committed state was rebuilt from it (the outbox is kept). |
1243
- | `HostDefect` | `error` | A document host broke on its side, at a `stage`: `Upgrade` (the socket pair), `Resolve` (the `layer` or resolver), `Journal`, `Exchange` (`opens` or `settle` threw) answer a 500; `Revalidate` closes the socket with 1011; `Notice` (`opens` failed before a commit notice) sends none; `Changes` (the journal's stream of commits broke) sends no more. Carries the `cause`, which the replica is never told. |
1339
+ | `HostDefect` | `error` | A document host broke on its side, at a `stage`: `Upgrade` (the socket pair), `Resolve` (the `layer` or resolver), `Journal`, `Exchange` (`opens` or `settle` threw) answer a 500 with an `incident`, which the report carries too; `Revalidate` closes the socket with 1011; `Notice` (`opens` failed before a commit notice) sends none; `Changes` (the journal's stream of commits broke) sends no more. Carries the `cause`, which the replica is never told. |
1244
1340
  | `ListenerFailed` | `error` | A listener the application gave threw: a presence subscriber, a listener on the socket transport's shared `socket`, or `journalChanges`' listener (`Notice`, called again on the next commit). The others still ran. |
1245
1341
 
1246
1342
  A replica reports to the reporter in the Effect context it runs in:
@@ -1364,6 +1460,35 @@ refuse them. The replica validates every field; see
1364
1460
 
1365
1461
  A refusal is data in the answer; only a wire failure is a `TransportError`.
1366
1462
 
1463
+ **When a served exchange throws.** What the handler given to
1464
+ `Sync.transport.serve` throws is the server's own, and its replica reads none
1465
+ of it: the error frame is `{ id, error: 'Exchange failed', incident }`, and
1466
+ what was thrown is reported as an `ExchangeDefect` under that incident, to
1467
+ `serve`'s `diagnostics` reporter when given, else the default. The replica
1468
+ fails the exchange with a `TransportError` carrying the `incident`, shows
1469
+ `Exchange failed` in `status.lastError`, keeps its outbox whole and asks again
1470
+ on its backoff, as for any wire failure. This is the failure of an exchange as
1471
+ a whole; an operation the journal refuses is still a per-operation `rejected`,
1472
+ which the replica drops. Words meant for the replica are thrown as a
1473
+ `new ExchangeRefused({ message })`, sent as written with no incident: the
1474
+ journal's own are `This connection may not open the document`, a cursor ahead
1475
+ of the server's, and a pending entry that names no operation; a replica newer
1476
+ than the server (`UnsupportedMessageVersionError`) is told so the same way. A
1477
+ stored operation no build reads (`UnreadableHistoryError`) is both: reported
1478
+ under an incident, and answered with the journal's one sentence for it. A
1479
+ replica older than this change reads the frame as before: `error` is still a
1480
+ string, and `incident` a field it ignores.
1481
+
1482
+ **When the host cannot say who is asking.** A caller the resolver refuses
1483
+ reads the refusal's `reason`, or `Unauthenticated`: a 401 at the upgrade, a
1484
+ 4401 close on an open socket. A resolver that breaks answers a 500
1485
+ `Internal error` with an incident, or closes with 1011; the cause is a
1486
+ `HostDefect`. The socket transport reads neither a refused upgrade's body
1487
+ nor a close's code: to the replica each is a connection that closed, so it
1488
+ reconnects on its backoff, shows `transport closed` in `status.lastError`
1489
+ once the retries are spent, and keeps its outbox until a socket opens.
1490
+ Nothing here signs anyone out.
1491
+
1367
1492
  ### Presence
1368
1493
 
1369
1494
  "Who is viewing this" and "where is their caret" should vanish when the peer
@@ -59,6 +59,21 @@ export interface HostDefect extends Diagnostic {
59
59
  readonly _tag: 'HostDefect';
60
60
  readonly stage: HostStage;
61
61
  readonly cause: Cause.Cause<unknown>;
62
+ /** The id an upgrade answered 500 carries, to find this report by; none where nothing was answered. */
63
+ readonly incident: Option.Option<string>;
64
+ }
65
+ /**
66
+ * A served exchange threw: the journal, its database, or a handler of the
67
+ * application's. The replica was answered "Exchange failed" and `incident`,
68
+ * and is told nothing of `thrown`; it keeps its pending operations and asks
69
+ * again.
70
+ */
71
+ export interface ExchangeDefect extends Diagnostic {
72
+ readonly _tag: 'ExchangeDefect';
73
+ /** The id the replica was answered with, to find this report by. */
74
+ readonly incident: string;
75
+ /** What the exchange threw. */
76
+ readonly thrown: unknown;
62
77
  }
63
78
  /** Where a listener the application gave was called. */
64
79
  export type ListenerSite =
@@ -124,7 +139,7 @@ export interface ReactionSkipped extends Diagnostic {
124
139
  readonly to: number;
125
140
  }
126
141
  /** Every diagnostic Sync reports. */
127
- export type SyncDiagnostic = ExchangeFailed | HistoryRebuilt | HostDefect | ListenerFailed | ReactionFailed | ReactionParked | ReactionSkipped | ServerOnlySubmitted | UnknownRefusal;
142
+ export type SyncDiagnostic = ExchangeDefect | ExchangeFailed | HistoryRebuilt | HostDefect | ListenerFailed | ReactionFailed | ReactionParked | ReactionSkipped | ServerOnlySubmitted | UnknownRefusal;
128
143
  export declare const exchangeFailed: (documentId: string, replicaId: string, error: ReplicaError | TransportError) => ExchangeFailed;
129
144
  export declare const historyRebuilt: (documentId: string, replicaId: string) => HistoryRebuilt;
130
145
  export declare const unknownRefusal: (documentId: string, replicaId: string, opId: string, issue: string) => UnknownRefusal;
@@ -135,8 +150,20 @@ export declare const reactionFailed: (documentId: string, reaction: string, at:
135
150
  }>, cause: string) => ReactionFailed;
136
151
  export declare const reactionParked: (documentId: string, reaction: string, opId: string, sequence: number, cause: string) => ReactionParked;
137
152
  export declare const reactionSkipped: (documentId: string, reaction: string, from: number, to: number) => ReactionSkipped;
138
- export declare const hostDefect: (stage: HostStage, cause: Cause.Cause<unknown>) => HostDefect;
153
+ export declare const hostDefect: (stage: HostStage, cause: Cause.Cause<unknown>, incident?: Option.Option<string>) => HostDefect;
154
+ /**
155
+ * 64 random bits as hex, short enough to quote: the id a caller is answered
156
+ * with in place of what broke, and the report of it is found by. Sync mints
157
+ * its own, as `foldkit-remote-server` does, since neither depends on the other.
158
+ */
159
+ export declare const mintIncident: () => string;
160
+ export declare const exchangeDefect: (incident: string, thrown: unknown) => ExchangeDefect;
139
161
  export declare const listenerFailed: (site: ListenerSite, thrown: unknown) => ListenerFailed;
140
162
  /** Reports `diagnostic` to `reporter` when a host gave one, else to the reporter in context. */
141
163
  export declare const reportTo: (reporter: ReportDiagnostic | undefined, diagnostic: SyncDiagnostic) => Effect.Effect<void>;
164
+ /**
165
+ * The answer to an upgrade this side broke on, before any socket opened: a
166
+ * 500 that says "Internal error" and the incident `cause` is reported under.
167
+ */
168
+ export declare const answerHostDefect: (reporter: ReportDiagnostic | undefined, stage: HostStage, cause: Cause.Cause<unknown>) => Effect.Effect<Response>;
142
169
  //# sourceMappingURL=diagnostics.d.ts.map
@@ -1 +1 @@
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
+ {"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;;WAEb,UAAU,OAAO;;;;;;;;iBASX,uBAAuB;WAC7B;;WAEA;;WAEA;;;YAIC;;;;;;;;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,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,OACd,WAAS,OACT,MAAM,gBAAc,WACjB,OAAO,mBAChB;;;;;;qBAkBU;qBAKA,iBAAc,kBAAoB,oBAAoB;qBAetD,iBAAc,MAAU,cAAY,oBAAoB;;qBAUxD,WAAQ,UACT,8BAA4B,YAC1B,mBACX,OAAO;;;;;qBAWG,mBAAgB,UACjB,8BAA4B,OAC/B,WAAS,OACT,MAAM,mBACZ,OAAO,OAAO"}
@@ -92,13 +92,31 @@ const stageText = {
92
92
  Changes: "the journal's stream of commits broke, and this connection hears of no more commits",
93
93
  Alarm: "running the reactions broke, and the alarm was set to run them again later"
94
94
  };
95
- const hostDefect = (stage, cause) => ({
95
+ const hostDefect = (stage, cause, incident = Option.none()) => ({
96
96
  _tag: "HostDefect",
97
97
  source,
98
98
  level: "error",
99
- message: `a document host broke: ${stageText[stage]}\n${Cause.pretty(cause)}`,
99
+ message: `${Option.match(incident, {
100
+ onNone: () => "",
101
+ onSome: (id) => `incident ${id}: `
102
+ })}a document host broke: ${stageText[stage]}\n${Cause.pretty(cause)}`,
100
103
  stage,
101
- cause
104
+ cause,
105
+ incident
106
+ });
107
+ /**
108
+ * 64 random bits as hex, short enough to quote: the id a caller is answered
109
+ * with in place of what broke, and the report of it is found by. Sync mints
110
+ * its own, as `foldkit-remote-server` does, since neither depends on the other.
111
+ */
112
+ const mintIncident = () => Array.from(globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(8)), (byte) => byte.toString(16).padStart(2, "0")).join("");
113
+ const exchangeDefect = (incident, thrown) => ({
114
+ _tag: "ExchangeDefect",
115
+ source,
116
+ level: "error",
117
+ message: `incident ${incident}: a served exchange threw. Its replica is told no more of it than this id.\n${Cause.pretty(Cause.die(thrown))}`,
118
+ incident,
119
+ thrown
102
120
  });
103
121
  const siteText = {
104
122
  Presence: "a presence listener",
@@ -118,6 +136,17 @@ const reportTo = (reporter, diagnostic) => {
118
136
  const reported = Diagnostics.report(diagnostic);
119
137
  return reporter === void 0 ? reported : Effect.provideService(reported, Diagnostics.Reporter, reporter);
120
138
  };
121
- export { exchangeFailed, historyRebuilt, hostDefect, listenerFailed, reactionFailed, reactionParked, reactionSkipped, reportTo, serverOnlySubmitted, unknownRefusal };
139
+ /**
140
+ * The answer to an upgrade this side broke on, before any socket opened: a
141
+ * 500 that says "Internal error" and the incident `cause` is reported under.
142
+ */
143
+ const answerHostDefect = (reporter, stage, cause) => {
144
+ const incident = mintIncident();
145
+ return Effect.as(reportTo(reporter, hostDefect(stage, cause, Option.some(incident))), Response.json({
146
+ error: "Internal error",
147
+ incident
148
+ }, { status: 500 }));
149
+ };
150
+ export { answerHostDefect, exchangeDefect, exchangeFailed, historyRebuilt, hostDefect, listenerFailed, mintIncident, reactionFailed, reactionParked, reactionSkipped, reportTo, serverOnlySubmitted, unknownRefusal };
122
151
 
123
152
  //# 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`), 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"}
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 /** The id an upgrade answered 500 carries, to find this report by; none where nothing was answered. */\n readonly incident: Option.Option<string>\n}\n\n/**\n * A served exchange threw: the journal, its database, or a handler of the\n * application's. The replica was answered \"Exchange failed\" and `incident`,\n * and is told nothing of `thrown`; it keeps its pending operations and asks\n * again.\n */\nexport interface ExchangeDefect extends Diagnostic {\n readonly _tag: 'ExchangeDefect'\n /** The id the replica was answered with, to find this report by. */\n readonly incident: string\n /** What the exchange threw. */\n readonly thrown: 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 | ExchangeDefect\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 = (\n stage: HostStage,\n cause: Cause.Cause<unknown>,\n incident: Option.Option<string> = Option.none(),\n): HostDefect => ({\n _tag: 'HostDefect',\n source,\n level: 'error',\n message: `${Option.match(incident, {\n onNone: () => '',\n onSome: id => `incident ${id}: `,\n })}a document host broke: ${stageText[stage]}\\n${Cause.pretty(cause)}`,\n stage,\n cause,\n incident,\n})\n\n/**\n * 64 random bits as hex, short enough to quote: the id a caller is answered\n * with in place of what broke, and the report of it is found by. Sync mints\n * its own, as `foldkit-remote-server` does, since neither depends on the other.\n */\nexport const mintIncident = (): string =>\n Array.from(globalThis.crypto.getRandomValues(new Uint8Array(8)), byte =>\n byte.toString(16).padStart(2, '0'),\n ).join('')\n\nexport const exchangeDefect = (incident: string, thrown: unknown): ExchangeDefect => ({\n _tag: 'ExchangeDefect',\n source,\n level: 'error',\n message: `incident ${incident}: a served exchange threw. Its replica is told no more of it than this id.\\n${Cause.pretty(Cause.die(thrown))}`,\n incident,\n thrown,\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\n/**\n * The answer to an upgrade this side broke on, before any socket opened: a\n * 500 that says \"Internal error\" and the incident `cause` is reported under.\n */\nexport const answerHostDefect = (\n reporter: ReportDiagnostic | undefined,\n stage: HostStage,\n cause: Cause.Cause<unknown>,\n): Effect.Effect<Response> => {\n const incident = mintIncident()\n return Effect.as(\n reportTo(reporter, hostDefect(stage, cause, Option.some(incident))),\n Response.json({ error: 'Internal error', incident }, { status: 500 }),\n )\n}\n"],"mappings":";;;;;;;;;;;;AAcA,MAAM,SAAS;AAmKf,MAAa,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"}
package/dist/do.d.ts CHANGED
@@ -50,10 +50,11 @@ export interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never>
50
50
  readonly openJournal: (ctx: DocumentHostContext, env: Env) => Promise<Journal<Operation, Shared, Principal, WrittenOperation>>;
51
51
  /**
52
52
  * Who is opening this socket, from the upgrade request. Fails with a
53
- * `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated()`
54
- * makes one) to refuse it: a 401 carrying its message. A defect is a 500
55
- * that says nothing of it. What it needs (a session store) comes from
56
- * `layer`.
53
+ * `RemoteUnauthenticated` (`foldkit-remote`; `RemoteServer.unauthenticated(reason?)`
54
+ * makes one) to refuse it: a 401 that says "Unauthenticated", or its
55
+ * `reason` when it has one, and never its `message`. A defect, or any
56
+ * other failure, is a 500 that says nothing of it. What it needs (a session
57
+ * store) comes from `layer`.
57
58
  */
58
59
  readonly resolvePrincipal: (request: Request, env: Env) => Effect.Effect<Principal, RemoteUnauthenticated, RP>;
59
60
  /**
@@ -65,10 +66,12 @@ export interface DocumentHostConfig<Message, Shared, Principal, Env, RP = never>
65
66
  readonly settle?: ((env: Env, journal: Journal<Operation, Shared, Principal, WrittenOperation>) => Effect.Effect<void, unknown>) | undefined;
66
67
  /**
67
68
  * Asks `resolvePrincipal` again, of the upgrade request, every `every`
68
- * while the socket is open: a refusal closes it with 4401, and a principal
69
- * whose `key` differs from the one it opened with (`Policy.keyOf`) closes
70
- * it with 1012, which the replica reconnects after, as the new principal;
71
- * without `key` only a refusal closes it. Without it a socket
69
+ * while the socket is open: a refusal closes it with 4401 and the reason
70
+ * "Unauthenticated", or the refusal's `reason` when it has one, and a
71
+ * principal whose `key` differs from the one it opened with
72
+ * (`Policy.keyOf`) closes it with 1012, which the replica reconnects
73
+ * after, as the new principal; without `key` only a refusal closes it. A
74
+ * resolver that breaks closes it with 1011. Without `revalidate` a socket
72
75
  * serves the principal it opened with until it closes, a revoked session
73
76
  * included.
74
77
  */
package/dist/do.d.ts.map CHANGED
@@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
3
3
  import { documentHost } from "./journal.js";
4
4
  import { checkRevalidate } from "./revalidate.js";
5
- import { hostDefect, reportTo } from "./diagnostics.js";
5
+ import { answerHostDefect, hostDefect, reportTo } from "./diagnostics.js";
6
6
  import { workerSocket } from "./transport.js";
7
7
  import { serverJournal } from "./serverJournal.js";
8
8
  // src/do.ts
@@ -163,10 +163,9 @@ const defineDocumentHost = (Base, config) => {
163
163
  }
164
164
  async fetch(request) {
165
165
  if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return Response.json({ error: "not found" }, { status: 404 });
166
- const broke = async (error) => {
166
+ const broke = (error) => {
167
167
  const { diagnostics } = config;
168
- await Effect.runPromise(reportTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request), hostDefect("Upgrade", Cause.die(error))));
169
- return Response.json({ error: "Internal error" }, { status: 500 });
168
+ return Effect.runPromise(answerHostDefect(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request), "Upgrade", Cause.die(error)));
170
169
  };
171
170
  let pair;
172
171
  try {