000001_webhooks.up.sql37 lines, 1.6 KB
| 1 | BEGIN; |
| 2 | |
| 3 | -- Where a user wants their events delivered, and the secret we sign them with. |
| 4 | CREATE TABLE webhook_endpoints ( |
| 5 | id uuid PRIMARY KEY, |
| 6 | user_id uuid NOT NULL, |
| 7 | url text NOT NULL, |
| 8 | event_types text[] NOT NULL, |
| 9 | secret text NOT NULL, |
| 10 | created_at timestamptz NOT NULL DEFAULT now() |
| 11 | ); |
| 12 | CREATE INDEX webhook_endpoints_user_id_idx ON webhook_endpoints (user_id); |
| 13 | |
| 14 | -- One row per event, per endpoint: the work queue, and the delivery log. |
| 15 | CREATE TABLE webhook_deliveries ( |
| 16 | id uuid PRIMARY KEY DEFAULT gen_random_uuid(), |
| 17 | endpoint_id uuid NOT NULL REFERENCES webhook_endpoints (id) ON DELETE CASCADE, |
| 18 | event_id uuid NOT NULL, |
| 19 | event_type text NOT NULL, |
| 20 | -- the exact bytes we sign and send, every time |
| 21 | payload bytea NOT NULL, |
| 22 | state text NOT NULL DEFAULT 'pending' |
| 23 | CHECK (state IN ('pending', 'succeeded', 'failed')), |
| 24 | attempts integer NOT NULL DEFAULT 0, |
| 25 | next_attempt_at timestamptz NOT NULL DEFAULT now(), |
| 26 | last_status integer NOT NULL DEFAULT 0, -- 0: no response at all |
| 27 | last_error text NOT NULL DEFAULT '', |
| 28 | last_response_ms integer NOT NULL DEFAULT 0, |
| 29 | created_at timestamptz NOT NULL DEFAULT now(), |
| 30 | -- an event redelivered by NATS finds its row |
| 31 | UNIQUE (endpoint_id, event_id) |
| 32 | ); |
| 33 | -- The worker's question, many times a second: what's due? |
| 34 | CREATE INDEX webhook_deliveries_due_idx ON webhook_deliveries (next_attempt_at) |
| 35 | WHERE state = 'pending'; |
| 36 | |
| 37 | COMMIT; |