| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "time" |
| 7 | |
| 8 | "github.com/jackc/pgx/v5" |
| 9 | "github.com/jackc/pgx/v5/pgxpool" |
| 10 | ) |
| 11 | |
| 12 | const ( |
| 13 | backOffBase = 10 * |
| 14 | backOffCap = time. |
| 15 | ) |
| 16 | |
| 17 | type Job struct { |
| 18 | ID, Kind, |
| 19 | Payload json. |
| 20 | EndpointID *string |
| 21 | Attempts int |
| 22 | } |
| 23 | |
| 24 | type sendFunc func(ctx |
| 25 | |
| 26 | const claimSQL = ` |
| 27 | UPDATE delivery_job |
| 28 | SET locked_until = now() + interval '60 seconds', |
| 29 | claim_token = gen_random_uuid(), |
| 30 | attempts = attempts + 1, |
| 31 | updated_at = now() |
| 32 | WHERE id IN ( |
| 33 | SELECT id FROM delivery_job |
| 34 | WHERE status = 'pending' AND next_attempt_at <= now() AND locked_until < now() |
| 35 | ORDER BY next_attempt_at |
| 36 | LIMIT $1 |
| 37 | FOR UPDATE SKIP LOCKED |
| 38 | ) |
| 39 | RETURNING id, kind, claim_token, payload, endpoint_id, attempts;` |
| 40 | |
| 41 | func claim(ctx context |
| 42 | rows, err := |
| 43 | if err != nil |
| 44 | return nil, err |
| 45 | } |
| 46 | return pgx.CollectRows( |
| 47 | } |
| 48 | |
| 49 | const completeSQL = ` |
| 50 | UPDATE delivery_job |
| 51 | SET status = 'succeeded', last_error = NULL, locked_until = now(), updated_at = now() |
| 52 | WHERE id = $1 AND claim_token = $2` |
| 53 | |
| 54 | func complete(ctx context |
| 55 | tag, err := |
| 56 | if err != nil |
| 57 | return err |
| 58 | } |
| 59 | if tag.RowsAffected() |
| 60 | return errLeaseLost |
| 61 | } |
| 62 | return nil |
| 63 | } |
| 64 | |
| 65 | const failSQL = ` |
| 66 | UPDATE delivery_job SET |
| 67 | status = CASE WHEN created_at < now() - interval '3 days' |
| 68 | THEN 'dead'::delivery_job_status ELSE 'pending' END, |
| 69 | next_attempt_at = now() + $3 * interval '1 millisecond', |
| 70 | last_error = $4, locked_until = now(), updated_at = now() |
| 71 | WHERE id = $1 AND claim_token = $2 |
| 72 | ` |
| 73 | |
| 74 | func fail(ctx context |
| 75 | tag, err := |
| 76 | if err != nil |
| 77 | return err |
| 78 | } |
| 79 | if tag.RowsAffected() |
| 80 | return errLeaseLost |
| 81 | } |
| 82 | return nil |
| 83 | } |
| 84 | |
| 85 | func backoff(attempt int |
| 86 | attempt = min( |
| 87 | d := min( |
| 88 | n := randN( |
| 89 | return time.Duration( |
| 90 | } |
| 91 | |
| 92 | func listen(ctx context |
| 93 | panic("todo") |
| 94 | } |
| 95 | |
| 96 | func run(ctx context |
| 97 | panic("todo") |
| 98 | } |