nowity 1.2.1 → 1.4.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 (52) hide show
  1. package/README.md +307 -1
  2. package/dist/client/connection.d.ts +2 -0
  3. package/dist/client/connection.d.ts.map +1 -1
  4. package/dist/client/connection.js +13 -0
  5. package/dist/client/nowity-client.d.ts +23 -0
  6. package/dist/client/nowity-client.d.ts.map +1 -1
  7. package/dist/client/nowity-client.js +29 -1
  8. package/dist/core/protocol.d.ts +20 -1
  9. package/dist/core/protocol.d.ts.map +1 -1
  10. package/dist/index.d.ts +5 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +12 -1
  13. package/dist/server/api/collector.d.ts.map +1 -1
  14. package/dist/server/api/collector.js +4 -1
  15. package/dist/server/api/configure.d.ts +24 -0
  16. package/dist/server/api/configure.d.ts.map +1 -1
  17. package/dist/server/api/configure.js +51 -1
  18. package/dist/server/api/execution.d.ts +9 -0
  19. package/dist/server/api/execution.d.ts.map +1 -1
  20. package/dist/server/api/execution.js +19 -0
  21. package/dist/server/api/presence.d.ts +66 -0
  22. package/dist/server/api/presence.d.ts.map +1 -0
  23. package/dist/server/api/presence.js +181 -0
  24. package/dist/server/api/read-keys.d.ts +6 -0
  25. package/dist/server/api/read-keys.d.ts.map +1 -1
  26. package/dist/server/api/read-keys.js +12 -0
  27. package/dist/server/api/runtime.d.ts.map +1 -1
  28. package/dist/server/api/runtime.js +12 -0
  29. package/dist/server/api/scheduler.d.ts +122 -0
  30. package/dist/server/api/scheduler.d.ts.map +1 -0
  31. package/dist/server/api/scheduler.js +217 -0
  32. package/dist/server/change-source/wal-change-source.d.ts.map +1 -1
  33. package/dist/server/change-source/wal-change-source.js +10 -1
  34. package/dist/server/leader.d.ts +138 -0
  35. package/dist/server/leader.d.ts.map +1 -0
  36. package/dist/server/leader.js +342 -0
  37. package/dist/server/presence.d.ts +217 -0
  38. package/dist/server/presence.d.ts.map +1 -0
  39. package/dist/server/presence.js +428 -0
  40. package/dist/server/scheduler.d.ts +195 -0
  41. package/dist/server/scheduler.d.ts.map +1 -0
  42. package/dist/server/scheduler.js +432 -0
  43. package/dist/server/setup-sql.d.ts +1 -1
  44. package/dist/server/setup-sql.d.ts.map +1 -1
  45. package/dist/server/setup-sql.js +547 -0
  46. package/dist/server/sync-engine.d.ts +22 -1
  47. package/dist/server/sync-engine.d.ts.map +1 -1
  48. package/dist/server/sync-engine.js +30 -1
  49. package/dist/server/ws-server.d.ts +22 -0
  50. package/dist/server/ws-server.d.ts.map +1 -1
  51. package/dist/server/ws-server.js +81 -1
  52. package/package.json +1 -1
package/README.md CHANGED
@@ -562,6 +562,300 @@ Three things follow from it being the database that coordinates:
562
562
 
563
563
  Scenario 22 runs two instances against one database and checks each of these.
564
564
 
565
+ ### Presence
566
+
567
+ Who is connected is something the sync server already knows — sockets open and
568
+ close on it — so it can record it once, in the database, instead of every page
569
+ writing a heartbeat. Off unless configured:
570
+
571
+ ```ts
572
+ export const nowity = createNowityServer({
573
+ prisma,
574
+ db: Db,
575
+ auth: CookieAuth,
576
+ services: [LobbyApiImpl],
577
+ presence: {
578
+ graceMs: 8_000, // a reload is not a transition
579
+ nodeLeaseMs: 30_000, // how long a killed process's sockets outlive it
580
+ reaperIntervalMs: 1_000, // how often the leader reaps and delivers
581
+ meta: (session) => ({ device: session.meta.device }), // stored per connection
582
+ },
583
+ syncServer: {
584
+ heartbeat: { intervalMs: 15_000, maxMissed: 2 }, // on by default with presence; `false` turns it off
585
+ },
586
+ });
587
+ ```
588
+
589
+ An endpoint reads it through the injectable `Presence`, beside `Session` and
590
+ `Db`:
591
+
592
+ ```ts
593
+ @api(LobbyApi)
594
+ @component
595
+ export class LobbyApiImpl {
596
+ constructor(private readonly db: Db, private readonly presence: Presence) {}
597
+
598
+ @query()
599
+ async members(lobbyId: string) {
600
+ const members = await this.db.lobbyMember.findMany({ where: { lobbyId } });
601
+ const online = await this.presence.online(members.map((m) => m.userId));
602
+ return members.map((m) => ({ ...m, online: online.has(m.userId) }));
603
+ }
604
+ }
605
+ ```
606
+
607
+ | | |
608
+ | --- | --- |
609
+ | `isOnline(userId)` | `Promise<boolean>` |
610
+ | `online(userIds)` | `Promise<Set<string>>` — which of them are online |
611
+ | `onlineAll()` | `Promise<string[]>` — watches the whole table; for admin pages |
612
+ | `contexts(userIds)` | `Promise<Map<string, object[]>>` — what their tabs said they look at |
613
+ | `details(userIds?, {limit})` | `Promise<PresenceDetail[]>` — online users with `since`, `contexts` and their newest connection's `meta`, longest online first; for operator pages |
614
+ | `onOffline(handler)` | called after a user goes offline, at least once; returns the unsubscribe |
615
+
616
+ Inside a `@query` a read goes through the query's own snapshot and is recorded
617
+ in its read set **by user**: `members` above is recomputed when one of those
618
+ members comes or goes, and not when anyone else does. Outside a query — a script,
619
+ a server component — it reads the database directly. It works the same in the
620
+ Next process (`createNextNowity`), which has no socket and no presence of its
621
+ own: the sync processes keep the table current, everyone can read it.
622
+
623
+ **What counts as a change.** A user is online from their first authenticated
624
+ connection until a grace period after their last one closed. A second tab, a
625
+ reload within the grace period, a reconnect to another node — none of them is a
626
+ change, writes nothing to the outbox, and recomputes nothing. Only the
627
+ online ↔ offline transition, and a change in the set of contexts, are seen by
628
+ readers. Anonymous connections are not recorded.
629
+
630
+ **Contexts.** `connection.setContext({ path })` (or `NowityClient.setContext`)
631
+ tells the server what this socket is looking at — per socket, a small plain
632
+ object (4 KB at most), `null` clears it. It is sent only when it changed, and a
633
+ client that reconnects carries it in its hello. A *page reload* is a new client,
634
+ though, and gets the same treatment only if the context is known before it
635
+ connects: pass it as the `context` option of the connection (or call
636
+ `setContext` before `connect()`), and the new socket is recorded with it, so the
637
+ reload is no change. Set after the socket opened, a reload shows up to readers as
638
+ the context going and coming back. Closing one of several tabs changes the set,
639
+ and is a change. `Presence.contexts` returns each user's distinct contexts.
640
+
641
+ **Several processes.** Each process records its sockets in
642
+ `nowity.nowity_connection` and renews a lease on itself in `nowity.nowity_node`.
643
+ One process — elected with a PostgreSQL advisory lock on a dedicated connection
644
+ with server-side keepalives and a heartbeat, see `LeaderElection` — runs the
645
+ reaper: connections of processes whose lease ran out are dropped, and users with
646
+ nothing open for the grace period become offline. The transition is a
647
+ conditional update of the user's `nowity.nowity_presence` row, so it happens
648
+ once even if two processes briefly both believe they lead; leadership only
649
+ saves the work. A process that stops cleanly drops its connections at once, and
650
+ its users get the grace period to land on another one — a rolling deploy is not
651
+ a transition.
652
+
653
+ **Zombie sockets.** With presence on, the server pings every socket and
654
+ terminates one that missed two pongs, so a peer that vanished without closing — a
655
+ laptop lid, a mobile network — goes offline within the interval rather than
656
+ whenever the kernel gives up. Browsers answer pings by themselves. Without
657
+ presence the heartbeat stays off unless `syncServer.heartbeat` asks for it.
658
+
659
+ **Self-repair.** Every lease renewal compares the process's sockets with its
660
+ rows in `nowity_connection`: a socket without a row is recorded again (a lease
661
+ that looked expired, a failed write), a row without a socket is disconnected (a
662
+ failed disconnect). The reaper deletes a dead node's lease *before* its
663
+ connections, so a node that renews in that moment learns it lost them. A
664
+ process's row in `nowity_node` always carries a per-boot suffix (`nodeId` is
665
+ only its prefix), so a restarted process never inherits what its previous life
666
+ left behind.
667
+
668
+ **Offline handlers: at least once, and idempotent.**
669
+
670
+ ```ts
671
+ // On every sync process, before nowity.start().
672
+ getBaseApplicationContext().getBean(Presence).onOffline(async ({ userId, offlineAt }) => {
673
+ // Remove them from the matchmaking queue — unless they rejoined after offlineAt.
674
+ await prisma.queueEntry.deleteMany({ where: { userId, joinedAt: { lt: offlineAt } } });
675
+ });
676
+ ```
677
+
678
+ - The transition and the debt to the handlers are written in one statement; the
679
+ debt is paid (`handled_at = offline_at`) only after every handler returned.
680
+ - A handler that throws, or runs past `handlerTimeoutMs` (a minute), is called
681
+ again with backoff (`retry: { minDelayMs: 1000, maxDelayMs: 60000 }`). One that
682
+ dies with its process is picked up by the next leader once the claim expires.
683
+ So a handler **must be idempotent**, and gets `attempt` to tell a retry.
684
+ - Deliveries run on their own clock beside the reaper, at most `batchSize` (100)
685
+ at once, so a slow handler holds its own slot and never anyone else's
686
+ transition. A retry is not started while the previous attempt's handler is
687
+ still running in the process.
688
+ - `stop()` waits up to `stopTimeoutMs` (5 s) for running handlers; one that has
689
+ not finished by then is left running with its outcome unrecorded, so the next
690
+ leader delivers it again.
691
+ - Handlers run on the leader only; register them on every sync process, before
692
+ `start()`. While none is registered nothing is claimed, and a handler
693
+ registered later receives what was owed.
694
+ - A delivery still owed when the user comes back online is **dropped** — the
695
+ handler would act on someone who is, by then, there. One already running when
696
+ they come back is not stopped, which is why the event carries `offlineAt`
697
+ (and `onlineSince`): guard what the handler undoes with it.
698
+
699
+ **Tables.** `nowity_presence` (one row per user: `online`, `online_since`,
700
+ `offline_at`, `contexts`, and the bookkeeping `last_disconnect_at`, `handled_at`,
701
+ `attempts`, `next_attempt_at`, `last_error`), `nowity_connection`
702
+ (`connection_id`, `user_id`, `node_id`, `connected_at`, `meta`, `context`) and
703
+ `nowity_node` (`node_id`, `lease_until`). All three are created by
704
+ `setupNowity` whether presence is on or not, and stay empty while it is off.
705
+ Only `nowity_presence` reaches the outbox, and only when `online` or `contexts`
706
+ moved. With the WAL change source, which cannot filter by column, the bookkeeping
707
+ updates of that row wake its readers too — an empty recomputation, never a
708
+ wrong one.
709
+
710
+ `LeaderElection` and `PeriodicTask` are exported on their own, for jobs of the
711
+ application that have to run on one process at a time.
712
+
713
+ Scenarios 24 and 25 cover each of these: reloads, tabs on two nodes, a node
714
+ killed without cleanup, a failing handler, a restart of every node, three nodes
715
+ racing, a socket that stops answering pings, contexts, and queries that read
716
+ presence — including which of them a transition must *not* wake.
717
+
718
+ ### Scheduler
719
+
720
+ Jobs to run at a given time — a turn deadline, a reminder, a sweep every
721
+ minute — kept in the database and run once, by whichever sync process leads.
722
+ Off unless configured:
723
+
724
+ ```ts
725
+ export const nowity = createNowityServer({
726
+ prisma,
727
+ db: Db,
728
+ auth: CookieAuth,
729
+ services: [GameApiImpl],
730
+ scheduler: {
731
+ pollIntervalMs: 5_000, // the net under the timer and the notification
732
+ concurrency: 10, // jobs running at once on the leader
733
+ maxAttempts: 5, // before a job is `failed`
734
+ retry: { minDelayMs: 1_000, maxDelayMs: 60_000 },
735
+ handlerTimeoutMs: 60_000, // one attempt; the claim is leased a little longer
736
+ },
737
+ });
738
+ ```
739
+
740
+ Handlers are registered by name on the injectable `Scheduler`, on every sync
741
+ process (only the leader runs them, and any process may become it), before
742
+ `start()`:
743
+
744
+ ```ts
745
+ const scheduler = getBaseApplicationContext().getBean(Scheduler);
746
+
747
+ scheduler.handle<{ gameId: string }>("turn-deadline", async ({ payload, runAt }) => {
748
+ // Idempotent, and checking the job still means something: a move may have
749
+ // landed while this was on its way.
750
+ await markTimedOut(payload.gameId, runAt);
751
+ }, { maxAttempts: 3, onFailed: (job, err) => log.error("deadline gave up", { key: job.key, err }) });
752
+
753
+ scheduler.every("sweep", 60_000, async () => {
754
+ await sweepAbandonedLobbies();
755
+ });
756
+ ```
757
+
758
+ Scheduling works from any process — the Next half included — and needs no
759
+ scheduler of its own there:
760
+
761
+ ```ts
762
+ @api(GameApi)
763
+ @component
764
+ export class GameApiImpl {
765
+ constructor(private readonly db: Db, private readonly scheduler: Scheduler) {}
766
+
767
+ @mutation()
768
+ async move(gameId: string, move: Move) {
769
+ const game = await this.db.game.update({ where: { id: gameId }, data: { ... } });
770
+ // In the mutation's own transaction: the deadline moves with the move,
771
+ // or not at all.
772
+ await this.scheduler.schedule({
773
+ key: `deadline:${gameId}`,
774
+ handler: "turn-deadline",
775
+ runAt: game.turnDeadline,
776
+ payload: { gameId },
777
+ });
778
+ }
779
+ }
780
+ ```
781
+
782
+ | | |
783
+ | --- | --- |
784
+ | `schedule({ key, handler, runAt, payload?, maxAttempts? }, { tx? })` | upsert by key: scheduling a key again replaces the job and starts its attempts over |
785
+ | `reschedule(key, runAt, { tx? })` | `Promise<boolean>`; brings a `failed` job back |
786
+ | `cancel(key, { tx? })` | `Promise<boolean>`; an attempt already running is not stopped |
787
+ | `handle(name, handler, { maxAttempts?, timeoutMs?, retry?, onFailed? })` | register a handler; returns the unregister |
788
+ | `every(name, intervalMs, handler, options?)` | a periodic job, stored as `every:<name>` |
789
+ | `list({ handler?, state?, limit? })` | `Promise<JobInfo[]>`, soonest first |
790
+ | `metrics()` | counts across every process (`pending`, `due`, `running`, `failed`, `lagMs` of the most overdue) and this process's counters (`claimed`, `delivered`, `retried`, `failed`, `lastLagMs`, `maxLagMs`) |
791
+
792
+ **Where a write goes.** Through `{ tx }` when given — a Prisma interactive
793
+ transaction client (`prisma.$transaction(async (tx) => ...)`), or anything with
794
+ a `pg`-style `query(text, values)`; otherwise through the write transaction of
795
+ the `@mutation` it is called from; otherwise on its own. Either of the first two
796
+ commits or rolls back with the caller's change. A `@query` cannot schedule — it
797
+ is re-run whenever what it read changes. A schedule is one statement,
798
+ `SELECT nowity.nowity_job_schedule(...)`, an `INSERT … ON CONFLICT (key) DO
799
+ UPDATE`; `nowity_job` is not tracked, so it writes no outbox row and wakes no
800
+ live query, and is cheap enough for a write after every move.
801
+
802
+ **When it runs.** Never before `runAt`, by the database clock. The leader sleeps
803
+ until the earliest job is due; a schedule that comes before every job still to
804
+ come notifies it (`NOTIFY nowity_scheduler`, at commit — a later one does not, a
805
+ notification costs a lock at commit). The poll is the net under both, for a
806
+ notification lost with a connection.
807
+
808
+ **At least once, and idempotent.** The leader claims due jobs with
809
+ `FOR UPDATE SKIP LOCKED` and leases each claim for the handler's timeout and a
810
+ margin. A handler that throws or runs past its timeout is retried with backoff
811
+ (doubling from `minDelayMs` to `maxDelayMs`); when its attempts are used up a
812
+ one-off job is `failed` — it stays, with `last_error`, until someone
813
+ reschedules or cancels it — and `onFailed` is called. Every failed attempt goes
814
+ to the server's `onError`. A job whose process died mid-attempt is claimed again
815
+ when its lease runs out, by whichever process leads by then. So a handler
816
+ **must be idempotent**, and gets `attempt` to tell a retry.
817
+
818
+ - The outcome of an attempt is recorded under its claim. A job scheduled again
819
+ under the same key while an attempt runs is a new job: the old attempt's
820
+ success does not delete it, its failure does not fail it. The leader does not
821
+ start a key again while its previous handler still runs there (timed out or
822
+ not — such a handler also keeps its `concurrency` slot), but after a change of
823
+ leader the new one may. Guard on what the job was for (`runAt`, the payload)
824
+ rather than on the key.
825
+ - A periodic job moves on by its interval from when it was due, never into the
826
+ past, so a late run is not followed by a burst of the ones it missed. A run
827
+ that uses up its attempts gives up that run, not the job. It keeps its clock
828
+ across restarts; a new interval takes effect from its next run. Its row stays
829
+ when no process registers it any more, until `cancel("every:<name>")`;
830
+ cancelled while still registered, it is written again — at once by the
831
+ process that cancelled it, by the others when they restart. `schedule`
832
+ refuses keys starting with `every:`.
833
+ - Jobs of a handler the leader does not know are not claimed: they wait for a
834
+ leader that does. During a rolling deploy that adds a handler, its jobs may
835
+ wait until a new process leads.
836
+ - A job that is due but cannot be claimed — locked by a transaction that is
837
+ rescheduling it, or its previous handler still running — is looked at again
838
+ after a short backoff (100 ms), not in a loop. With every slot taken the
839
+ leader does not look at all until one frees.
840
+ - `stop()` waits up to `stopTimeoutMs` (5 s) for running jobs; one that has not
841
+ finished by then is left running with its outcome unrecorded, and is claimed
842
+ again when its lease runs out.
843
+
844
+ **Election.** Its own `LeaderElection` (lock `nowity:scheduler`), not the
845
+ presence reaper's: the two then tend to lead on different processes, and
846
+ neither depends on the other being configured.
847
+
848
+ **Table.** `nowity.nowity_job`: `key`, `handler`, `payload`, `run_at`, `next_at`
849
+ (when it may next be attempted), `state` (`pending`, `running`, `failed`),
850
+ `attempts`, `max_attempts`, `interval_ms`, `claim_id`, `locked_until`,
851
+ `last_error`, `created_at`. Created by `setupNowity` whether the scheduler is on
852
+ or not.
853
+
854
+ Scenario 26 covers each of these: time accuracy and the wakeup, reschedule and
855
+ cancel, an attempt racing a new schedule of its key, retries and `failed`, three
856
+ processes and racing claims, a leader killed mid-job, a restart of every
857
+ process, periodic jobs, and scheduling in a Prisma transaction and in a mutation.
858
+
565
859
  ### Escape hatches
566
860
 
567
861
  `@query({ tables: [...] })` for a query that reads through something the tracker
@@ -731,6 +1025,11 @@ produces an empty diff, so the client observes exactly once.
731
1025
  that needs a router that knows each node's read keys and sends it only what it
732
1026
  could care about; the data structure for it is `InvalidationIndex`, filed by
733
1027
  node instead of by subscription, and it is not written.
1028
+ - **A scheduled job is once in the normal run, not once always.** A leader that
1029
+ dies mid-job, a handler past its timeout, and two processes that both believe
1030
+ they lead for a heartbeat all end in a second attempt; the claim and the lease
1031
+ only make that rare. And `runAt` is compared with the database's clock, so an
1032
+ application server whose clock is off moves its jobs by as much.
734
1033
  - **The WAL source does not scale out.** One replication slot feeds one
735
1034
  consumer, so N processes means N slots and N times the retained WAL. Running
736
1035
  several instances is an outbox arrangement.
@@ -752,6 +1051,11 @@ src/server/api/ read-set tracker, contract→engine bridge, prerender, auth
752
1051
  src/server/api/list.ts paging an endpoint that has no paging
753
1052
  src/client/list.ts the windows a collection is actually showing
754
1053
  src/server/ engine: change sources, sync engine, mutators, WebSocket server
1054
+ src/server/presence.ts connections, node leases, the reaper, offline delivery
1055
+ src/server/leader.ts one process out of many: advisory-lock election, periodic tasks
1056
+ src/server/scheduler.ts jobs at a time: claims, leases, retries, the leader's loop
1057
+ src/server/api/scheduler.ts `Scheduler`, as application code uses it
1058
+ src/server/api/presence.ts `Presence`, as an endpoint reads it
755
1059
  src/client/ engine: confirmed store, overlay/rebase, identity map, live queries
756
1060
  src/client/connection.ts contract proxies, async acquisition, subscription lifetime
757
1061
  src/client/query-source.ts what a component reads through — the socket's, or a
@@ -762,7 +1066,9 @@ test/app/ demo app: shared.ts (client half) vs server.ts (server half),
762
1066
  test/scenarios/ 00 milestones, 01–11 acceptance scenarios, 12 Prisma, 13 WAL,
763
1067
  14 React, 15 SSR hydration, 16 DI containers, 17 SSR collection,
764
1068
  18 live collections, the grid and list over them, and hydration,
765
- 19 two tabs of one browser
1069
+ 19 two tabs of one browser, 20–21 read keys, 22 several nodes,
1070
+ 23 wire fidelity, 24 presence, 25 queries reading presence,
1071
+ 26 scheduler
766
1072
  example/demo.ts runnable walkthrough of the engine under the framework
767
1073
  example/contract-demo.ts the same story through contracts, with nothing declared
768
1074
  example-next/ a Next.js application: SSR, optimistic edits, access revoked live,
@@ -70,6 +70,8 @@ export declare class NowityConnection implements QuerySource {
70
70
  connect(): void;
71
71
  /** {@link QuerySource.hydrate} — the store's own, so both sources seed alike. */
72
72
  hydrate(payloads: HydrationPayload[]): void;
73
+ /** See {@link NowityClient.setContext}. */
74
+ setContext(context: Record<string, unknown> | null): void;
73
75
  close(): void;
74
76
  private adoptManifest;
75
77
  /** The proxy for a service, by its token. */
@@ -1 +1 @@
1
- {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/client/connection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAA0C,KAAK,gBAAgB,EAAE,MAAM,MAAM,CAAC;AACrF,OAAO,KAAK,EAAE,gBAAgB,EAAiB,MAAM,kBAAkB,CAAC;AAExE,OAAO,EAAmB,YAAY,EAAE,KAAK,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC1F,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAsB,KAAK,UAAU,EAAE,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAEvF,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG,UAAU,GAAG,MAAM,CAAC;AACzD,YAAY,EAAE,UAAU,EAAE,CAAC;AAE3B,MAAM,WAAW,uBAAwB,SAAQ,IAAI,CAAC,mBAAmB,EAAE,WAAW,CAAC;IACnF;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,mFAAmF;AACnF,cAAM,SAAS;IAeP,QAAQ,CAAC,GAAG,EAAE,MAAM;IAdxB,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,CAAC,CAAC;IAC9B,sEAAsE;IACtE,QAAQ,CAAC,IAA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EAAE,SAAS,GAAG,IAAI;IAK9B,OAAO,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IAK/B,OAAO,CAAC,eAAe;IAsBvB,OAAO,CAAC,UAAU;CAMrB"}
@@ -75,6 +75,15 @@ class LiveEntry {
75
75
  }
76
76
  /** Called once the server has said whether this endpoint returns one row. */
77
77
  watchCardinality(isSingle) {
78
+ // Known already (hydrated from the SSR snapshot): set it now. A `when`
79
+ // created during an observer render runs only after the surrounding batch,
80
+ // so that render would hand out the row list instead of the single row —
81
+ // a hydration mismatch against the server render.
82
+ const known = isSingle();
83
+ if (known !== undefined) {
84
+ this.single = known === true;
85
+ return;
86
+ }
78
87
  this.stopCardinality = (0, mobx_1.when)(() => isSingle() !== undefined, () => {
79
88
  this.single = isSingle() === true;
80
89
  });
@@ -141,6 +150,10 @@ class NowityConnection {
141
150
  hydrate(payloads) {
142
151
  this.client.hydrate(payloads);
143
152
  }
153
+ /** See {@link NowityClient.setContext}. */
154
+ setContext(context) {
155
+ this.client.setContext(context);
156
+ }
144
157
  close() {
145
158
  for (const entry of this.entries.values())
146
159
  entry.dispose();
@@ -51,6 +51,15 @@ export interface NowityClientOptions {
51
51
  minDelayMs?: number;
52
52
  maxDelayMs?: number;
53
53
  } | false;
54
+ /**
55
+ * The context the first hello already carries (see {@link NowityClient.setContext}).
56
+ *
57
+ * What a page knows before it connects — its own path — belongs here: the
58
+ * new connection is then recorded with it, and a reload is no change for
59
+ * anyone reading presence. Set after the socket opened, it is one write
60
+ * later, and a reload shows up as the context going and coming back.
61
+ */
62
+ context?: Record<string, unknown> | null;
54
63
  onError?: (error: Error) => void;
55
64
  /** Observability hook: every message received, before it is applied. */
56
65
  onServerMessage?: (message: ServerMessage) => void;
@@ -125,12 +134,26 @@ export declare class NowityClient {
125
134
  private intentionalClose;
126
135
  private connected;
127
136
  private everWelcomed;
137
+ /** What this connection says it is looking at; resent after every reconnect. */
138
+ private context;
128
139
  constructor(opts: NowityClientOptions);
129
140
  connect(): void;
130
141
  close(): void;
131
142
  /** Drop the connection as if the network died. For tests and for retry UX. */
132
143
  dropConnection(): void;
133
144
  private handleOpen;
145
+ /**
146
+ * Tell the server what this connection is looking at — `{ path }`, a game
147
+ * id — so that a server reading presence can show it (`Presence.contexts`).
148
+ *
149
+ * Sent only when it changed, kept across reconnects of this client (it
150
+ * rides on the hello), and cleared with `null`. It describes this socket,
151
+ * not the user: two tabs have two contexts. A server without presence
152
+ * ignores it. Called before `connect()` it goes out with the first hello —
153
+ * as does the `context` option — which is what keeps a page reload from
154
+ * being a change of context; called later, it is a separate message.
155
+ */
156
+ setContext(context: Record<string, unknown> | null): void;
134
157
  private handleClose;
135
158
  private send;
136
159
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"nowity-client.d.ts","sourceRoot":"","sources":["../../src/client/nowity-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,UAAU,EAAqD,MAAM,MAAM,CAAC;AAC7F,OAAO,KAAK,EAER,gBAAgB,EAGhB,aAAa,EAEb,aAAa,EAGhB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,KAAK,EAAE,QAAQ,EAAO,MAAM,eAAe,CAAC;AAEnD,OAAO,EACH,SAAS,EAET,KAAK,eAAe,EAEvB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAW,KAAK,OAAO,EAAE,MAAM,WAAW,CAAC;AAClD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C,MAAM,WAAW,kBAAkB;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,gEAAgE;IAChE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mEAAmE;IACnE,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,gBAAgB;IAC7B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;CAClD;AAED,MAAM,WAAW,gBAAgB,CAAC,CAAC,G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AA2E;IAC3E,OAAO,CAAC,aAAa;IAUrB;;;;;;;OAOG;IACH,OAAO,CAAC,UAAU;IAWlB,8DAA8D;IAC9D,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IASxE,uEAAuE;IACvE,MAAM,CAAC,CAAC,GAAG,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,GAAG,CAAC,GAAG,SAAS;IAIhE,uEAAuE;IACvE,OAAO,CAAC,MAAM,CAgBX;IAEH,+EAA+E;IAC/E,OAAO,CAAC,SAAS;IAiBjB,OAAO,CAAC,WAAW;IAkBnB,OAAO,CAAC,cAAc;IAmBtB,OAAO,CAAC,eAAe;IAiBvB,wFAAwF;IACxF,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS;IAI5C,OAAO,CAAC,SAAS;IASjB,OAAO,CAAC,YAAY;IAMpB,8EAA8E;IAC9E,IAAI,oBAAoB,IAAI,MAAM,CAEjC;IAED,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED,0EAA0E;IAC1E,aAAa,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI;CAG9C;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,CAEpE"}
@@ -77,6 +77,8 @@ class NowityClient {
77
77
  this.intentionalClose = false;
78
78
  this.connected = false;
79
79
  this.everWelcomed = false;
80
+ /** What this connection says it is looking at; resent after every reconnect. */
81
+ this.context = null;
80
82
  /** Rebuild the overlay from confirmed state plus pending mutations. */
81
83
  this.rebase = (0, mobx_1.action)(() => {
82
84
  this.pendingBox.set(this.pending.length > 0);
@@ -99,6 +101,7 @@ class NowityClient {
99
101
  });
100
102
  this.opts = opts;
101
103
  this.onError = opts.onError ?? ((err) => console.error("[nowity/client]", err));
104
+ this.context = opts.context ?? null;
102
105
  for (const mutator of opts.mutators ?? []) {
103
106
  this.mutators.set(mutator.name, mutator);
104
107
  }
@@ -137,7 +140,32 @@ class NowityClient {
137
140
  this.connected = true;
138
141
  this.reconnectAttempt = 0;
139
142
  (0, mobx_1.runInAction)(() => this.status.set("connected"));
140
- this.send({ t: "hello", v: protocol_1.PROTOCOL_VERSION, clientId: this.opts.clientId });
143
+ // The context rides on the hello: the server forgets it with the old
144
+ // socket, and a new socket has to be told before it is recorded.
145
+ this.send({
146
+ t: "hello",
147
+ v: protocol_1.PROTOCOL_VERSION,
148
+ clientId: this.opts.clientId,
149
+ ...(this.context !== null ? { context: this.context } : {}),
150
+ });
151
+ }
152
+ /**
153
+ * Tell the server what this connection is looking at — `{ path }`, a game
154
+ * id — so that a server reading presence can show it (`Presence.contexts`).
155
+ *
156
+ * Sent only when it changed, kept across reconnects of this client (it
157
+ * rides on the hello), and cleared with `null`. It describes this socket,
158
+ * not the user: two tabs have two contexts. A server without presence
159
+ * ignores it. Called before `connect()` it goes out with the first hello —
160
+ * as does the `context` option — which is what keeps a page reload from
161
+ * being a change of context; called later, it is a separate message.
162
+ */
163
+ setContext(context) {
164
+ if (JSON.stringify(context) === JSON.stringify(this.context))
165
+ return;
166
+ this.context = context;
167
+ if (this.connected)
168
+ this.send({ t: "context", context });
141
169
  }
142
170
  handleClose() {
143
171
  this.connected = false;
@@ -14,6 +14,13 @@ export interface ClientHello {
14
14
  t: "hello";
15
15
  v: number;
16
16
  clientId: string;
17
+ /**
18
+ * The connection's context ({@link ClientContext}), when it has one. Sent
19
+ * with the hello rather than after it so that a reconnect restores it in
20
+ * the same write that records the connection — a reload is then no change
21
+ * at all for anyone reading presence.
22
+ */
23
+ context?: Record<string, unknown> | null;
17
24
  }
18
25
  export interface ClientSubscribe {
19
26
  t: "subscribe";
@@ -31,7 +38,19 @@ export interface ClientMutate {
31
38
  name: string;
32
39
  args: unknown;
33
40
  }
34
- export type ClientMessage = ClientHello | ClientSubscribe | ClientUnsubscribe | ClientMutate;
41
+ /**
42
+ * What this connection is looking at — a path, a game — for presence readers.
43
+ *
44
+ * Not a mutation: it has no sequence number and no answer, and after a
45
+ * reconnect it travels in the hello instead, because it describes the socket
46
+ * rather than the data. `null` clears it. A server without presence ignores it,
47
+ * and so does a server older than it.
48
+ */
49
+ export interface ClientContext {
50
+ t: "context";
51
+ context: Record<string, unknown> | null;
52
+ }
53
+ export type ClientMessage = ClientHello | ClientSubscribe | ClientUnsubscribe | ClientMutate | ClientContext;
35
54
  /**
36
55
  * A query result rendered on the server for the first paint.
37
56
  *
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../src/core/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAEvD;;;;;;;;;GASG;AAEH,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAIlC,MAAM,WAAW,WAAW;IACxB,CAAC,EAAE,OAAO,CAAC;IACX,CAAC,EAAE,MAAM,CAAC;IACV,QAAQ,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,eAAe;IAC5B,CAAC,EAAE,WAAW,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,iBAAiB;IAC9B,CAAC,EAAE,aAAa,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,YAAY;IACzB,CAAC,EAAE,QAAQ,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,MAAM,aAAa,GAAG,WAAW,GAAG,eAAe,GAAG,iBAAiB,GAAG,YAAY,CAAC;AAE7F;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC7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,GACpB,WAAW,CAAC"}
package/dist/index.d.ts CHANGED
@@ -24,6 +24,11 @@ export { Forbidden, Rejected, isForbidden, isRejected } from "./api/errors";
24
24
  export { createNowityServer, type NowityServer, type NowityServerConfig, type DefaultOutboxOptions, DEFAULT_PRUNE_INTERVAL_MS, } from "./server/api/configure";
25
25
  export { createNowityRuntime, type NowityRuntime, type NowityRuntimeConfig, } from "./server/api/runtime";
26
26
  export { Session } from "./server/api/execution";
27
+ export { Presence, type PresenceDetail } from "./server/api/presence";
28
+ export { PresenceTracker, type OfflineEvent, type OfflineHandler, type PresenceContext, type PresenceOptions, } from "./server/presence";
29
+ export { Scheduler, type JobFilter, type JobInfo, type JobState, type ScheduleRequest, type SchedulerExecutor, type SchedulerMetrics, type SchedulerWriteOptions, } from "./server/api/scheduler";
30
+ export { SchedulerWorker, type JobHandler, type JobHandlerOptions, type RetryOptions, type ScheduledJob, type SchedulerOptions, type SchedulerStats, } from "./server/scheduler";
31
+ export { LeaderElection, PeriodicTask, type LeaderElectionOptions, type PeriodicTaskOptions, } from "./server/leader";
27
32
  export { Authenticator, AnonymousAuthenticator } from "./server/api/auth";
28
33
  export type { AuthRequest, AuthResult } from "./server/ws-server";
29
34
  export type { SessionInfo } from "./server/query";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,EACH,GAAG,EACH,QAAQ,EACR,KAAK,EACL,IAAI,EACJ,QAAQ,EACR,UAAU,EACV,YAAY,EACZ,SAAS,EACT,UAAU,EACV,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,eAAe,EACpB,KAAK,YAAY,GACpB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG5E,OAAO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,gBAAgB,EAChB,iBAAiB,EACjB,KAAK,UAAU,EACf,KAAK,MAAM,EACX,KAAK,WAAW,GACnB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,IAAI,EAAE,KAAK,SAAS,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,SAAS,EAAE,KAAK,gBAAgB,EAAE,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAGlE,OAAO,EAAE,qBAAqB,EAAE,KAAK,2BAA2B,EAAE,MAAM,mBAAmB,CAAC;AAC5F,cAAc,mBAAmB,CAAC;AAGlC,OAAO,EACH,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,KAAK,uBAAuB,EAC5B,KAAK,UAAU,GAClB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,kBAAkB,EAAE,KAAK,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAG3F,YAAY,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AAClD,YAAY,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC"}
package/dist/index.js CHANGED
@@ -35,7 +35,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
35
35
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
36
36
  };
37
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.WebSocketTransport = exports.currentConnection = exports.activeConnection = exports.NowityConnection = exports.configureNowityServer = exports.withNowity = exports.serveNext = exports.Live = exports.currentNextNowity = exports.createNextNowity = exports.NOWITY_SETUP_SQL = exports.setReplicaIdentityFull = exports.untrackTable = exports.trackTable = exports.setupNowity = exports.WalChangeSource = exports.OutboxChangeSource = exports.prerender = exports.AnonymousAuthenticator = exports.Authenticator = exports.Session = exports.createNowityRuntime = exports.DEFAULT_PRUNE_INTERVAL_MS = exports.createNowityServer = exports.isRejected = exports.isForbidden = exports.Rejected = exports.Forbidden = exports.countQuery = exports.pageQuery = exports.endpointName = exports.contractOf = exports.mutation = exports.list = exports.query = exports.contract = exports.api = void 0;
38
+ exports.WebSocketTransport = exports.currentConnection = exports.activeConnection = exports.NowityConnection = exports.configureNowityServer = exports.withNowity = exports.serveNext = exports.Live = exports.currentNextNowity = exports.createNextNowity = exports.NOWITY_SETUP_SQL = exports.setReplicaIdentityFull = exports.untrackTable = exports.trackTable = exports.setupNowity = exports.WalChangeSource = exports.OutboxChangeSource = exports.prerender = exports.AnonymousAuthenticator = exports.Authenticator = exports.PeriodicTask = exports.LeaderElection = exports.SchedulerWorker = exports.Scheduler = exports.PresenceTracker = exports.Presence = exports.Session = exports.createNowityRuntime = exports.DEFAULT_PRUNE_INTERVAL_MS = exports.createNowityServer = exports.isRejected = exports.isForbidden = exports.Rejected = exports.Forbidden = exports.countQuery = exports.pageQuery = exports.endpointName = exports.contractOf = exports.mutation = exports.list = exports.query = exports.contract = exports.api = void 0;
39
39
  // ------------------------------------------------------------------- contracts
40
40
  var contract_1 = require("./api/contract");
41
41
  Object.defineProperty(exports, "api", { enumerable: true, get: function () { return contract_1.api; } });
@@ -60,6 +60,17 @@ var runtime_1 = require("./server/api/runtime");
60
60
  Object.defineProperty(exports, "createNowityRuntime", { enumerable: true, get: function () { return runtime_1.createNowityRuntime; } });
61
61
  var execution_1 = require("./server/api/execution");
62
62
  Object.defineProperty(exports, "Session", { enumerable: true, get: function () { return execution_1.Session; } });
63
+ var presence_1 = require("./server/api/presence");
64
+ Object.defineProperty(exports, "Presence", { enumerable: true, get: function () { return presence_1.Presence; } });
65
+ var presence_2 = require("./server/presence");
66
+ Object.defineProperty(exports, "PresenceTracker", { enumerable: true, get: function () { return presence_2.PresenceTracker; } });
67
+ var scheduler_1 = require("./server/api/scheduler");
68
+ Object.defineProperty(exports, "Scheduler", { enumerable: true, get: function () { return scheduler_1.Scheduler; } });
69
+ var scheduler_2 = require("./server/scheduler");
70
+ Object.defineProperty(exports, "SchedulerWorker", { enumerable: true, get: function () { return scheduler_2.SchedulerWorker; } });
71
+ var leader_1 = require("./server/leader");
72
+ Object.defineProperty(exports, "LeaderElection", { enumerable: true, get: function () { return leader_1.LeaderElection; } });
73
+ Object.defineProperty(exports, "PeriodicTask", { enumerable: true, get: function () { return leader_1.PeriodicTask; } });
63
74
  var auth_1 = require("./server/api/auth");
64
75
  Object.defineProperty(exports, "Authenticator", { enumerable: true, get: function () { return auth_1.Authenticator; } });
65
76
  Object.defineProperty(exports, "AnonymousAuthenticator", { enumerable: true, get: function () { return auth_1.AnonymousAuthenticator; } });
@@ -1 +1 @@
1
- {"version":3,"file":"collector.d.ts","sourceRoot":"","sources":["../../../src/server/api/collector.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAoB,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAkD,KAAK,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvG,OAAO,KAAK,EAAmB,cAAc,EAAE,MAAM,OAAO,CAAC;AAE7D,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE3D,MAAM,WAAW,gBAAgB;IAC7B,SAAS,EAAE,cAAc,CAAC;IAC1B,OAAO,EAAE,aAAa,CAAC;IACvB,QAAQ,CAAC,EAAE,aAAa,CAAC,KAAK,CAAC,CAAC;IAChC;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,YAAa,SAAQ,SAAS;IAC3C,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,oFAAoF;IACpF,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,WAAW,GAAG,YAAY,CAsH3F"}
1
+ {"version":3,"file":"collector.d.ts","sourceRoot":"","sources":["../../../src/server/api/collector.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAoB,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAkD,KAAK,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvG,OAAO,KAAK,EAAmB,cAAc,EAAE,MAAM,OAAO,CAAC;AAE7D,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE3D,MAAM,WAAW,gBAAgB;IAC7B,SAAS,EAAE,cAAc,CAAC;IAC1B,OAAO,EAAE,aAAa,CAAC;IACvB,QAAQ,CAAC,EAAE,aAAa,CAAC,KAAK,CAAC,CAAC;IAChC;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,YAAa,SAAQ,SAAS;IAC3C,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,oFAAoF;IACpF,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,WAAW,GAAG,YAAY,CAyH3F"}
@@ -115,7 +115,10 @@ function openSsrCollector(deps, session) {
115
115
  async function collected() {
116
116
  for (let settled = 0; settled < 20 && !closed;) {
117
117
  const before = payloads.length;
118
- await new Promise((resolve) => setImmediate(resolve));
118
+ // A timer, not an immediate: Next 16.4 Cache Components (dev staged render) runs immediates
119
+ // queued during a render stage as "fast immediates" ahead of I/O, so an immediate-polling
120
+ // loop waiting for a database read starves the very I/O it waits for and spins forever.
121
+ await new Promise((resolve) => setTimeout(resolve, 0));
119
122
  settled = pending === 0 && payloads.length === before ? settled + 1 : 0;
120
123
  if (settled >= 2)
121
124
  break;