Skip to main content

Cloud schema

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

-- Excubio cloud database schema, v1.
--
-- Reference DDL. The sqlx migrations in crates/ex-store-cloud/migrations
-- build this schema; `mise run check-schema-drift` compares the two
-- (pg_dump --schema-only) and fails on a difference. Targets PostgreSQL
-- 18, no extensions.
--
-- Conventions:
-- * ids: uuid (v7, generated by the application).
-- * tenancy (docs/architecture.md §12): every table with a tenant_id column
-- is tenant data. References between tenant tables are composite foreign
-- keys over (tenant_id, …), so a row can only point into its own tenant;
-- each such table has UNIQUE (tenant_id, id) as the target. Row-level
-- security (§9) hides other tenants' rows. Tables without tenant_id are
-- installation-wide, as are installation_hub and hub_usage (§3), the
-- vendor's records of the hubs its installations run, which name a
-- tenant by its id without being its data.
-- * personal data (names, e-mail addresses, phone numbers, push tokens)
-- is sealed with the tenant's data key
-- (AES-256-GCM, tenant id as associated data). Exact lookups use a
-- keyed hash (HMAC-SHA-256): number_hmac, email_hmac. Its key is
-- derived from the tenant's first data key, which is kept for it when
-- a later key seals (docs/operations.md §6), so a rotation of the data
-- key changes no hash. Name search unseals the tenant's people in the
-- cloud process; a tenant has thousands of people at most.
-- * timestamps: timestamptz; hashes: bytea (SHA-256).
-- * all objects live in schema "excubio", owned by excubio_owner.
-- * roles (§9): excubio_owner, excubio_app and excubio_lookup are group
-- roles without login. Roles belong to the cluster, not to the
-- database, so the schema creates them only when they are missing (the
-- block below): a first migration by a superuser or a login with
-- CREATEROLE creates them, and on a cluster where the administrator
-- created them beforehand the block changes nothing. The migration
-- login must be able to SET ROLE excubio_owner; everything after the
-- block is created as excubio_owner. The drift check compares the
-- objects, policies and functions with their owners and grants; the
-- migration tests check the grants too (crates/ex-store-cloud/tests).

DO $$
DECLARE r text;
BEGIN
FOREACH r IN ARRAY ARRAY['excubio_owner', 'excubio_app', 'excubio_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;
-- excubio_owner hands the lookup functions to excubio_lookup (§9).
IF NOT pg_has_role('excubio_owner', 'excubio_lookup', 'MEMBER') THEN
BEGIN
GRANT excubio_lookup TO excubio_owner;
EXCEPTION WHEN duplicate_object OR unique_violation THEN
NULL;
END;
END IF;
IF NOT has_database_privilege('excubio_owner', current_database(), 'CREATE') THEN
EXECUTE format('GRANT CREATE ON DATABASE %I TO excubio_owner', current_database());
END IF;
END $$;

SET ROLE excubio_owner;
CREATE SCHEMA IF NOT EXISTS excubio;
SET search_path = excubio;

-------------------------------------------------------------------------------
-- 1. Tenants, identity and access
-------------------------------------------------------------------------------

-- What each state allows each credential: docs/architecture.md §12.
-- active: normal operation. suspended: paging and responding continue,
-- management writes are refused. deleting: every request is refused; once
-- Watch has deleted the tenant, the deletion job calls tenant_delete (§9),
-- which removes the tenant's rows, its audit and its data keys, the tenant
-- row last.
CREATE TYPE tenant_state AS ENUM ('active', 'suspended', 'deleting');

-- The vendor's hub installations (docs/operations.md §3): one hub
-- database with its nodes, run by the vendor, that serves the hubs the
-- cloud places on it (hub.installation_id). Installation-wide, not tenant
-- data. A shared installation serves many tenants' hubs; a dedicated one
-- the hubs of the one tenant that names it (tenant.installation_id). A
-- hub the customer runs itself belongs to no installation of this table.
-- Vendor operators create, change and delete installations (cloud.yaml
-- tag platform, audited in platform_audit); the installation itself
-- calls the installation channel (cloud.yaml tag installation) with a
-- client certificate of the cloud's hub CA.
-- state: active takes new hubs within capacity; draining takes none and
-- keeps serving its hubs. An installation with hubs (installation_hub)
-- can't be deleted.
CREATE TABLE installation (
id uuid PRIMARY KEY,
name text NOT NULL UNIQUE CHECK (name ~ '^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$'),
kind text NOT NULL CHECK (kind IN ('shared', 'dedicated')),
-- the domain its hubs' hosts live under: <host label>.<hub_domain>
-- (hub.host_label); fixed when the installation is created
hub_domain text NOT NULL CHECK (length(hub_domain) <= 190 AND hub_domain ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$'),
capacity int NOT NULL CHECK (capacity > 0), -- hubs it serves at most
state text NOT NULL DEFAULT 'active' CHECK (state IN ('active', 'draining')),
-- exm_…, valid 24 h, cleared by the installation's enrolment; issued
-- again (issueInstallationEnrolmentToken) to enrol it again
enrol_token_hash bytea UNIQUE,
enrol_expires_at timestamptz,
-- the SHA-256 of the DER of its current client certificate, issued by
-- the hub CA (subject common name installation:<id>, valid 1 year), and
-- the one a renewal replaced, valid until the first call with the new
-- one, as a hub's (hub.prev_cert_fingerprint)
cert_fingerprint bytea UNIQUE,
cert_expires_at timestamptz,
prev_cert_fingerprint bytea UNIQUE,
version text, -- the hub version it last called with
last_seen_at timestamptz,
-- the last sequence given to one of its installation_hub rows
seq bigint NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
-- the installation's operator hub, which a vendor operator names
-- (updateInstallation); pollInstallation hands it to the installation
-- and Watch tests it hourly (docs/watch.md §1). A hub placed on the
-- installation: of a shared one the vendor's own, of a dedicated one
-- also its tenant's (docs/operations.md §1).
operator_hub_id uuid
);

CREATE TABLE tenant (
id uuid PRIMARY KEY,
slug text NOT NULL UNIQUE CHECK (slug ~ '^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$'),
display_name text NOT NULL,
idp_org_id text, -- Zitadel organization id; several tenants may share one
-- (docs/architecture.md §12)
state tenant_state NOT NULL DEFAULT 'active',
shard int NOT NULL, -- controller shard (docs/architecture.md §8)
-- licence limits (docs/architecture.md §12): rotations, hubs,
-- watch_checks, and per hub on an installation events_per_second,
-- events_per_day, cis, sources, relays, retention_days,
-- replay_window_days; an absent limit is unlimited
limits jsonb NOT NULL DEFAULT '{}',
-- rotation minimums (docs/on-call.md §2): escalation_levels, number_test, min_people
rotation_minimums jsonb NOT NULL DEFAULT '{}',
-- who sees per-person reports (docs/compliance.md §7)
person_reporting text NOT NULL DEFAULT 'aggregated' CHECK (person_reporting IN ('named', 'aggregated', 'off')),
-- office hours for out-of-hours counts; NULL: Mon–Fri 07:00–17:00 (docs/on-call.md §2)
office_hours jsonb,
-- country calling codes allowed for contact numbers (docs/on-call.md §1);
-- the default is the EEA, Switzerland and the United Kingdom
contact_calling_codes text[] NOT NULL DEFAULT ARRAY['30', '31', '32', '33', '34', '351', '352',
'353', '354', '356', '357', '358', '359', '36', '370', '371', '372', '385', '386', '39',
'40', '41', '420', '421', '423', '43', '44', '45', '46', '47', '48', '49'],
created_at timestamptz NOT NULL DEFAULT now(),
-- how long incidents, deliveries, notices and responses are kept (docs/compliance.md §2)
incident_retention_months int NOT NULL DEFAULT 13 CHECK (incident_retention_months BETWEEN 3 AND 25),
-- true: an SMS reply acknowledges only with the incident's code (docs/on-call.md §5)
sms_ack_code boolean NOT NULL DEFAULT false,
-- the last push of the tenant that Watch confirmed (docs/watch.md §5)
watch_synced_at timestamptz,
-- when the tenant's people last reached the daily budget of codes and
-- test messages; its admins and the vendor are told at most once a day
-- (docs/on-call.md §1)
budget_reached_at timestamptz,
-- how its messages go out (docs/on-call.md §4 Evaluation delivery, Trial
-- delivery): live through the carriers, trial through the carriers
-- within the trial's rules, evaluation to its people's evaluation inbox;
-- set by a vendor operator (cloud.yaml updateTenant) or the billing
-- service (putBillingEntitlement) only
delivery text NOT NULL DEFAULT 'evaluation' CHECK (delivery IN ('live', 'trial', 'evaluation')),
-- where its new vendor-run hubs go (cloud.yaml createHub hosting
-- vendor), set by a vendor operator: a shared installation, or the
-- dedicated one that serves this tenant alone; NULL: the cloud picks a
-- shared installation
installation_id uuid REFERENCES installation(id),
-- what the billing service set (docs/architecture.md §12 Plans): the
-- account it created the tenant for (NULL for a tenant a vendor
-- operator created), the plan's name as a label, whether Watch may call
-- (voice), the synthetic test's cadence of its hubs in seconds (NULL:
-- Watch's default) and the version of the last entitlement applied
billing_account text CHECK (length(billing_account) <= 100),
plan text CHECK (length(plan) <= 100),
voice boolean NOT NULL DEFAULT true,
synthetic_every int CHECK (synthetic_every BETWEEN 3600 AND 604800),
entitlements_version bigint
);

CREATE INDEX tenant_idp_org ON tenant (idp_org_id);
CREATE INDEX tenant_billing_account ON tenant (billing_account);

-- Data keys per tenant, wrapped by the deployment key. Deleting a tenant
-- deletes its keys with its rows; backups keep them until the backup
-- retention ends (docs/compliance.md §5).
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,
created_at timestamptz NOT NULL DEFAULT now(),
retired_at timestamptz,
PRIMARY KEY (tenant_id, id)
);

-- A person: a member of the tenant who can be on call. Login identity is
-- (issuer, subject) from Zitadel. A person who is in no team and holds no
-- tenant role is pseudonymised (name replaced by person-<the first 8 hex
-- digits of the id>, e-mail and contacts deleted), never deleted, so shifts, deliveries and responses keep their
-- references; issuer and subject stay, so a person who returns is the same
-- row (docs/on-call.md §1, docs/compliance.md §5).
CREATE TABLE person (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id uuid NOT NULL,
issuer text NOT NULL,
subject text NOT NULL,
display_name_sealed bytea NOT NULL,
email_sealed bytea,
email_hmac bytea, -- exact lookup by e-mail (searchPeople, oncall apply)
language text NOT NULL DEFAULT 'de' CHECK (language IN ('de', 'en')), -- set at the first login (docs/on-call.md §1)
timezone text NOT NULL DEFAULT 'Europe/Berlin',
-- notification rules, 1–3, checked in order (docs/on-call.md §4); empty
-- for a new person, who is unreachable until one is saved:
-- [{name, times: [{days, from, to}], min_severity, chain: [{medium:
-- push|sms|voice, contact (sms, voice), level: critical|standard (push),
-- wait}], repeat}]; the last has no times and no min_severity
notification_rules jsonb NOT NULL DEFAULT '[]',
-- shift reminder: {medium: push|sms|email, before: duration} or NULL (docs/on-call.md §10)
reminder jsonb,
calendar_token_hash bytea UNIQUE, -- private ICS feed of own shifts
last_login_at timestamptz, -- last IdP login, web or app (docs/on-call.md §1, leavers)
active boolean NOT NULL DEFAULT true, -- false: in no team and without a tenant role; pseudonymised
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id),
UNIQUE (tenant_id, issuer, subject)
);

CREATE INDEX person_email ON person (tenant_id, email_hmac);

-- Phone numbers. number_hmac (keyed with a tenant key) finds the person of an
-- inbound SMS without decrypting all numbers. A verified number belongs to
-- one person of the tenant (docs/on-call.md §1).
CREATE TABLE contact_method (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
person_id uuid NOT NULL,
label text NOT NULL,
media text[] NOT NULL CHECK (media <@ ARRAY['sms', 'voice']),
number_sealed bytea NOT NULL,
number_hmac bytea NOT NULL,
verified_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id) ON DELETE CASCADE
);

CREATE INDEX contact_method_lookup ON contact_method (tenant_id, number_hmac);
CREATE UNIQUE INDEX contact_method_verified ON contact_method (tenant_id, number_hmac) WHERE verified_at IS NOT NULL;

-- The current verification code of an unverified number (docs/on-call.md
-- §1): its keyed hash, never the code. A new code replaces the row; a
-- wrong entry counts in attempts, and at 5 the code is spent
-- (contact.code_exhausted). The row goes when the number is verified. The
-- code's message is a notice of kind verification (§5), and a person's
-- codes of the last hour are counted from those notices.
CREATE TABLE contact_verification (
tenant_id uuid NOT NULL,
contact_id uuid NOT NULL,
code_hmac bytea NOT NULL,
expires_at timestamptz NOT NULL, -- created_at + 10 minutes
attempts int NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 5),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, contact_id),
FOREIGN KEY (tenant_id, contact_id) REFERENCES contact_method(tenant_id, id) ON DELETE CASCADE
);

-- Devices with the Excubio app (docs/mobile.md §2). The device token (exd_…)
-- is stored as a hash; public_key is the device's P-256 key that push
-- contents are encrypted to (docs/mobile.md §3). ready: the last readiness
-- report (docs/mobile.md §4). unreachable: the push service reported the
-- push token as unregistered. At most 5 devices per person; a revoked or
-- expired device keeps its row for the deliveries that reference it.
CREATE TABLE device (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
person_id uuid NOT NULL,
name text NOT NULL,
platform text NOT NULL CHECK (platform IN ('ios', 'android')),
app_version text NOT NULL,
token_hash bytea NOT NULL UNIQUE,
push_token_sealed bytea,
public_key bytea NOT NULL,
readiness text NOT NULL DEFAULT 'not-ready' CHECK (readiness IN ('ready', 'limited', 'not-ready')),
checks jsonb NOT NULL DEFAULT '{}', -- the checks of the last report
sound jsonb NOT NULL DEFAULT '{}', -- page sound and volume
unreachable boolean NOT NULL DEFAULT false,
login_at timestamptz NOT NULL, -- last IdP login on the device
expires_at timestamptz NOT NULL, -- login_at + 30 days
reported_at timestamptz,
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id) ON DELETE CASCADE
);

CREATE INDEX device_person ON device (tenant_id, person_id) WHERE revoked_at IS NULL;

-- Absences: the person is skipped in all layers (docs/on-call.md §1–§2).
CREATE TABLE absence (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
person_id uuid NOT NULL,
starts_at timestamptz NOT NULL,
ends_at timestamptz NOT NULL CHECK (ends_at > starts_at),
created_by uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, created_by) REFERENCES person(tenant_id, id)
);

CREATE TABLE team (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id uuid NOT NULL,
slug text NOT NULL CHECK (slug ~ '^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$'),
name text NOT NULL,
mail text,
idp_group text, -- members synced from this group at login
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id),
UNIQUE (tenant_id, slug)
);

-- A team's members. An IdP-synced member (source idp) starts as member; a
-- team admin sets the role and can remove the row, and a person who is
-- still in the group gets it again, as member, at their next login
-- (docs/on-call.md §1).
CREATE TABLE team_member (
tenant_id uuid NOT NULL,
team_id uuid NOT NULL,
person_id uuid NOT NULL,
role text NOT NULL CHECK (role IN ('member', 'rotation-manager', 'team-admin')),
source text NOT NULL CHECK (source IN ('idp', 'manual')),
PRIMARY KEY (tenant_id, team_id, person_id),
FOREIGN KEY (tenant_id, team_id) REFERENCES team(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id) ON DELETE CASCADE
);

-- Tenant-wide roles: auditor, tenant-admin.
CREATE TABLE tenant_role (
tenant_id uuid NOT NULL,
person_id uuid NOT NULL,
role text NOT NULL CHECK (role IN ('auditor', 'tenant-admin')),
PRIMARY KEY (tenant_id, person_id, role),
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id) ON DELETE CASCADE
);

-- The tenant admins a vendor operator names when creating the tenant or
-- later (cloud.yaml createTenant, updateTenant admins), by their subject at
-- the installation's issuer or by their e-mail address (keyed hash; sealed
-- for display). The first login of that subject, or with that e-mail
-- address verified by the IdP, gets the role tenant-admin, audited, and
-- consumes the invitation (consumed_at, person_id); a consumed one changes
-- nothing more.
CREATE TABLE tenant_invite (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id uuid NOT NULL,
subject text,
email_sealed bytea,
email_hmac bytea,
role text NOT NULL DEFAULT 'tenant-admin' CHECK (role = 'tenant-admin'),
created_at timestamptz NOT NULL DEFAULT now(),
consumed_at timestamptz,
person_id uuid,
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id) ON DELETE CASCADE,
CHECK ((subject IS NULL) <> (email_hmac IS NULL)),
CHECK ((email_hmac IS NULL) = (email_sealed IS NULL)),
CHECK ((consumed_at IS NULL) = (person_id IS NULL))
);

-- API tokens (exk_…) of people and service accounts. The scope config
-- (docs/architecture.md §10 Configuration tokens) is only a service-account
-- token's with an expiry; the API also bounds the expiry (cloud.yaml
-- createApiToken).
CREATE TABLE api_token (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id uuid NOT NULL,
person_id uuid, -- NULL: service account token
name text NOT NULL,
token_hash bytea NOT NULL UNIQUE,
scopes text[] NOT NULL, -- pages, incidents, oncall, config, each optionally :<team>
expires_at timestamptz,
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id),
CONSTRAINT api_token_config_check
CHECK (array_to_string(scopes, ' ') !~ '(^| )config(:| |$)' OR (person_id IS NULL AND expires_at IS NOT NULL))
);

-- Vendor staff who may call the platform operations (tenants with their
-- limits and numbers); they authenticate with an access token of the
-- vendor's own Zitadel organization (cloud.yaml operatorLogin). Not tenant
-- data, so not under row-level security. They see no tenant's people or
-- incidents without a support grant (docs/architecture.md §10).
-- `excubio-cloud operator add` and `remove` change them with the migration
-- login (docs/operations.md §3); a removed operator keeps its row, which
-- support grants name, and can't sign in.
CREATE TABLE platform_operator (
issuer text NOT NULL,
subject text NOT NULL,
display_name text NOT NULL,
added_at timestamptz NOT NULL DEFAULT now(),
removed_at timestamptz,
PRIMARY KEY (issuer, subject)
);

-- The installation's own audit, not hash-chained, not tenant data: the
-- changes of the server subcommands (operators added and removed, tenants
-- created, suspended and deleted, docs/cli.md §6), each by the database
-- login that ran it, and the changes of the hub installations, by the
-- vendor operator or the installation that made them. The servers may
-- only read and append to it (§9).
CREATE TABLE platform_audit (
seq bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
at timestamptz NOT NULL DEFAULT now(),
-- the database login (session_user) of a subcommand, the operator
-- (<issuer>#<subject>), the installation (installation:<id>) or the
-- billing service (billing:<subject>; billing:pull for an entitlement
-- the cloud read from it, docs/architecture.md §10)
actor text NOT NULL,
-- operator.add, operator.remove, tenant.create, tenant.update,
-- installation.create, installation.update, installation.delete,
-- installation.enrolment_token, installation.enrol, installation.renew,
-- tenant.entitlements (the billing service's entitlement)
action text NOT NULL,
object text NOT NULL, -- <issuer>#<subject>, tenant:<id>, installation:<id>
details jsonb NOT NULL DEFAULT '{}'
);

-- The verification codes requested by the people of tenants in trial
-- (docs/on-call.md §4 Trial delivery), installation-wide, for the limits
-- per number and per source address across tenants: the number's keyed
-- hash under a key derived from the deployment key (number_hash), and the
-- request's source address. Deleted after a day; no tenant data.
CREATE TABLE code_request (
at timestamptz NOT NULL DEFAULT now(),
number_hash bytea NOT NULL,
source text NOT NULL CHECK (length(source) <= 64)
);

CREATE INDEX code_request_number ON code_request (number_hash, at);
CREATE INDEX code_request_source ON code_request (source, at);

-- A tenant admin's time-limited grant to one vendor operator to read the
-- tenant's data with the rights of auditor (docs/architecture.md §10).
CREATE TABLE support_grant (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id uuid NOT NULL,
op_issuer text NOT NULL,
op_subject text NOT NULL,
granted_by uuid NOT NULL,
reason text NOT NULL,
expires_at timestamptz NOT NULL, -- at most 72 h after created_at
revoked_at timestamptz,
first_used_at timestamptz, -- the tenant admins are told by e-mail
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (op_issuer, op_subject) REFERENCES platform_operator(issuer, subject),
FOREIGN KEY (tenant_id, granted_by) REFERENCES person(tenant_id, id),
CHECK (expires_at <= created_at + interval '72 hours')
);

-- Signed incident links in SMS (exl_…, docs/on-call.md §5): one person and
-- one incident, valid until the incident resolves and at most 24 h.
CREATE TABLE incident_link (
tenant_id uuid NOT NULL,
token_hash bytea NOT NULL UNIQUE,
incident_id uuid NOT NULL,
person_id uuid NOT NULL,
expires_at timestamptz NOT NULL,
PRIMARY KEY (tenant_id, token_hash),
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id) ON DELETE CASCADE
);

-- Sessions of the cloud UI (docs/architecture.md §11), as the hub's
-- (docs/schema/hub.sql web_session): id is the SHA-256 of the cookie
-- value; expires_at is the end of the session's longest life, counted from
-- created_at, and a session without a request since last_seen_at for the
-- idle time has ended too. last_seen_at is written at most once a minute
-- per session; ended sessions are deleted by the housekeeper. The tenant
-- comes from the host name, so a session is looked up under its tenant.
-- csrf_token: the value every request with the cookie other than GET
-- carries in X-CSRF-Token (docs/api/cloud.yaml conventions).
CREATE TABLE web_session (
tenant_id uuid NOT NULL,
id bytea NOT NULL,
person_id uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
last_seen_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL,
csrf_token text NOT NULL,
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id) ON DELETE CASCADE
);

CREATE INDEX web_session_expiry ON web_session (expires_at);

-- A sign-in of the cloud UI (docs/architecture.md §11 Sign-in): started on
-- the tenant's host (startOidcLogin) with its state, its PKCE verifier,
-- nonce and the UI path to return to, sealed, and the SHA-256 of the
-- binding cookie ex_login, which only the browser that started it holds.
-- The IdP returns to the installation host's one callback
-- (completeOidcLogin), which finds the login by the state's hash, signs
-- the person in and sets the SHA-256 of a code that hands the login over
-- to the tenant's host within 60 s, once, from the same browser
-- (redeemLoginHandoff, which deletes the row). Expired rows are deleted
-- by the housekeeper.
CREATE TABLE login_attempt (
tenant_id uuid NOT NULL REFERENCES tenant(id),
state_hash bytea NOT NULL,
pending_sealed bytea NOT NULL,
binding_hash bytea NOT NULL,
handoff_hash bytea UNIQUE,
person_id uuid,
expires_at timestamptz NOT NULL,
PRIMARY KEY (tenant_id, state_hash),
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id) ON DELETE CASCADE,
CHECK ((handoff_hash IS NULL) = (person_id IS NULL))
);

CREATE INDEX login_attempt_expiry ON login_attempt (expires_at);

-------------------------------------------------------------------------------
-- 2. Rotations and shifts (docs/on-call.md §2)
-------------------------------------------------------------------------------

-- kind 'synthetic' is the Watch test rotation (docs/watch.md §1); it does not
-- count against the rotations limit.
CREATE TABLE rotation (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
team_id uuid NOT NULL,
slug text NOT NULL,
name text NOT NULL,
-- synthetic: the rotation "synthetic" of the reserved team "excubio",
-- created with the tenant; no layers, the handset is Watch's test number,
-- not counted in the licence, not shown (docs/watch.md §1).
kind text NOT NULL DEFAULT 'normal' CHECK (kind IN ('normal', 'synthetic')),
timezone text NOT NULL,
-- grouping: {window, storm_incidents, storm_window}
grouping jsonb NOT NULL DEFAULT '{"window": "10m", "storm_incidents": 3, "storm_window": "5m"}',
-- escalation: levels [{target, after (1m–24h)}] in level order, the
-- first is level 1; empty: one level, on-call for 30m. repeat (0–5),
-- ack_timeout (15m–7d, NULL = off); docs/on-call.md §7
escalation jsonb NOT NULL DEFAULT '{"levels": [], "repeat": 0, "ack_timeout": null}',
min_media text[] NOT NULL DEFAULT '{}', -- media that every chain must contain
-- handset passed on at hand-over (docs/on-call.md §2), with its media chain
handset_sealed bytea,
handset_hmac bytea,
handset_chain jsonb,
resolve_message boolean NOT NULL DEFAULT true,
number_test jsonb, -- {days, time} or NULL
version bigint NOT NULL DEFAULT 1, -- incremented on every change; the API's ETag
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id),
UNIQUE (tenant_id, team_id, slug),
FOREIGN KEY (tenant_id, team_id) REFERENCES team(tenant_id, id) ON DELETE CASCADE,
CHECK ((handset_sealed IS NULL) = (handset_hmac IS NULL))
);

CREATE UNIQUE INDEX rotation_handset ON rotation (tenant_id, handset_hmac) WHERE handset_hmac IS NOT NULL;

-- People paged for a gap (docs/on-call.md §2). They and the people of the
-- layers (layer_member) are members of the rotation's team; a person who
-- leaves the team is removed from both (docs/on-call.md §1).
CREATE TABLE rotation_fallback (
tenant_id uuid NOT NULL,
rotation_id uuid NOT NULL,
person_id uuid NOT NULL,
PRIMARY KEY (tenant_id, rotation_id, person_id),
FOREIGN KEY (tenant_id, rotation_id) REFERENCES rotation(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id)
);

-- Built-in holiday regions and their days, installation-wide, written
-- from the installation's holiday file at a server's start
-- (docs/operations.md §3).
CREATE TABLE holiday_region (
code text PRIMARY KEY, -- e.g. DE-RP
name text NOT NULL
);

CREATE TABLE holiday (
region text NOT NULL REFERENCES holiday_region(code),
day date NOT NULL,
name text NOT NULL,
PRIMARY KEY (region, day)
);

-- A tenant's calendar: a built-in region plus own additions and removals.
CREATE TABLE tenant_calendar (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id uuid NOT NULL,
name text NOT NULL,
region text REFERENCES holiday_region(code),
PRIMARY KEY (tenant_id, id),
UNIQUE (tenant_id, name)
);

CREATE TABLE tenant_calendar_day (
tenant_id uuid NOT NULL,
calendar_id uuid NOT NULL,
day date NOT NULL,
name text NOT NULL,
holiday boolean NOT NULL DEFAULT true, -- false removes a built-in day
PRIMARY KEY (tenant_id, calendar_id, day),
FOREIGN KEY (tenant_id, calendar_id) REFERENCES tenant_calendar(tenant_id, id) ON DELETE CASCADE
);

-- A layer covers from starts_at to ends_at; its pattern runs from anchor:
-- the first person of the order is on call from the anchor to the first
-- hand-over after it. Day patterns hand over at the local handover time
-- (weekly on handover_day, or the anchor's weekday), custom day lengths
-- counted from the anchor's local date; hour patterns hand over at the
-- anchor plus multiples of length and have no handover. anchor is
-- starts_at at creation; a change of the layer's people moves it to the
-- start of the current shift, with layer_member rotated so that the order
-- continues from the person on call, or the next one when that person was
-- removed (docs/on-call.md §2).
CREATE TABLE layer (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
rotation_id uuid NOT NULL,
position int NOT NULL, -- 0 = top
name text NOT NULL,
pattern text NOT NULL CHECK (pattern IN ('daily', 'weekly', 'custom')),
length interval, -- custom only: whole days or whole hours
handover time, -- NULL only for hour patterns
handover_day int CHECK (handover_day BETWEEN 1 AND 7), -- weekly
mode text NOT NULL DEFAULT 'one' CHECK (mode IN ('one', 'all', 'punch')),
min_on_duty int CHECK (min_on_duty >= 0), -- punch layers (docs/on-call.md §2.2)
max_duty interval, -- punch layers: automatic punch-out
starts_at timestamptz NOT NULL, -- start of coverage
ends_at timestamptz CHECK (ends_at > starts_at), -- NULL: open-ended
anchor timestamptz NOT NULL, -- start of the pattern
-- restrictions: [{days, from, to}]; empty = always. days: the weekdays a
-- window starts on; from = to: the 24 hours from from. Restrictions don't
-- move hand-overs.
restrictions jsonb NOT NULL DEFAULT '[]',
-- holidays are local calendar days of the rotation's timezone; without a
-- calendar the layer has no holidays
calendar_id uuid,
holidays text NOT NULL DEFAULT 'uncovered' CHECK (holidays IN ('uncovered', 'only', 'ignore')),
PRIMARY KEY (tenant_id, id),
UNIQUE (tenant_id, rotation_id, position),
FOREIGN KEY (tenant_id, rotation_id) REFERENCES rotation(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, calendar_id) REFERENCES tenant_calendar(tenant_id, id),
CHECK (handover IS NOT NULL OR pattern = 'custom')
);

-- The ordered people of a layer; position 0 is on call from the anchor.
CREATE TABLE layer_member (
tenant_id uuid NOT NULL,
layer_id uuid NOT NULL,
position int NOT NULL,
person_id uuid NOT NULL,
PRIMARY KEY (tenant_id, layer_id, position),
UNIQUE (tenant_id, layer_id, person_id),
FOREIGN KEY (tenant_id, layer_id) REFERENCES layer(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id)
);

-- Overrides and swaps (docs/on-call.md §2). A swap (swap_with set) replaces
-- the requester swap_with in their shifts of the period, before absences are
-- checked, and not in punch layers; person_id is the person asked, or NULL
-- for an open request until someone accepts. Active overrides of one
-- rotation don't overlap, and swaps don't overlap with overrides or with
-- swaps of the same requester; the application checks this under a lock on
-- the rotation. replace shortens an older override that overlaps one edge
-- of the new one, cancels one that lies within it and splits one that
-- encloses it: it keeps the part before, and a new row with the same
-- person, creator and reason takes the part after. Absences don't affect
-- overrides (docs/on-call.md §2).
CREATE TABLE override (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
rotation_id uuid NOT NULL,
person_id uuid,
starts_at timestamptz NOT NULL,
ends_at timestamptz NOT NULL CHECK (ends_at > starts_at),
swap_with uuid, -- swap: the requester whose shifts are taken
state text NOT NULL DEFAULT 'active' CHECK (state IN ('requested', 'active', 'declined', 'expired', 'cancelled')),
created_by uuid NOT NULL,
reason text,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, rotation_id) REFERENCES rotation(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id),
FOREIGN KEY (tenant_id, swap_with) REFERENCES person(tenant_id, id),
FOREIGN KEY (tenant_id, created_by) REFERENCES person(tenant_id, id),
CHECK (person_id IS NOT NULL OR (swap_with IS NOT NULL AND state <> 'active'))
);

-- Punch-in periods of punch layers (docs/on-call.md §2.2); each is also a
-- shift with source 'punch'. ends_at NULL: punched in now. until: the
-- max-duty punch-out of a layer with max_duty, moved on by an extension;
-- the shifts of a punch-in end there until it ends otherwise.
CREATE TABLE punch (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
layer_id uuid NOT NULL,
person_id uuid NOT NULL,
starts_at timestamptz NOT NULL,
ends_at timestamptz CHECK (ends_at > starts_at),
ended_by text CHECK (ended_by IN ('person', 'manager', 'max-duty')),
created_by uuid NOT NULL,
until timestamptz,
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, layer_id) REFERENCES layer(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id),
FOREIGN KEY (tenant_id, created_by) REFERENCES person(tenant_id, id)
);

CREATE UNIQUE INDEX punch_open ON punch (tenant_id, layer_id, person_id) WHERE ends_at IS NULL;

-- Materialised shifts, 30 days ahead, kept for retention. A change ends the
-- affected rows (superseded_at) and inserts new ones; history is never
-- rewritten (docs/on-call.md §2). For a shift in progress, the new rows
-- are a copy that ends at the change and the shifts from then on. A shift
-- is one person's continuous time in one pattern slot of a layer (or one
-- override, absence cover, punch or gap); a shift that restriction windows
-- cut has a row per window. The last row is cut at the horizon and is
-- superseded and inserted again when the horizon moves.
CREATE TABLE shift (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
rotation_id uuid NOT NULL,
person_id uuid, -- NULL: gap
starts_at timestamptz NOT NULL,
ends_at timestamptz NOT NULL,
source text NOT NULL CHECK (source IN ('layer', 'override', 'absence-cover', 'gap', 'punch')),
layer_id uuid,
override_id uuid,
absence_id uuid, -- absence-cover: the absence covered
created_at timestamptz NOT NULL DEFAULT now(),
superseded_at timestamptz,
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, rotation_id) REFERENCES rotation(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id),
FOREIGN KEY (tenant_id, layer_id) REFERENCES layer(tenant_id, id) ON DELETE SET NULL (layer_id),
FOREIGN KEY (tenant_id, override_id) REFERENCES override(tenant_id, id) ON DELETE SET NULL (override_id),
FOREIGN KEY (tenant_id, absence_id) REFERENCES absence(tenant_id, id) ON DELETE SET NULL (absence_id)
);

CREATE INDEX shift_current ON shift (tenant_id, rotation_id, starts_at, ends_at) WHERE superseded_at IS NULL;

-------------------------------------------------------------------------------
-- 3. Hubs (docs/operations.md §4)
-------------------------------------------------------------------------------

-- A tenant's hub. Its hosting: on an installation of the vendor
-- (installation_id, shared or dedicated), or run by the customer
-- (installation_id NULL), which enrols it with an enrolment token. A hub
-- on an installation has no enrolment token: its installation enrols it
-- (cloud.yaml enrolInstallationHub) once the installation_hub row tells
-- the installation to run it. Its state as cloud.yaml Hub shows it:
-- decommissioned, revoked, failed (the installation reported a failure),
-- enrolled (a certificate), provisioning (on an installation, not
-- enrolled yet) or not_enrolled.
CREATE TABLE hub (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id uuid NOT NULL,
name text NOT NULL,
enrol_token_hash bytea UNIQUE, -- exe_…, valid 24 h, cleared by enrolment; issued again to enrol again
enrol_expires_at timestamptz,
-- the SHA-256 of the DER of the current client certificate, issued by
-- the cloud's hub CA (subject common name: the hub's id, valid 1 year)
cert_fingerprint bytea UNIQUE,
cert_expires_at timestamptz,
version text,
-- The down stream (docs/architecture.md §5): link_epoch is renewed at
-- every enrolment and for every hub when the database is restored;
-- down_seq is the last sequence written, acked_seq the last the hub
-- confirmed with the stream cursor.
link_epoch uuid NOT NULL,
-- the epoch of the newest stream opened for the hub: incremented by the
-- cloud for each stream it opens; a cursor with an older one is refused
-- (link.stale_holder, docs/architecture.md §5)
stream_epoch bigint NOT NULL DEFAULT 0,
-- rotations the hub may page and receives (docs/architecture.md §12):
-- globs over team/rotation; empty for a new hub
rotations text[] NOT NULL DEFAULT '{}',
down_seq bigint NOT NULL DEFAULT 0,
acked_seq bigint NOT NULL DEFAULT 0 CHECK (acked_seq <= down_seq),
-- Watch (docs/watch.md §1): the hub's public Watch key from enrolment,
-- and the rotation and fallback numbers of its hub and synthetic checks.
watch_key bytea, -- NULL while revoked: Watch rejects the hub's beats
watch_rotation_id uuid NOT NULL,
watch_fallback_sealed bytea NOT NULL,
-- the hub's last link call, or the last sweep of its open down stream
-- (docs/architecture.md §5); written at most every 30 s
last_seen_at timestamptz,
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
watch_synced_at timestamptz, -- the last push of the hub that Watch confirmed (docs/watch.md §5)
-- the certificate a renewal replaced: it stays valid until the hub
-- first calls with the new one, so a renewal whose answer was lost can be
-- repeated (docs/operations.md §4); enrolment and revocation clear it
prev_cert_fingerprint bytea UNIQUE,
-- decommissioned (revokeHub with decommission): revoked, left out of
-- the tenant's hubs at Watch; enrolling again ends it
decommissioned_at timestamptz,
-- On an installation: the installation, the hub's host label, unique
-- within the installation while installation_hub holds it, so its URL
-- is https://<host_label>.<installation.hub_domain>, and the IdP subject
-- at the installation's Zitadel of its first admin, whom the
-- installation binds admin hub-wide. Fixed when the hub is created; a
-- decommissioned hub whose installation was deleted keeps the other two.
installation_id uuid REFERENCES installation(id) ON DELETE SET NULL,
host_label text CHECK (host_label ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'),
admin_subject text CHECK (length(admin_subject) <= 254),
PRIMARY KEY (tenant_id, id),
UNIQUE (tenant_id, name),
FOREIGN KEY (tenant_id, watch_rotation_id) REFERENCES rotation(tenant_id, id),
CHECK ((host_label IS NULL) = (admin_subject IS NULL) AND (installation_id IS NULL OR host_label IS NOT NULL))
);

-- What an installation is to run (docs/operations.md §4), one row per hub
-- placed on it, read by the installation with pollInstallation (cloud.yaml
-- tag installation): desired is the hub's current desired state as
-- InstallationHub, never a difference, written in the transaction that
-- changed one of its inputs (the hub created, enrolled, revoked or
-- decommissioned; the tenant's state or limits changed) whenever it
-- differs from the stored one, each time with the installation's next
-- sequence (installation.seq, whose row lock orders the writers), so the
-- installation's cursor never passes a change. Its state: active;
-- suspended with the tenant; deleted when the hub is decommissioned or
-- the tenant is deleting, and then only the hub's id, tenant and host
-- label are kept. Not tenant data: a tenant's deletion leaves the rows,
-- which name the tenant by its id only, until the installation reports
-- the hub deleted (reportHubState), which deletes the row and frees its
-- host label and place. reported is the installation's last report,
-- reason that of a failure, shown to tenant admins and operators.
CREATE TABLE installation_hub (
hub_id uuid PRIMARY KEY,
installation_id uuid NOT NULL REFERENCES installation(id),
tenant_id uuid NOT NULL,
host_label text NOT NULL,
seq bigint NOT NULL,
desired jsonb NOT NULL,
reported text CHECK (reported IN ('provisioned', 'failed', 'deleted')),
reason text CHECK (length(reason) <= 1000),
reported_at timestamptz,
UNIQUE (installation_id, host_label),
UNIQUE (installation_id, seq)
);

CREATE INDEX installation_hub_tenant ON installation_hub (tenant_id);

-- Daily usage of a hub on an installation (cloud.yaml reportUsage), for
-- the vendor's billing (listUsage): per UTC day the events received and
-- refused and, at the day's end, the CIs, sources, relays and stored
-- bytes. A repeated report of a day replaces it. Kept 25 months, through
-- a tenant's deletion: counts, no tenant data.
CREATE TABLE hub_usage (
day date NOT NULL,
hub_id uuid NOT NULL,
tenant_id uuid NOT NULL,
installation_id uuid NOT NULL,
events_received bigint NOT NULL CHECK (events_received >= 0),
events_refused bigint NOT NULL CHECK (events_refused >= 0),
cis bigint NOT NULL CHECK (cis >= 0),
sources bigint NOT NULL CHECK (sources >= 0),
relays bigint NOT NULL CHECK (relays >= 0),
stored_bytes bigint NOT NULL CHECK (stored_bytes >= 0),
reported_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (day, hub_id)
);

CREATE INDEX hub_usage_tenant ON hub_usage (tenant_id, day);

-- The down stream of the link: every update for a hub with its sequence,
-- written in the transaction that changed the object. body is the object's
-- current state as the hub sees it (cloud.yaml HubUpdate), or, with
-- deleted, only its id. Pruned once confirmed (seq <= acked_seq) and older
-- than 7 days; all of a hub's updates are deleted when its link epoch is
-- renewed. A body with contact data (type fallback-cache: numbers) is
-- stored sealed in body_sealed, and body is then {}. The display names in
-- the other bodies are the one personal datum the cloud stores unsealed,
-- for the life of these rows.
CREATE TABLE hub_update (
tenant_id uuid NOT NULL,
hub_id uuid NOT NULL,
seq bigint NOT NULL,
type text NOT NULL CHECK (type IN ('incident', 'delivery', 'response', 'shift', 'team', 'rotation', 'rotation-readiness', 'fallback-cache', 'person')),
object_id text NOT NULL, -- id of the object, team slug, or team/rotation
body jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
deleted boolean NOT NULL DEFAULT false,
body_sealed bytea,
PRIMARY KEY (tenant_id, hub_id, seq),
FOREIGN KEY (tenant_id, hub_id) REFERENCES hub(tenant_id, id) ON DELETE CASCADE
);

-- Idempotency keys of writes (docs/api/hub.yaml conventions), per caller:
-- a hub, an API token, a device or a session's person. Kept 24 h, a
-- hub's 7 days (docs/architecture.md §5). A
-- repeated key with the same request hash returns the stored response; with
-- another hash it is rejected (idempotency.mismatch). The first request
-- inserts the row with status NULL and holds its row lock until it
-- commits; a concurrent repeat of a hub's link call waits on that lock
-- and then returns the stored response, any other is answered
-- idempotency.in_progress (docs/api/cloud.yaml conventions). A response that
-- carries a token shown once (a device, API or enrolment token, a calendar
-- URL) is stored sealed in response_sealed, and response is then NULL, so
-- no token is kept in clear.
CREATE TABLE idempotency_key (
tenant_id uuid NOT NULL REFERENCES tenant(id),
caller text NOT NULL, -- hub:<id>, token:<id>, device:<id>, person:<id>
key text NOT NULL,
request_hash bytea NOT NULL, -- method, path and body
status int,
response jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
response_sealed bytea,
PRIMARY KEY (tenant_id, caller, key)
);

CREATE INDEX idempotency_key_age ON idempotency_key (created_at);

-- The cloud's pushes to Watch (docs/watch.md §5; docs/api/watch.yaml tag
-- replica) that are to be sent: the tenant (object_id: the tenant's id)
-- with its roles, numbers and hubs, a hub with its Watch key, rotation
-- and fallback numbers (a decommissioned one is deleted), and the
-- rotation replica (object_id: the tenant's id). A change queues its
-- object, and the replica push queues them all every 5 minutes; a queued
-- object is sent as it is when the push is sent, once however often it
-- was queued. A push Watch took deletes its row and sets the object's
-- watch_synced_at; a failed one is tried again after 5 s, doubled per
-- attempt up to 5 minutes. Any cloud server sends what is due.
CREATE TABLE watch_push (
tenant_id uuid NOT NULL REFERENCES tenant(id),
kind text NOT NULL CHECK (kind IN ('tenant', 'hub', 'rotations')),
object_id uuid NOT NULL,
due_at timestamptz NOT NULL DEFAULT now(),
attempts int NOT NULL DEFAULT 0,
last_error text,
PRIMARY KEY (tenant_id, kind, object_id)
);

CREATE INDEX watch_push_due ON watch_push (due_at);

-------------------------------------------------------------------------------
-- 4. Incidents (docs/on-call.md §3)
-------------------------------------------------------------------------------

CREATE TYPE incident_state AS ENUM ('triggered', 'acknowledged', 'resolved');

-- short_code: four-digit SMS reply code, shown with leading zeros; not
-- reused within 7 days after the incident resolved (docs/on-call.md §5). policy: the rotation's escalation
-- and grouping when the incident was triggered. acked_at, acked_response:
-- the latest ack and its response (person, token or hub user), cleared by
-- an un-ack. unanswered_at: escalation ran out without a response
-- (docs/on-call.md §7), set again each time it runs out; kept as history
-- after an ack or a resolve. The incident shows as unanswered from
-- unanswered_at until the next applied ack or snooze, or its resolve. severity: the alert's; for kind manual the one the person
-- picked (default major, docs/on-call.md §9); for kind test always
-- critical (docs/on-call.md §8). A manual page (docs/on-call.md §9) has
-- its text and who paged: created_by (a person), created_token (a service
-- account's token) or created_actor (a hub user, '<hub id>/<hub user
-- id>'); a person's manual pages of the last hour are counted from
-- created_by. request_key: the idempotency key of a manual page sent by a
-- hub (manual/<id>), unique for good, as incident_alert.idempotency_key
-- is for alerts. origin_rotation: set by the first reassign to the
-- rotation the incident was triggered for, and kept: alerts for that
-- rotation with the grouping key keep joining it (docs/on-call.md §3).
-- round: the repeats of the policy done (0 in the first pass through the
-- levels), set back to 0 by a reassign. level_at: when the current level
-- started (or started again after an un-ack or an ack timeout); a
-- hand-over during it starts the chains of those who came on call since
-- (docs/on-call.md §3). skipped: the levels skipped because their target
-- reached nobody reachable, [{level, round, target, at}] in order
-- (docs/on-call.md §7).
CREATE TABLE incident (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
short_code int NOT NULL CHECK (short_code BETWEEN 0 AND 9999),
rotation_id uuid NOT NULL,
kind text NOT NULL CHECK (kind IN ('alert', 'storm', 'manual', 'test', 'synthetic')),
grouping_key text,
group_ref uuid, -- the hub's group alert, for group incidents (docs/on-call.md §3)
merged_into uuid, -- set when merged into another incident
state incident_state NOT NULL DEFAULT 'triggered',
title text NOT NULL,
severity text NOT NULL,
policy jsonb NOT NULL, -- {escalation, grouping} at trigger time
level int NOT NULL DEFAULT 1, -- current escalation level
hub_id uuid, -- origin hub, for alert incidents
triggered_at timestamptz NOT NULL DEFAULT now(),
last_alert_at timestamptz NOT NULL DEFAULT now(),
acked_at timestamptz,
acked_response uuid, -- FK below, after response
unanswered_at timestamptz,
resolved_at timestamptz,
resolved_by text CHECK (resolved_by IN ('source', 'person', 'api', 'merge', 'timeout')), -- timeout: a test incident (docs/on-call.md §6)
reassigned_from uuid, -- previous rotation after a reassign
text text, -- manual
created_by uuid,
created_token uuid,
created_actor text,
request_key text,
origin_rotation uuid,
round int NOT NULL DEFAULT 0,
level_at timestamptz NOT NULL DEFAULT now(),
skipped jsonb NOT NULL DEFAULT '[]',
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, rotation_id) REFERENCES rotation(tenant_id, id),
FOREIGN KEY (tenant_id, hub_id) REFERENCES hub(tenant_id, id),
FOREIGN KEY (tenant_id, merged_into) REFERENCES incident(tenant_id, id),
FOREIGN KEY (tenant_id, reassigned_from) REFERENCES rotation(tenant_id, id),
FOREIGN KEY (tenant_id, created_by) REFERENCES person(tenant_id, id),
FOREIGN KEY (tenant_id, created_token) REFERENCES api_token(tenant_id, id),
FOREIGN KEY (tenant_id, origin_rotation) REFERENCES rotation(tenant_id, id),
CONSTRAINT incident_test_severity_check CHECK (kind <> 'test' OR severity = 'critical')
);

CREATE INDEX incident_group ON incident (tenant_id, group_ref) WHERE group_ref IS NOT NULL;
-- listIncidents by trigger time and its since filter (docs/api/cloud.yaml),
-- with the id that breaks ties.
CREATE INDEX incident_triggered ON incident (tenant_id, triggered_at, id);

ALTER TABLE incident_link ADD FOREIGN KEY (tenant_id, incident_id) REFERENCES incident(tenant_id, id) ON DELETE CASCADE;

-- Involved rotations of a group incident (docs/on-call.md §3): inform sends
-- an information message to the people on call; page opens a linked
-- incident (linked_incident) on the rotation.
CREATE TABLE incident_involved (
tenant_id uuid NOT NULL,
incident_id uuid NOT NULL,
rotation_id uuid NOT NULL,
mode text NOT NULL CHECK (mode IN ('inform', 'page')),
informed_at timestamptz,
linked_incident uuid,
PRIMARY KEY (tenant_id, incident_id, rotation_id),
FOREIGN KEY (tenant_id, incident_id) REFERENCES incident(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, rotation_id) REFERENCES rotation(tenant_id, id),
FOREIGN KEY (tenant_id, linked_incident) REFERENCES incident(tenant_id, id)
);

CREATE UNIQUE INDEX incident_open_code ON incident (tenant_id, short_code) WHERE state <> 'resolved';
CREATE INDEX incident_code_recent ON incident (tenant_id, short_code, resolved_at);
CREATE INDEX incident_grouping ON incident (tenant_id, rotation_id, grouping_key) WHERE state <> 'resolved';
CREATE INDEX incident_grouping_origin ON incident (tenant_id, origin_rotation, grouping_key) WHERE state <> 'resolved' AND origin_rotation IS NOT NULL;
CREATE UNIQUE INDEX incident_request_key ON incident (tenant_id, request_key) WHERE request_key IS NOT NULL;
CREATE INDEX incident_created_by ON incident (tenant_id, created_by, triggered_at) WHERE created_by IS NOT NULL;

-- Page requests from hubs. idempotency_key is the hub's action run key
-- (alert, identity, run; docs/pipeline.md §10), unique for good: a repeated
-- request returns the incident it went to. An alert can belong to several
-- incidents (its page and attach runs, involved rotations paged).
CREATE TABLE incident_alert (
tenant_id uuid NOT NULL,
incident_id uuid NOT NULL,
hub_id uuid NOT NULL,
alert_id uuid NOT NULL, -- the hub's alert id
idempotency_key text NOT NULL,
title text NOT NULL,
severity text NOT NULL,
payload jsonb NOT NULL, -- as redacted by the hub
-- lost: the hub no longer knows the alert after a hub restore
-- (docs/architecture.md §5); it keeps its incident open.
state text NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'closed', 'lost')),
added_at timestamptz NOT NULL DEFAULT now(),
closed_at timestamptz,
PRIMARY KEY (tenant_id, incident_id, alert_id),
UNIQUE (tenant_id, idempotency_key),
FOREIGN KEY (tenant_id, incident_id) REFERENCES incident(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, hub_id) REFERENCES hub(tenant_id, id)
);

-------------------------------------------------------------------------------
-- 5. Delivery and responses (docs/on-call.md §4–§5)
-------------------------------------------------------------------------------

-- One media chain per person notified for an incident; chains of one
-- incident run side by side (docs/on-call.md §4). A rotation's handset has
-- one chain per incident, recorded for the first person on call in layer
-- order when it starts; a hand-over starts no second one (docs/on-call.md
-- §2). Synthetic incidents have
-- none: their one SMS is a delivery without a person (docs/on-call.md §6). Reaching the person again
-- resets step and round. next_at is the due time of
-- the next step, run by the holder of the tenant's controller shard
-- (docs/architecture.md §8); a throttled step
-- sets it to the end of the person's throttle window. failures counts the
-- tries in a row of a step the cloud couldn't run, with the last error; a
-- step that ran sets it to 0 (docs/on-call.md §4). invited: started by
-- an invite; a new level stops the chains of earlier levels but not
-- these, an ack, a reassign, a resolve or a merge stops them too
-- (docs/on-call.md §7).
CREATE TABLE chain (
tenant_id uuid NOT NULL,
incident_id uuid NOT NULL,
person_id uuid NOT NULL,
level int NOT NULL, -- escalation level that started it
rule text NOT NULL, -- the notification rule that matched at start
steps jsonb NOT NULL, -- its media chain as it was at start
step int NOT NULL DEFAULT 0,
round int NOT NULL DEFAULT 1, -- repeat of the whole chain
state text NOT NULL DEFAULT 'running' CHECK (state IN ('running', 'responded', 'declined', 'ended', 'stopped')),
next_at timestamptz,
failures int NOT NULL DEFAULT 0,
last_error text,
invited boolean NOT NULL DEFAULT false,
started_at timestamptz NOT NULL DEFAULT now(), -- when it started (again) from its first step
PRIMARY KEY (tenant_id, incident_id, person_id),
FOREIGN KEY (tenant_id, incident_id) REFERENCES incident(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id)
);

CREATE INDEX chain_due ON chain (next_at) WHERE state = 'running';

-- no-answer includes calls without the attention key (voicemail). For push,
-- sent means accepted by APNs or FCM, delivered means the device's receipt,
-- no-receipt that none came within 30 s (docs/mobile.md §3). throttled: a
-- step deferred to the end of the person's throttle window
-- (docs/on-call.md §4); its chain stays at the step until then, when the
-- merged message is queued for all of the person's deferred steps of the
-- medium (of the device, for push) and their chains move on, each waiting
-- for its send.
CREATE TYPE delivery_status AS ENUM ('queued', 'sent', 'delivered', 'failed', 'no-answer', 'busy', 'throttled', 'finished', 'no-receipt');

-- A delivery is one attempt of a chain step. level, chain_step and
-- chain_round are NULL exactly for a synthetic incident's SMS to its
-- handset, which has no person and no chain (docs/on-call.md §6). A
-- deferred step (status throttled) that went out in a merged message
-- names that message's delivery in merged_into and takes its status from
-- it (docs/on-call.md §4). A delivery to a rotation's handset names the
-- rotation in handset_rotation and has no contact_id, so its destination
-- stays known after a reassign.
--
-- Outbox: a delivery and a notice are written queued, with their message
-- (destination and text) sealed with the tenant's data key in
-- message_sealed, in the transaction that decides them; nothing is sent
-- inside a request or a chain step. A sender claims queued rows (FOR
-- UPDATE SKIP LOCKED) by setting claimed_until, a lease of the time its
-- carriers may take, and claim, a random id of its own; it sends, and
-- records the outcome, which clears the message and the lease. Before
-- each carrier's send the sender checks, in a transaction, that the row
-- is still queued under its own claim with time left on the lease, and
-- that the message may still go out, and renews the lease for that
-- send (the carrier's 10 s and a minute for the record); a sender whose
-- check fails sends nothing, so a send that outlived its lease, which
-- another sender has claimed since, never goes to a carrier a second
-- time. A sender that dies leaves its rows queued, and another claims
-- them once the lease has passed: a message is never lost, and goes out
-- twice only when a sender dies between the carrier's acceptance and the
-- record of it. A delivery that a carrier refuses is failed, and the next
-- attempt is a new queued row with the same message and the claim of the
-- same sender; the attempts of a step skip the carriers that refused it.
-- A chain started again ends what it queued: a queued row no sender holds
-- ends unsent, a deferred step too, and a claimed one is marked stopped,
-- which the sender's check before its send ends unsent.
CREATE TABLE delivery (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
incident_id uuid NOT NULL,
person_id uuid, -- NULL only for a synthetic incident's delivery to its handset (docs/watch.md §1)
contact_id uuid, -- sms, voice; NULL for the rotation's handset
device_id uuid, -- push
medium text NOT NULL CHECK (medium IN ('push', 'sms', 'voice')),
carrier text, -- for push: apns or fcm
carrier_ref text, -- unique per carrier, installation-wide
attempt int NOT NULL,
level int,
chain_step int,
chain_round int,
status delivery_status NOT NULL DEFAULT 'queued',
merged_count int NOT NULL DEFAULT 0, -- deferred steps of other incidents carried by this message
by_fallback boolean NOT NULL DEFAULT false, -- reported by a hub after a fallback send
queued_at timestamptz NOT NULL DEFAULT now(),
sent_at timestamptz,
receipt_at timestamptz, -- push: the device's receipt, also when late
final_at timestamptz,
reason text, -- why it failed, e.g. device.expired; incident.answered: still queued when
-- the incident was acknowledged or resolved or its chain was stopped
-- (a later level, a reassign), and not sent;
-- carrier.not_delivered: the carrier's receipt says so;
-- push: device.expired, device.not_ready, device.unreachable,
-- device.unregistered (the service's answer), push.unconfigured,
-- push.unhealthy (docs/mobile.md §3); a synthetic incident's SMS:
-- watch.no_test_number, and under evaluation delivery (carrier
-- 'watch') watch.unconfigured, watch.not_accepted
-- (docs/on-call.md §4); in trial (docs/on-call.md §4 Trial
-- delivery) trial.no_voice for a call not made, and for an SMS
-- that went to the evaluation inbox instead (carrier 'inbox',
-- delivered) trial.unverified, trial.country, trial.sms_cap
country text, -- sms, voice through a carrier: the destination's country calling code
merged_into uuid, -- throttled: the delivery of the merged message
message_sealed bytea, -- queued: the message, sealed (outbox above); NULL once final, but
-- kept for the person's inbox under evaluation delivery (carrier
-- 'inbox', docs/on-call.md §4)
claimed_until timestamptz, -- queued: the lease of the sender that claimed it
handset_rotation uuid, -- sms, voice to the rotation's handset
claim uuid, -- queued: the claim of the sender that holds it (outbox above)
stopped boolean NOT NULL DEFAULT false, -- queued and claimed when its chain was started again: not sent
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, incident_id) REFERENCES incident(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id),
FOREIGN KEY (tenant_id, contact_id) REFERENCES contact_method(tenant_id, id) ON DELETE SET NULL (contact_id),
FOREIGN KEY (tenant_id, device_id) REFERENCES device(tenant_id, id),
FOREIGN KEY (tenant_id, merged_into) REFERENCES delivery(tenant_id, id),
FOREIGN KEY (tenant_id, handset_rotation) REFERENCES rotation(tenant_id, id),
CHECK ((medium = 'push') = (device_id IS NOT NULL)),
CONSTRAINT delivery_chain_check CHECK ((person_id IS NULL) = (level IS NULL)
AND (level IS NULL) = (chain_step IS NULL) AND (level IS NULL) = (chain_round IS NULL))
);

CREATE UNIQUE INDEX delivery_carrier_ref ON delivery (carrier, carrier_ref);
CREATE INDEX delivery_outbox ON delivery (queued_at) WHERE status = 'queued';

-- A response is given by a person, or by a service account through an API
-- token; hub responses name the hub user in actor, by id, never by name:
-- '<hub id>/<hub user id>' (the hub's app_user.id). The hub resolves
-- its user's name on display; the cloud shows the hub's name. App
-- responses name the
-- device and, when they were queued offline, the device time
-- (docs/mobile.md §5). seq orders the responses of an incident: the
-- incident's next number, taken under the incident's row lock (SELECT ...
-- FOR UPDATE) in the transaction that applies the response; responses
-- apply in seq order, never by at (docs/on-call.md §5).
CREATE TABLE response (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
incident_id uuid NOT NULL,
person_id uuid,
token_id uuid, -- API token of a service account
actor text, -- channel hub: '<hub id>/<hub user id>'
delivery_id uuid, -- the delivery replied to (push, SMS, voice, link)
device_id uuid, -- channel app
channel text NOT NULL CHECK (channel IN ('app', 'sms', 'voice', 'web', 'hub', 'api')),
type text NOT NULL CHECK (type IN ('ack', 'snooze', 'unack', 'decline', 'escalate', 'reassign', 'invite', 'join', 'merge', 'resolve', 'note')),
snooze_until timestamptz, -- snooze: when the incident pages again
note text,
share boolean NOT NULL DEFAULT false, -- note: a status update for stakeholders (docs/on-call.md §11)
target_rotation uuid, -- reassign
target_person uuid, -- invite
target_incident uuid, -- merge
outcome text NOT NULL DEFAULT 'applied' CHECK (outcome IN ('applied', 'no-op', 'rejected')), -- docs/on-call.md §5
outcome_code text, -- rejected: the problem code, e.g. incident.resolved
at timestamptz NOT NULL DEFAULT now(), -- when it arrived; recorded, not the order
device_at timestamptz, -- app, queued offline; or the hub's time for channel hub
seq bigint NOT NULL,
PRIMARY KEY (tenant_id, id),
CONSTRAINT response_incident_seq UNIQUE (tenant_id, incident_id, seq),
FOREIGN KEY (tenant_id, incident_id) REFERENCES incident(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id),
FOREIGN KEY (tenant_id, token_id) REFERENCES api_token(tenant_id, id),
FOREIGN KEY (tenant_id, delivery_id) REFERENCES delivery(tenant_id, id),
FOREIGN KEY (tenant_id, target_rotation) REFERENCES rotation(tenant_id, id),
FOREIGN KEY (tenant_id, target_person) REFERENCES person(tenant_id, id),
FOREIGN KEY (tenant_id, target_incident) REFERENCES incident(tenant_id, id),
FOREIGN KEY (tenant_id, device_id) REFERENCES device(tenant_id, id),
CHECK (num_nonnulls(person_id, token_id, actor) >= 1)
);

ALTER TABLE incident ADD FOREIGN KEY (tenant_id, acked_response) REFERENCES response(tenant_id, id);

-- Messages that aren't steps of a chain (docs/on-call.md §4): the reply to
-- an SMS response (reply), the final message of a resolved incident
-- (resolved) or of a merged one (merged), the message to rotation
-- managers and team admins about an unanswered incident (unanswered), a
-- severity increase sent to the person who acknowledged (severity), a
-- verification code (verification), a test message to a number or a
-- device (test), a shift, swap, login or punch reminder (reminder), the
-- information to an involved rotation (inform), a stakeholder
-- notification (stakeholder), the reports to rotation managers and team
-- admins (report: gaps, minimums, unacknowledged number tests, too few
-- people punched in), the update of a notification on a device (update)
-- and messages about the account (account: changed sender numbers, an app
-- too old, a support grant used, an SMS acknowledgement). It goes to a
-- person's number (contact_id; voice only for a verification code or a
-- test of a voice number) or device (device_id), to a rotation's handset
-- (handset_rotation), or by e-mail to the address in its sealed message
-- (the person's, a stakeholder's or a team's). Each is sent once, through
-- the first carrier that accepts it, e-mail through the cloud's mail
-- relay (docs/operations.md §3); it is not throttled or retried, isn't
-- replicated to the hub and isn't counted as a delivery. Receipts update
-- it as they do a delivery; the device's receipt of a test push is its
-- result. Replies are answered at most 10 times per number in 10 minutes.
-- The hourly limits per person (docs/on-call.md §1) and the daily budget
-- per tenant count the notices of kind verification and test
-- (notice_person). Queued notices are sent through the outbox of
-- delivery (above). code, for a reply: reply.codes (answered with the
-- open codes), reply.unknown_code (a code not delivered to the number), or
-- the problem code of the rejected response it answers, e.g.
-- incident.resolved.
--
-- Notices and deliveries stay two tables: a delivery is an attempt of a
-- chain step, counts as notifying its person (who may then respond),
-- drives the chain, is replicated to the hub and counted in reports; a
-- notice does none of these, and may name no incident.
CREATE TABLE notice (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
kind text NOT NULL CHECK (kind IN ('reply', 'resolved', 'merged', 'unanswered', 'severity',
'verification', 'test', 'reminder', 'inform', 'stakeholder', 'report', 'update', 'account')),
code text,
incident_id uuid, -- NULL: a reply that names no incident
person_id uuid,
contact_id uuid, -- sms
device_id uuid, -- push: an update of a notification, a test push, an information notification
response_id uuid, -- reply: the response it answers
medium text NOT NULL CHECK (medium IN ('push', 'sms', 'voice', 'email')),
carrier text,
carrier_ref text, -- unique per carrier, installation-wide
status delivery_status NOT NULL DEFAULT 'queued',
queued_at timestamptz NOT NULL DEFAULT now(),
sent_at timestamptz,
receipt_at timestamptz,
final_at timestamptz,
reason text, -- why it failed at once, e.g. carrier.not_accepted; in trial
-- trial.no_voice, trial.unverified, trial.country, trial.sms_cap
-- (docs/on-call.md §4 Trial delivery)
country text, -- sms, voice through a carrier: the destination's country calling code
handset_rotation uuid, -- sms to the rotation's handset
message_sealed bytea, -- queued: the message, sealed (outbox of delivery); NULL once final,
-- but kept under evaluation delivery (as delivery's)
claimed_until timestamptz, -- queued: the lease of the sender that claimed it
claim uuid, -- queued: the claim of that sender (outbox of delivery)
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, incident_id) REFERENCES incident(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id),
FOREIGN KEY (tenant_id, contact_id) REFERENCES contact_method(tenant_id, id) ON DELETE SET NULL (contact_id),
FOREIGN KEY (tenant_id, device_id) REFERENCES device(tenant_id, id),
FOREIGN KEY (tenant_id, response_id) REFERENCES response(tenant_id, id),
FOREIGN KEY (tenant_id, handset_rotation) REFERENCES rotation(tenant_id, id) ON DELETE CASCADE,
CHECK ((medium = 'push') = (device_id IS NOT NULL)),
CHECK ((kind = 'reply') = (code IS NOT NULL)),
CONSTRAINT notice_destination_check CHECK (num_nonnulls(contact_id, device_id, handset_rotation) <= 1)
);

CREATE UNIQUE INDEX notice_carrier_ref ON notice (carrier, carrier_ref);
CREATE INDEX notice_outbox ON notice (queued_at) WHERE status = 'queued';
CREATE INDEX notice_person ON notice (tenant_id, person_id, kind, queued_at);

-- The SMS a tenant in trial sent through the carriers per UTC day, codes
-- included (docs/on-call.md §4 Trial delivery): a sender takes one before
-- the carrier's send, only while sent is below the installation's cap.
CREATE TABLE tenant_sms_day (
tenant_id uuid NOT NULL REFERENCES tenant(id),
day date NOT NULL,
sent int NOT NULL CHECK (sent >= 0),
PRIMARY KEY (tenant_id, day)
);

-- Carriers, installation-wide; for push, APNs and FCM (docs/mobile.md §3).
-- The rows come from the cloud's configuration, which a server writes at
-- its start (docs/operations.md §3).
CREATE TABLE carrier (
id text PRIMARY KEY, -- e.g. 'carrier-a-sms', 'apns'
medium text NOT NULL CHECK (medium IN ('push', 'sms', 'voice')),
priority int NOT NULL
);

-- Health per carrier (and so medium) and destination country
-- (docs/on-call.md §4, which has the rule); push uses country '*'. Rows
-- appear with the first attempt. Every change of healthy is also a row of
-- carrier_health_event.
CREATE TABLE carrier_health (
carrier text NOT NULL REFERENCES carrier(id),
country text NOT NULL, -- the number's country calling code (49), or '*'
healthy boolean NOT NULL DEFAULT true,
since timestamptz NOT NULL DEFAULT now(),
-- the window per minute (attempts, not accepted), the last two probes'
-- outcomes and when the last probe started
stats jsonb NOT NULL DEFAULT '{}',
PRIMARY KEY (carrier, country)
);

-- The history of carrier_health: one row per change, with the numbers
-- that caused it. Kept 13 months.
CREATE TABLE carrier_health_event (
carrier text NOT NULL REFERENCES carrier(id),
country text NOT NULL,
at timestamptz NOT NULL DEFAULT now(),
healthy boolean NOT NULL,
stats jsonb NOT NULL DEFAULT '{}',
PRIMARY KEY (carrier, country, at)
);

-- The probes (docs/on-call.md §4): an SMS or a call through an SMS or
-- voice carrier to the vendor's test number of a country, from the
-- carrier's probe number (docs/operations.md §3). It succeeds with a
-- delivered receipt or an answered call within 2 minutes; not-accepted:
-- the carrier refused it; no-receipt: nothing came in time. Kept with
-- the health history.
CREATE TABLE carrier_probe (
id uuid PRIMARY KEY,
carrier text NOT NULL REFERENCES carrier(id),
country text NOT NULL,
carrier_ref text,
sent_at timestamptz NOT NULL DEFAULT now(),
outcome text CHECK (outcome IN ('delivered', 'failed', 'no-receipt', 'not-accepted')),
ended_at timestamptz,
UNIQUE (carrier, carrier_ref)
);

CREATE INDEX carrier_probe_open ON carrier_probe (sent_at) WHERE outcome IS NULL;

-- Stakeholders of a team (docs/on-call.md §11): a person or an address.
CREATE TABLE stakeholder (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
team_id uuid NOT NULL,
person_id uuid,
email_sealed bytea,
min_severity text NOT NULL DEFAULT 'warning',
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, team_id) REFERENCES team(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id) ON DELETE CASCADE,
CHECK (num_nonnulls(person_id, email_sealed) = 1)
);

-- Sender and caller numbers of a tenant at a carrier (docs/on-call.md §4).
-- A number serves one tenant (number is unique): an inbound SMS finds its
-- tenant by the called number, before any tenant is set, so the lookup
-- runs as the cross-tenant role (§9). country: the number's country
-- calling code without + (as tenant.contact_calling_codes). A message or call
-- goes out from the tenant's number at the carrier with the medium whose
-- country is the longest prefix of the recipient's number, else from the
-- one marked is_default (one per carrier and medium, kept by the
-- application). Vendor operators set the rows with the tenant (cloud.yaml
-- updateTenant).
CREATE TABLE sender_number (
tenant_id uuid NOT NULL REFERENCES tenant(id),
carrier text NOT NULL REFERENCES carrier(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, carrier, number)
);

-- Watch's own sender and caller numbers for the tenant, at Watch's carrier
-- (docs/watch.md §2). Their home is here: vendor operators set them with
-- the tenant (cloud.yaml updateTenant), the cloud passes them to Watch
-- with the tenant (watch.yaml putTenant) and publishes them with the
-- tenant's own on the numbers page and contact card (docs/on-call.md §4).
-- country and is_default as in sender_number.
CREATE TABLE watch_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)
);

-- Inbound SMS and call events by the carrier's event id
-- (docs/on-call.md §4): the transaction that handles an event first
-- inserts its row; when the row exists, the event is a repeat and 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)
);

-- A call the cloud placed, a page (its delivery) or a verification code or
-- test call (its notice), by that row's id (docs/on-call.md §4 Voice). It
-- is written before the carrier gets the call; each of the carrier's
-- events updates it under its row lock: phase ringing → attention (asked
-- to press 1, asks counts the asks) → menu (the page read, repeats and
-- invalid count the keys) → ended. incidents: those the keys act on, all
-- of a merged call's. control: the answer to the last event, which a
-- repeated event gets again. Kept 7 days; the tenant's deletion removes
-- them with the tenant.
CREATE TABLE call (
tenant_id uuid NOT NULL REFERENCES tenant(id) ON DELETE CASCADE,
id uuid NOT NULL,
kind text NOT NULL CHECK (kind IN ('page', 'notice')),
person_id uuid,
incidents uuid[] NOT NULL DEFAULT '{}',
language text NOT NULL,
script_sealed bytea NOT NULL, -- what the call reads, sealed
phase text NOT NULL DEFAULT 'ringing' CHECK (phase IN ('ringing', 'attention', 'menu', 'ended')),
asks int NOT NULL DEFAULT 0,
repeats int NOT NULL DEFAULT 0,
invalid int NOT NULL DEFAULT 0,
responded boolean NOT NULL DEFAULT false,
control jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, id)
);

CREATE INDEX call_age ON call (created_at);

-------------------------------------------------------------------------------
-- 6. Number tests (docs/on-call.md §8)
-------------------------------------------------------------------------------

-- One row per person tested; with several people on call, one test
-- incident each. A test that falls in a gap pages nobody: its row has
-- outcome gap and neither person nor incident (docs/on-call.md §8).
CREATE TABLE number_test (
tenant_id uuid NOT NULL,
id uuid NOT NULL,
rotation_id uuid NOT NULL,
incident_id uuid,
person_id uuid,
scheduled_at timestamptz NOT NULL,
outcome text CHECK (outcome IN ('acknowledged', 'unacknowledged', 'gap')),
PRIMARY KEY (tenant_id, id),
FOREIGN KEY (tenant_id, rotation_id) REFERENCES rotation(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, incident_id) REFERENCES incident(tenant_id, id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, person_id) REFERENCES person(tenant_id, id)
);

-------------------------------------------------------------------------------
-- 7. Escalation and delivery timers
-------------------------------------------------------------------------------

-- Due work per incident, run by the holder of the tenant's controller
-- shard (docs/architecture.md §8). Media chain
-- steps are timed per person in chain.next_at. escalate: the current
-- level's after; ack-timeout: the rotation's ack timeout or a snooze;
-- test-check: 30 min after a number test page (docs/on-call.md §7, §8);
-- handover: the next start or end of a stored shift of the rotation the
-- current level's target names (on-call, rotation:…), due at once when
-- the tenant's shifts are stored again; it starts the chains of the people
-- who came on call while the incident is triggered (docs/on-call.md §3).
-- Each transition sets or deletes them in its transaction as the table of
-- docs/on-call.md §7 says; resolve and merge delete all of the incident's
-- timers (models/Escalation.tla). The handler of a due timer locks the
-- incident row (SELECT ... FOR UPDATE), reads the timer row again and acts
-- only if it still exists with the same due_at and the incident is in the
-- timer's state (triggered for escalate, acknowledged for ack-timeout);
-- otherwise it does nothing.
CREATE TABLE incident_timer (
tenant_id uuid NOT NULL,
incident_id uuid NOT NULL,
kind text NOT NULL CHECK (kind IN ('escalate', 'ack-timeout', 'test-check', 'handover')),
due_at timestamptz NOT NULL,
PRIMARY KEY (tenant_id, incident_id, kind),
FOREIGN KEY (tenant_id, incident_id) REFERENCES incident(tenant_id, id) ON DELETE CASCADE
);

CREATE INDEX incident_timer_due ON incident_timer (due_at);

-- Due work outside incidents, run by the holder of the tenant's
-- controller shard:
-- swap-remind and swap-expire (an override in state requested), punch-remind
-- and punch-out (a punch with max_duty), number-test (a rotation's next
-- test), shift-remind (a person's shift reminder), daily-report (gaps,
-- unreachable people, minimums and members not logged in per rotation,
-- and the reminders of device logins that expire during a shift, at
-- 06:00 UTC), materialise (extend shifts to 30 days ahead); login-remind
-- is not set. The housekeeper sets the number-test, shift-remind and
-- daily-report timers that are missing.
CREATE TABLE cloud_timer (
tenant_id uuid NOT NULL REFERENCES tenant(id),
kind text NOT NULL CHECK (kind IN ('swap-remind', 'swap-expire', 'punch-remind', 'punch-out', 'number-test', 'shift-remind', 'login-remind', 'daily-report', 'materialise')),
ref uuid NOT NULL, -- override, punch, rotation, person, device or tenant id
due_at timestamptz NOT NULL,
PRIMARY KEY (tenant_id, kind, ref)
);

CREATE INDEX cloud_timer_due ON cloud_timer (due_at);

-- Positions of the UI and app event stream (cloud.yaml GET /api/v1/stream),
-- per tenant: one row per changed object, written in the transaction that
-- changes it, kept 1 hour. A position is (xid, seq): the writing
-- transaction's id and a number of the global sequence. A stream reads
-- the rows after its position in that order, and only those of
-- transactions older than every transaction still running
-- (pg_snapshot_xmin), so a row that commits later never lands before a
-- position already sent. Last-Event-ID resumes after a position still
-- held; otherwise the stream starts with reset. Each subscriber gets only
-- the rows of objects it may see: incident_id names the incident of an
-- incident, delivery or response, rotation (team/rotation) the rotation
-- of a shift, override, punch or rotation.
CREATE SEQUENCE stream_event_seq;

CREATE TABLE stream_event (
tenant_id uuid NOT NULL REFERENCES tenant(id),
seq bigint NOT NULL DEFAULT nextval('stream_event_seq'),
type text NOT NULL, -- incident, shift, override, punch, device, …
object_id uuid NOT NULL,
at timestamptz NOT NULL DEFAULT now(),
xid xid8 NOT NULL DEFAULT pg_current_xact_id(),
incident_id uuid,
rotation text,
deleted boolean NOT NULL DEFAULT false,
PRIMARY KEY (tenant_id, seq)
);

CREATE INDEX stream_event_age ON stream_event (at);
CREATE INDEX stream_event_position ON stream_event (tenant_id, xid, seq);

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

-- Hash-chained per tenant as the hub's (docs/schema/hub.sql
-- audit_event), with the same canonical form (docs/compliance.md §3.2); a
-- writer takes the advisory transaction lock of class 5 with the last
-- four bytes of the tenant id as its key before it reads the tenant's
-- head. The servers only read and append (§9), expiry is
-- audit_expire. actor is an id, never a name: the person, API token,
-- hub or vendor operator id, or the component (system); names are
-- resolved on display. The hourly anchors are entries of action
-- audit.anchor, the hubs' anchors entries of action hub.audit_anchor
-- (docs/compliance.md §3).
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', 'hub', 'vendor')),
actor text NOT NULL,
action text NOT NULL,
object text NOT NULL,
reason text,
details jsonb NOT NULL DEFAULT '{}',
prev_hash bytea NOT NULL,
hash bytea NOT NULL,
request_id text,
PRIMARY KEY (tenant_id, seq)
);

-- The entries by time: listAudit's since and until.
CREATE INDEX audit_event_at ON audit_event (tenant_id, at);

-- One row per expiry of a tenant's audit, written by audit_expire: the
-- last expired entry (seq, hash).
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)
);

-- Audit sinks of a tenant with their delivery cursor (outbox over
-- audit_event.seq), as on the hub.
CREATE TABLE audit_sink (
tenant_id uuid NOT NULL REFERENCES tenant(id),
id uuid NOT NULL,
kind text NOT NULL CHECK (kind IN ('syslog', 'https')),
target text NOT NULL,
token_sealed bytea,
cursor_seq bigint NOT NULL DEFAULT 0,
last_error text,
enabled boolean NOT NULL DEFAULT true,
PRIMARY KEY (tenant_id, id)
);

-------------------------------------------------------------------------------
-- 9. Roles and row-level security
-------------------------------------------------------------------------------

-- Roles, all without login; the deployment grants them to login roles
-- (docs/operations.md §3):
-- * excubio_owner owns the schema and its objects and runs the
-- migrations (excubio-cloud migrate). It serves nothing.
-- * excubio_app is the cloud's servers and controllers: SELECT, INSERT,
-- UPDATE and DELETE on every table, except audit_event and
-- platform_audit, which it may only read and append to, and
-- audit_checkpoint, which it may only read; the lookup functions,
-- audit_expire and tenant_delete. A server
-- refuses to start as a login that is a superuser, has BYPASSRLS or is
-- a member of excubio_owner. The migrations also grant it SELECT on
-- public._sqlx_migrations (sqlx's record of them, outside this
-- schema), which the servers' readiness compares with their own.
-- * excubio_lookup owns the lookup functions below and may read, across
-- tenants, only the columns they need. No login is a member of it.
-- No role has BYPASSRLS, and FORCE applies the policies to the owner too.
--
-- The tenant: every transaction on tenant data first sets the setting
-- excubio.tenant_id for the transaction only: SET LOCAL excubio.tenant_id
-- = '<uuid>', or set_config('excubio.tenant_id', '<uuid>', true). The
-- policy tenant_isolation shows and accepts only rows of that tenant;
-- without it (unset or empty) a query sees no tenant rows and can write
-- none. One transaction is one tenant's unit of work: a request, a chain
-- step, a receipt, an inbound message.
--
-- Work that arrives before its tenant is known (an inbound SMS, a
-- link request, a token, a carrier receipt) and the controllers' search
-- for due work find their tenant through the SECURITY DEFINER functions
-- below. They return tenant ids and row ids, nothing else; the work then
-- runs in its own transaction under its tenant. Each function pins its
-- search_path and names its tables with the schema.

GRANT USAGE ON SCHEMA excubio TO excubio_app, excubio_lookup;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA excubio TO excubio_app;
ALTER DEFAULT PRIVILEGES FOR ROLE excubio_owner IN SCHEMA excubio
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO excubio_app;
REVOKE UPDATE, DELETE ON audit_event FROM excubio_app;
REVOKE INSERT, UPDATE, DELETE ON audit_checkpoint FROM excubio_app;
REVOKE UPDATE, DELETE ON platform_audit FROM excubio_app;
GRANT USAGE ON SEQUENCE stream_event_seq TO excubio_app;

GRANT SELECT (id, shard) ON tenant TO excubio_lookup;
GRANT SELECT (tenant_id, number) ON sender_number TO excubio_lookup;
GRANT SELECT (tenant_id, id, cert_fingerprint, enrol_token_hash, revoked_at, prev_cert_fingerprint) ON hub TO excubio_lookup;
GRANT SELECT (tenant_id, incident_id, token_hash) ON incident_link TO excubio_lookup;
GRANT SELECT (tenant_id, id, token_hash) ON device TO excubio_lookup;
GRANT SELECT (tenant_id, id, token_hash) ON api_token TO excubio_lookup;
GRANT SELECT (tenant_id, id, calendar_token_hash) ON person TO excubio_lookup;
GRANT SELECT (tenant_id, id, carrier, carrier_ref, status, queued_at, claimed_until) ON delivery TO excubio_lookup;
GRANT SELECT (tenant_id, id, carrier, carrier_ref, status, queued_at, claimed_until) ON notice TO excubio_lookup;
GRANT SELECT (tenant_id, incident_id, person_id, state, next_at) ON chain TO excubio_lookup;
GRANT SELECT (tenant_id, incident_id, kind, due_at) ON incident_timer TO excubio_lookup;
GRANT SELECT (tenant_id, kind, ref, due_at) ON cloud_timer TO excubio_lookup;
GRANT SELECT (tenant_id, kind, object_id, due_at) ON watch_push TO excubio_lookup;

DO $$
DECLARE t text;
BEGIN
FOREACH t IN ARRAY ARRAY['tenant_key', 'person', 'contact_method', 'contact_verification', 'web_session', 'device', 'absence', 'team',
'team_member', 'tenant_role', 'api_token', 'support_grant', 'rotation', 'rotation_fallback',
'tenant_calendar', 'tenant_calendar_day', 'layer', 'layer_member', 'override', 'punch', 'shift',
'stakeholder', 'sender_number', 'watch_number', 'carrier_event',
'hub', 'hub_update', 'idempotency_key', 'incident', 'incident_involved', 'incident_alert', 'chain', 'delivery', 'response',
'notice', 'number_test', 'incident_timer', 'cloud_timer', 'incident_link', 'stream_event', 'audit_event', 'audit_checkpoint', 'audit_sink',
'call', 'watch_push', 'tenant_invite', 'login_attempt', 'tenant_sms_day']
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;
-- The lookup functions read these across tenants.
FOREACH t IN ARRAY ARRAY['sender_number', 'hub', 'incident_link', 'device', 'api_token', 'person',
'delivery', 'notice', 'chain', 'incident_timer', 'cloud_timer', 'watch_push']
LOOP
EXECUTE format('CREATE POLICY lookup ON %I FOR SELECT TO excubio_lookup USING (true)', t);
END LOOP;
END $$;

-- The tenant of a called number (an inbound SMS): sender_number.number is
-- unique, so a number names one tenant.
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.sender_number s WHERE s.number = called
$$;

-- The tenant and hub of a link request, by the SHA-256 fingerprint of its
-- client certificate, the current one or the one a renewal replaced; not
-- for a revoked hub.
CREATE FUNCTION lookup_hub_by_certificate(fingerprint bytea) RETURNS TABLE (tenant_id uuid, hub_id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT e.tenant_id, e.id FROM excubio.hub e
WHERE (e.cert_fingerprint = fingerprint OR e.prev_cert_fingerprint = fingerprint) AND e.revoked_at IS NULL
$$;

-- The tenant of a hub by its id.
CREATE FUNCTION lookup_hub(hub uuid) RETURNS uuid
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT e.tenant_id FROM excubio.hub e WHERE e.id = hub
$$;

-- The tenant and row of a token, by its SHA-256. kind: link (exl_, the
-- incident link in an SMS, by which a person acknowledges: returns the
-- incident), device (exd_), api (exk_), calendar (the ICS feed: returns
-- the person), enrol (exe_: returns the hub). Expiry and revocation are
-- checked under the tenant.
CREATE FUNCTION lookup_token(kind text, hash bytea) RETURNS TABLE (tenant_id uuid, id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT l.tenant_id, l.incident_id FROM excubio.incident_link l WHERE kind = 'link' AND l.token_hash = hash
UNION ALL
SELECT d.tenant_id, d.id FROM excubio.device d WHERE kind = 'device' AND d.token_hash = hash
UNION ALL
SELECT a.tenant_id, a.id FROM excubio.api_token a WHERE kind = 'api' AND a.token_hash = hash
UNION ALL
SELECT p.tenant_id, p.id FROM excubio.person p WHERE kind = 'calendar' AND p.calendar_token_hash = hash
UNION ALL
SELECT e.tenant_id, e.id FROM excubio.hub e WHERE kind = 'enrol' AND e.enrol_token_hash = hash
$$;

-- The tenant and the delivery or notice of a carrier receipt.
CREATE FUNCTION lookup_carrier_ref(carrier text, ref text) RETURNS TABLE (tenant_id uuid, delivery_id uuid, notice_id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT d.tenant_id, d.id, NULL::uuid FROM excubio.delivery d WHERE d.carrier = lookup_carrier_ref.carrier AND d.carrier_ref = ref
UNION ALL
SELECT n.tenant_id, NULL::uuid, n.id FROM excubio.notice n WHERE n.carrier = lookup_carrier_ref.carrier AND n.carrier_ref = ref
$$;

-- Due work of the controllers, for the tenants of the shards the caller
-- holds (tenant.shard, docs/architecture.md §8): chain steps (§5) and
-- timers (§7). The outbox (§5) has no shards: any sender claims queued
-- deliveries and notices that no sender holds. Chain steps and the outbox
-- come in turns of the tenants, every tenant's oldest row before any
-- tenant's second, so the due work of one tenant can't fill a batch and
-- hold up the others'; timers oldest first.
CREATE FUNCTION lookup_due_chains(shards int[], lim int) RETURNS TABLE (tenant_id uuid, incident_id uuid, person_id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT d.tenant_id, d.incident_id, d.person_id FROM (
SELECT c.tenant_id, c.incident_id, c.person_id, c.next_at,
row_number() OVER (PARTITION BY c.tenant_id ORDER BY c.next_at) AS turn
FROM excubio.chain c JOIN excubio.tenant t ON t.id = c.tenant_id
WHERE t.shard = ANY (shards) AND c.state = 'running' AND c.next_at <= now()
) d ORDER BY d.turn, d.next_at LIMIT lim
$$;

CREATE FUNCTION lookup_outbox(lim int) RETURNS TABLE (tenant_id uuid, kind text, id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT q.tenant_id, q.kind, q.id FROM (
SELECT o.tenant_id, o.kind, o.id, o.queued_at,
row_number() OVER (PARTITION BY o.tenant_id ORDER BY o.queued_at) AS turn
FROM (
SELECT d.tenant_id, 'delivery' AS kind, d.id, d.queued_at FROM excubio.delivery d
WHERE d.status = 'queued' AND (d.claimed_until IS NULL OR d.claimed_until <= now())
UNION ALL
SELECT n.tenant_id, 'notice', n.id, n.queued_at FROM excubio.notice n
WHERE n.status = 'queued' AND (n.claimed_until IS NULL OR n.claimed_until <= now())
) o
) q ORDER BY q.turn, q.queued_at LIMIT lim
$$;

CREATE FUNCTION lookup_due_incident_timers(shards int[], lim int) RETURNS TABLE (tenant_id uuid, incident_id uuid, kind text)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT i.tenant_id, i.incident_id, i.kind FROM excubio.incident_timer i JOIN excubio.tenant t ON t.id = i.tenant_id
WHERE t.shard = ANY (shards) AND i.due_at <= now() ORDER BY i.due_at LIMIT lim
$$;

CREATE FUNCTION lookup_due_cloud_timers(shards int[], lim int) RETURNS TABLE (tenant_id uuid, kind text, ref uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT c.tenant_id, c.kind, c.ref FROM excubio.cloud_timer c JOIN excubio.tenant t ON t.id = c.tenant_id
WHERE t.shard = ANY (shards) AND c.due_at <= now() ORDER BY c.due_at LIMIT lim
$$;

-- Pushes to Watch that are due (watch_push), oldest first, of every tenant.
CREATE FUNCTION lookup_due_watch_pushes(lim int) RETURNS TABLE (tenant_id uuid, kind text, object_id uuid)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT w.tenant_id, w.kind, w.object_id FROM excubio.watch_push w WHERE w.due_at <= now() ORDER BY w.due_at LIMIT lim
$$;

-- Deletes the current tenant's audit entries older than five years
-- (docs/compliance.md §2) as a prefix of its chain that leaves the newest
-- entry, and records the last deleted one in audit_checkpoint; returns
-- their number. Runs as excubio_owner, under the tenant's policy.
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.audit_event e WHERE e.tenant_id = tenant;
SELECT coalesce(min(e.seq), head) - 1 INTO last_seq FROM excubio.audit_event e
WHERE e.tenant_id = tenant AND e.at >= now() - interval '5 years';
SELECT e.hash INTO last_hash FROM excubio.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.audit_event e WHERE e.tenant_id = tenant AND e.seq <= last_seq;
GET DIAGNOSTICS n = ROW_COUNT;
INSERT INTO excubio.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_app;

-- Deletes a tenant in state deleting with everything it has: its rows in
-- an order its foreign keys allow, its audit log and checkpoints, its data
-- keys and at last the tenant row (docs/compliance.md §5). The app role
-- can delete neither the audit nor a checkpoint itself, so the deletion
-- job calls this function, which runs as excubio_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.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);
UPDATE excubio.incident i SET acked_response = NULL WHERE i.tenant_id = target AND i.acked_response IS NOT NULL;
FOREACH t IN ARRAY ARRAY['watch_push', 'call', 'notice', 'number_test', 'incident_timer', 'incident_link', 'incident_alert',
'incident_involved', 'chain', 'response', 'delivery', 'incident', 'hub_update', 'idempotency_key', 'login_attempt',
'carrier_event', 'stream_event', 'cloud_timer', 'hub', 'shift', 'punch', 'override', 'layer_member',
'layer', 'rotation_fallback', 'rotation', 'tenant_calendar_day', 'tenant_calendar', 'stakeholder',
'team_member', 'team', 'absence', 'device', 'contact_verification', 'contact_method', 'web_session',
'support_grant', 'api_token', 'tenant_role', 'tenant_invite', 'person', 'sender_number', 'watch_number', 'audit_sink',
'audit_checkpoint', 'audit_event', 'tenant_sms_day', 'tenant_key']
LOOP
EXECUTE format('DELETE FROM excubio.%I x WHERE x.tenant_id = $1', t) USING target;
END LOOP;
DELETE FROM excubio.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_app;

-- excubio_lookup owns the lookup functions (CREATE on the schema is needed
-- for the change of owner only), and only excubio_app may call them.
GRANT CREATE ON SCHEMA excubio TO excubio_lookup;
DO $$
DECLARE f regprocedure;
BEGIN
FOR f IN SELECT p.oid FROM pg_proc p WHERE p.pronamespace = 'excubio'::regnamespace AND p.proname LIKE 'lookup\_%' LOOP
EXECUTE format('ALTER FUNCTION %s OWNER TO excubio_lookup', f);
EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM PUBLIC', f);
EXECUTE format('GRANT EXECUTE ON FUNCTION %s TO excubio_app', f);
END LOOP;
END $$;
REVOKE CREATE ON SCHEMA excubio FROM excubio_lookup;