nowity 1.1.1 → 1.2.1

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
@@ -534,15 +534,11 @@ export const nowity = createNowityServer({
534
534
  db: Db,
535
535
  auth: CookieAuth,
536
536
  services: [DocumentApiImpl],
537
- changeSource: () =>
538
- new OutboxChangeSource({
539
- pool,
540
- // Stable per deployment slot, so a restart reclaims its own
541
- // watermark instead of leaving it to age out.
542
- consumerId: process.env.NODE_NAME,
543
- // Only set on the instances that should collect. Any of them may.
544
- pruneIntervalMs: 60_000,
545
- }),
537
+ outbox: {
538
+ // Stable per deployment slot, so a restart reclaims its own
539
+ // watermark instead of leaving it to age out.
540
+ consumerId: process.env.NODE_NAME,
541
+ },
546
542
  });
547
543
  ```
548
544
 
@@ -558,7 +554,11 @@ Three things follow from it being the database that coordinates:
558
554
  - **Retention waits for the slowest live reader.** `nowity.nowity_prune_outbox` deletes
559
555
  only what every consumer seen recently has passed. A consumer silent longer
560
556
  than the staleness window is treated as gone, so set it well above any pause a
561
- healthy process can take.
557
+ healthy process can take. The default outbox prunes once a minute
558
+ (`outbox: { pruneIntervalMs }`, `0` keeps every row), and a prune also drops
559
+ the rows of consumers it treats as gone — a crash or a restart that never said
560
+ goodbye does not stay in `nowity_consumer` for good. An `OutboxChangeSource`
561
+ built by hand deletes nothing unless given `pruneIntervalMs`.
562
562
 
563
563
  Scenario 22 runs two instances against one database and checks each of these.
564
564
 
@@ -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,OA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AAE,QAAQ,MAAM,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,CAAC;IAIvE;;;;;;;OAOG;IACH,QAAQ,CAAC,CAAC,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,CAAC;IAuB3C,OAAO,CAAC,IAAI;IAON,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC;YA0B7C,MAAM;IAepB;;;;;;OAMG;IACH,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,SAAS;IAehD,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IAK9B,OAAO,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IAK/B,OAAO,CAAC,eAAe;IAsBvB,OAAO,CAAC,UAAU;CAMrB"}
@@ -268,6 +268,16 @@ class NowityConnection {
268
268
  entry.timer = null;
269
269
  if (entry.refs > 0)
270
270
  return;
271
+ // Unheld is not unwanted while the first answer is still out: a render
272
+ // suspended on it retains only on commit, and it cannot commit until
273
+ // this answer arrives. Withdrawing the subscription now would leave it
274
+ // waiting for good. The grace period starts again once it settles, so
275
+ // a render that really was thrown away is still collected.
276
+ if (entry.loading) {
277
+ const again = () => this.scheduleRelease(entry);
278
+ entry.settled.then(again, again);
279
+ return;
280
+ }
271
281
  this.entries.delete(entry.key);
272
282
  entry.dispose();
273
283
  }, this.graceMs);
package/dist/index.d.ts CHANGED
@@ -21,7 +21,7 @@
21
21
  */
22
22
  export { api, contract, query, list, mutation, contractOf, endpointName, pageQuery, countQuery, type ApiManifest, type ContractMeta, type EndpointKind, type ListOptions, type MutationOptions, type QueryOptions, } from "./api/contract";
23
23
  export { Forbidden, Rejected, isForbidden, isRejected } from "./api/errors";
24
- export { createNowityServer, type NowityServer, type NowityServerConfig, } from "./server/api/configure";
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
27
  export { Authenticator, AnonymousAuthenticator } from "./server/api/auth";
@@ -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,EACH,kBAAkB,EAClB,KAAK,YAAY,EACjB,KAAK,kBAAkB,GAC1B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACH,mBAAmB,EACnB,KAAK,aAAa,EAClB,KAAK,mBAAmB,GAC3B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC1E,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAClE,YAAY,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EACH,SAAS,EACT,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,eAAe,GACvB,MAAM,wBAAwB,CAAC;AAEhC,oFAAoF;AACpF,OAAO,EACH,kBAAkB,EAClB,KAAK,yBAAyB,GACjC,MAAM,6CAA6C,CAAC;AACrD,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U,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.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.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; } });
@@ -55,6 +55,7 @@ Object.defineProperty(exports, "isRejected", { enumerable: true, get: function (
55
55
  // ---------------------------------------------------------------------- server
56
56
  var configure_1 = require("./server/api/configure");
57
57
  Object.defineProperty(exports, "createNowityServer", { enumerable: true, get: function () { return configure_1.createNowityServer; } });
58
+ Object.defineProperty(exports, "DEFAULT_PRUNE_INTERVAL_MS", { enumerable: true, get: function () { return configure_1.DEFAULT_PRUNE_INTERVAL_MS; } });
58
59
  var runtime_1 = require("./server/api/runtime");
59
60
  Object.defineProperty(exports, "createNowityRuntime", { enumerable: true, get: function () { return runtime_1.createNowityRuntime; } });
60
61
  var execution_1 = require("./server/api/execution");
@@ -10,11 +10,32 @@ export interface NowityServerConfig extends NowityRuntimeConfig {
10
10
  changeSource?: ChangeSource | (() => ChangeSource);
11
11
  /** Used for the default change source. Defaults to `DATABASE_URL`. */
12
12
  databaseUrl?: string;
13
+ /**
14
+ * Tuning of the default outbox change source; ignored when
15
+ * {@link changeSource} is given. Unlike a hand-built `OutboxChangeSource`,
16
+ * the default one prunes: an application that never chose a change source
17
+ * never chose to keep every change it ever made either.
18
+ */
19
+ outbox?: DefaultOutboxOptions;
13
20
  syncServer?: Omit<NowitySyncServerOptions, "engine">;
14
21
  /** See {@link SyncEngineOptions.narrowInvalidation}. On unless set. */
15
22
  narrowInvalidation?: boolean;
16
23
  onError?: (err: Error) => void;
17
24
  }
25
+ export interface DefaultOutboxOptions {
26
+ /** See `consumerId` of {@link OutboxChangeSource}. */
27
+ consumerId?: string;
28
+ /**
29
+ * See `pruneIntervalMs` of {@link OutboxChangeSource}. A minute unless
30
+ * set; `0` keeps every row. Safe on any number of nodes — a prune never
31
+ * passes the slowest live reader.
32
+ */
33
+ pruneIntervalMs?: number;
34
+ /** See `pruneStaleAfter` of {@link OutboxChangeSource}. */
35
+ pruneStaleAfter?: string;
36
+ }
37
+ /** How often the default outbox prunes. */
38
+ export declare const DEFAULT_PRUNE_INTERVAL_MS = 60000;
18
39
  export interface NowityServer extends NowityRuntime {
19
40
  engine: SyncEngine;
20
41
  server: NowitySyncServer;
@@ -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,sEAAsE;IACtE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,IAAI,CAAC,uBAAuB,EAAE,QAAQ,C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AAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,2DAA2D;IAC3D,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,2CAA2C;AAC3C,eAAO,MAAM,yBAAyB,QAAS,CAAC;AAEhD,MAAM,WAAW,YAAa,SAAQ,aAAa;IAC/C,MAAM,EAAE,UAAU,CAAC;IACnB,MAAM,EAAE,gBAAgB,CAAC;IACzB,sEAAsE;IACtE,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IACzB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACzB;AAoBD,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAoC3E"}
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_PRUNE_INTERVAL_MS = void 0;
3
4
  exports.createNowityServer = createNowityServer;
4
5
  /**
5
6
  * The sync process: the read runtime plus the change stream and the socket.
@@ -17,6 +18,8 @@ const sync_engine_1 = require("../sync-engine");
17
18
  const ws_server_1 = require("../ws-server");
18
19
  const auth_1 = require("./auth");
19
20
  const runtime_1 = require("./runtime");
21
+ /** How often the default outbox prunes. */
22
+ exports.DEFAULT_PRUNE_INTERVAL_MS = 60000;
20
23
  function resolveChangeSource(config) {
21
24
  if (typeof config.changeSource === "function")
22
25
  return config.changeSource();
@@ -29,7 +32,11 @@ function resolveChangeSource(config) {
29
32
  // Required lazily: an application that brings its own change source should
30
33
  // not be made to depend on `pg` for one it never uses.
31
34
  const { Pool } = require("pg");
32
- return new outbox_change_source_1.OutboxChangeSource({ pool: new Pool({ connectionString }) });
35
+ return new outbox_change_source_1.OutboxChangeSource({
36
+ pool: new Pool({ connectionString }),
37
+ ...config.outbox,
38
+ pruneIntervalMs: config.outbox?.pruneIntervalMs ?? exports.DEFAULT_PRUNE_INTERVAL_MS,
39
+ });
33
40
  }
34
41
  function createNowityServer(config) {
35
42
  const runtime = (0, runtime_1.createNowityRuntime)(config);
@@ -6,5 +6,5 @@
6
6
  * bundler has been through the module. Idempotent, so it runs at every boot;
7
7
  * paste it into a migration instead if the schema is managed that way.
8
8
  */
9
- export declare const NOWITY_SETUP_SQL = "-- Nowity change capture: outbox + authorization epochs + mutation bookkeeping.\n--\n-- Everything lives in its own schema, `nowity`. The application's schema is the\n-- application's: a Prisma `db push` compares `public` against schema.prisma and\n-- would offer to drop tables it did not declare.\n\nCREATE SCHEMA IF NOT EXISTS nowity;\n\n-- Up to 1.0 the tables and functions lived in `public`. Tables move with their\n-- data; the capture function moves too, because every tracked table's trigger\n-- points at it by oid \u2014 moving it keeps them firing, dropping it would take them\n-- all with it. The rest is recreated below, so the old copies just go.\nDO $$\nDECLARE\n v_table text;\nBEGIN\n FOREACH v_table IN ARRAY ARRAY['nowity_outbox', 'nowity_scope_epoch', 'nowity_consumer', 'nowity_client'] LOOP\n IF to_regclass('public.' || v_table) IS NOT NULL AND to_regclass('nowity.' || v_table) IS NULL THEN\n EXECUTE format('ALTER TABLE public.%I SET SCHEMA nowity', v_table);\n END IF;\n END LOOP;\n IF to_regprocedure('public.nowity_capture()') IS NOT NULL\n AND to_regprocedure('nowity.nowity_capture()') IS NULL THEN\n ALTER FUNCTION public.nowity_capture() SET SCHEMA nowity;\n END IF;\nEND;\n$$;\n\nDROP FUNCTION IF EXISTS public.nowity_track(regclass, text[]);\nDROP FUNCTION IF EXISTS public.nowity_untrack(regclass);\nDROP FUNCTION IF EXISTS public.nowity_bump_epoch(text);\nDROP FUNCTION IF EXISTS public.nowity_bump_epoch(text, text);\nDROP FUNCTION IF EXISTS public.nowity_consumer_seen(text, text);\nDROP FUNCTION IF EXISTS public.nowity_consumer_forget(text);\nDROP FUNCTION IF EXISTS public.nowity_prune_outbox(interval);\n--\n-- Design notes (see \"Implementa\u010Dn\u00ED zad\u00E1n\u00ED\" \u00A75.1 in the design doc):\n--\n-- The outbox is filled by a trigger, not by application code. That way *any*\n-- writer \u2014 Prisma, a raw SQL migration, a psql session \u2014 produces change events,\n-- and the application never has to remember to publish them.\n--\n-- `xid` is the transaction id assigned by `pg_current_xact_id()`. It is what\n-- makes gap-free reading possible: a `bigserial` alone is not enough, because\n-- sequence values are handed out before commit, so a reader ordering by `seq`\n-- can walk past a row belonging to a transaction that commits later. Readers\n-- therefore only consume rows whose `xid` is below the oldest in-flight\n-- transaction id (see OutboxChangeSource).\n\nCREATE TABLE IF NOT EXISTS nowity.nowity_outbox (\n seq bigserial PRIMARY KEY,\n xid xid8 NOT NULL DEFAULT pg_current_xact_id(),\n tbl text NOT NULL,\n op text NOT NULL CHECK (op IN ('insert', 'update', 'delete')),\n pk jsonb NOT NULL,\n before jsonb,\n after jsonb,\n client_id text,\n mutation_id bigint,\n created_at timestamptz NOT NULL DEFAULT clock_timestamp()\n);\n\nCREATE INDEX IF NOT EXISTS nowity_outbox_xid_seq_idx ON nowity.nowity_outbox (xid, seq);\n\n-- Authorization epoch per scope (typically one project / tenant / workspace).\n-- Bumped whenever a row in a permission table changes; every snapshot and patch\n-- carries the epoch it was computed under.\n--\n-- `last_position` is what makes the bump happen once per *change* rather than\n-- once per reader. Several sync processes see the same transaction and each\n-- would otherwise increment this row, so one permission change would cost N\n-- writes to one very hot row \u2014 and an at-least-once replay would inflate it on a\n-- single process too.\nCREATE TABLE IF NOT EXISTS nowity.nowity_scope_epoch (\n scope text PRIMARY KEY,\n version bigint NOT NULL DEFAULT 1,\n last_position text\n);\n\nALTER TABLE nowity.nowity_scope_epoch ADD COLUMN IF NOT EXISTS last_position text;\n\n-- Where each sync process has read the outbox up to.\n--\n-- Only ever a retention watermark: a process that restarts resumes from the\n-- current transaction horizon, never from here, so a cursor left behind by a\n-- crashed node can hold rows back but can never make one skip a change.\nCREATE TABLE IF NOT EXISTS nowity.nowity_consumer (\n consumer_id text PRIMARY KEY,\n cursor_xid xid8 NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\n-- Last mutation of each client the server has durably processed. Written in the\n-- same transaction as the mutation itself, so it can never disagree with the\n-- data.\n--\n-- `session_token` is which connection currently owns the id. Two connections\n-- sharing one client id is a write-losing bug, and within a single process the\n-- engine can see both and complain \u2014 with several sync processes neither can see\n-- the other's sessions, and the collision is otherwise perfectly silent: both\n-- sides keep numbering from one, each takes the other's mutation for a replay of\n-- its own, and every second write is acknowledged and discarded. The token moves\n-- that argument into the one place both processes share.\nCREATE TABLE IF NOT EXISTS nowity.nowity_client (\n client_id text PRIMARY KEY,\n last_mutation_id bigint NOT NULL DEFAULT 0,\n session_token text,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nALTER TABLE nowity.nowity_client ADD COLUMN IF NOT EXISTS session_token text;\n\n-- Capture trigger. TG_ARGV[0] is the primary key column list, e.g. '{id}'.\nCREATE OR REPLACE FUNCTION nowity.nowity_capture() RETURNS trigger AS $$\nDECLARE\n v_pk_cols text[] := COALESCE(TG_ARGV[0]::text[], ARRAY['id']);\n v_before jsonb := CASE WHEN TG_OP = 'INSERT' THEN NULL ELSE to_jsonb(OLD) END;\n v_after jsonb := CASE WHEN TG_OP = 'DELETE' THEN NULL ELSE to_jsonb(NEW) END;\n v_source jsonb := COALESCE(v_after, v_before);\n v_pk jsonb;\nBEGIN\n SELECT jsonb_object_agg(col, v_source -> col) INTO v_pk\n FROM unnest(v_pk_cols) AS col;\n\n INSERT INTO nowity.nowity_outbox (tbl, op, pk, before, after, client_id, mutation_id)\n VALUES (\n TG_TABLE_NAME,\n lower(TG_OP),\n v_pk,\n v_before,\n v_after,\n NULLIF(current_setting('nowity.client_id', true), ''),\n NULLIF(current_setting('nowity.mutation_id', true), '')::bigint\n );\n\n -- Wake the sync engine up at commit. The payload is intentionally tiny; it\n -- is a doorbell, not a data channel (NOTIFY payloads are capped at 8000 B).\n PERFORM pg_notify('nowity_change', TG_TABLE_NAME);\n\n RETURN NULL; -- AFTER trigger, return value is ignored\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Attach change capture to a table.\nCREATE OR REPLACE FUNCTION nowity.nowity_track(p_table regclass, p_pk text[] DEFAULT ARRAY['id'])\nRETURNS void AS $$\nBEGIN\n EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);\n EXECUTE format(\n 'CREATE TRIGGER nowity_capture_trg AFTER INSERT OR UPDATE OR DELETE ON %s '\n 'FOR EACH ROW EXECUTE FUNCTION nowity.nowity_capture(%L)',\n p_table, p_pk\n );\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION nowity.nowity_untrack(p_table regclass) RETURNS void AS $$\nBEGIN\n EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);\nEND;\n$$ LANGUAGE plpgsql;\n\n-- The single-argument form is gone: left in place it would be an overload of the\n-- one below, and `nowity.nowity_bump_epoch($1)` would stop resolving.\nDROP FUNCTION IF EXISTS nowity.nowity_bump_epoch(text);\n\n-- Increment the authorization epoch of a scope and return the current value.\n--\n-- With a position, the increment happens only the first time that position is\n-- seen for the scope. Whichever process gets there first does the write and the\n-- rest read the same answer, because the `ON CONFLICT` takes a row lock and they\n-- queue behind it.\n--\n-- Skipping the increment on a replay is not a missed invalidation: the epoch had\n-- already moved when the position was first handled, and a process replaying it\n-- still recomputes its subscriptions and stamps them with the value it reads\n-- here.\nCREATE OR REPLACE FUNCTION nowity.nowity_bump_epoch(p_scope text, p_position text DEFAULT NULL)\nRETURNS bigint AS $$\nDECLARE\n v_version bigint;\nBEGIN\n INSERT INTO nowity.nowity_scope_epoch AS e (scope, version, last_position)\n VALUES (p_scope, 1, p_position)\n ON CONFLICT (scope) DO UPDATE\n SET version = e.version\n + CASE\n WHEN p_position IS NULL THEN 1\n WHEN e.last_position IS DISTINCT FROM p_position THEN 1\n ELSE 0\n END,\n last_position = COALESCE(p_position, e.last_position)\n RETURNING version INTO v_version;\n RETURN v_version;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Record how far a consumer has read, for retention only.\nCREATE OR REPLACE FUNCTION nowity.nowity_consumer_seen(p_consumer text, p_cursor text)\nRETURNS void AS $$\nBEGIN\n INSERT INTO nowity.nowity_consumer (consumer_id, cursor_xid)\n VALUES (p_consumer, p_cursor::xid8)\n ON CONFLICT (consumer_id) DO UPDATE\n SET cursor_xid = EXCLUDED.cursor_xid, updated_at = now();\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION nowity.nowity_consumer_forget(p_consumer text) RETURNS void AS $$\nBEGIN\n DELETE FROM nowity.nowity_consumer WHERE consumer_id = p_consumer;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Delete outbox rows every live consumer has already read.\n--\n-- \"Live\" is a wall-clock judgement, and it is the only unsafe part of retention:\n-- a consumer quiet for longer than `p_stale_after` is treated as gone, and rows\n-- it had not reached may be deleted. It resumes from the transaction horizon\n-- rather than from its old cursor, so it does not read a hole \u2014 it simply never\n-- learns about those changes and its clients keep whatever they had until\n-- something else touches it. Set the interval well above any pause a healthy\n-- process can take.\n--\n-- With no live consumers at all this deletes nothing. An empty table means \"the\n-- readers have not registered yet\", not \"nobody will ever read this\".\nCREATE OR REPLACE FUNCTION nowity.nowity_prune_outbox(p_stale_after interval DEFAULT '1 hour')\nRETURNS bigint AS $$\nDECLARE\n v_min xid8;\n v_deleted bigint;\nBEGIN\n -- `ORDER BY \u2026 LIMIT 1` rather than `min()`: xid8 has the comparison\n -- operators but not the aggregate.\n SELECT cursor_xid INTO v_min\n FROM nowity.nowity_consumer\n WHERE updated_at > now() - p_stale_after\n ORDER BY cursor_xid\n LIMIT 1;\n\n IF v_min IS NULL THEN\n RETURN 0;\n END IF;\n\n DELETE FROM nowity.nowity_outbox WHERE xid <= v_min;\n GET DIAGNOSTICS v_deleted = ROW_COUNT;\n RETURN v_deleted;\nEND;\n$$ LANGUAGE plpgsql;\n";
9
+ export declare const NOWITY_SETUP_SQL = "-- Nowity change capture: outbox + authorization epochs + mutation bookkeeping.\n--\n-- Everything lives in its own schema, `nowity`. The application's schema is the\n-- application's: a Prisma `db push` compares `public` against schema.prisma and\n-- would offer to drop tables it did not declare.\n\nCREATE SCHEMA IF NOT EXISTS nowity;\n\n-- Up to 1.0 the tables and functions lived in `public`. Tables move with their\n-- data; the capture function moves too, because every tracked table's trigger\n-- points at it by oid \u2014 moving it keeps them firing, dropping it would take them\n-- all with it. The rest is recreated below, so the old copies just go.\nDO $$\nDECLARE\n v_table text;\nBEGIN\n FOREACH v_table IN ARRAY ARRAY['nowity_outbox', 'nowity_scope_epoch', 'nowity_consumer', 'nowity_client'] LOOP\n IF to_regclass('public.' || v_table) IS NOT NULL AND to_regclass('nowity.' || v_table) IS NULL THEN\n EXECUTE format('ALTER TABLE public.%I SET SCHEMA nowity', v_table);\n END IF;\n END LOOP;\n IF to_regprocedure('public.nowity_capture()') IS NOT NULL\n AND to_regprocedure('nowity.nowity_capture()') IS NULL THEN\n ALTER FUNCTION public.nowity_capture() SET SCHEMA nowity;\n END IF;\nEND;\n$$;\n\nDROP FUNCTION IF EXISTS public.nowity_track(regclass, text[]);\nDROP FUNCTION IF EXISTS public.nowity_untrack(regclass);\nDROP FUNCTION IF EXISTS public.nowity_bump_epoch(text);\nDROP FUNCTION IF EXISTS public.nowity_bump_epoch(text, text);\nDROP FUNCTION IF EXISTS public.nowity_consumer_seen(text, text);\nDROP FUNCTION IF EXISTS public.nowity_consumer_forget(text);\nDROP FUNCTION IF EXISTS public.nowity_prune_outbox(interval);\n--\n-- Design notes (see \"Implementa\u010Dn\u00ED zad\u00E1n\u00ED\" \u00A75.1 in the design doc):\n--\n-- The outbox is filled by a trigger, not by application code. That way *any*\n-- writer \u2014 Prisma, a raw SQL migration, a psql session \u2014 produces change events,\n-- and the application never has to remember to publish them.\n--\n-- `xid` is the transaction id assigned by `pg_current_xact_id()`. It is what\n-- makes gap-free reading possible: a `bigserial` alone is not enough, because\n-- sequence values are handed out before commit, so a reader ordering by `seq`\n-- can walk past a row belonging to a transaction that commits later. Readers\n-- therefore only consume rows whose `xid` is below the oldest in-flight\n-- transaction id (see OutboxChangeSource).\n\nCREATE TABLE IF NOT EXISTS nowity.nowity_outbox (\n seq bigserial PRIMARY KEY,\n xid xid8 NOT NULL DEFAULT pg_current_xact_id(),\n tbl text NOT NULL,\n op text NOT NULL CHECK (op IN ('insert', 'update', 'delete')),\n pk jsonb NOT NULL,\n before jsonb,\n after jsonb,\n client_id text,\n mutation_id bigint,\n created_at timestamptz NOT NULL DEFAULT clock_timestamp()\n);\n\nCREATE INDEX IF NOT EXISTS nowity_outbox_xid_seq_idx ON nowity.nowity_outbox (xid, seq);\n\n-- Authorization epoch per scope (typically one project / tenant / workspace).\n-- Bumped whenever a row in a permission table changes; every snapshot and patch\n-- carries the epoch it was computed under.\n--\n-- `last_position` is what makes the bump happen once per *change* rather than\n-- once per reader. Several sync processes see the same transaction and each\n-- would otherwise increment this row, so one permission change would cost N\n-- writes to one very hot row \u2014 and an at-least-once replay would inflate it on a\n-- single process too.\nCREATE TABLE IF NOT EXISTS nowity.nowity_scope_epoch (\n scope text PRIMARY KEY,\n version bigint NOT NULL DEFAULT 1,\n last_position text\n);\n\nALTER TABLE nowity.nowity_scope_epoch ADD COLUMN IF NOT EXISTS last_position text;\n\n-- Where each sync process has read the outbox up to.\n--\n-- Only ever a retention watermark: a process that restarts resumes from the\n-- current transaction horizon, never from here, so a cursor left behind by a\n-- crashed node can hold rows back but can never make one skip a change.\nCREATE TABLE IF NOT EXISTS nowity.nowity_consumer (\n consumer_id text PRIMARY KEY,\n cursor_xid xid8 NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\n-- Last mutation of each client the server has durably processed. Written in the\n-- same transaction as the mutation itself, so it can never disagree with the\n-- data.\n--\n-- `session_token` is which connection currently owns the id. Two connections\n-- sharing one client id is a write-losing bug, and within a single process the\n-- engine can see both and complain \u2014 with several sync processes neither can see\n-- the other's sessions, and the collision is otherwise perfectly silent: both\n-- sides keep numbering from one, each takes the other's mutation for a replay of\n-- its own, and every second write is acknowledged and discarded. The token moves\n-- that argument into the one place both processes share.\nCREATE TABLE IF NOT EXISTS nowity.nowity_client (\n client_id text PRIMARY KEY,\n last_mutation_id bigint NOT NULL DEFAULT 0,\n session_token text,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nALTER TABLE nowity.nowity_client ADD COLUMN IF NOT EXISTS session_token text;\n\n-- Capture trigger. TG_ARGV[0] is the primary key column list, e.g. '{id}'.\nCREATE OR REPLACE FUNCTION nowity.nowity_capture() RETURNS trigger AS $$\nDECLARE\n v_pk_cols text[] := COALESCE(TG_ARGV[0]::text[], ARRAY['id']);\n v_before jsonb := CASE WHEN TG_OP = 'INSERT' THEN NULL ELSE to_jsonb(OLD) END;\n v_after jsonb := CASE WHEN TG_OP = 'DELETE' THEN NULL ELSE to_jsonb(NEW) END;\n v_source jsonb := COALESCE(v_after, v_before);\n v_pk jsonb;\nBEGIN\n SELECT jsonb_object_agg(col, v_source -> col) INTO v_pk\n FROM unnest(v_pk_cols) AS col;\n\n INSERT INTO nowity.nowity_outbox (tbl, op, pk, before, after, client_id, mutation_id)\n VALUES (\n TG_TABLE_NAME,\n lower(TG_OP),\n v_pk,\n v_before,\n v_after,\n NULLIF(current_setting('nowity.client_id', true), ''),\n NULLIF(current_setting('nowity.mutation_id', true), '')::bigint\n );\n\n -- Wake the sync engine up at commit. The payload is intentionally tiny; it\n -- is a doorbell, not a data channel (NOTIFY payloads are capped at 8000 B).\n PERFORM pg_notify('nowity_change', TG_TABLE_NAME);\n\n RETURN NULL; -- AFTER trigger, return value is ignored\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Attach change capture to a table.\nCREATE OR REPLACE FUNCTION nowity.nowity_track(p_table regclass, p_pk text[] DEFAULT ARRAY['id'])\nRETURNS void AS $$\nBEGIN\n EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);\n EXECUTE format(\n 'CREATE TRIGGER nowity_capture_trg AFTER INSERT OR UPDATE OR DELETE ON %s '\n 'FOR EACH ROW EXECUTE FUNCTION nowity.nowity_capture(%L)',\n p_table, p_pk\n );\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION nowity.nowity_untrack(p_table regclass) RETURNS void AS $$\nBEGIN\n EXECUTE format('DROP TRIGGER IF EXISTS nowity_capture_trg ON %s', p_table);\nEND;\n$$ LANGUAGE plpgsql;\n\n-- The single-argument form is gone: left in place it would be an overload of the\n-- one below, and `nowity.nowity_bump_epoch($1)` would stop resolving.\nDROP FUNCTION IF EXISTS nowity.nowity_bump_epoch(text);\n\n-- Increment the authorization epoch of a scope and return the current value.\n--\n-- With a position, the increment happens only the first time that position is\n-- seen for the scope. Whichever process gets there first does the write and the\n-- rest read the same answer, because the `ON CONFLICT` takes a row lock and they\n-- queue behind it.\n--\n-- Skipping the increment on a replay is not a missed invalidation: the epoch had\n-- already moved when the position was first handled, and a process replaying it\n-- still recomputes its subscriptions and stamps them with the value it reads\n-- here.\nCREATE OR REPLACE FUNCTION nowity.nowity_bump_epoch(p_scope text, p_position text DEFAULT NULL)\nRETURNS bigint AS $$\nDECLARE\n v_version bigint;\nBEGIN\n INSERT INTO nowity.nowity_scope_epoch AS e (scope, version, last_position)\n VALUES (p_scope, 1, p_position)\n ON CONFLICT (scope) DO UPDATE\n SET version = e.version\n + CASE\n WHEN p_position IS NULL THEN 1\n WHEN e.last_position IS DISTINCT FROM p_position THEN 1\n ELSE 0\n END,\n last_position = COALESCE(p_position, e.last_position)\n RETURNING version INTO v_version;\n RETURN v_version;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Record how far a consumer has read, for retention only.\nCREATE OR REPLACE FUNCTION nowity.nowity_consumer_seen(p_consumer text, p_cursor text)\nRETURNS void AS $$\nBEGIN\n INSERT INTO nowity.nowity_consumer (consumer_id, cursor_xid)\n VALUES (p_consumer, p_cursor::xid8)\n ON CONFLICT (consumer_id) DO UPDATE\n SET cursor_xid = EXCLUDED.cursor_xid, updated_at = now();\nEND;\n$$ LANGUAGE plpgsql;\n\nCREATE OR REPLACE FUNCTION nowity.nowity_consumer_forget(p_consumer text) RETURNS void AS $$\nBEGIN\n DELETE FROM nowity.nowity_consumer WHERE consumer_id = p_consumer;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Delete outbox rows every live consumer has already read.\n--\n-- \"Live\" is a wall-clock judgement, and it is the only unsafe part of retention:\n-- a consumer quiet for longer than `p_stale_after` is treated as gone, and rows\n-- it had not reached may be deleted. It resumes from the transaction horizon\n-- rather than from its old cursor, so it does not read a hole \u2014 it simply never\n-- learns about those changes and its clients keep whatever they had until\n-- something else touches it. Set the interval well above any pause a healthy\n-- process can take.\n--\n-- With no live consumers at all this deletes nothing. An empty table means \"the\n-- readers have not registered yet\", not \"nobody will ever read this\".\nCREATE OR REPLACE FUNCTION nowity.nowity_prune_outbox(p_stale_after interval DEFAULT '1 hour')\nRETURNS bigint AS $$\nDECLARE\n v_min xid8;\n v_deleted bigint;\nBEGIN\n -- A consumer silent past the window is already treated as gone below; its\n -- row goes too, or every crashed process \u2014 and every restart that did not\n -- get to say goodbye \u2014 would stay in the table for good. One that was only\n -- paused writes its row back on its next `nowity_consumer_seen`.\n DELETE FROM nowity.nowity_consumer WHERE updated_at <= now() - p_stale_after;\n\n -- `ORDER BY \u2026 LIMIT 1` rather than `min()`: xid8 has the comparison\n -- operators but not the aggregate.\n SELECT cursor_xid INTO v_min\n FROM nowity.nowity_consumer\n WHERE updated_at > now() - p_stale_after\n ORDER BY cursor_xid\n LIMIT 1;\n\n IF v_min IS NULL THEN\n RETURN 0;\n END IF;\n\n DELETE FROM nowity.nowity_outbox WHERE xid <= v_min;\n GET DIAGNOSTICS v_deleted = ROW_COUNT;\n RETURN v_deleted;\nEND;\n$$ LANGUAGE plpgsql;\n";
10
10
  //# sourceMappingURL=setup-sql.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"setup-sql.d.ts","sourceRoot":"","sources":["../../src/server/setup-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,2pVAyP5B,CAAC"}
1
+ {"version":3,"file":"setup-sql.d.ts","sourceRoot":"","sources":["../../src/server/setup-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,kjWA+P5B,CAAC"}
@@ -241,6 +241,12 @@ DECLARE
241
241
  v_min xid8;
242
242
  v_deleted bigint;
243
243
  BEGIN
244
+ -- A consumer silent past the window is already treated as gone below; its
245
+ -- row goes too, or every crashed process — and every restart that did not
246
+ -- get to say goodbye — would stay in the table for good. One that was only
247
+ -- paused writes its row back on its next \`nowity_consumer_seen\`.
248
+ DELETE FROM nowity.nowity_consumer WHERE updated_at <= now() - p_stale_after;
249
+
244
250
  -- \`ORDER BY … LIMIT 1\` rather than \`min()\`: xid8 has the comparison
245
251
  -- operators but not the aggregate.
246
252
  SELECT cursor_xid INTO v_min
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nowity",
3
- "version": "1.1.1",
3
+ "version": "1.2.1",
4
4
  "description": "Realtime object model over PostgreSQL: logical change stream, query-scoped subscriptions, MobX identity map",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {