nowity 1.2.0 → 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 +23 -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
@@ -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;
@@ -1,6 +1,8 @@
1
1
  import type { ChangeSource } from "../change-source/change-source";
2
2
  import { SyncEngine } from "../sync-engine";
3
3
  import { NowitySyncServer, type NowitySyncServerOptions } from "../ws-server";
4
+ import { PresenceTracker, type PresenceOptions } from "../presence";
5
+ import { SchedulerWorker, type SchedulerOptions } from "../scheduler";
4
6
  import { type NowityRuntime, type NowityRuntimeConfig } from "./runtime";
5
7
  export interface NowityServerConfig extends NowityRuntimeConfig {
6
8
  /**
@@ -20,6 +22,24 @@ export interface NowityServerConfig extends NowityRuntimeConfig {
20
22
  syncServer?: Omit<NowitySyncServerOptions, "engine">;
21
23
  /** See {@link SyncEngineOptions.narrowInvalidation}. On unless set. */
22
24
  narrowInvalidation?: boolean;
25
+ /**
26
+ * Record who is connected, so endpoints can read it through the injectable
27
+ * {@link Presence} and react to users going offline (`Presence.onOffline`).
28
+ *
29
+ * Off unless set — `presence: {}` turns it on with the defaults. Off, the
30
+ * server writes nothing about connections; `Presence` still reads, and
31
+ * finds nobody online.
32
+ */
33
+ presence?: PresenceOptions;
34
+ /**
35
+ * Run the jobs scheduled through the injectable {@link Scheduler}, on
36
+ * whichever sync process leads.
37
+ *
38
+ * Off unless set — `scheduler: {}` turns it on with the defaults. Off,
39
+ * nothing here runs jobs; `Scheduler` still schedules them, for a process
40
+ * that has it on.
41
+ */
42
+ scheduler?: SchedulerOptions;
23
43
  onError?: (err: Error) => void;
24
44
  }
25
45
  export interface DefaultOutboxOptions {
@@ -39,6 +59,10 @@ export declare const DEFAULT_PRUNE_INTERVAL_MS = 60000;
39
59
  export interface NowityServer extends NowityRuntime {
40
60
  engine: SyncEngine;
41
61
  server: NowitySyncServer;
62
+ /** This process's half of presence, when it is on. */
63
+ presence: PresenceTracker | null;
64
+ /** This process's half of the scheduler, when it is on. */
65
+ scheduler: SchedulerWorker | null;
42
66
  /** Start the change stream and the socket; resolves with the port. */
43
67
  start(): Promise<number>;
44
68
  stop(): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"configure.d.ts","sourceRoot":"","sources":["../../../src/server/api/configure.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAGnE,OAAO,EAAE,UAAU,EAA0B,MAAM,gBAAgB,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,KAAK,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAE9E,OAAO,EAAuB,KAAK,aAAa,EAAE,KAAK,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAE9F,MAAM,WAAW,kBAAmB,SAAQ,mBAAmB;IAC3D;;;OAGG;IACH,YAAY,CAAC,EAAE,YAAY,GAAG,CAAC,MAAM,YAAY,CAAC,CAAC;IACnD,sEAAs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A4D3E"}
@@ -16,7 +16,11 @@ const outbox_change_source_1 = require("../change-source/outbox-change-source");
16
16
  const mutator_1 = require("../mutator");
17
17
  const sync_engine_1 = require("../sync-engine");
18
18
  const ws_server_1 = require("../ws-server");
19
+ const presence_1 = require("../presence");
20
+ const scheduler_1 = require("../scheduler");
19
21
  const auth_1 = require("./auth");
22
+ const presence_2 = require("./presence");
23
+ const scheduler_2 = require("./scheduler");
20
24
  const runtime_1 = require("./runtime");
21
25
  /** How often the default outbox prunes. */
22
26
  exports.DEFAULT_PRUNE_INTERVAL_MS = 60000;
@@ -40,7 +44,10 @@ function resolveChangeSource(config) {
40
44
  }
41
45
  function createNowityServer(config) {
42
46
  const runtime = (0, runtime_1.createNowityRuntime)(config);
43
- const authenticator = (0, ironbean_1.getBaseApplicationContext)().getBean(auth_1.Authenticator);
47
+ const context = (0, ironbean_1.getBaseApplicationContext)();
48
+ const authenticator = context.getBean(auth_1.Authenticator);
49
+ const presence = config.presence ? createPresence(config, runtime, context.getBean(presence_2.Presence)) : null;
50
+ const scheduler = config.scheduler ? createScheduler(config, runtime, context.getBean(scheduler_2.Scheduler)) : null;
44
51
  const engine = new sync_engine_1.SyncEngine({
45
52
  snapshots: runtime.snapshots,
46
53
  writes: new mutator_1.PrismaWriteRunner(runtime.prisma),
@@ -49,10 +56,14 @@ function createNowityServer(config) {
49
56
  mutators: runtime.api.mutators,
50
57
  api: { contracts: runtime.api.manifest.contracts, entities: runtime.api.entities },
51
58
  narrowInvalidation: config.narrowInvalidation,
59
+ ...(presence ? { presence } : {}),
52
60
  onError: config.onError,
53
61
  });
54
62
  const server = new ws_server_1.NowitySyncServer({
55
63
  ...config.syncServer,
64
+ // A connection whose peer vanished is someone shown online, so with
65
+ // presence on, the heartbeat is too. Without it nothing changes.
66
+ heartbeat: config.syncServer?.heartbeat ?? (presence ? {} : false),
56
67
  engine,
57
68
  authenticate: (request) => authenticator.authenticate(request),
58
69
  onError: config.onError,
@@ -61,13 +72,52 @@ function createNowityServer(config) {
61
72
  ...runtime,
62
73
  engine,
63
74
  server,
75
+ presence,
76
+ scheduler,
64
77
  async start() {
65
78
  await engine.start();
79
+ // Before the socket: the node's lease has to exist before the first
80
+ // connection names it.
81
+ await presence?.start();
82
+ scheduler?.start();
66
83
  return server.listen();
67
84
  },
68
85
  async stop() {
86
+ // Before any of the below: the scheduler needs nothing from the
87
+ // sockets, and stopping it first hands its lead on while they drain.
88
+ await scheduler?.stop();
89
+ // Presence stops writing first, then the socket stops accepting and
90
+ // closes everything it has, and only then is this node's departure
91
+ // recorded — in one statement rather than a disconnect per socket,
92
+ // and after the last socket, so nothing it accepted is left out.
93
+ // The users get the grace period to land on another node.
94
+ presence?.drain();
69
95
  await server.close();
96
+ await presence?.stop();
70
97
  await engine.stop();
71
98
  },
72
99
  };
73
100
  }
101
+ function createPresence(config, runtime, service) {
102
+ const options = config.presence;
103
+ return new presence_1.PresenceTracker({
104
+ ...options,
105
+ databaseUrl: options.databaseUrl ?? config.databaseUrl ?? process.env.DATABASE_URL,
106
+ writes: new mutator_1.PrismaWriteRunner(runtime.prisma),
107
+ handlers: () => service.offlineHandlers(),
108
+ onError: config.onError,
109
+ });
110
+ }
111
+ function createScheduler(config, runtime, service) {
112
+ const options = config.scheduler;
113
+ const worker = new scheduler_1.SchedulerWorker({
114
+ ...options,
115
+ databaseUrl: options.databaseUrl ?? config.databaseUrl ?? process.env.DATABASE_URL,
116
+ writes: new mutator_1.PrismaWriteRunner(runtime.prisma),
117
+ handlers: () => service.registeredHandlers(),
118
+ periodic: () => service.periodicJobs(),
119
+ onError: config.onError,
120
+ });
121
+ service.bindWorker(worker);
122
+ return worker;
123
+ }
@@ -51,6 +51,15 @@ export interface Execution {
51
51
  list?: ListExecution;
52
52
  }
53
53
  export declare function runInExecution<T>(execution: Execution, fn: () => Promise<T>): Promise<T>;
54
+ /**
55
+ * Run `fn` where the tracking client cannot see it.
56
+ *
57
+ * For Nowity's own reads inside an endpoint — presence, say — which record
58
+ * their read set themselves, precisely, and must not have the raw SQL they run
59
+ * mark the whole execution as untracked. The frame is a copy whose recorders go
60
+ * nowhere; the snapshot and the session are the execution's own.
61
+ */
62
+ export declare function runUntracked<T>(execution: Execution, fn: () => Promise<T>): Promise<T>;
54
63
  export declare function currentExecution(): Execution;
55
64
  export declare function peekExecution(): Execution | undefined;
56
65
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"execution.d.ts","sourceRoot":"","sources":["../../../src/server/api/execution.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC5C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,WAAW,SAAS;IACtB,IAAI,EAAE,OAAO,GAAG,UAAU,CAAC;IAC3B,OAAO,EAAE,WAAW,CAAC;IACrB,6EAA6E;IAC7E,MAAM,EAAE,GAAG,CAAC;IACZ,iEAAiE;IACjE,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACnB;;;;;;OAMG;IACH,IAAI,CAAC,EAAE,YAAY,CAAC;IACpB;;;;;;;;OAQG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;OAGG;IACH,SAAS,EAAE,OAAO,CAAC;IACnB;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kCAAkC;IAClC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;OAMG;IACH,IAAI,CAAC,EAAE,aAAa,CAAC;CACxB;AAID,wBAAgB,cAAc,CAAC,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAOxF;AAED,wBAAgB,gBAAgB,IAAI,SAAS,CAS5C;AAED,wBAAgB,aAAa,IAAI,SAAS,GAAG,SAAS,CAErD;AAED;;;;;G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;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAStF;AAED,wBAAgB,gBAAgB,IAAI,SAAS,CAS5C;AAED,wBAAgB,aAAa,IAAI,SAAS,GAAG,SAAS,CAErD;AAED;;;;;GAKG;AACH,qBACa,OAAO;IAChB,IAAI,QAAQ,IAAI,MAAM,CAIrB;IAED,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,CAE1B;IAED,qDAAqD;IACrD,IAAI,IAAI,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAElC;IAED,uEAAuE;IACvE,aAAa,IAAI,MAAM;CAK1B;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,MAAM,KAAK,CAAC,CAcnD"}
@@ -8,6 +8,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.Session = void 0;
10
10
  exports.runInExecution = runInExecution;
11
+ exports.runUntracked = runUntracked;
11
12
  exports.currentExecution = currentExecution;
12
13
  exports.peekExecution = peekExecution;
13
14
  exports.ambientPrisma = ambientPrisma;
@@ -35,6 +36,24 @@ function runInExecution(execution, fn) {
35
36
  // nothing at all.
36
37
  return storage.run(execution, async () => await fn());
37
38
  }
39
+ /**
40
+ * Run `fn` where the tracking client cannot see it.
41
+ *
42
+ * For Nowity's own reads inside an endpoint — presence, say — which record
43
+ * their read set themselves, precisely, and must not have the raw SQL they run
44
+ * mark the whole execution as untracked. The frame is a copy whose recorders go
45
+ * nowhere; the snapshot and the session are the execution's own.
46
+ */
47
+ function runUntracked(execution, fn) {
48
+ const shadow = {
49
+ ...execution,
50
+ reads: new Set(),
51
+ keys: undefined,
52
+ untracked: false,
53
+ list: undefined,
54
+ };
55
+ return storage.run(shadow, async () => await fn());
56
+ }
38
57
  function currentExecution() {
39
58
  const execution = storage.getStore();
40
59
  if (!execution) {
@@ -0,0 +1,66 @@
1
+ import type { Queryable } from "../db";
2
+ import type { OfflineHandler, PresenceContext } from "../presence";
3
+ /** One online user as `Presence.details` describes them. */
4
+ export interface PresenceDetail {
5
+ userId: string;
6
+ /** When the current online period began. */
7
+ since: Date;
8
+ /** What their connections said they were looking at, deduplicated. */
9
+ contexts: PresenceContext[];
10
+ /** The `meta` of their newest connection (`presence.meta`); empty if none was stored. */
11
+ meta: Record<string, unknown>;
12
+ }
13
+ /** The table queries reading presence are invalidated by, as change events name it. */
14
+ export declare const PRESENCE_TABLE = "nowity_presence";
15
+ /** Where reads outside an execution go. Set by the runtime. */
16
+ export declare function bindPresenceReader(reader: Queryable | null): void;
17
+ export declare class Presence {
18
+ private readonly handlers;
19
+ /** Whether the user has a connection open (or had one within the grace period). */
20
+ isOnline(userId: string): Promise<boolean>;
21
+ /** Which of the given users are online. */
22
+ online(userIds: readonly string[]): Promise<Set<string>>;
23
+ /**
24
+ * Every online user. Watches the whole table, so a query built on it is
25
+ * recomputed on every transition of anyone — fine for an admin page, not
26
+ * for something every visitor has open.
27
+ */
28
+ onlineAll(): Promise<string[]>;
29
+ /**
30
+ * What each of the given users' connections said they were looking at
31
+ * (`NowityClient.setContext`), deduplicated. A user who is offline, or set
32
+ * nothing, has an empty list.
33
+ */
34
+ contexts(userIds: readonly string[]): Promise<Map<string, PresenceContext[]>>;
35
+ /**
36
+ * Who is online and since when, what they look at and what their newest
37
+ * connection stored as `meta` — for operator pages, which should not read
38
+ * Nowity's tables themselves. Longest online first. With `userIds` only
39
+ * those (and the read is keyed by them); without, everyone online — which
40
+ * watches the whole table like `onlineAll`, so cap it with `limit`.
41
+ *
42
+ * `meta` comes from `nowity_connection`, which does not reach the outbox: a
43
+ * query is recomputed on the user's transitions and context changes, not
44
+ * on a new connection with different meta.
45
+ */
46
+ details(userIds?: readonly string[], options?: {
47
+ limit?: number;
48
+ }): Promise<PresenceDetail[]>;
49
+ /**
50
+ * Be called after a user goes offline — at least once per transition, by
51
+ * whichever sync process leads. **The handler must be idempotent**; see
52
+ * `OfflineHandler`. Register it before the server starts, on every sync
53
+ * process. Returns the unsubscribe.
54
+ */
55
+ onOffline(handler: OfflineHandler): () => void;
56
+ /** The registered handlers. For the presence tracker. */
57
+ offlineHandlers(): OfflineHandler[];
58
+ /**
59
+ * Run one read, recording it when inside a query.
60
+ *
61
+ * `keys` are the user ids the read is confined to, or null for a read of the
62
+ * whole table.
63
+ */
64
+ private read;
65
+ }
66
+ //# sourceMappingURL=presence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"presence.d.ts","sourceRoot":"","sources":["../../../src/server/api/presence.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AACvC,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAGnE,4DAA4D;AAC5D,MAAM,WAAW,cAAc;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,4CAA4C;IAC5C,KAAK,EAAE,IAAI,CAAC;IACZ,sEAAsE;IACtE,QAAQ,EAAE,eAAe,EAAE,CAAC;IAC5B,yFAAyF;IACzF,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAED,uFAAuF;AACvF,eAAO,MAAM,cAAc,oBAAoB,CAAC;AAOhD,+DAA+D;AAC/D,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,SAAS,GAAG,IAAI,GAAG,IAAI,CAEjE;AAED,qBACa,QAAQ;IACjB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA6B;IAEtD,mFAAmF;IAC7E,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAShD,2CAA2C;IACrC,MAAM,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAY9D;;;;OAIG;IACG,SAAS,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IASpC;;;;OAIG;IACG,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,eAAe,EAAE,CAAC,CAAC;IAkBnF;;;;;;;;;;OAUG;IACG,OAAO,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,GAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAO,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;IAmCvG;;;;;OAKG;IACH,SAAS,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,IAAI;IAO9C,yDAAyD;IACzD,eAAe,IAAI,cAAc,EAAE;IAInC;;;;;OAKG;YACW,IAAI;CAoBrB"}
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.Presence = exports.PRESENCE_TABLE = void 0;
10
+ exports.bindPresenceReader = bindPresenceReader;
11
+ /**
12
+ * Presence, as an endpoint reads it.
13
+ *
14
+ * Injectable like `Session` and `Db`, and ambient in the same way: inside a
15
+ * `@query` every read goes through the execution's own snapshot and is recorded
16
+ * in its read set, keyed by user — so a query that asked whether Alice is online
17
+ * is recomputed when Alice comes or goes, and not when Bob does. Outside an
18
+ * execution (a script, a background job, a server component) it reads the
19
+ * database directly.
20
+ *
21
+ * What is read is `nowity.nowity_presence`, which only changes on transitions:
22
+ * a user opening a second tab, or reloading inside the grace period, produces no
23
+ * change here and therefore no recomputation anywhere.
24
+ *
25
+ * Works in a process without a socket of its own — the Next half — because it
26
+ * is only ever reading; the sync processes are what keep the table current.
27
+ */
28
+ const ironbean_1 = require("ironbean");
29
+ const execution_1 = require("./execution");
30
+ /** The table queries reading presence are invalidated by, as change events name it. */
31
+ exports.PRESENCE_TABLE = "nowity_presence";
32
+ /** Keyed by this column, so a change to one user wakes only that user's readers. */
33
+ const USER_COLUMN = "user_id";
34
+ let fallbackReader = null;
35
+ /** Where reads outside an execution go. Set by the runtime. */
36
+ function bindPresenceReader(reader) {
37
+ fallbackReader = reader;
38
+ }
39
+ let Presence = class Presence {
40
+ constructor() {
41
+ this.handlers = new Set();
42
+ }
43
+ /** Whether the user has a connection open (or had one within the grace period). */
44
+ async isOnline(userId) {
45
+ const rows = await this.read(`SELECT online FROM nowity.nowity_presence WHERE user_id = $1`, [userId], [userId]);
46
+ return rows[0]?.online === true;
47
+ }
48
+ /** Which of the given users are online. */
49
+ async online(userIds) {
50
+ const ids = unique(userIds);
51
+ if (ids.length === 0)
52
+ return new Set();
53
+ const rows = await this.read(`SELECT user_id FROM nowity.nowity_presence
54
+ WHERE online AND user_id IN (${placeholders(ids.length)})`, ids, ids);
55
+ return new Set(rows.map((row) => row.user_id));
56
+ }
57
+ /**
58
+ * Every online user. Watches the whole table, so a query built on it is
59
+ * recomputed on every transition of anyone — fine for an admin page, not
60
+ * for something every visitor has open.
61
+ */
62
+ async onlineAll() {
63
+ const rows = await this.read(`SELECT user_id FROM nowity.nowity_presence WHERE online ORDER BY user_id`, [], null);
64
+ return rows.map((row) => row.user_id);
65
+ }
66
+ /**
67
+ * What each of the given users' connections said they were looking at
68
+ * (`NowityClient.setContext`), deduplicated. A user who is offline, or set
69
+ * nothing, has an empty list.
70
+ */
71
+ async contexts(userIds) {
72
+ const ids = unique(userIds);
73
+ const out = new Map();
74
+ for (const id of ids)
75
+ out.set(id, []);
76
+ if (ids.length === 0)
77
+ return out;
78
+ const rows = await this.read(`SELECT user_id, contexts FROM nowity.nowity_presence
79
+ WHERE online AND user_id IN (${placeholders(ids.length)})`, ids, ids);
80
+ for (const row of rows) {
81
+ const contexts = typeof row.contexts === "string" ? JSON.parse(row.contexts) : row.contexts;
82
+ out.set(row.user_id, Array.isArray(contexts) ? contexts : []);
83
+ }
84
+ return out;
85
+ }
86
+ /**
87
+ * Who is online and since when, what they look at and what their newest
88
+ * connection stored as `meta` — for operator pages, which should not read
89
+ * Nowity's tables themselves. Longest online first. With `userIds` only
90
+ * those (and the read is keyed by them); without, everyone online — which
91
+ * watches the whole table like `onlineAll`, so cap it with `limit`.
92
+ *
93
+ * `meta` comes from `nowity_connection`, which does not reach the outbox: a
94
+ * query is recomputed on the user's transitions and context changes, not
95
+ * on a new connection with different meta.
96
+ */
97
+ async details(userIds, options = {}) {
98
+ const ids = userIds ? unique(userIds) : null;
99
+ if (ids && ids.length === 0)
100
+ return [];
101
+ const values = ids ? [...ids] : [];
102
+ const where = ids ? `AND p.user_id IN (${placeholders(ids.length)})` : "";
103
+ let limit = "";
104
+ if (options.limit !== undefined) {
105
+ values.push(Math.max(0, Math.floor(options.limit)));
106
+ limit = `LIMIT $${values.length}`;
107
+ }
108
+ const rows = await this.read(`SELECT p.user_id, COALESCE(p.online_since, p.updated_at) AS since, p.contexts, c.meta
109
+ FROM nowity.nowity_presence p
110
+ LEFT JOIN LATERAL (
111
+ SELECT meta FROM nowity.nowity_connection
112
+ WHERE user_id = p.user_id ORDER BY connected_at DESC LIMIT 1
113
+ ) c ON true
114
+ WHERE p.online ${where}
115
+ ORDER BY since ASC, p.user_id ASC
116
+ ${limit}`, values, ids);
117
+ return rows.map((row) => {
118
+ const contexts = parseJson(row.contexts);
119
+ const meta = parseJson(row.meta);
120
+ return {
121
+ userId: row.user_id,
122
+ since: row.since instanceof Date ? row.since : new Date(row.since),
123
+ contexts: Array.isArray(contexts) ? contexts : [],
124
+ meta: meta && typeof meta === "object" && !Array.isArray(meta) ? meta : {},
125
+ };
126
+ });
127
+ }
128
+ /**
129
+ * Be called after a user goes offline — at least once per transition, by
130
+ * whichever sync process leads. **The handler must be idempotent**; see
131
+ * `OfflineHandler`. Register it before the server starts, on every sync
132
+ * process. Returns the unsubscribe.
133
+ */
134
+ onOffline(handler) {
135
+ this.handlers.add(handler);
136
+ return () => {
137
+ this.handlers.delete(handler);
138
+ };
139
+ }
140
+ /** The registered handlers. For the presence tracker. */
141
+ offlineHandlers() {
142
+ return [...this.handlers];
143
+ }
144
+ /**
145
+ * Run one read, recording it when inside a query.
146
+ *
147
+ * `keys` are the user ids the read is confined to, or null for a read of the
148
+ * whole table.
149
+ */
150
+ async read(text, values, keys) {
151
+ const execution = (0, execution_1.peekExecution)();
152
+ if (execution) {
153
+ if (execution.kind === "query") {
154
+ execution.reads.add(exports.PRESENCE_TABLE);
155
+ execution.keys?.recordRows(exports.PRESENCE_TABLE, USER_COLUMN, keys);
156
+ }
157
+ const client = execution.prisma;
158
+ return (0, execution_1.runUntracked)(execution, async () => (await client.$queryRawUnsafe(text, ...values)));
159
+ }
160
+ if (!fallbackReader) {
161
+ throw new Error("Presence was read outside a @query or @mutation before any Nowity runtime " +
162
+ "was created, so there is no database to read it from.");
163
+ }
164
+ return (await fallbackReader.query(text, values)).rows;
165
+ }
166
+ };
167
+ exports.Presence = Presence;
168
+ exports.Presence = Presence = __decorate([
169
+ ironbean_1.component
170
+ ], Presence);
171
+ function unique(ids) {
172
+ return [...new Set(ids)];
173
+ }
174
+ function parseJson(value) {
175
+ return typeof value === "string" ? JSON.parse(value) : value;
176
+ }
177
+ function placeholders(count) {
178
+ // Explicit placeholders rather than `= ANY($1)`: array parameters are not
179
+ // portable across the adapters this runs on (pg vs Prisma raw).
180
+ return Array.from({ length: count }, (_, index) => `$${index + 1}`).join(", ");
181
+ }
@@ -86,6 +86,12 @@ export declare class KeyCollector {
86
86
  record(model: string | undefined, args: unknown): void;
87
87
  /** Everything read so far, collapsed to keys per table. */
88
88
  result(): ReadKeySet;
89
+ /**
90
+ * Record a read of a table that is not a Prisma model — one of Nowity's
91
+ * own — whose rows were selected by `column IN values`. `null` for values
92
+ * means the read was not narrowed at all.
93
+ */
94
+ recordRows(table: string, column: string, values: readonly KeyValue[] | null): void;
89
95
  /** Mark a model's table as read without knowing anything about which rows. */
90
96
  widen(model: string): void;
91
97
  private push;
@@ -1 +1 @@
1
- {"version":3,"file":"read-keys.d.ts","sourceRoot":"","sources":["../../../src/server/api/read-keys.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,OAAO,EAAY,KAAK,QAAQ,EAAE,KAAK,OAAO,EAAE,KAAK,UAAU,EAAY,KAAK,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACpH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,YAAY,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC;AAEzD,mDAAmD;AACnD,eAAO,MAAM,GAAG,OAAW,CAAC;AAE5B;;;;;;;GAOG;AACH,MAAM,MAAM,OAAO,GACb;IAAE,IAAI,EAAE,KAAK,CAAA;CAAE,GACf;IAAE,IAAI,EAAE,IAAI,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,QAAQ,CAAA;CAAE,GAC/C;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,OAAO,EAAE,CAAA;CAAE,GACjC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,OAAO,EAAE,CAAA;CAAE,CAAC;AAmDzC,MAAM,WAAW,gBAAgB;IAC7B,OAAO,EAAE,cAAc,CAAC;CAC3B;AAED;;;;;;;GAOG;AACH,qBAAa,YAAY;IACrB,yEAAyE;IACzE,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA0D;IACnF,OAAO,CAAC,Q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CAmB3F;AAsFD,iEAAiE;AACjE,wBAAgB,YAAY,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,GAAG,IAAI,CAarE"}
@@ -138,6 +138,18 @@ class KeyCollector {
138
138
  }
139
139
  return out;
140
140
  }
141
+ /**
142
+ * Record a read of a table that is not a Prisma model — one of Nowity's
143
+ * own — whose rows were selected by `column IN values`. `null` for values
144
+ * means the read was not narrowed at all.
145
+ */
146
+ recordRows(table, column, values) {
147
+ if (values === null || values.length === 0 || values.length > MAX_IN) {
148
+ this.push(table, ANY_EXPR);
149
+ return;
150
+ }
151
+ this.push(table, some(values.map((value) => ({ kind: "eq", column, value }))));
152
+ }
141
153
  /** Mark a model's table as read without knowing anything about which rows. */
142
154
  widen(model) {
143
155
  this.push(model, ANY_EXPR);
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/server/api/runtime.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEnD,OAAO,EAAE,cAAc,EAAe,KAAK,SAAS,EAAE,MAAM,YAAY,CAAC;AAGzE,MAAM,WAAW,mBAAmB;IAChC,uCAAuC;IACvC,MAAM,EAAE,GAAG,CAAC;IACZ,gDAAgD;IAChD,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB;;;;;OAKG;IACH,EAAE,CAAC,EAAE,QAAQ,CAAC;IACd;;;;;;;;OAQG;IACH,QAAQ,CAAC,EAAE,QAAQ,EAAE,CAAC;IACtB;;;;;;OAMG;IACH,IAAI,CAAC,EAAE,QAAQ,CAAC;IAChB,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC;AAED,MAAM,WAAW,aAAa;IAC1B,GAAG,EAAE,QAAQ,CAAC;IACd,SAAS,EAAE,oBAAoB,CAAC;IAChC,2EAA2E;IAC3E,MAAM,EAAE,GAAG,CAAC;IACZ,OAAO,EAAE,cAAc,CAAC;CAC3B;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,mBAAmB,GAAG,aAAa,CAgC9E"}
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/server/api/runtime.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,oBAAoB,EAAkB,MAAM,OAAO,CAAC;AAC7D,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,UAAU,CAAC;AAInD,OAAO,EAAE,cAAc,EAAe,KAAK,SAAS,EAAE,MAAM,YAAY,CAAC;AAGzE,MAAM,WAAW,mBAAmB;IAChC,uCAAuC;IACvC,MAAM,EAAE,GAAG,CAAC;IACZ,gDAAgD;IAChD,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB;;;;;OAKG;IACH,EAAE,CAAC,EAAE,QAAQ,CAAC;IACd;;;;;;;;OAQG;IACH,QAAQ,CAAC,EAAE,QAAQ,EAAE,CAAC;IACtB;;;;;;OAMG;IACH,IAAI,CAAC,EAAE,QAAQ,CAAC;IAChB,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC;AAED,MAAM,WAAW,aAAa;IAC1B,GAAG,EAAE,QAAQ,CAAC;IACd,SAAS,EAAE,oBAAoB,CAAC;IAChC,2EAA2E;IAC3E,MAAM,EAAE,GAAG,CAAC;IACZ,OAAO,EAAE,cAAc,CAAC;CAC3B;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,mBAAmB,GAAG,aAAa,CA0C9E"}
@@ -20,11 +20,23 @@ const auth_1 = require("./auth");
20
20
  const db_1 = require("../db");
21
21
  const bridge_1 = require("./bridge");
22
22
  const execution_1 = require("./execution");
23
+ const presence_1 = require("./presence");
24
+ const scheduler_1 = require("./scheduler");
23
25
  const read_set_1 = require("./read-set");
24
26
  const tracked_client_1 = require("./tracked-client");
25
27
  function createNowityRuntime(config) {
26
28
  const tracker = new read_set_1.ReadSetTracker(config.datamodel ?? (0, read_set_1.datamodelOf)(config.prisma));
27
29
  const prisma = (0, tracked_client_1.trackReads)(config.prisma, tracker);
30
+ // Outside an execution the tracking client passes straight through, so it
31
+ // is as good a reader as the raw one — and, for the scheduler, writer — and
32
+ // keeps a single client in play.
33
+ const direct = {
34
+ query: async (text, values) => ({
35
+ rows: (await prisma.$queryRawUnsafe(text, ...(values ?? []))),
36
+ }),
37
+ };
38
+ (0, presence_1.bindPresenceReader)(direct);
39
+ (0, scheduler_1.bindSchedulerExecutor)(direct);
28
40
  if (config.db)
29
41
  (0, ironbean_1.take)(config.db).setFactory(() => (0, execution_1.ambientPrisma)());
30
42
  (0, ironbean_1.take)(auth_1.Authenticator).bindTo((config.auth ?? auth_1.AnonymousAuthenticator));