nowity 1.2.1 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +316 -3
- package/dist/client/connection.d.ts +2 -0
- package/dist/client/connection.d.ts.map +1 -1
- package/dist/client/connection.js +13 -0
- package/dist/client/nowity-client.d.ts +23 -0
- package/dist/client/nowity-client.d.ts.map +1 -1
- package/dist/client/nowity-client.js +29 -1
- package/dist/client/overlay.d.ts +52 -2
- package/dist/client/overlay.d.ts.map +1 -1
- package/dist/client/overlay.js +43 -0
- package/dist/client.d.ts +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/core/protocol.d.ts +20 -1
- package/dist/core/protocol.d.ts.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -1
- package/dist/server/api/collector.d.ts.map +1 -1
- package/dist/server/api/collector.js +4 -1
- package/dist/server/api/configure.d.ts +24 -0
- package/dist/server/api/configure.d.ts.map +1 -1
- package/dist/server/api/configure.js +51 -1
- package/dist/server/api/execution.d.ts +9 -0
- package/dist/server/api/execution.d.ts.map +1 -1
- package/dist/server/api/execution.js +19 -0
- package/dist/server/api/presence.d.ts +66 -0
- package/dist/server/api/presence.d.ts.map +1 -0
- package/dist/server/api/presence.js +181 -0
- package/dist/server/api/read-keys.d.ts +6 -0
- package/dist/server/api/read-keys.d.ts.map +1 -1
- package/dist/server/api/read-keys.js +12 -0
- package/dist/server/api/runtime.d.ts.map +1 -1
- package/dist/server/api/runtime.js +12 -0
- package/dist/server/api/scheduler.d.ts +122 -0
- package/dist/server/api/scheduler.d.ts.map +1 -0
- package/dist/server/api/scheduler.js +217 -0
- package/dist/server/change-source/wal-change-source.d.ts.map +1 -1
- package/dist/server/change-source/wal-change-source.js +10 -1
- package/dist/server/leader.d.ts +138 -0
- package/dist/server/leader.d.ts.map +1 -0
- package/dist/server/leader.js +342 -0
- package/dist/server/presence.d.ts +217 -0
- package/dist/server/presence.d.ts.map +1 -0
- package/dist/server/presence.js +428 -0
- package/dist/server/scheduler.d.ts +195 -0
- package/dist/server/scheduler.d.ts.map +1 -0
- package/dist/server/scheduler.js +432 -0
- package/dist/server/setup-sql.d.ts +1 -1
- package/dist/server/setup-sql.d.ts.map +1 -1
- package/dist/server/setup-sql.js +547 -0
- package/dist/server/sync-engine.d.ts +22 -1
- package/dist/server/sync-engine.d.ts.map +1 -1
- package/dist/server/sync-engine.js +30 -1
- package/dist/server/ws-server.d.ts +22 -0
- package/dist/server/ws-server.d.ts.map +1 -1
- package/dist/server/ws-server.js +81 -1
- package/package.json +1 -1
|
@@ -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 -- 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";
|
|
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\n-- ------------------------------------------------------------------ presence\n--\n-- Who is connected, kept in the database rather than in a process, because no\n-- single sync process can answer it: a user with two tabs may have one socket on\n-- each of two nodes, and a node that dies takes its own memory with it.\n--\n-- Three tables, with deliberately different visibility:\n--\n-- - `nowity_node` is a lease per sync process. A process that stops renewing it\n-- is dead, and its connections are reaped by whichever process is leader.\n-- - `nowity_connection` is one row per open, authenticated socket. Never tracked:\n-- a second tab opening or closing is not news to anybody as long as the user\n-- stays online, and a capture trigger here would wake every query that reads\n-- presence on every page load.\n-- - `nowity_presence` is one row per user, and the only one live queries see.\n-- Its capture triggers fire only when `online` or `contexts` actually change;\n-- the rest of the row is bookkeeping (grace, delivery watermark, retries) that\n-- moves often and means nothing to a reader.\n--\n-- Everything is written with the database clock (`now()`), so the grace period\n-- and the leases are measured by one clock however skewed the nodes' are.\n--\n-- Nothing here is filled unless the sync server is started with `presence`\n-- configured; the tables exist either way, so reading presence is always legal.\n\nCREATE TABLE IF NOT EXISTS nowity.nowity_node (\n node_id text PRIMARY KEY,\n started_at timestamptz NOT NULL DEFAULT now(),\n lease_until timestamptz NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS nowity.nowity_connection (\n connection_id text PRIMARY KEY,\n user_id text NOT NULL,\n node_id text NOT NULL,\n connected_at timestamptz NOT NULL DEFAULT now(),\n meta jsonb NOT NULL DEFAULT '{}'::jsonb,\n context jsonb\n);\n\nCREATE INDEX IF NOT EXISTS nowity_connection_user_idx ON nowity.nowity_connection (user_id);\nCREATE INDEX IF NOT EXISTS nowity_connection_node_idx ON nowity.nowity_connection (node_id);\n\n-- `last_disconnect_at` is when the user's last connection went away, i.e. when\n-- the grace period started; null while any connection is open.\n--\n-- `offline_at` is the moment of the last online \u2192 offline transition, and\n-- `handled_at` the `offline_at` whose offline handlers last completed. The two\n-- differing (while the user is still offline) is what \"a delivery is owed\" means;\n-- `next_attempt_at` is when it may next be attempted, null when none is owed.\nCREATE TABLE IF NOT EXISTS nowity.nowity_presence (\n user_id text PRIMARY KEY,\n online boolean NOT NULL,\n online_since timestamptz,\n offline_at timestamptz,\n last_disconnect_at timestamptz,\n contexts jsonb NOT NULL DEFAULT '[]'::jsonb,\n handled_at timestamptz,\n attempts integer NOT NULL DEFAULT 0,\n next_attempt_at timestamptz,\n last_error text,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE INDEX IF NOT EXISTS nowity_presence_online_idx\n ON nowity.nowity_presence (user_id) WHERE online;\nCREATE INDEX IF NOT EXISTS nowity_presence_grace_idx\n ON nowity.nowity_presence (last_disconnect_at) WHERE online AND last_disconnect_at IS NOT NULL;\nCREATE INDEX IF NOT EXISTS nowity_presence_pending_idx\n ON nowity.nowity_presence (next_attempt_at) WHERE next_attempt_at IS NOT NULL;\n\n-- Capture for presence, narrower than `nowity_track`: an update reaches the\n-- outbox only when something a reader can see changed. Created only when absent,\n-- so a boot does not take an exclusive lock on a table every connection writes.\nDO $$\nBEGIN\n IF NOT EXISTS (\n SELECT 1 FROM pg_trigger\n WHERE tgname = 'nowity_presence_capture_trg'\n AND tgrelid = 'nowity.nowity_presence'::regclass\n ) THEN\n CREATE TRIGGER nowity_presence_capture_trg\n AFTER INSERT OR DELETE ON nowity.nowity_presence\n FOR EACH ROW EXECUTE FUNCTION nowity.nowity_capture('{user_id}');\n END IF;\n IF NOT EXISTS (\n SELECT 1 FROM pg_trigger\n WHERE tgname = 'nowity_presence_change_trg'\n AND tgrelid = 'nowity.nowity_presence'::regclass\n ) THEN\n CREATE TRIGGER nowity_presence_change_trg\n AFTER UPDATE ON nowity.nowity_presence\n FOR EACH ROW\n WHEN (OLD.online IS DISTINCT FROM NEW.online OR OLD.contexts IS DISTINCT FROM NEW.contexts)\n EXECUTE FUNCTION nowity.nowity_capture('{user_id}');\n END IF;\nEXCEPTION WHEN duplicate_object THEN\n -- Another process booting at the same moment got there first.\n NULL;\nEND;\n$$;\n\n-- Bring a user's row in line with their connections. The caller holds the row\n-- lock. Returns whether any connection is left.\n--\n-- Writes only when something moved, which is what keeps a tab without a context\n-- opening and closing from producing an outbox row.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_settle(p_user text) RETURNS boolean AS $$\nDECLARE\n v_any boolean;\n v_contexts jsonb;\nBEGIN\n SELECT EXISTS (SELECT 1 FROM nowity.nowity_connection WHERE user_id = p_user) INTO v_any;\n\n IF NOT v_any THEN\n -- The last connection went; the grace period starts. Its contexts stay\n -- for now: a reload is about to put them back, and clearing them in\n -- between would be two changes for readers where there was none. The\n -- offline transition clears them.\n UPDATE nowity.nowity_presence AS p\n SET last_disconnect_at = now(), updated_at = now()\n WHERE p.user_id = p_user AND p.online AND p.last_disconnect_at IS NULL;\n RETURN false;\n END IF;\n\n SELECT COALESCE(jsonb_agg(DISTINCT context ORDER BY context), '[]'::jsonb) INTO v_contexts\n FROM nowity.nowity_connection\n WHERE user_id = p_user AND context IS NOT NULL;\n\n UPDATE nowity.nowity_presence AS p\n SET contexts = v_contexts, last_disconnect_at = NULL, updated_at = now()\n WHERE p.user_id = p_user\n AND p.online\n AND (p.contexts IS DISTINCT FROM v_contexts OR p.last_disconnect_at IS NOT NULL);\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Record an open connection. Returns true when it made the user online.\n--\n-- The presence row is locked before the connection is written, and every other\n-- function here does the same, so a connect and a disconnect of one user on two\n-- nodes are ordered rather than interleaved \u2014 the disconnect cannot count the\n-- connections, miss one still being inserted and start the grace period.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_connect(\n p_connection text, p_user text, p_node text, p_meta jsonb, p_context jsonb\n) RETURNS boolean AS $$\nDECLARE\n v_was boolean;\nBEGIN\n INSERT INTO nowity.nowity_presence (user_id, online, online_since)\n VALUES (p_user, true, now())\n ON CONFLICT (user_id) DO NOTHING;\n\n IF FOUND THEN\n v_was := false;\n ELSE\n SELECT online INTO v_was FROM nowity.nowity_presence WHERE user_id = p_user FOR UPDATE;\n -- Coming back after the grace period ran out. A delivery still owed for\n -- the offline period that just ended is dropped: the handler would act\n -- on a user who is, by now, online.\n UPDATE nowity.nowity_presence AS p\n SET online = true,\n online_since = CASE WHEN v_was THEN p.online_since ELSE now() END,\n last_disconnect_at = NULL,\n next_attempt_at = CASE WHEN v_was THEN p.next_attempt_at ELSE NULL END,\n updated_at = now()\n WHERE p.user_id = p_user\n AND (NOT p.online OR p.last_disconnect_at IS NOT NULL);\n END IF;\n\n INSERT INTO nowity.nowity_connection (connection_id, user_id, node_id, meta, context)\n VALUES (p_connection, p_user, p_node, COALESCE(p_meta, '{}'::jsonb), p_context)\n ON CONFLICT (connection_id) DO UPDATE\n SET node_id = EXCLUDED.node_id, meta = EXCLUDED.meta, context = EXCLUDED.context;\n\n -- The context arrives with the connection (it is part of the client's\n -- hello), so a reload that puts back what was there before changes nothing.\n PERFORM nowity.nowity_presence_settle(p_user);\n RETURN NOT v_was;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Forget a connection. Returns whether the user has any left, null when the\n-- connection was not known (already reaped, or never recorded).\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_disconnect(p_connection text) RETURNS boolean AS $$\nDECLARE\n v_user text;\nBEGIN\n SELECT user_id INTO v_user FROM nowity.nowity_connection WHERE connection_id = p_connection;\n IF NOT FOUND THEN\n RETURN NULL;\n END IF;\n PERFORM 1 FROM nowity.nowity_presence WHERE user_id = v_user FOR UPDATE;\n DELETE FROM nowity.nowity_connection WHERE connection_id = p_connection;\n RETURN nowity.nowity_presence_settle(v_user);\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Set what one connection is looking at. Returns false when the connection is\n-- not known.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_set_context(p_connection text, p_context jsonb)\nRETURNS boolean AS $$\nDECLARE\n v_user text;\nBEGIN\n SELECT user_id INTO v_user FROM nowity.nowity_connection WHERE connection_id = p_connection;\n IF NOT FOUND THEN\n RETURN false;\n END IF;\n PERFORM 1 FROM nowity.nowity_presence WHERE user_id = v_user FOR UPDATE;\n UPDATE nowity.nowity_connection SET context = p_context\n WHERE connection_id = p_connection AND context IS DISTINCT FROM p_context;\n PERFORM nowity.nowity_presence_settle(v_user);\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Renew a node's lease. Returns false when the row was not there \u2014 a fresh\n-- node, or one whose lease ran out and whose connections were reaped while it\n-- was not looking, which then has to record them again.\nCREATE OR REPLACE FUNCTION nowity.nowity_node_renew(p_node text, p_lease interval) RETURNS boolean AS $$\nBEGIN\n UPDATE nowity.nowity_node SET lease_until = now() + p_lease WHERE node_id = p_node;\n IF FOUND THEN\n RETURN true;\n END IF;\n INSERT INTO nowity.nowity_node (node_id, lease_until) VALUES (p_node, now() + p_lease)\n ON CONFLICT (node_id) DO UPDATE SET lease_until = EXCLUDED.lease_until;\n RETURN false;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Drop the given node (or every node whose lease ran out, when p_node is null)\n-- together with its connections \u2014 and, for the reaper, the connections of nodes\n-- nobody registered \u2014 and start the grace period of the users left with none.\n-- Returns how many connections went.\n--\n-- The node rows go first, and that order is what keeps a live node from losing\n-- connections silently. Deleting a row locks it, so a renewal of that node waits\n-- for this transaction and then finds no row: it answers `false`, and its\n-- process records every connection again. Deleting connections first would let a\n-- renewal slip in between, find the lease still there, extend it, and keep a node\n-- that had just lost some of its connections.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_drop_nodes(p_node text) RETURNS integer AS $$\nDECLARE\n v_dead text[];\n v_user text;\n v_dropped integer := 0;\n v_count integer;\nBEGIN\n IF p_node IS NULL THEN\n WITH dead AS (\n DELETE FROM nowity.nowity_node WHERE lease_until < now() RETURNING node_id\n )\n SELECT COALESCE(array_agg(node_id), ARRAY[]::text[]) INTO v_dead FROM dead;\n ELSE\n DELETE FROM nowity.nowity_node WHERE node_id = p_node;\n v_dead := ARRAY[p_node];\n END IF;\n\n -- Users first, locked in a fixed order, so two reapers (a leader that has\n -- just lost its lock and the one that took it) cannot deadlock each other.\n FOR v_user IN\n SELECT DISTINCT c.user_id\n FROM nowity.nowity_connection c\n WHERE c.node_id = ANY (v_dead)\n OR (p_node IS NULL\n AND NOT EXISTS (SELECT 1 FROM nowity.nowity_node n WHERE n.node_id = c.node_id))\n ORDER BY c.user_id\n LOOP\n PERFORM 1 FROM nowity.nowity_presence WHERE user_id = v_user FOR UPDATE;\n DELETE FROM nowity.nowity_connection c\n WHERE c.user_id = v_user\n AND (c.node_id = ANY (v_dead)\n OR (p_node IS NULL\n AND NOT EXISTS (SELECT 1 FROM nowity.nowity_node n WHERE n.node_id = c.node_id)));\n GET DIAGNOSTICS v_count = ROW_COUNT;\n v_dropped := v_dropped + v_count;\n PERFORM nowity.nowity_presence_settle(v_user);\n END LOOP;\n\n RETURN v_dropped;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- One pass of the reaper: connections of dead nodes go, and users whose grace\n-- ran out with nothing open become offline. Returns those transitions.\n--\n-- The transition is a conditional update, so it happens once however many\n-- processes run this at the same time: the second one re-reads the row after the\n-- first commits, finds it offline, and skips it. Leadership only keeps the\n-- reaper from being run N times for nothing; it is not what makes it correct.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_reap(p_grace interval)\nRETURNS TABLE (user_id text, offline_at timestamptz) AS $$\n#variable_conflict use_column\nBEGIN\n PERFORM nowity.nowity_presence_drop_nodes(NULL);\n\n RETURN QUERY\n UPDATE nowity.nowity_presence AS p\n SET online = false,\n offline_at = now(),\n last_disconnect_at = NULL,\n contexts = '[]'::jsonb,\n attempts = 0,\n next_attempt_at = now(),\n last_error = NULL,\n updated_at = now()\n WHERE p.online\n AND p.last_disconnect_at IS NOT NULL\n AND p.last_disconnect_at <= now() - p_grace\n AND NOT EXISTS (SELECT 1 FROM nowity.nowity_connection c WHERE c.user_id = p.user_id)\n RETURNING p.user_id, p.offline_at;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Claim offline deliveries that are due. A claim is a lease: `next_attempt_at`\n-- moves past the handler timeout, so a process that dies holding it hands the\n-- delivery to the next pass instead of losing it.\nCREATE OR REPLACE FUNCTION nowity.nowity_presence_claim(p_limit integer, p_hold interval)\nRETURNS TABLE (user_id text, offline_at timestamptz, online_since timestamptz, attempts integer) AS $$\n#variable_conflict use_column\nBEGIN\n RETURN QUERY\n UPDATE nowity.nowity_presence AS p\n SET next_attempt_at = now() + p_hold,\n attempts = p.attempts + 1,\n updated_at = now()\n WHERE p.user_id IN (\n SELECT q.user_id FROM nowity.nowity_presence q\n WHERE q.next_attempt_at IS NOT NULL\n AND q.next_attempt_at <= now()\n AND NOT q.online\n ORDER BY q.next_attempt_at\n LIMIT p_limit\n FOR UPDATE SKIP LOCKED)\n RETURNING p.user_id, p.offline_at, p.online_since, p.attempts;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- ----------------------------------------------------------------- scheduler\n--\n-- Jobs to run at a given time, by whichever sync process leads the scheduler.\n--\n-- Never tracked. A job is the application's bookkeeping, not something a\n-- reader sees, and the typical caller \u2014 a game moving its turn deadline after\n-- every move \u2014 writes here on the hottest path there is. A capture trigger\n-- would put an outbox row and a fan-out pass behind each of those writes.\n--\n-- `run_at` is when the job was asked for, `next_at` when it may next be\n-- attempted \u2014 the same until an attempt fails and backs off. A claimed job is\n-- `running` and leased until `locked_until`; a process that dies holding it\n-- hands it to the next claim once the lease runs out. `claim_id` names the\n-- claim, and finishing an attempt is conditional on it: a job scheduled again\n-- under the same key while an old attempt runs is a different job, and that\n-- attempt's outcome must not touch it.\n--\n-- `interval_ms` set makes the job periodic: finishing it moves it on instead\n-- of deleting it.\nCREATE TABLE IF NOT EXISTS nowity.nowity_job (\n key text PRIMARY KEY,\n handler text NOT NULL,\n payload jsonb,\n run_at timestamptz NOT NULL,\n next_at timestamptz NOT NULL,\n state text NOT NULL DEFAULT 'pending',\n attempts integer NOT NULL DEFAULT 0,\n max_attempts integer,\n interval_ms bigint,\n claim_id text,\n locked_until timestamptz,\n last_error text,\n created_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE INDEX IF NOT EXISTS nowity_job_due_idx\n ON nowity.nowity_job (next_at) WHERE state = 'pending';\nCREATE INDEX IF NOT EXISTS nowity_job_lease_idx\n ON nowity.nowity_job (locked_until) WHERE state = 'running';\n\n-- Schedule a job, or schedule it again: one statement either way.\n--\n-- Wakes the leader (`NOTIFY nowity_scheduler`, delivered at commit) only when\n-- the job comes before every other one still to come. A later one needs no\n-- wakeup \u2014 the leader already sleeps until something earlier \u2014 and a\n-- notification is not free: committing one takes a lock every notifying\n-- transaction queues on. Jobs already overdue do not count: the leader is either\n-- busy with them, and asks again as each finishes, or has no handler for them\n-- and is not waiting on them at all. Returns whether it notified.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_schedule(\n p_key text, p_handler text, p_payload jsonb, p_run_at timestamptz, p_max_attempts integer\n) RETURNS boolean AS $$\nDECLARE\n v_first timestamptz;\nBEGIN\n SELECT min(next_at) INTO v_first FROM nowity.nowity_job\n WHERE state = 'pending' AND next_at > now() AND key <> p_key;\n\n INSERT INTO nowity.nowity_job (key, handler, payload, run_at, next_at, max_attempts)\n VALUES (p_key, p_handler, p_payload, p_run_at, p_run_at, p_max_attempts)\n ON CONFLICT (key) DO UPDATE\n SET handler = EXCLUDED.handler,\n payload = EXCLUDED.payload,\n run_at = EXCLUDED.run_at,\n next_at = EXCLUDED.next_at,\n max_attempts = EXCLUDED.max_attempts,\n state = 'pending',\n attempts = 0,\n interval_ms = NULL,\n claim_id = NULL,\n locked_until = NULL,\n last_error = NULL;\n\n IF v_first IS NULL OR p_run_at < v_first THEN\n PERFORM pg_notify('nowity_scheduler', '');\n RETURN true;\n END IF;\n RETURN false;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Move a job to another time, keeping what it carries. A failed job comes back\n-- to life. Returns false when there is no such job.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_reschedule(p_key text, p_run_at timestamptz)\nRETURNS boolean AS $$\nDECLARE\n v_first timestamptz;\nBEGIN\n SELECT min(next_at) INTO v_first FROM nowity.nowity_job\n WHERE state = 'pending' AND next_at > now() AND key <> p_key;\n\n UPDATE nowity.nowity_job\n SET run_at = p_run_at, next_at = p_run_at, state = 'pending', attempts = 0,\n claim_id = NULL, locked_until = NULL, last_error = NULL\n WHERE key = p_key;\n IF NOT FOUND THEN\n RETURN false;\n END IF;\n\n IF v_first IS NULL OR p_run_at < v_first THEN\n PERFORM pg_notify('nowity_scheduler', '');\n END IF;\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Claim jobs that are due, and jobs whose lease ran out, for the given handlers\n-- (a JSON array of names: array parameters do not travel the same way through\n-- every adapter). Jobs of a handler this process does not know stay where they\n-- are, for a process that does; so do the keys in `p_skip` \u2014 those whose\n-- previous attempt is still running in the claiming process \u2014 untouched, with\n-- no attempt spent on them.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_claim(\n p_handlers jsonb, p_skip jsonb, p_limit integer, p_hold interval, p_claim text\n) RETURNS TABLE (\n key text, handler text, payload jsonb, run_at timestamptz, attempts integer,\n max_attempts integer, interval_ms double precision, lag_ms double precision\n) AS $$\n#variable_conflict use_column\nBEGIN\n RETURN QUERY\n UPDATE nowity.nowity_job AS j\n SET state = 'running',\n attempts = j.attempts + 1,\n claim_id = p_claim,\n locked_until = now() + p_hold\n WHERE j.key IN (\n SELECT q.key FROM nowity.nowity_job q\n WHERE q.handler IN (SELECT jsonb_array_elements_text(p_handlers))\n AND q.key NOT IN (SELECT jsonb_array_elements_text(p_skip))\n AND ((q.state = 'pending' AND q.next_at <= now())\n OR (q.state = 'running' AND q.locked_until <= now()))\n ORDER BY CASE WHEN q.state = 'pending' THEN q.next_at ELSE q.locked_until END\n LIMIT p_limit\n FOR UPDATE SKIP LOCKED)\n RETURNING j.key, j.handler, j.payload, j.run_at, j.attempts, j.max_attempts,\n j.interval_ms::float8, (EXTRACT(EPOCH FROM now() - j.run_at) * 1000)::float8;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- Milliseconds until the given handlers next have something to do \u2014 a job\n-- coming due or a lease running out \u2014 negative when it is already overdue,\n-- null when there is nothing at all.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_next(p_handlers jsonb) RETURNS double precision AS $$\n SELECT (EXTRACT(EPOCH FROM LEAST(\n (SELECT min(next_at) FROM nowity.nowity_job\n WHERE state = 'pending' AND handler IN (SELECT jsonb_array_elements_text(p_handlers))),\n (SELECT min(locked_until) FROM nowity.nowity_job\n WHERE state = 'running' AND handler IN (SELECT jsonb_array_elements_text(p_handlers)))\n ) - now()) * 1000)::float8;\n$$ LANGUAGE sql STABLE;\n\n-- An attempt went through. A one-off job is done and goes; a periodic one moves\n-- on by its interval \u2014 from when it was due rather than from now, so it does not\n-- drift, but never into the past, so a late run is not followed by a burst of\n-- the ones it missed. Returns false when the claim was no longer the job's.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_done(p_key text, p_claim text) RETURNS boolean AS $$\nDECLARE\n v_next timestamptz;\nBEGIN\n DELETE FROM nowity.nowity_job WHERE key = p_key AND claim_id = p_claim AND interval_ms IS NULL;\n IF FOUND THEN\n RETURN true;\n END IF;\n\n SELECT GREATEST(run_at + interval_ms * interval '1 millisecond', now()) INTO v_next\n FROM nowity.nowity_job WHERE key = p_key AND claim_id = p_claim FOR UPDATE;\n IF NOT FOUND THEN\n RETURN false;\n END IF;\n UPDATE nowity.nowity_job\n SET state = 'pending', run_at = v_next, next_at = v_next, attempts = 0,\n claim_id = NULL, locked_until = NULL, last_error = NULL\n WHERE key = p_key;\n RETURN true;\nEND;\n$$ LANGUAGE plpgsql;\n\n-- An attempt failed. With attempts left it is tried again after `p_delay`;\n-- without, a one-off job is `failed` and stays for someone to look at (or to\n-- reschedule), and a periodic one gives up this run and waits for its next.\n-- Returns false when the claim was no longer the job's.\nCREATE OR REPLACE FUNCTION nowity.nowity_job_fail(\n p_key text, p_claim text, p_error text, p_delay interval, p_final boolean\n) RETURNS boolean AS $$\nBEGIN\n IF p_final THEN\n UPDATE nowity.nowity_job AS j\n SET state = CASE WHEN j.interval_ms IS NULL THEN 'failed' ELSE 'pending' END,\n run_at = CASE WHEN j.interval_ms IS NULL THEN j.run_at\n ELSE GREATEST(j.run_at + j.interval_ms * interval '1 millisecond', now()) END,\n next_at = CASE WHEN j.interval_ms IS NULL THEN j.next_at\n ELSE GREATEST(j.run_at + j.interval_ms * interval '1 millisecond', now()) END,\n attempts = CASE WHEN j.interval_ms IS NULL THEN j.attempts ELSE 0 END,\n claim_id = NULL, locked_until = NULL, last_error = p_error\n WHERE j.key = p_key AND j.claim_id = p_claim;\n ELSE\n UPDATE nowity.nowity_job\n SET state = 'pending', next_at = now() + p_delay,\n claim_id = NULL, locked_until = NULL, last_error = p_error\n WHERE key = p_key AND claim_id = p_claim;\n END IF;\n RETURN FOUND;\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,
|
|
1
|
+
{"version":3,"file":"setup-sql.d.ts","sourceRoot":"","sources":["../../src/server/setup-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,mzmCAkyB5B,CAAC"}
|
package/dist/server/setup-sql.js
CHANGED
|
@@ -264,4 +264,551 @@ BEGIN
|
|
|
264
264
|
RETURN v_deleted;
|
|
265
265
|
END;
|
|
266
266
|
$$ LANGUAGE plpgsql;
|
|
267
|
+
|
|
268
|
+
-- ------------------------------------------------------------------ presence
|
|
269
|
+
--
|
|
270
|
+
-- Who is connected, kept in the database rather than in a process, because no
|
|
271
|
+
-- single sync process can answer it: a user with two tabs may have one socket on
|
|
272
|
+
-- each of two nodes, and a node that dies takes its own memory with it.
|
|
273
|
+
--
|
|
274
|
+
-- Three tables, with deliberately different visibility:
|
|
275
|
+
--
|
|
276
|
+
-- - \`nowity_node\` is a lease per sync process. A process that stops renewing it
|
|
277
|
+
-- is dead, and its connections are reaped by whichever process is leader.
|
|
278
|
+
-- - \`nowity_connection\` is one row per open, authenticated socket. Never tracked:
|
|
279
|
+
-- a second tab opening or closing is not news to anybody as long as the user
|
|
280
|
+
-- stays online, and a capture trigger here would wake every query that reads
|
|
281
|
+
-- presence on every page load.
|
|
282
|
+
-- - \`nowity_presence\` is one row per user, and the only one live queries see.
|
|
283
|
+
-- Its capture triggers fire only when \`online\` or \`contexts\` actually change;
|
|
284
|
+
-- the rest of the row is bookkeeping (grace, delivery watermark, retries) that
|
|
285
|
+
-- moves often and means nothing to a reader.
|
|
286
|
+
--
|
|
287
|
+
-- Everything is written with the database clock (\`now()\`), so the grace period
|
|
288
|
+
-- and the leases are measured by one clock however skewed the nodes' are.
|
|
289
|
+
--
|
|
290
|
+
-- Nothing here is filled unless the sync server is started with \`presence\`
|
|
291
|
+
-- configured; the tables exist either way, so reading presence is always legal.
|
|
292
|
+
|
|
293
|
+
CREATE TABLE IF NOT EXISTS nowity.nowity_node (
|
|
294
|
+
node_id text PRIMARY KEY,
|
|
295
|
+
started_at timestamptz NOT NULL DEFAULT now(),
|
|
296
|
+
lease_until timestamptz NOT NULL
|
|
297
|
+
);
|
|
298
|
+
|
|
299
|
+
CREATE TABLE IF NOT EXISTS nowity.nowity_connection (
|
|
300
|
+
connection_id text PRIMARY KEY,
|
|
301
|
+
user_id text NOT NULL,
|
|
302
|
+
node_id text NOT NULL,
|
|
303
|
+
connected_at timestamptz NOT NULL DEFAULT now(),
|
|
304
|
+
meta jsonb NOT NULL DEFAULT '{}'::jsonb,
|
|
305
|
+
context jsonb
|
|
306
|
+
);
|
|
307
|
+
|
|
308
|
+
CREATE INDEX IF NOT EXISTS nowity_connection_user_idx ON nowity.nowity_connection (user_id);
|
|
309
|
+
CREATE INDEX IF NOT EXISTS nowity_connection_node_idx ON nowity.nowity_connection (node_id);
|
|
310
|
+
|
|
311
|
+
-- \`last_disconnect_at\` is when the user's last connection went away, i.e. when
|
|
312
|
+
-- the grace period started; null while any connection is open.
|
|
313
|
+
--
|
|
314
|
+
-- \`offline_at\` is the moment of the last online → offline transition, and
|
|
315
|
+
-- \`handled_at\` the \`offline_at\` whose offline handlers last completed. The two
|
|
316
|
+
-- differing (while the user is still offline) is what "a delivery is owed" means;
|
|
317
|
+
-- \`next_attempt_at\` is when it may next be attempted, null when none is owed.
|
|
318
|
+
CREATE TABLE IF NOT EXISTS nowity.nowity_presence (
|
|
319
|
+
user_id text PRIMARY KEY,
|
|
320
|
+
online boolean NOT NULL,
|
|
321
|
+
online_since timestamptz,
|
|
322
|
+
offline_at timestamptz,
|
|
323
|
+
last_disconnect_at timestamptz,
|
|
324
|
+
contexts jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
325
|
+
handled_at timestamptz,
|
|
326
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
327
|
+
next_attempt_at timestamptz,
|
|
328
|
+
last_error text,
|
|
329
|
+
updated_at timestamptz NOT NULL DEFAULT now()
|
|
330
|
+
);
|
|
331
|
+
|
|
332
|
+
CREATE INDEX IF NOT EXISTS nowity_presence_online_idx
|
|
333
|
+
ON nowity.nowity_presence (user_id) WHERE online;
|
|
334
|
+
CREATE INDEX IF NOT EXISTS nowity_presence_grace_idx
|
|
335
|
+
ON nowity.nowity_presence (last_disconnect_at) WHERE online AND last_disconnect_at IS NOT NULL;
|
|
336
|
+
CREATE INDEX IF NOT EXISTS nowity_presence_pending_idx
|
|
337
|
+
ON nowity.nowity_presence (next_attempt_at) WHERE next_attempt_at IS NOT NULL;
|
|
338
|
+
|
|
339
|
+
-- Capture for presence, narrower than \`nowity_track\`: an update reaches the
|
|
340
|
+
-- outbox only when something a reader can see changed. Created only when absent,
|
|
341
|
+
-- so a boot does not take an exclusive lock on a table every connection writes.
|
|
342
|
+
DO $$
|
|
343
|
+
BEGIN
|
|
344
|
+
IF NOT EXISTS (
|
|
345
|
+
SELECT 1 FROM pg_trigger
|
|
346
|
+
WHERE tgname = 'nowity_presence_capture_trg'
|
|
347
|
+
AND tgrelid = 'nowity.nowity_presence'::regclass
|
|
348
|
+
) THEN
|
|
349
|
+
CREATE TRIGGER nowity_presence_capture_trg
|
|
350
|
+
AFTER INSERT OR DELETE ON nowity.nowity_presence
|
|
351
|
+
FOR EACH ROW EXECUTE FUNCTION nowity.nowity_capture('{user_id}');
|
|
352
|
+
END IF;
|
|
353
|
+
IF NOT EXISTS (
|
|
354
|
+
SELECT 1 FROM pg_trigger
|
|
355
|
+
WHERE tgname = 'nowity_presence_change_trg'
|
|
356
|
+
AND tgrelid = 'nowity.nowity_presence'::regclass
|
|
357
|
+
) THEN
|
|
358
|
+
CREATE TRIGGER nowity_presence_change_trg
|
|
359
|
+
AFTER UPDATE ON nowity.nowity_presence
|
|
360
|
+
FOR EACH ROW
|
|
361
|
+
WHEN (OLD.online IS DISTINCT FROM NEW.online OR OLD.contexts IS DISTINCT FROM NEW.contexts)
|
|
362
|
+
EXECUTE FUNCTION nowity.nowity_capture('{user_id}');
|
|
363
|
+
END IF;
|
|
364
|
+
EXCEPTION WHEN duplicate_object THEN
|
|
365
|
+
-- Another process booting at the same moment got there first.
|
|
366
|
+
NULL;
|
|
367
|
+
END;
|
|
368
|
+
$$;
|
|
369
|
+
|
|
370
|
+
-- Bring a user's row in line with their connections. The caller holds the row
|
|
371
|
+
-- lock. Returns whether any connection is left.
|
|
372
|
+
--
|
|
373
|
+
-- Writes only when something moved, which is what keeps a tab without a context
|
|
374
|
+
-- opening and closing from producing an outbox row.
|
|
375
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_presence_settle(p_user text) RETURNS boolean AS $$
|
|
376
|
+
DECLARE
|
|
377
|
+
v_any boolean;
|
|
378
|
+
v_contexts jsonb;
|
|
379
|
+
BEGIN
|
|
380
|
+
SELECT EXISTS (SELECT 1 FROM nowity.nowity_connection WHERE user_id = p_user) INTO v_any;
|
|
381
|
+
|
|
382
|
+
IF NOT v_any THEN
|
|
383
|
+
-- The last connection went; the grace period starts. Its contexts stay
|
|
384
|
+
-- for now: a reload is about to put them back, and clearing them in
|
|
385
|
+
-- between would be two changes for readers where there was none. The
|
|
386
|
+
-- offline transition clears them.
|
|
387
|
+
UPDATE nowity.nowity_presence AS p
|
|
388
|
+
SET last_disconnect_at = now(), updated_at = now()
|
|
389
|
+
WHERE p.user_id = p_user AND p.online AND p.last_disconnect_at IS NULL;
|
|
390
|
+
RETURN false;
|
|
391
|
+
END IF;
|
|
392
|
+
|
|
393
|
+
SELECT COALESCE(jsonb_agg(DISTINCT context ORDER BY context), '[]'::jsonb) INTO v_contexts
|
|
394
|
+
FROM nowity.nowity_connection
|
|
395
|
+
WHERE user_id = p_user AND context IS NOT NULL;
|
|
396
|
+
|
|
397
|
+
UPDATE nowity.nowity_presence AS p
|
|
398
|
+
SET contexts = v_contexts, last_disconnect_at = NULL, updated_at = now()
|
|
399
|
+
WHERE p.user_id = p_user
|
|
400
|
+
AND p.online
|
|
401
|
+
AND (p.contexts IS DISTINCT FROM v_contexts OR p.last_disconnect_at IS NOT NULL);
|
|
402
|
+
RETURN true;
|
|
403
|
+
END;
|
|
404
|
+
$$ LANGUAGE plpgsql;
|
|
405
|
+
|
|
406
|
+
-- Record an open connection. Returns true when it made the user online.
|
|
407
|
+
--
|
|
408
|
+
-- The presence row is locked before the connection is written, and every other
|
|
409
|
+
-- function here does the same, so a connect and a disconnect of one user on two
|
|
410
|
+
-- nodes are ordered rather than interleaved — the disconnect cannot count the
|
|
411
|
+
-- connections, miss one still being inserted and start the grace period.
|
|
412
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_presence_connect(
|
|
413
|
+
p_connection text, p_user text, p_node text, p_meta jsonb, p_context jsonb
|
|
414
|
+
) RETURNS boolean AS $$
|
|
415
|
+
DECLARE
|
|
416
|
+
v_was boolean;
|
|
417
|
+
BEGIN
|
|
418
|
+
INSERT INTO nowity.nowity_presence (user_id, online, online_since)
|
|
419
|
+
VALUES (p_user, true, now())
|
|
420
|
+
ON CONFLICT (user_id) DO NOTHING;
|
|
421
|
+
|
|
422
|
+
IF FOUND THEN
|
|
423
|
+
v_was := false;
|
|
424
|
+
ELSE
|
|
425
|
+
SELECT online INTO v_was FROM nowity.nowity_presence WHERE user_id = p_user FOR UPDATE;
|
|
426
|
+
-- Coming back after the grace period ran out. A delivery still owed for
|
|
427
|
+
-- the offline period that just ended is dropped: the handler would act
|
|
428
|
+
-- on a user who is, by now, online.
|
|
429
|
+
UPDATE nowity.nowity_presence AS p
|
|
430
|
+
SET online = true,
|
|
431
|
+
online_since = CASE WHEN v_was THEN p.online_since ELSE now() END,
|
|
432
|
+
last_disconnect_at = NULL,
|
|
433
|
+
next_attempt_at = CASE WHEN v_was THEN p.next_attempt_at ELSE NULL END,
|
|
434
|
+
updated_at = now()
|
|
435
|
+
WHERE p.user_id = p_user
|
|
436
|
+
AND (NOT p.online OR p.last_disconnect_at IS NOT NULL);
|
|
437
|
+
END IF;
|
|
438
|
+
|
|
439
|
+
INSERT INTO nowity.nowity_connection (connection_id, user_id, node_id, meta, context)
|
|
440
|
+
VALUES (p_connection, p_user, p_node, COALESCE(p_meta, '{}'::jsonb), p_context)
|
|
441
|
+
ON CONFLICT (connection_id) DO UPDATE
|
|
442
|
+
SET node_id = EXCLUDED.node_id, meta = EXCLUDED.meta, context = EXCLUDED.context;
|
|
443
|
+
|
|
444
|
+
-- The context arrives with the connection (it is part of the client's
|
|
445
|
+
-- hello), so a reload that puts back what was there before changes nothing.
|
|
446
|
+
PERFORM nowity.nowity_presence_settle(p_user);
|
|
447
|
+
RETURN NOT v_was;
|
|
448
|
+
END;
|
|
449
|
+
$$ LANGUAGE plpgsql;
|
|
450
|
+
|
|
451
|
+
-- Forget a connection. Returns whether the user has any left, null when the
|
|
452
|
+
-- connection was not known (already reaped, or never recorded).
|
|
453
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_presence_disconnect(p_connection text) RETURNS boolean AS $$
|
|
454
|
+
DECLARE
|
|
455
|
+
v_user text;
|
|
456
|
+
BEGIN
|
|
457
|
+
SELECT user_id INTO v_user FROM nowity.nowity_connection WHERE connection_id = p_connection;
|
|
458
|
+
IF NOT FOUND THEN
|
|
459
|
+
RETURN NULL;
|
|
460
|
+
END IF;
|
|
461
|
+
PERFORM 1 FROM nowity.nowity_presence WHERE user_id = v_user FOR UPDATE;
|
|
462
|
+
DELETE FROM nowity.nowity_connection WHERE connection_id = p_connection;
|
|
463
|
+
RETURN nowity.nowity_presence_settle(v_user);
|
|
464
|
+
END;
|
|
465
|
+
$$ LANGUAGE plpgsql;
|
|
466
|
+
|
|
467
|
+
-- Set what one connection is looking at. Returns false when the connection is
|
|
468
|
+
-- not known.
|
|
469
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_presence_set_context(p_connection text, p_context jsonb)
|
|
470
|
+
RETURNS boolean AS $$
|
|
471
|
+
DECLARE
|
|
472
|
+
v_user text;
|
|
473
|
+
BEGIN
|
|
474
|
+
SELECT user_id INTO v_user FROM nowity.nowity_connection WHERE connection_id = p_connection;
|
|
475
|
+
IF NOT FOUND THEN
|
|
476
|
+
RETURN false;
|
|
477
|
+
END IF;
|
|
478
|
+
PERFORM 1 FROM nowity.nowity_presence WHERE user_id = v_user FOR UPDATE;
|
|
479
|
+
UPDATE nowity.nowity_connection SET context = p_context
|
|
480
|
+
WHERE connection_id = p_connection AND context IS DISTINCT FROM p_context;
|
|
481
|
+
PERFORM nowity.nowity_presence_settle(v_user);
|
|
482
|
+
RETURN true;
|
|
483
|
+
END;
|
|
484
|
+
$$ LANGUAGE plpgsql;
|
|
485
|
+
|
|
486
|
+
-- Renew a node's lease. Returns false when the row was not there — a fresh
|
|
487
|
+
-- node, or one whose lease ran out and whose connections were reaped while it
|
|
488
|
+
-- was not looking, which then has to record them again.
|
|
489
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_node_renew(p_node text, p_lease interval) RETURNS boolean AS $$
|
|
490
|
+
BEGIN
|
|
491
|
+
UPDATE nowity.nowity_node SET lease_until = now() + p_lease WHERE node_id = p_node;
|
|
492
|
+
IF FOUND THEN
|
|
493
|
+
RETURN true;
|
|
494
|
+
END IF;
|
|
495
|
+
INSERT INTO nowity.nowity_node (node_id, lease_until) VALUES (p_node, now() + p_lease)
|
|
496
|
+
ON CONFLICT (node_id) DO UPDATE SET lease_until = EXCLUDED.lease_until;
|
|
497
|
+
RETURN false;
|
|
498
|
+
END;
|
|
499
|
+
$$ LANGUAGE plpgsql;
|
|
500
|
+
|
|
501
|
+
-- Drop the given node (or every node whose lease ran out, when p_node is null)
|
|
502
|
+
-- together with its connections — and, for the reaper, the connections of nodes
|
|
503
|
+
-- nobody registered — and start the grace period of the users left with none.
|
|
504
|
+
-- Returns how many connections went.
|
|
505
|
+
--
|
|
506
|
+
-- The node rows go first, and that order is what keeps a live node from losing
|
|
507
|
+
-- connections silently. Deleting a row locks it, so a renewal of that node waits
|
|
508
|
+
-- for this transaction and then finds no row: it answers \`false\`, and its
|
|
509
|
+
-- process records every connection again. Deleting connections first would let a
|
|
510
|
+
-- renewal slip in between, find the lease still there, extend it, and keep a node
|
|
511
|
+
-- that had just lost some of its connections.
|
|
512
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_presence_drop_nodes(p_node text) RETURNS integer AS $$
|
|
513
|
+
DECLARE
|
|
514
|
+
v_dead text[];
|
|
515
|
+
v_user text;
|
|
516
|
+
v_dropped integer := 0;
|
|
517
|
+
v_count integer;
|
|
518
|
+
BEGIN
|
|
519
|
+
IF p_node IS NULL THEN
|
|
520
|
+
WITH dead AS (
|
|
521
|
+
DELETE FROM nowity.nowity_node WHERE lease_until < now() RETURNING node_id
|
|
522
|
+
)
|
|
523
|
+
SELECT COALESCE(array_agg(node_id), ARRAY[]::text[]) INTO v_dead FROM dead;
|
|
524
|
+
ELSE
|
|
525
|
+
DELETE FROM nowity.nowity_node WHERE node_id = p_node;
|
|
526
|
+
v_dead := ARRAY[p_node];
|
|
527
|
+
END IF;
|
|
528
|
+
|
|
529
|
+
-- Users first, locked in a fixed order, so two reapers (a leader that has
|
|
530
|
+
-- just lost its lock and the one that took it) cannot deadlock each other.
|
|
531
|
+
FOR v_user IN
|
|
532
|
+
SELECT DISTINCT c.user_id
|
|
533
|
+
FROM nowity.nowity_connection c
|
|
534
|
+
WHERE c.node_id = ANY (v_dead)
|
|
535
|
+
OR (p_node IS NULL
|
|
536
|
+
AND NOT EXISTS (SELECT 1 FROM nowity.nowity_node n WHERE n.node_id = c.node_id))
|
|
537
|
+
ORDER BY c.user_id
|
|
538
|
+
LOOP
|
|
539
|
+
PERFORM 1 FROM nowity.nowity_presence WHERE user_id = v_user FOR UPDATE;
|
|
540
|
+
DELETE FROM nowity.nowity_connection c
|
|
541
|
+
WHERE c.user_id = v_user
|
|
542
|
+
AND (c.node_id = ANY (v_dead)
|
|
543
|
+
OR (p_node IS NULL
|
|
544
|
+
AND NOT EXISTS (SELECT 1 FROM nowity.nowity_node n WHERE n.node_id = c.node_id)));
|
|
545
|
+
GET DIAGNOSTICS v_count = ROW_COUNT;
|
|
546
|
+
v_dropped := v_dropped + v_count;
|
|
547
|
+
PERFORM nowity.nowity_presence_settle(v_user);
|
|
548
|
+
END LOOP;
|
|
549
|
+
|
|
550
|
+
RETURN v_dropped;
|
|
551
|
+
END;
|
|
552
|
+
$$ LANGUAGE plpgsql;
|
|
553
|
+
|
|
554
|
+
-- One pass of the reaper: connections of dead nodes go, and users whose grace
|
|
555
|
+
-- ran out with nothing open become offline. Returns those transitions.
|
|
556
|
+
--
|
|
557
|
+
-- The transition is a conditional update, so it happens once however many
|
|
558
|
+
-- processes run this at the same time: the second one re-reads the row after the
|
|
559
|
+
-- first commits, finds it offline, and skips it. Leadership only keeps the
|
|
560
|
+
-- reaper from being run N times for nothing; it is not what makes it correct.
|
|
561
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_presence_reap(p_grace interval)
|
|
562
|
+
RETURNS TABLE (user_id text, offline_at timestamptz) AS $$
|
|
563
|
+
#variable_conflict use_column
|
|
564
|
+
BEGIN
|
|
565
|
+
PERFORM nowity.nowity_presence_drop_nodes(NULL);
|
|
566
|
+
|
|
567
|
+
RETURN QUERY
|
|
568
|
+
UPDATE nowity.nowity_presence AS p
|
|
569
|
+
SET online = false,
|
|
570
|
+
offline_at = now(),
|
|
571
|
+
last_disconnect_at = NULL,
|
|
572
|
+
contexts = '[]'::jsonb,
|
|
573
|
+
attempts = 0,
|
|
574
|
+
next_attempt_at = now(),
|
|
575
|
+
last_error = NULL,
|
|
576
|
+
updated_at = now()
|
|
577
|
+
WHERE p.online
|
|
578
|
+
AND p.last_disconnect_at IS NOT NULL
|
|
579
|
+
AND p.last_disconnect_at <= now() - p_grace
|
|
580
|
+
AND NOT EXISTS (SELECT 1 FROM nowity.nowity_connection c WHERE c.user_id = p.user_id)
|
|
581
|
+
RETURNING p.user_id, p.offline_at;
|
|
582
|
+
END;
|
|
583
|
+
$$ LANGUAGE plpgsql;
|
|
584
|
+
|
|
585
|
+
-- Claim offline deliveries that are due. A claim is a lease: \`next_attempt_at\`
|
|
586
|
+
-- moves past the handler timeout, so a process that dies holding it hands the
|
|
587
|
+
-- delivery to the next pass instead of losing it.
|
|
588
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_presence_claim(p_limit integer, p_hold interval)
|
|
589
|
+
RETURNS TABLE (user_id text, offline_at timestamptz, online_since timestamptz, attempts integer) AS $$
|
|
590
|
+
#variable_conflict use_column
|
|
591
|
+
BEGIN
|
|
592
|
+
RETURN QUERY
|
|
593
|
+
UPDATE nowity.nowity_presence AS p
|
|
594
|
+
SET next_attempt_at = now() + p_hold,
|
|
595
|
+
attempts = p.attempts + 1,
|
|
596
|
+
updated_at = now()
|
|
597
|
+
WHERE p.user_id IN (
|
|
598
|
+
SELECT q.user_id FROM nowity.nowity_presence q
|
|
599
|
+
WHERE q.next_attempt_at IS NOT NULL
|
|
600
|
+
AND q.next_attempt_at <= now()
|
|
601
|
+
AND NOT q.online
|
|
602
|
+
ORDER BY q.next_attempt_at
|
|
603
|
+
LIMIT p_limit
|
|
604
|
+
FOR UPDATE SKIP LOCKED)
|
|
605
|
+
RETURNING p.user_id, p.offline_at, p.online_since, p.attempts;
|
|
606
|
+
END;
|
|
607
|
+
$$ LANGUAGE plpgsql;
|
|
608
|
+
|
|
609
|
+
-- ----------------------------------------------------------------- scheduler
|
|
610
|
+
--
|
|
611
|
+
-- Jobs to run at a given time, by whichever sync process leads the scheduler.
|
|
612
|
+
--
|
|
613
|
+
-- Never tracked. A job is the application's bookkeeping, not something a
|
|
614
|
+
-- reader sees, and the typical caller — a game moving its turn deadline after
|
|
615
|
+
-- every move — writes here on the hottest path there is. A capture trigger
|
|
616
|
+
-- would put an outbox row and a fan-out pass behind each of those writes.
|
|
617
|
+
--
|
|
618
|
+
-- \`run_at\` is when the job was asked for, \`next_at\` when it may next be
|
|
619
|
+
-- attempted — the same until an attempt fails and backs off. A claimed job is
|
|
620
|
+
-- \`running\` and leased until \`locked_until\`; a process that dies holding it
|
|
621
|
+
-- hands it to the next claim once the lease runs out. \`claim_id\` names the
|
|
622
|
+
-- claim, and finishing an attempt is conditional on it: a job scheduled again
|
|
623
|
+
-- under the same key while an old attempt runs is a different job, and that
|
|
624
|
+
-- attempt's outcome must not touch it.
|
|
625
|
+
--
|
|
626
|
+
-- \`interval_ms\` set makes the job periodic: finishing it moves it on instead
|
|
627
|
+
-- of deleting it.
|
|
628
|
+
CREATE TABLE IF NOT EXISTS nowity.nowity_job (
|
|
629
|
+
key text PRIMARY KEY,
|
|
630
|
+
handler text NOT NULL,
|
|
631
|
+
payload jsonb,
|
|
632
|
+
run_at timestamptz NOT NULL,
|
|
633
|
+
next_at timestamptz NOT NULL,
|
|
634
|
+
state text NOT NULL DEFAULT 'pending',
|
|
635
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
636
|
+
max_attempts integer,
|
|
637
|
+
interval_ms bigint,
|
|
638
|
+
claim_id text,
|
|
639
|
+
locked_until timestamptz,
|
|
640
|
+
last_error text,
|
|
641
|
+
created_at timestamptz NOT NULL DEFAULT now()
|
|
642
|
+
);
|
|
643
|
+
|
|
644
|
+
CREATE INDEX IF NOT EXISTS nowity_job_due_idx
|
|
645
|
+
ON nowity.nowity_job (next_at) WHERE state = 'pending';
|
|
646
|
+
CREATE INDEX IF NOT EXISTS nowity_job_lease_idx
|
|
647
|
+
ON nowity.nowity_job (locked_until) WHERE state = 'running';
|
|
648
|
+
|
|
649
|
+
-- Schedule a job, or schedule it again: one statement either way.
|
|
650
|
+
--
|
|
651
|
+
-- Wakes the leader (\`NOTIFY nowity_scheduler\`, delivered at commit) only when
|
|
652
|
+
-- the job comes before every other one still to come. A later one needs no
|
|
653
|
+
-- wakeup — the leader already sleeps until something earlier — and a
|
|
654
|
+
-- notification is not free: committing one takes a lock every notifying
|
|
655
|
+
-- transaction queues on. Jobs already overdue do not count: the leader is either
|
|
656
|
+
-- busy with them, and asks again as each finishes, or has no handler for them
|
|
657
|
+
-- and is not waiting on them at all. Returns whether it notified.
|
|
658
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_job_schedule(
|
|
659
|
+
p_key text, p_handler text, p_payload jsonb, p_run_at timestamptz, p_max_attempts integer
|
|
660
|
+
) RETURNS boolean AS $$
|
|
661
|
+
DECLARE
|
|
662
|
+
v_first timestamptz;
|
|
663
|
+
BEGIN
|
|
664
|
+
SELECT min(next_at) INTO v_first FROM nowity.nowity_job
|
|
665
|
+
WHERE state = 'pending' AND next_at > now() AND key <> p_key;
|
|
666
|
+
|
|
667
|
+
INSERT INTO nowity.nowity_job (key, handler, payload, run_at, next_at, max_attempts)
|
|
668
|
+
VALUES (p_key, p_handler, p_payload, p_run_at, p_run_at, p_max_attempts)
|
|
669
|
+
ON CONFLICT (key) DO UPDATE
|
|
670
|
+
SET handler = EXCLUDED.handler,
|
|
671
|
+
payload = EXCLUDED.payload,
|
|
672
|
+
run_at = EXCLUDED.run_at,
|
|
673
|
+
next_at = EXCLUDED.next_at,
|
|
674
|
+
max_attempts = EXCLUDED.max_attempts,
|
|
675
|
+
state = 'pending',
|
|
676
|
+
attempts = 0,
|
|
677
|
+
interval_ms = NULL,
|
|
678
|
+
claim_id = NULL,
|
|
679
|
+
locked_until = NULL,
|
|
680
|
+
last_error = NULL;
|
|
681
|
+
|
|
682
|
+
IF v_first IS NULL OR p_run_at < v_first THEN
|
|
683
|
+
PERFORM pg_notify('nowity_scheduler', '');
|
|
684
|
+
RETURN true;
|
|
685
|
+
END IF;
|
|
686
|
+
RETURN false;
|
|
687
|
+
END;
|
|
688
|
+
$$ LANGUAGE plpgsql;
|
|
689
|
+
|
|
690
|
+
-- Move a job to another time, keeping what it carries. A failed job comes back
|
|
691
|
+
-- to life. Returns false when there is no such job.
|
|
692
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_job_reschedule(p_key text, p_run_at timestamptz)
|
|
693
|
+
RETURNS boolean AS $$
|
|
694
|
+
DECLARE
|
|
695
|
+
v_first timestamptz;
|
|
696
|
+
BEGIN
|
|
697
|
+
SELECT min(next_at) INTO v_first FROM nowity.nowity_job
|
|
698
|
+
WHERE state = 'pending' AND next_at > now() AND key <> p_key;
|
|
699
|
+
|
|
700
|
+
UPDATE nowity.nowity_job
|
|
701
|
+
SET run_at = p_run_at, next_at = p_run_at, state = 'pending', attempts = 0,
|
|
702
|
+
claim_id = NULL, locked_until = NULL, last_error = NULL
|
|
703
|
+
WHERE key = p_key;
|
|
704
|
+
IF NOT FOUND THEN
|
|
705
|
+
RETURN false;
|
|
706
|
+
END IF;
|
|
707
|
+
|
|
708
|
+
IF v_first IS NULL OR p_run_at < v_first THEN
|
|
709
|
+
PERFORM pg_notify('nowity_scheduler', '');
|
|
710
|
+
END IF;
|
|
711
|
+
RETURN true;
|
|
712
|
+
END;
|
|
713
|
+
$$ LANGUAGE plpgsql;
|
|
714
|
+
|
|
715
|
+
-- Claim jobs that are due, and jobs whose lease ran out, for the given handlers
|
|
716
|
+
-- (a JSON array of names: array parameters do not travel the same way through
|
|
717
|
+
-- every adapter). Jobs of a handler this process does not know stay where they
|
|
718
|
+
-- are, for a process that does; so do the keys in \`p_skip\` — those whose
|
|
719
|
+
-- previous attempt is still running in the claiming process — untouched, with
|
|
720
|
+
-- no attempt spent on them.
|
|
721
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_job_claim(
|
|
722
|
+
p_handlers jsonb, p_skip jsonb, p_limit integer, p_hold interval, p_claim text
|
|
723
|
+
) RETURNS TABLE (
|
|
724
|
+
key text, handler text, payload jsonb, run_at timestamptz, attempts integer,
|
|
725
|
+
max_attempts integer, interval_ms double precision, lag_ms double precision
|
|
726
|
+
) AS $$
|
|
727
|
+
#variable_conflict use_column
|
|
728
|
+
BEGIN
|
|
729
|
+
RETURN QUERY
|
|
730
|
+
UPDATE nowity.nowity_job AS j
|
|
731
|
+
SET state = 'running',
|
|
732
|
+
attempts = j.attempts + 1,
|
|
733
|
+
claim_id = p_claim,
|
|
734
|
+
locked_until = now() + p_hold
|
|
735
|
+
WHERE j.key IN (
|
|
736
|
+
SELECT q.key FROM nowity.nowity_job q
|
|
737
|
+
WHERE q.handler IN (SELECT jsonb_array_elements_text(p_handlers))
|
|
738
|
+
AND q.key NOT IN (SELECT jsonb_array_elements_text(p_skip))
|
|
739
|
+
AND ((q.state = 'pending' AND q.next_at <= now())
|
|
740
|
+
OR (q.state = 'running' AND q.locked_until <= now()))
|
|
741
|
+
ORDER BY CASE WHEN q.state = 'pending' THEN q.next_at ELSE q.locked_until END
|
|
742
|
+
LIMIT p_limit
|
|
743
|
+
FOR UPDATE SKIP LOCKED)
|
|
744
|
+
RETURNING j.key, j.handler, j.payload, j.run_at, j.attempts, j.max_attempts,
|
|
745
|
+
j.interval_ms::float8, (EXTRACT(EPOCH FROM now() - j.run_at) * 1000)::float8;
|
|
746
|
+
END;
|
|
747
|
+
$$ LANGUAGE plpgsql;
|
|
748
|
+
|
|
749
|
+
-- Milliseconds until the given handlers next have something to do — a job
|
|
750
|
+
-- coming due or a lease running out — negative when it is already overdue,
|
|
751
|
+
-- null when there is nothing at all.
|
|
752
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_job_next(p_handlers jsonb) RETURNS double precision AS $$
|
|
753
|
+
SELECT (EXTRACT(EPOCH FROM LEAST(
|
|
754
|
+
(SELECT min(next_at) FROM nowity.nowity_job
|
|
755
|
+
WHERE state = 'pending' AND handler IN (SELECT jsonb_array_elements_text(p_handlers))),
|
|
756
|
+
(SELECT min(locked_until) FROM nowity.nowity_job
|
|
757
|
+
WHERE state = 'running' AND handler IN (SELECT jsonb_array_elements_text(p_handlers)))
|
|
758
|
+
) - now()) * 1000)::float8;
|
|
759
|
+
$$ LANGUAGE sql STABLE;
|
|
760
|
+
|
|
761
|
+
-- An attempt went through. A one-off job is done and goes; a periodic one moves
|
|
762
|
+
-- on by its interval — from when it was due rather than from now, so it does not
|
|
763
|
+
-- drift, but never into the past, so a late run is not followed by a burst of
|
|
764
|
+
-- the ones it missed. Returns false when the claim was no longer the job's.
|
|
765
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_job_done(p_key text, p_claim text) RETURNS boolean AS $$
|
|
766
|
+
DECLARE
|
|
767
|
+
v_next timestamptz;
|
|
768
|
+
BEGIN
|
|
769
|
+
DELETE FROM nowity.nowity_job WHERE key = p_key AND claim_id = p_claim AND interval_ms IS NULL;
|
|
770
|
+
IF FOUND THEN
|
|
771
|
+
RETURN true;
|
|
772
|
+
END IF;
|
|
773
|
+
|
|
774
|
+
SELECT GREATEST(run_at + interval_ms * interval '1 millisecond', now()) INTO v_next
|
|
775
|
+
FROM nowity.nowity_job WHERE key = p_key AND claim_id = p_claim FOR UPDATE;
|
|
776
|
+
IF NOT FOUND THEN
|
|
777
|
+
RETURN false;
|
|
778
|
+
END IF;
|
|
779
|
+
UPDATE nowity.nowity_job
|
|
780
|
+
SET state = 'pending', run_at = v_next, next_at = v_next, attempts = 0,
|
|
781
|
+
claim_id = NULL, locked_until = NULL, last_error = NULL
|
|
782
|
+
WHERE key = p_key;
|
|
783
|
+
RETURN true;
|
|
784
|
+
END;
|
|
785
|
+
$$ LANGUAGE plpgsql;
|
|
786
|
+
|
|
787
|
+
-- An attempt failed. With attempts left it is tried again after \`p_delay\`;
|
|
788
|
+
-- without, a one-off job is \`failed\` and stays for someone to look at (or to
|
|
789
|
+
-- reschedule), and a periodic one gives up this run and waits for its next.
|
|
790
|
+
-- Returns false when the claim was no longer the job's.
|
|
791
|
+
CREATE OR REPLACE FUNCTION nowity.nowity_job_fail(
|
|
792
|
+
p_key text, p_claim text, p_error text, p_delay interval, p_final boolean
|
|
793
|
+
) RETURNS boolean AS $$
|
|
794
|
+
BEGIN
|
|
795
|
+
IF p_final THEN
|
|
796
|
+
UPDATE nowity.nowity_job AS j
|
|
797
|
+
SET state = CASE WHEN j.interval_ms IS NULL THEN 'failed' ELSE 'pending' END,
|
|
798
|
+
run_at = CASE WHEN j.interval_ms IS NULL THEN j.run_at
|
|
799
|
+
ELSE GREATEST(j.run_at + j.interval_ms * interval '1 millisecond', now()) END,
|
|
800
|
+
next_at = CASE WHEN j.interval_ms IS NULL THEN j.next_at
|
|
801
|
+
ELSE GREATEST(j.run_at + j.interval_ms * interval '1 millisecond', now()) END,
|
|
802
|
+
attempts = CASE WHEN j.interval_ms IS NULL THEN j.attempts ELSE 0 END,
|
|
803
|
+
claim_id = NULL, locked_until = NULL, last_error = p_error
|
|
804
|
+
WHERE j.key = p_key AND j.claim_id = p_claim;
|
|
805
|
+
ELSE
|
|
806
|
+
UPDATE nowity.nowity_job
|
|
807
|
+
SET state = 'pending', next_at = now() + p_delay,
|
|
808
|
+
claim_id = NULL, locked_until = NULL, last_error = p_error
|
|
809
|
+
WHERE key = p_key AND claim_id = p_claim;
|
|
810
|
+
END IF;
|
|
811
|
+
RETURN FOUND;
|
|
812
|
+
END;
|
|
813
|
+
$$ LANGUAGE plpgsql;
|
|
267
814
|
`;
|