| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "log" |
| 8 | "math/rand/v2" |
| 9 | "sync" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/jackc/pgx/v5" |
| 13 | "github.com/jackc/pgx/v5/pgxpool" |
| 14 | ) |
| 15 | |
| 16 | const ( |
| 17 | backOffBase = 10 * |
| 18 | backOffCap = time. |
| 19 | ) |
| 20 | |
| 21 | type Job struct { |
| 22 | ID, Kind, |
| 23 | Payload json. |
| 24 | EndpointID *string |
| 25 | Attempts int |
| 26 | } |
| 27 | |
| 28 | type sendFunc func(ctx |
| 29 | |
| 30 | const claimSQL = ` |
| 31 | UPDATE delivery_job |
| 32 | SET locked_until = now() + interval '60 seconds', |
| 33 | claim_token = gen_random_uuid(), |
| 34 | attempts = attempts + 1, |
| 35 | updated_at = now() |
| 36 | WHERE id IN ( |
| 37 | SELECT id FROM delivery_job |
| 38 | WHERE status = 'pending' AND next_attempt_at <= now() AND locked_until < now() |
| 39 | ORDER BY next_attempt_at |
| 40 | LIMIT $1 |
| 41 | FOR UPDATE SKIP LOCKED |
| 42 | ) |
| 43 | RETURNING id, kind, claim_token, payload, endpoint_id, attempts;` |
| 44 | |
| 45 | func claim(ctx context |
| 46 | rows, err := |
| 47 | if err != nil |
| 48 | return nil, err |
| 49 | } |
| 50 | return pgx.CollectRows( |
| 51 | } |
| 52 | |
| 53 | const completeSQL = ` |
| 54 | UPDATE delivery_job |
| 55 | SET status = 'succeeded', last_error = NULL, locked_until = now(), updated_at = now() |
| 56 | WHERE id = $1 AND claim_token = $2` |
| 57 | |
| 58 | func complete(ctx context |
| 59 | tag, err := |
| 60 | if err != nil |
| 61 | return err |
| 62 | } |
| 63 | if tag.RowsAffected() |
| 64 | return errLeaseLost |
| 65 | } |
| 66 | return nil |
| 67 | } |
| 68 | |
| 69 | const failSQL = ` |
| 70 | UPDATE delivery_job SET |
| 71 | status = CASE WHEN created_at < now() - interval '3 days' |
| 72 | THEN 'dead'::delivery_job_status ELSE 'pending' END, |
| 73 | next_attempt_at = now() + $3 * interval '1 millisecond', |
| 74 | last_error = $4, locked_until = now(), updated_at = now() |
| 75 | WHERE id = $1 AND claim_token = $2 |
| 76 | ` |
| 77 | |
| 78 | func fail(ctx context |
| 79 | tag, err := |
| 80 | if err != nil |
| 81 | return err |
| 82 | } |
| 83 | if tag.RowsAffected() |
| 84 | return errLeaseLost |
| 85 | } |
| 86 | return nil |
| 87 | } |
| 88 | |
| 89 | func backoff(attempt int |
| 90 | attempt = min( |
| 91 | d := min( |
| 92 | n := randN( |
| 93 | return time.Duration( |
| 94 | } |
| 95 | |
| 96 | // listen signals wake on every NOTIFY delivery until ctx is canceled, reconnecting when the connection drops. Polling in run covers any gap. |
| 97 | func listen(ctx context |
| 98 | for { |
| 99 | err := listenOnce( |
| 100 | if ctx.Err() |
| 101 | return |
| 102 | } |
| 103 | log.Printf("listen: |
| 104 | select { |
| 105 | case <-ctx.Done |
| 106 | return |
| 107 | case <-time.After |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | // listenOnce holds one connection and returns when it breaks. |
| 113 | func listenOnce(ctx context |
| 114 | conn, err := |
| 115 | if err != nil |
| 116 | return err |
| 117 | } |
| 118 | defer conn.Release() |
| 119 | |
| 120 | if _, err |
| 121 | return err |
| 122 | } |
| 123 | // Jobs inserted while we were disconnected got no NOTIFY. |
| 124 | notify(wake) |
| 125 | |
| 126 | for { |
| 127 | if _, err |
| 128 | return err |
| 129 | } |
| 130 | notify(wake) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | // notify sends on wake without blocking; a pending signal already covers this one. |
| 135 | func notify(wake chan |
| 136 | select { |
| 137 | case wake <- struct |
| 138 | default: |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | const ( |
| 143 | pollInterval = 5 * |
| 144 | sendTimeout = 10 * |
| 145 | ) |
| 146 | |
| 147 | // run keeps up to workers sends in flight until ctx is canceled, then waits |
| 148 | // for the in-flight sends to finish and record their result. |
| 149 | func run(ctx context |
| 150 | sem := make( |
| 151 | freed := make( |
| 152 | var wg sync |
| 153 | defer wg.Wait() |
| 154 | |
| 155 | // SIGTERM stops claiming, but a send already started must finish and be recorded. |
| 156 | jobCtx := context. |
| 157 | |
| 158 | tick := time. |
| 159 | defer tick.Stop() |
| 160 | |
| 161 | for { |
| 162 | // Claim until the queue is empty or every slot is busy. |
| 163 | for ctx.Err() |
| 164 | free := cap( |
| 165 | if free == 0 |
| 166 | break |
| 167 | } |
| 168 | jobs, err := |
| 169 | if err != nil |
| 170 | log.Printf("claim: |
| 171 | break |
| 172 | } |
| 173 | for _, j |
| 174 | sem <- struct{}{} |
| 175 | wg.Go(func() |
| 176 | defer func() { |
| 177 | <-sem |
| 178 | notify(freed) |
| 179 | }() |
| 180 | process(jobCtx, db |
| 181 | }) |
| 182 | } |
| 183 | if len(jobs) |
| 184 | break |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | select { |
| 189 | case <-ctx.Done |
| 190 | return |
| 191 | case <-wake: |
| 192 | case <-freed: |
| 193 | case <-tick.C |
| 194 | } |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | // process sends one job and records the result. |
| 199 | func process(ctx context |
| 200 | sendCtx, cancel := |
| 201 | err := send( |
| 202 | cancel() |
| 203 | |
| 204 | if err == nil |
| 205 | err = complete( |
| 206 | } else { |
| 207 | // attempts was already incremented by claim, so the first retry uses attempt 0. |
| 208 | err = fail( |
| 209 | } |
| 210 | if errors.Is( |
| 211 | log.Printf("job |
| 212 | } else if err |
| 213 | log.Printf("job |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // logSend is the phase 3 fake sender: it only logs. |
| 218 | func logSend(ctx context |
| 219 | log.Printf("send |
| 220 | return nil |
| 221 | } |