webhooks.sql56 lines, 2.3 KB
| 1 | -- name: CreateEndpoint :one |
| 2 | INSERT INTO webhook_endpoints (id, user_id, url, event_types, secret) |
| 3 | VALUES ($1, $2, $3, $4, $5) |
| 4 | RETURNING *; |
| 5 | |
| 6 | -- name: ListEndpoints :many |
| 7 | -- Never the secrets: they're shown once, when an endpoint is created. |
| 8 | SELECT id, url, event_types, created_at FROM webhook_endpoints |
| 9 | WHERE user_id = $1 |
| 10 | ORDER BY created_at; |
| 11 | |
| 12 | -- name: DeleteEndpoint :execrows |
| 13 | DELETE FROM webhook_endpoints WHERE id = $1 AND user_id = $2; |
| 14 | |
| 15 | -- name: FanOut :execrows |
| 16 | -- A delivery for each of the user's endpoints that wants this event. |
| 17 | INSERT INTO webhook_deliveries (endpoint_id, event_id, event_type, payload) |
| 18 | SELECT id, @event_id::uuid, @event_type::text, @payload::bytea FROM webhook_endpoints |
| 19 | WHERE user_id = @user_id AND @event_type = ANY (event_types) |
| 20 | ON CONFLICT (endpoint_id, event_id) DO NOTHING; |
| 21 | |
| 22 | -- name: ClaimDue :many |
| 23 | -- Takes up to $1 due deliveries, and leases them for a minute: a worker that |
| 24 | -- dies holding them only delays them. SKIP LOCKED lets workers share the work. |
| 25 | UPDATE webhook_deliveries d SET next_attempt_at = now() + interval '1 minute' |
| 26 | FROM webhook_endpoints e |
| 27 | WHERE e.id = d.endpoint_id AND d.id IN ( |
| 28 | SELECT id FROM webhook_deliveries |
| 29 | WHERE state = 'pending' AND next_attempt_at <= now() |
| 30 | ORDER BY next_attempt_at |
| 31 | LIMIT $1 |
| 32 | FOR UPDATE SKIP LOCKED |
| 33 | ) |
| 34 | RETURNING d.id, d.event_id, d.payload, d.attempts, e.url, e.secret; |
| 35 | |
| 36 | -- name: RecordAttempt :exec |
| 37 | -- The next attempt is due by the database clock, the one ClaimDue goes by. |
| 38 | UPDATE webhook_deliveries |
| 39 | SET attempts = attempts + 1, state = @state, |
| 40 | next_attempt_at = now() + make_interval(secs => @retry_in_seconds), |
| 41 | last_status = @last_status, last_error = @last_error, last_response_ms = @last_response_ms |
| 42 | WHERE id = @id; |
| 43 | |
| 44 | -- name: ListDeliveries :many |
| 45 | SELECT d.id, d.event_id, d.event_type, d.state, d.attempts, d.last_status, |
| 46 | d.last_error, d.last_response_ms, d.next_attempt_at, d.created_at |
| 47 | FROM webhook_deliveries d JOIN webhook_endpoints e ON e.id = d.endpoint_id |
| 48 | WHERE e.user_id = $1 AND d.endpoint_id = $2 |
| 49 | ORDER BY d.created_at DESC |
| 50 | LIMIT 50; |
| 51 | |
| 52 | -- name: Replay :execrows |
| 53 | -- Sends a delivery again, as new: due now, with the whole schedule ahead. |
| 54 | UPDATE webhook_deliveries d SET state = 'pending', attempts = 0, next_attempt_at = now() |
| 55 | FROM webhook_endpoints e |
| 56 | WHERE e.id = d.endpoint_id AND d.id = $1 AND e.user_id = $2; |