| 1 | BEGIN; |
| 2 | |
| 3 | -- One row per idempotency key: the proof that a request ran, and the response |
| 4 | -- we sent, so a retry gets the same answer instead of running again. |
| 5 | CREATE TABLE idempotency_keys ( |
| 6 | -- who sent the key: clients choose keys, so they're only unique per caller |
| 7 | scope text NOT NULL, |
| 8 | key text NOT NULL, |
| 9 | -- SHA-256 of the method, the path and the canonical body |
| 10 | fingerprint bytea NOT NULL, |
| 11 | status text NOT NULL DEFAULT 'in_progress' |
| 12 | CHECK (status IN ('in_progress', 'completed')), |
| 13 | -- the response we sent, replayed byte for byte |
| 14 | response_code integer, |
| 15 | response_body bytea, |
| 16 | created_at timestamptz NOT NULL DEFAULT now(), |
| 17 | -- when a request last claimed the key: a claim that's too old was abandoned |
| 18 | locked_at timestamptz NOT NULL DEFAULT now(), |
| 19 | completed_at timestamptz, |
| 20 | expires_at timestamptz NOT NULL, |
| 21 | PRIMARY KEY (scope, key), |
| 22 | -- a completed key always has its response, and only a completed key does |
| 23 | CHECK ((status = 'completed') = (response_code IS NOT NULL AND response_body IS NOT NULL)) |
| 24 | ); |
| 25 | |
| 26 | -- The cleanup job deletes expired keys, oldest first. |
| 27 | CREATE INDEX idempotency_keys_expires_at_idx ON idempotency_keys (expires_at); |
| 28 | |
| 29 | COMMIT; |