Skip to main content

Watch schema

The tables and their state semantics, in their comments. The other schemas: hub, cloud; the architecture describes the parts they belong to.

-- Excubio Watch database schema, v1.
--
-- Reference DDL. Watch shares no database with the cloud
-- (docs/watch.md §3). Same conventions as docs/schema/cloud.sql: tenant data
-- carries tenant_id, composite foreign keys, row-level security (§6); the
-- roles are created when missing, as the cloud's are (its header), and
-- everything after the block is created as excubio_watch_owner.

DO $$
DECLARE r text;
BEGIN
FOREACH r IN ARRAY ARRAY['excubio_watch_owner', 'excubio_watch_app', 'excubio_watch_lookup'] LOOP
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = r) THEN
BEGIN
EXECUTE format('CREATE ROLE %I NOLOGIN', r);
EXCEPTION WHEN duplicate_object OR unique_violation THEN
NULL; -- created by a concurrent migration of another database
END;
END IF;
END LOOP;
IF NOT pg_has_role('excubio_watch_owner', 'excubio_watch_lookup', 'MEMBER') THEN
BEGIN
GRANT excubio_watch_lookup TO excubio_watch_owner;
EXCEPTION WHEN duplicate_object OR unique_violation THEN
NULL;
END;
END IF;
IF NOT has_database_privilege('excubio_watch_owner', current_database(), 'CREATE') THEN
EXECUTE format('GRANT CREATE ON DATABASE %I TO excubio_watch_owner', current_database());
END IF;
END $$;

SET ROLE excubio_watch_owner;
CREATE SCHEMA IF NOT EXISTS excubio_watch;
SET search_path = excubio_watch;

-------------------------------------------------------------------------------
-- 1. Tenants
-------------------------------------------------------------------------------

-- Written only by the cloud's push (watch.yaml putTenant): the cloud is
-- the home of tenants, and Watch follows it (docs/watch.md §5). What each
-- state allows: docs/architecture.md §12. A push with state deleting
-- deletes the tenant here (tenant_delete, §6).
CREATE TABLE tenant (
id uuid PRIMARY KEY, -- same id as the cloud tenant
slug text NOT NULL UNIQUE,
idp_org_id text, -- several tenants may share one (docs/architecture.md §12)
state text NOT NULL DEFAULT 'active' CHECK (state IN ('active', 'suspended', 'deleting')),
limits jsonb NOT NULL DEFAULT '{}', -- watch_checks
-- The cloud's last replica push of the tenant (watch.yaml
-- putRotationReplica); Watch pages the vendor's on-call team when the
-- newest of all tenants is more than 15 minutes old (docs/watch.md §5).
replica_at timestamptz,
-- the tenant's delivery mode as the cloud pushes it (watch.yaml
-- putTenant): under evaluation Watch sends nothing to the tenant's
-- numbers (docs/on-call.md §4 Evaluation delivery)
delivery text NOT NULL DEFAULT 'live' CHECK (delivery IN ('live', 'evaluation')),
-- whether the tenant's plan allows calls, as the cloud pushes it
-- (watch.yaml putTenant): without, Watch pages the tenant's people and
-- fallback numbers by SMS only (docs/watch.md §2)
voice boolean NOT NULL DEFAULT true
);

CREATE INDEX tenant_idp_org ON tenant (idp_org_id);

CREATE TABLE tenant_key (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id int NOT NULL,
wrapped bytea NOT NULL,
deployment_key text NOT NULL,
retired_at timestamptz,
PRIMARY KEY (tenant_id, id)
);

-- Who may manage the tenant's checks, pushed by the cloud with the tenant
-- (watch.yaml putTenant): the people with a tenant role, by their login.
-- Watch never asks the cloud.
CREATE TABLE tenant_role (
tenant_id uuid NOT NULL REFERENCES tenant(id),
issuer text NOT NULL,
subject text NOT NULL,
role text NOT NULL CHECK (role IN ('auditor', 'tenant-admin')),
PRIMARY KEY (tenant_id, issuer, subject, role)
);

-- API tokens of Watch (exk_…), issued by Watch for scripts and
-- excubioctl; stored as hashes.
CREATE TABLE api_token (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id uuid NOT NULL,
name text NOT NULL,
token_hash bytea NOT NULL UNIQUE,
role text NOT NULL CHECK (role IN ('auditor', 'tenant-admin')),
created_by text NOT NULL, -- issuer and subject of the login
expires_at timestamptz,
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id)
);

-- Idempotency keys of management writes, as the cloud's
-- (docs/schema/cloud.sql idempotency_key): per caller, kept 24 h. A
-- response with a token shown once is stored sealed in response_sealed.
CREATE TABLE idempotency_key (
tenant_id uuid NOT NULL REFERENCES tenant(id),
caller text NOT NULL, -- token:<id>, or login:<issuer>/<subject>
key text NOT NULL,
request_hash bytea NOT NULL, -- method, path and body
status int,
response jsonb,
response_sealed bytea,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, caller, key)
);

CREATE INDEX idempotency_key_age ON idempotency_key (created_at);

-------------------------------------------------------------------------------
-- 2. Rotation replica (docs/watch.md §3)
-------------------------------------------------------------------------------

-- Pushed by the cloud every 5 minutes; Watch never queries the cloud.
-- entries: sealed JSON with current and next person, each with
-- sms_number and voice_number, either NULL when the person has none for
-- that medium (docs/on-call.md §2, on call with numbers); Watch then uses
-- the check's fallback numbers for that medium (docs/watch.md §2).
-- The current person is valid until current_until, the next one until
-- valid_until (docs/watch.md §2).
-- Keyed by the cloud's rotation id; team and rotation slugs are for
-- display, so a rename keeps the checks that reference the rotation.
CREATE TABLE rotation_replica (
tenant_id uuid NOT NULL REFERENCES tenant(id),
rotation_id uuid NOT NULL,
team text NOT NULL,
rotation text NOT NULL,
entries bytea NOT NULL,
current_until timestamptz NOT NULL,
valid_until timestamptz NOT NULL CHECK (valid_until >= current_until),
received_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, rotation_id)
);

-- The vendor's installations of hubs, as the cloud names them with
-- their hubs (watch.yaml putHub): installation-wide, not tenant data.
-- Watch groups the failures of an installation's hubs (docs/watch.md §5,
-- installation failures). The cloud names it with every push of its hubs;
-- the evaluator's housekeeping deletes one that no push named for a day
-- and that had no failure in the last 13 months.
CREATE TABLE installation (
id uuid PRIMARY KEY, -- the cloud's installation id
name text NOT NULL,
kind text NOT NULL CHECK (kind IN ('shared', 'dedicated')),
updated_at timestamptz NOT NULL DEFAULT now() -- the last push that named it, within the hour
);

-- Hubs of the tenant, from the cloud (docs/watch.md §1): the public key
-- that verifies their heartbeats and the installation that runs them
-- (NULL: the customer runs it). Revoking a hub clears the key and pauses
-- its checks until it enrols again; decommissioning deletes the row and
-- its checks.
CREATE TABLE hub (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id uuid NOT NULL, -- the cloud's hub id
name text NOT NULL,
watch_key bytea, -- Ed25519 public key; NULL while revoked
installation_id uuid REFERENCES installation(id) ON DELETE SET NULL,
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id)
);

CREATE INDEX hub_installation ON hub (installation_id) WHERE installation_id IS NOT NULL;

-------------------------------------------------------------------------------
-- 3. Checks (docs/watch.md §1–§2)
-------------------------------------------------------------------------------

CREATE TABLE check_def (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id uuid NOT NULL,
name text NOT NULL,
type text NOT NULL CHECK (type IN ('hub', 'push', 'reverse', 'synthetic')),
token_hash bytea UNIQUE, -- exw_… for push and reverse
old_token_hash bytea UNIQUE, -- previous token, during rotation
old_token_until timestamptz,
hub_id uuid, -- hub and synthetic checks, created by the cloud
-- synthetic: the cadence of its tests, as the cloud passes it
-- (watch.yaml putHub synthetic_every, docs/watch.md §1)
interval interval NOT NULL,
grace interval NOT NULL,
-- hub checks: limits on the newest report of any node, keys as the
-- heartbeat's state: {"pipeline_lag_seconds": 300, "tasks_pending": 10000,
-- "cloud_link_down_seconds": 300}
thresholds jsonb NOT NULL DEFAULT '{}',
expect boolean NOT NULL DEFAULT false, -- reverse: alert when the probe stops calling
severity text NOT NULL DEFAULT 'critical',
rotation_id uuid NOT NULL, -- the cloud's rotation id
also_notify uuid[] NOT NULL DEFAULT '{}', -- rotation ids
fallback_sealed bytea NOT NULL, -- fallback numbers, at least one
recovery text NOT NULL DEFAULT 'notify' CHECK (recovery IN ('notify', 'none')),
webhook_url text,
webhook_key_sealed bytea,
paused_until timestamptz,
pause_reason text,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id),
UNIQUE (tenant_id, name),
FOREIGN KEY (tenant_id, hub_id) REFERENCES hub(tenant_id, id) ON DELETE CASCADE,
CHECK ((type IN ('hub', 'synthetic')) = (hub_id IS NOT NULL))
);

-- unknown: no beat yet, or none since the check was resumed; missing
-- counts from since. up, failed: as evaluated. held: failed by the
-- flapping guard until beats have been seen for 15 minutes. paused: until
-- check_def.paused_until, or while the check's hub is revoked
-- (hub.watch_key NULL; pause_reason 'hub revoked'). The beat handlers
-- write only last_beat_at, beating_since, last_report and fail_reported_at
-- with fail_reason; the evaluator writes the rest (docs/watch.md §2).
CREATE TABLE check_state (
tenant_id uuid NOT NULL,
check_id uuid NOT NULL,
state text NOT NULL DEFAULT 'unknown' CHECK (state IN ('unknown', 'up', 'failed', 'held', 'paused')),
last_beat_at timestamptz,
last_report jsonb, -- hub: the newest heartbeat of any node, with the node
since timestamptz NOT NULL DEFAULT now(),
beating_since timestamptz, -- first beat after the last miss; the flapping guard's 15 minutes count from it
recoveries timestamptz[] NOT NULL DEFAULT '{}', -- recoveries in the last hour: three hold the next one (flapping guard)
fail_reported_at timestamptz, -- push: the newest POST /hb/<token>/fail; a later beat recovers
fail_reason text,
-- The open failure, from its check_event 'failed' to the recovery: its
-- code, the rounds sent, when the next is due, and its acknowledgement,
-- which stops the rounds until it pages again 4 hours later
-- (next_round_at, docs/watch.md §2).
failure_id uuid,
failure_code int CHECK (failure_code BETWEEN 1000 AND 9999),
failure_cause text CHECK (failure_cause IN ('missing', 'fail-reported', 'bad-state', 'no-receipt')),
round int NOT NULL DEFAULT 0,
next_round_at timestamptz,
acked_at timestamptz,
-- synthetic: the test handed to a node and its code, matched against the
-- SMS at Watch's test number; failed with no-receipt 5 min after issue
synthetic_test_id uuid,
synthetic_code text,
synthetic_issued_at timestamptz,
synthetic_next_at timestamptz, -- when the next test is due: the hub's offset within its cadence (docs/watch.md §1)
PRIMARY KEY (tenant_id, check_id),
FOREIGN KEY (tenant_id, check_id) REFERENCES check_def(tenant_id, id) ON DELETE CASCADE,
CHECK ((failure_id IS NULL) = (failure_code IS NULL))
);

-- A failure's code is unique among the tenant's open failures.
CREATE UNIQUE INDEX check_state_failure_code ON check_state (tenant_id, failure_code) WHERE failure_id IS NOT NULL;

-- Synthetic tests across tenants, without their tenant: when at least 5
-- had their receipt due in 10 minutes and more than half got none, Watch
-- takes its test number or the cloud's SMS path as the cause
-- (docs/watch.md §5). Kept a day.
CREATE TABLE synthetic_test (
id uuid PRIMARY KEY, -- check_state.synthetic_test_id
due_at timestamptz NOT NULL, -- issue plus 5 minutes
received_at timestamptz
);

CREATE INDEX synthetic_test_due ON synthetic_test (due_at);

-- changed: the cloud changed the rotation or the fallback numbers of a
-- hub's check, or revoked its hub; sent to the previous fallback numbers
-- (docs/watch.md §5). test: a test notification (watch.yaml testCheck).
-- Kept 13 months (docs/compliance.md §2) with their notifications and
-- webhook posts, which go with them: the evaluator's hourly housekeeping
-- deletes the older ones, except the 'failed' event of a failure that is
-- still open (check_state.failure_id).
CREATE TABLE check_event (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
check_id uuid NOT NULL,
type text NOT NULL CHECK (type IN ('failed', 'recovered', 'held', 'acknowledged', 'paused', 'resumed', 'changed', 'test')),
at timestamptz NOT NULL DEFAULT now(),
cause text CHECK (cause IN ('missing', 'fail-reported', 'bad-state', 'no-receipt')),
reason text, -- /fail reason, pause reason
acked_by text, -- person id from the replica, or 'fallback:<n>'
acked_via text CHECK (acked_via IN ('sms', 'voice')),
details jsonb NOT NULL DEFAULT '{}',
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, check_id) REFERENCES check_def(tenant_id, id) ON DELETE CASCADE
);

CREATE INDEX check_event_check ON check_event (tenant_id, check_id, at);
CREATE INDEX check_event_age ON check_event (tenant_id, at);

-- The outbox of a check's webhook (docs/watch.md §2): one row per event
-- and check with a webhook, written with the event. The evaluator posts
-- it, at least once, and retries with backoff (1 s to 15 min) for 24 h;
-- then the row keeps its last error. Kept as check events.
CREATE TABLE webhook_delivery (
tenant_id uuid NOT NULL,
check_event_id uuid NOT NULL,
attempts int NOT NULL DEFAULT 0,
next_at timestamptz, -- NULL: sent, or given up
sent_at timestamptz,
last_error text,
PRIMARY KEY (tenant_id, check_event_id),
FOREIGN KEY (tenant_id, check_event_id) REFERENCES check_event(tenant_id, id) ON DELETE CASCADE
);

CREATE INDEX webhook_delivery_due ON webhook_delivery (next_at) WHERE next_at IS NOT NULL;

-- Watch's evaluation passes, across all tenants (docs/watch.md §2). Only
-- the node that holds the advisory lock pg_try_advisory_lock(hashtext(
-- 'excubio_watch.evaluation')), on a session of its own, evaluates; each
-- of its transactions runs on that session and first checks in pg_locks
-- that the session holds the lock. Each pass sets last_pass_at to its
-- start; a pass that finds it older than 30 s, and the first pass of a new
-- holder, first inserts the gap from last_pass_at to its own start.
-- Missing is judged from greatest(check_state.last_beat_at, end of the
-- newest gap, and check_state.since while the state is unknown). Every
-- time here and in check_state is the database's clock
-- (clock_timestamp()), whichever node wrote it.
CREATE TABLE evaluation (
id boolean PRIMARY KEY DEFAULT true CHECK (id), -- one row
last_pass_at timestamptz NOT NULL
);

-- Kept 13 months, as check events (docs/compliance.md §2).
CREATE TABLE evaluation_gap (
started_at timestamptz PRIMARY KEY, -- the last pass before the gap
ended_at timestamptz NOT NULL CHECK (ended_at > started_at)
);

CREATE INDEX evaluation_gap_age ON evaluation_gap (ended_at);

-- An installation failure (docs/watch.md §5): of an installation's hubs
-- whose hub checks aren't paused, at least the larger of 5 and 20 % had
-- their hub check fail within 5 minutes. It opens with the counts that
-- opened it and ends (ended_at) when fewer than that share are failed.
-- The vendor's on-call team is paged when it opens (vendor_sent_at, set
-- by the claim before the page is sent) and every 30 minutes while it
-- lasts, and told when it ends (ended_sent_at). A check event of a hub
-- on the installation from 5 minutes before started_at to 5 minutes
-- after ended_at belongs to it (installation_failure_of); the messages
-- about it (notification) are claimed only after the vendor's first
-- page. Kept 13 months, as check events.
CREATE TABLE installation_failure (
installation_id uuid NOT NULL REFERENCES installation(id) ON DELETE CASCADE,
started_at timestamptz NOT NULL,
ended_at timestamptz CHECK (ended_at >= started_at),
hubs int NOT NULL, -- its hubs whose hub checks weren't paused
failing int NOT NULL, -- of them failed, the most while it lasted
vendor_sent_at timestamptz,
ended_sent_at timestamptz,
PRIMARY KEY (installation_id, started_at)
);

CREATE UNIQUE INDEX installation_failure_open ON installation_failure (installation_id) WHERE ended_at IS NULL;

-- The installation failure that a check event of `hub` at `at` belongs
-- to, if any. Runs with the caller's rights: under the tenant, or in a
-- lookup function.
CREATE FUNCTION installation_failure_of(tenant uuid, hub uuid, at timestamptz)
RETURNS TABLE (installation_id uuid, started_at timestamptz, vendor_sent_at timestamptz)
LANGUAGE sql STABLE SET search_path = pg_catalog, pg_temp AS $$
SELECT f.installation_id, f.started_at, f.vendor_sent_at
FROM excubio_watch.hub h JOIN excubio_watch.installation_failure f ON f.installation_id = h.installation_id
WHERE h.tenant_id = tenant AND h.id = hub
AND at >= f.started_at - interval '5 minutes' AND (f.ended_at IS NULL OR at <= f.ended_at + interval '5 minutes')
ORDER BY f.started_at DESC LIMIT 1
$$;

-- Pages to the vendor's on-call team (docs/watch.md §5), installation-wide:
-- one row per cause while it lasts, paged when it starts and again every
-- 30 minutes; the evaluator deletes the row when the cause ends.
-- replica-stale: no replica push for 15 minutes; test-number: the
-- synthetic tests of many tenants got no receipt; cloud-removals: the
-- cloud revoked or deleted more than 20 hubs in an hour.
CREATE TABLE vendor_page (
cause text PRIMARY KEY CHECK (cause IN ('replica-stale', 'test-number', 'cloud-removals')),
since timestamptz NOT NULL DEFAULT now(),
sent_at timestamptz,
details jsonb NOT NULL DEFAULT '{}'
);

-- The cloud's revocations and deletions of hubs, installation-wide: at
-- most 20 within an hour are taken (docs/watch.md §5). Kept an hour.
CREATE TABLE cloud_removal (
at timestamptz NOT NULL DEFAULT now(),
hub_id uuid NOT NULL,
PRIMARY KEY (at, hub_id)
);

-------------------------------------------------------------------------------
-- 4. Notifications
-------------------------------------------------------------------------------

-- Watch's sender and caller numbers for a tenant at its carrier, assigned
-- by the cloud and passed on with the tenant (watch.yaml putTenant; the
-- cloud's copy is docs/schema/cloud.sql watch_number). A number serves one
-- tenant (number is unique): a reply finds its tenant by the called
-- number (lookup_called_number). country: the number's country calling
-- code without +; a message goes out from the number in the recipient's
-- country, else from the default (docs/on-call.md §4, sender numbers).
CREATE TABLE sender_number (
tenant_id uuid NOT NULL REFERENCES tenant(id),
number text NOT NULL UNIQUE, -- E.164; a company number, not personal data
media text[] NOT NULL CHECK (media <@ ARRAY['sms', 'voice']),
country text NOT NULL,
is_default boolean NOT NULL DEFAULT false,
PRIMARY KEY (tenant_id, number)
);

-- recipient_hmac: the keyed hash (HMAC-SHA-256 with a tenant key, as the
-- cloud's number_hmac) of the number sent to. A reply's tenant comes from
-- the called number; within the tenant, the failures sent to the replying
-- number are found by its hash, and a code resolves only among them
-- (docs/watch.md §2). message_sealed: the number and the text, sealed
-- with the tenant's data key. Every Watch node queues notifications; only
-- the evaluator sends them (docs/watch.md §2), each claimed first: queued
-- → sending in a transaction of its own on the lock's session, then sent,
-- then sent or failed, and later delivered, failed or no-answer by the
-- carrier's receipt, or acknowledged. A notification stays sending when
-- its holder lost the lock before recording the outcome; it is never
-- sent again. The messages of a failure's rounds (those of its check_event
-- 'failed') are cancelled while queued when the failure is acknowledged,
-- recovers or is paused, and the claim cancels one whose failure is no
-- longer open and unacknowledged. sent_at: when it was claimed.
-- not_before: claimed no earlier; claims go oldest check event first, at
-- most 10 a second (docs/watch.md §2, Throttle), and the first round of
-- a failure of a hub on a shared installation waits 30 s. A message about
-- a check event of an installation failure (installation_failure_of) is
-- claimed only after the vendor's page of it, and its sealed message
-- holds a second text that says the installation is affected, which is
-- the one sent (docs/watch.md §5).
CREATE TABLE notification (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
check_event_id uuid NOT NULL,
short_code int, -- the failure's code (check_state.failure_code); NULL for messages about no failure
medium text NOT NULL CHECK (medium IN ('sms', 'voice')),
recipient text NOT NULL, -- person id from the replica, or 'fallback:<n>'
recipient_hmac bytea NOT NULL,
carrier_ref text,
status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'sending', 'sent', 'delivered', 'failed', 'no-answer', 'acknowledged', 'cancelled', 'evaluation')), -- evaluation: not sent, the tenant is under evaluation (docs/watch.md §2)
attempt int NOT NULL DEFAULT 1, -- round: every 5 min for 3 rounds, then every 30 min; again from 1 when an acknowledged failure pages again (docs/watch.md §2)
message_sealed bytea NOT NULL,
not_before timestamptz NOT NULL DEFAULT now(),
sent_at timestamptz,
final_at timestamptz,
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, check_event_id) REFERENCES check_event(tenant_id, id) ON DELETE CASCADE
);

CREATE INDEX notification_recipient ON notification (tenant_id, recipient_hmac, sent_at);
CREATE INDEX notification_queued ON notification (tenant_id, check_event_id) WHERE status = 'queued';
CREATE INDEX notification_due ON notification (not_before) WHERE status = 'queued';
CREATE INDEX notification_event ON notification (tenant_id, check_event_id);

-- Inbound SMS and call events by the carrier's event id: a repeat of one
-- is ignored. Kept 7 days.
CREATE TABLE carrier_event (
tenant_id uuid NOT NULL REFERENCES tenant(id),
carrier text NOT NULL,
event_id text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (carrier, event_id)
);

-------------------------------------------------------------------------------
-- 5. Audit (docs/compliance.md §3)
-------------------------------------------------------------------------------

-- Hash-chained like the cloud's audit_event: check changes, pauses,
-- tokens, acknowledgements and the cloud's pushes of hubs and roles. The
-- app role only reads and appends (§6); entries older than the retention
-- (5 years, docs/compliance.md §2) are removed only by audit_expire.
-- actor is an id, never a name: the login (issuer and subject), API token,
-- the cloud or the component (system); names are resolved on display.
CREATE TABLE audit_event (
tenant_id uuid NOT NULL REFERENCES tenant(id),
seq bigint NOT NULL, -- gap-free per tenant
at timestamptz NOT NULL DEFAULT now(),
actor_kind text NOT NULL CHECK (actor_kind IN ('person', 'service', 'system', 'cloud')),
actor text NOT NULL,
action text NOT NULL,
object text NOT NULL,
reason text,
request_id text, -- the API request that wrote it
details jsonb NOT NULL DEFAULT '{}',
prev_hash bytea NOT NULL,
hash bytea NOT NULL,
PRIMARY KEY (tenant_id, seq)
);

-- One row per expiry of a tenant's audit, written by audit_expire: the
-- last expired entry (seq, hash), so the chain stays verifiable from it.
CREATE TABLE audit_checkpoint (
tenant_id uuid NOT NULL REFERENCES tenant(id),
seq bigint NOT NULL,
hash bytea NOT NULL,
expired bigint NOT NULL, -- entries deleted
at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, seq)
);

-------------------------------------------------------------------------------
-- 6. Roles and row-level security
-------------------------------------------------------------------------------

-- As in the cloud (docs/schema/cloud.sql §9), with Watch's own roles:
-- excubio_watch_owner owns the schema and runs the migrations;
-- excubio_watch_app is Watch's servers and its evaluation, with SELECT,
-- INSERT, UPDATE and DELETE on every table, except audit_event, which it
-- may only read and append to, and audit_checkpoint, which it may only
-- read; and the lookup functions, audit_expire and tenant_delete;
-- excubio_watch_lookup owns the lookup functions and may read, across
-- tenants, only the columns they need. All are without login, none has
-- BYPASSRLS, and FORCE applies the policies to the owner too. Every
-- transaction on tenant data sets excubio.tenant_id for the transaction
-- only, as in the cloud; without it a query sees no tenant rows.
--
-- The tenant of a beat (by its token), of a batch's heartbeats (by their
-- hubs, with the hubs' public Watch keys), of an API token, of the SMS of
-- a synthetic test, of a reply (by the called number) and of a carrier
-- receipt, the checks an evaluation pass evaluates, the notifications it
-- sends and the counts of an installation's failing hubs are found
-- through the SECURITY DEFINER functions below, which return tenant ids,
-- row ids, counts and public keys only; each check is then evaluated,
-- and each notification claimed, in its own transaction under its
-- tenant. hub_beats records a batch's verified heartbeats across its
-- tenants in one call.

GRANT USAGE ON SCHEMA excubio_watch TO excubio_watch_app, excubio_watch_lookup;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA excubio_watch TO excubio_watch_app;
ALTER DEFAULT PRIVILEGES FOR ROLE excubio_watch_owner IN SCHEMA excubio_watch
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO excubio_watch_app;
REVOKE UPDATE, DELETE ON audit_event FROM excubio_watch_app;
REVOKE INSERT, UPDATE, DELETE ON audit_checkpoint FROM excubio_watch_app;

GRANT SELECT (tenant_id, id, token_hash, old_token_hash, type, hub_id, interval, grace, thresholds, expect, paused_until)
ON check_def TO excubio_watch_lookup;
GRANT SELECT (tenant_id, check_id, synthetic_code, state, last_beat_at, last_report, fail_reported_at, failure_id,
synthetic_test_id, synthetic_issued_at) ON check_state TO excubio_watch_lookup;
GRANT SELECT (tenant_id, id, watch_key, installation_id) ON hub TO excubio_watch_lookup;
GRANT SELECT (tenant_id, id, check_id, at) ON check_event TO excubio_watch_lookup;
GRANT SELECT ON installation_failure TO excubio_watch_lookup;
GRANT SELECT (tenant_id, id, token_hash) ON api_token TO excubio_watch_lookup;
GRANT SELECT (tenant_id, id, carrier_ref, check_event_id, status, not_before) ON notification TO excubio_watch_lookup;
GRANT SELECT (tenant_id, number) ON sender_number TO excubio_watch_lookup;
GRANT SELECT (tenant_id, check_event_id, next_at) ON webhook_delivery TO excubio_watch_lookup;

DO $$
DECLARE t text;
BEGIN
FOREACH t IN ARRAY ARRAY['tenant_key', 'tenant_role', 'api_token', 'idempotency_key', 'rotation_replica', 'hub', 'check_def', 'check_state',
'check_event', 'webhook_delivery', 'sender_number', 'notification', 'carrier_event', 'audit_event', 'audit_checkpoint']
LOOP
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', t);
EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY', t);
EXECUTE format(
'CREATE POLICY tenant_isolation ON %I USING (tenant_id = NULLIF(current_setting(''excubio.tenant_id'', true), '''')::uuid)', t);
END LOOP;
FOREACH t IN ARRAY ARRAY['check_def', 'check_state', 'check_event', 'hub', 'api_token', 'notification', 'sender_number', 'webhook_delivery'] LOOP
EXECUTE format('CREATE POLICY lookup ON %I FOR SELECT TO excubio_watch_lookup USING (true)', t);
END LOOP;
END $$;

-- The tenant and check of a push or reverse beat, by the SHA-256 of its
-- token (exw_), current or previous; the previous one's validity is
-- checked under the tenant.
CREATE FUNCTION lookup_check_token(hash bytea) RETURNS TABLE (tenant_id uuid, check_id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT c.tenant_id, c.id FROM excubio_watch.check_def c WHERE c.token_hash = hash OR c.old_token_hash = hash
$$;

-- The tenants and public Watch keys of a batch's hubs, by their ids
-- (docs/watch.md §1); a revoked hub's key is NULL.
CREATE FUNCTION lookup_hub_keys(hubs uuid[]) RETURNS TABLE (hub_id uuid, tenant_id uuid, watch_key bytea)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT e.id, e.tenant_id, e.watch_key FROM excubio_watch.hub e WHERE e.id = ANY (hubs)
$$;

-- The tenant and API token (exk_) of a token's SHA-256.
CREATE FUNCTION lookup_token(hash bytea) RETURNS TABLE (tenant_id uuid, id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT a.tenant_id, a.id FROM excubio_watch.api_token a WHERE a.token_hash = hash
$$;

-- The tenant and check of an SMS at Watch's test number, by its test code.
CREATE FUNCTION lookup_synthetic_code(code text) RETURNS TABLE (tenant_id uuid, check_id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT s.tenant_id, s.check_id FROM excubio_watch.check_state s WHERE s.synthetic_code = code
$$;

-- The tenant of a called number (a reply): sender_number.number is unique.
CREATE FUNCTION lookup_called_number(called text) RETURNS uuid
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT s.tenant_id FROM excubio_watch.sender_number s WHERE s.number = called
$$;

-- The tenant and notification of a carrier receipt.
CREATE FUNCTION lookup_carrier_ref(ref text) RETURNS TABLE (tenant_id uuid, notification_id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT n.tenant_id, n.id FROM excubio_watch.notification n WHERE n.carrier_ref = ref
$$;

-- The checks an evaluation pass evaluates at `clock` (docs/watch.md §2,
-- One evaluator): those whose state may change, a superset of the checks
-- whose evaluation changes anything. Left out is a check that is up, has
-- no open failure, no pause starting and no revoked hub, and is beating:
-- its last beat within interval + grace (hub, push, and reverse with
-- expect), no failure reported after it (push), a report within its
-- thresholds with the cloud link up (hub), no test past its receipt
-- window (synthetic). The end of a gap only moves missing later.
CREATE FUNCTION lookup_checks_due(clock timestamptz) RETURNS TABLE (tenant_id uuid, check_id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT c.tenant_id, c.id
FROM excubio_watch.check_def c
JOIN excubio_watch.check_state s ON s.tenant_id = c.tenant_id AND s.check_id = c.id
LEFT JOIN excubio_watch.hub h ON h.tenant_id = c.tenant_id AND h.id = c.hub_id
WHERE s.state <> 'up'
OR s.failure_id IS NOT NULL
OR c.paused_until > clock
OR (h.id IS NOT NULL AND h.watch_key IS NULL)
OR ((c.type IN ('hub', 'push') OR (c.type = 'reverse' AND c.expect))
AND (s.last_beat_at IS NULL OR s.last_beat_at + c.interval + c.grace < clock))
OR (c.type = 'push' AND s.fail_reported_at IS NOT NULL AND (s.last_beat_at IS NULL OR s.last_beat_at <= s.fail_reported_at))
OR (c.type = 'hub' AND s.last_report IS NOT NULL AND (
(s.last_report->'state'->>'cloud_link_up')::boolean IS FALSE
OR (s.last_report->'state'->>'pipeline_lag_seconds')::float8 > (c.thresholds->>'pipeline_lag_seconds')::float8
OR (s.last_report->'state'->>'tasks_pending')::float8 > (c.thresholds->>'tasks_pending')::float8))
OR (c.type = 'synthetic' AND s.synthetic_test_id IS NOT NULL AND s.synthetic_issued_at + interval '5 minutes' <= clock)
ORDER BY c.tenant_id, c.id
$$;

-- The queued notifications a pass may claim, at most `lim`, oldest check
-- event first (docs/watch.md §2, Throttle): those whose not_before has
-- come, and of an installation failure's only those after the vendor's
-- page of it was claimed.
CREATE FUNCTION lookup_queued(lim int) RETURNS TABLE (tenant_id uuid, notification_id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT n.tenant_id, n.id
FROM excubio_watch.notification n
JOIN excubio_watch.check_event e ON e.tenant_id = n.tenant_id AND e.id = n.check_event_id
JOIN excubio_watch.check_def c ON c.tenant_id = e.tenant_id AND c.id = e.check_id
WHERE n.status = 'queued' AND n.not_before <= now()
AND NOT EXISTS (SELECT FROM excubio_watch.installation_failure_of(c.tenant_id, c.hub_id, e.at) f WHERE f.vendor_sent_at IS NULL)
ORDER BY e.at, n.id
LIMIT lim
$$;

-- Per installation: its hubs whose hub checks aren't paused, of them
-- those failed, and those whose failure opened at `opened_after` or later
-- (docs/watch.md §5, installation failures). Counts only.
CREATE FUNCTION lookup_installation_health(opened_after timestamptz)
RETURNS TABLE (installation_id uuid, hubs bigint, failing bigint, recent bigint)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT h.installation_id, count(*), count(*) FILTER (WHERE s.state IN ('failed', 'held')),
count(*) FILTER (WHERE s.state IN ('failed', 'held') AND e.at >= opened_after)
FROM excubio_watch.hub h
JOIN excubio_watch.check_def c ON c.tenant_id = h.tenant_id AND c.hub_id = h.id AND c.type = 'hub'
JOIN excubio_watch.check_state s ON s.tenant_id = c.tenant_id AND s.check_id = c.id
LEFT JOIN excubio_watch.check_event e ON e.tenant_id = s.tenant_id AND e.id = s.failure_id
WHERE h.installation_id IS NOT NULL AND s.state <> 'paused'
GROUP BY h.installation_id
$$;

-- The webhook posts that are due, oldest first.
CREATE FUNCTION lookup_due_webhooks(lim int) RETURNS TABLE (tenant_id uuid, check_event_id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT w.tenant_id, w.check_event_id FROM excubio_watch.webhook_delivery w WHERE w.next_at <= now() ORDER BY w.next_at LIMIT lim
$$;

-- Expires the current tenant's audit: deletes the entries older than
-- 5 years, keeping at least the newest entry, and records the last
-- deleted one in audit_checkpoint; returns the count. Runs as its owner,
-- excubio_watch_owner (SECURITY DEFINER), under the tenant set by the
-- caller; the app role may call it but can't delete entries itself.
CREATE FUNCTION audit_expire() RETURNS bigint
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE
tenant uuid := NULLIF(current_setting('excubio.tenant_id', true), '')::uuid;
head bigint;
last_seq bigint;
last_hash bytea;
n bigint;
BEGIN
IF tenant IS NULL THEN
RAISE EXCEPTION 'audit_expire runs under a tenant (excubio.tenant_id)';
END IF;
SELECT max(e.seq) INTO head FROM excubio_watch.audit_event e WHERE e.tenant_id = tenant;
SELECT coalesce(min(e.seq), head) - 1 INTO last_seq FROM excubio_watch.audit_event e
WHERE e.tenant_id = tenant AND e.at >= now() - interval '5 years';
SELECT e.hash INTO last_hash FROM excubio_watch.audit_event e WHERE e.tenant_id = tenant AND e.seq = last_seq;
IF last_hash IS NULL THEN
RETURN 0;
END IF;
DELETE FROM excubio_watch.audit_event e WHERE e.tenant_id = tenant AND e.seq <= last_seq;
GET DIAGNOSTICS n = ROW_COUNT;
INSERT INTO excubio_watch.audit_checkpoint (tenant_id, seq, hash, expired) VALUES (tenant, last_seq, last_hash, n);
RETURN n;
END
$$;

REVOKE EXECUTE ON FUNCTION audit_expire() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION audit_expire() TO excubio_watch_app;

-- Deletes a tenant in state deleting with its rows, its audit and its
-- data keys, the tenant row last, as the cloud's tenant_delete does
-- (docs/schema/cloud.sql §9). Runs as excubio_watch_owner under the
-- tenant's policy.
CREATE FUNCTION tenant_delete(target uuid) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE t text;
BEGIN
IF NOT EXISTS (SELECT FROM excubio_watch.tenant x WHERE x.id = target AND x.state = 'deleting') THEN
RAISE EXCEPTION 'tenant_delete needs a tenant in state deleting';
END IF;
PERFORM set_config('excubio.tenant_id', target::text, true);
FOREACH t IN ARRAY ARRAY['notification', 'webhook_delivery', 'check_event', 'check_state', 'check_def', 'hub',
'rotation_replica', 'sender_number', 'carrier_event', 'idempotency_key', 'api_token', 'tenant_role',
'audit_checkpoint', 'audit_event', 'tenant_key']
LOOP
EXECUTE format('DELETE FROM excubio_watch.%I x WHERE x.tenant_id = $1', t) USING target;
END LOOP;
DELETE FROM excubio_watch.tenant x WHERE x.id = target;
END
$$;

REVOKE EXECUTE ON FUNCTION tenant_delete(uuid) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION tenant_delete(uuid) TO excubio_watch_app;

-- Records a batch's heartbeats, each verified by the caller with its
-- hub's Watch key (docs/watch.md §1): beats is a JSON array of
-- {tenant_id, hub_id, at, report, test_id, code}. Per tenant of the
-- batch, under that tenant's policy: the hub checks of its hubs get the
-- beat at the database's clock and the newest report of any node, and
-- the synthetic check of one of its hubs whose test is due gets the
-- entry's test, returned with its hub. Runs as excubio_watch_owner, as
-- tenant_delete; the app calls it with the heartbeats it verified only.
CREATE FUNCTION hub_beats(beats jsonb) RETURNS TABLE (beat_hub uuid, beat_test uuid, beat_code text)
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE
t uuid;
clock timestamptz := clock_timestamp();
BEGIN
FOR t IN SELECT DISTINCT (b->>'tenant_id')::uuid FROM jsonb_array_elements(beats) b LOOP
PERFORM set_config('excubio.tenant_id', t::text, true);
UPDATE excubio_watch.check_state s
SET last_beat_at = greatest(s.last_beat_at, clock), beating_since = coalesce(s.beating_since, clock),
last_report = CASE WHEN s.last_report IS NULL OR (s.last_report->>'at')::timestamptz <= x.at THEN x.report ELSE s.last_report END
FROM excubio_watch.check_def c,
(SELECT DISTINCT ON (b->>'hub_id') (b->>'hub_id')::uuid AS hub, (b->>'at')::timestamptz AS at, b->'report' AS report
FROM jsonb_array_elements(beats) b WHERE (b->>'tenant_id')::uuid = t
ORDER BY b->>'hub_id', (b->>'at')::timestamptz DESC) x
WHERE c.tenant_id = s.tenant_id AND c.id = s.check_id AND c.tenant_id = t AND c.hub_id = x.hub AND c.type = 'hub';
RETURN QUERY
WITH issued AS (
UPDATE excubio_watch.check_state s
SET synthetic_test_id = x.test, synthetic_code = x.code, synthetic_issued_at = clock
FROM excubio_watch.check_def c,
(SELECT DISTINCT ON (b->>'hub_id') (b->>'hub_id')::uuid AS hub, (b->>'test_id')::uuid AS test, b->>'code' AS code
FROM jsonb_array_elements(beats) b WHERE (b->>'tenant_id')::uuid = t ORDER BY b->>'hub_id') x
WHERE c.tenant_id = s.tenant_id AND c.id = s.check_id AND c.tenant_id = t AND c.hub_id = x.hub AND c.type = 'synthetic'
AND s.synthetic_test_id IS NULL AND s.synthetic_next_at <= clock AND s.state <> 'paused'
AND (c.paused_until IS NULL OR c.paused_until <= clock)
RETURNING c.hub_id AS hub, s.synthetic_test_id AS test, s.synthetic_code AS code
), recorded AS (
INSERT INTO excubio_watch.synthetic_test (id, due_at) SELECT i.test, clock + interval '5 minutes' FROM issued i
)
SELECT i.hub, i.test, i.code FROM issued i;
END LOOP;
END
$$;

REVOKE EXECUTE ON FUNCTION hub_beats(jsonb) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION hub_beats(jsonb) TO excubio_watch_app;

GRANT CREATE ON SCHEMA excubio_watch TO excubio_watch_lookup;
DO $$
DECLARE f regprocedure;
BEGIN
FOR f IN SELECT p.oid FROM pg_proc p WHERE p.pronamespace = 'excubio_watch'::regnamespace AND p.proname LIKE 'lookup\_%' LOOP
EXECUTE format('ALTER FUNCTION %s OWNER TO excubio_watch_lookup', f);
EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM PUBLIC', f);
EXECUTE format('GRANT EXECUTE ON FUNCTION %s TO excubio_watch_app', f);
END LOOP;
END $$;
REVOKE CREATE ON SCHEMA excubio_watch FROM excubio_watch_lookup;