| 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/pgconn" |
| 14 | "github.com/jackc/pgx/v5/pgxpool" |
| 15 | ) |
| 16 | |
| 17 | const ( |
| 18 | backOffBase = 10 * |
| 19 | backOffCap = time. |
| 20 | ) |
| 21 | |
| 22 | type Job struct { |
| 23 | ID, Kind, |
| 24 | Payload json. |
| 25 | EndpointID *string |
| 26 | Attempts int |
| 27 | } |
| 28 | |
| 29 | type sendFunc func(ctx |
| 30 | |
| 31 | const claimSQL = ` |
| 32 | UPDATE delivery_job |
| 33 | SET locked_until = now() + interval '60 seconds', |
| 34 | claim_token = gen_random_uuid(), |
| 35 | attempts = attempts + 1, |
| 36 | updated_at = now() |
| 37 | WHERE id IN ( |
| 38 | SELECT id FROM delivery_job |
| 39 | WHERE status = 'pending' AND next_attempt_at <= now() AND locked_until < now() |
| 40 | ORDER BY next_attempt_at |
| 41 | LIMIT $1 |
| 42 | FOR UPDATE SKIP LOCKED |
| 43 | ) |
| 44 | RETURNING id, kind, claim_token, payload, endpoint_id, attempts;` |
| 45 | |
| 46 | func claim(ctx context |
| 47 | rows, err := |
| 48 | if err != nil |
| 49 | return nil, err |
| 50 | } |
| 51 | return pgx.CollectRows( |
| 52 | } |
| 53 | |
| 54 | const completeSQL = ` |
| 55 | UPDATE delivery_job |
| 56 | SET status = 'succeeded', last_error = NULL, locked_until = now(), updated_at = now() |
| 57 | WHERE id = $1 AND claim_token = $2` |
| 58 | |
| 59 | func complete(ctx context |
| 60 | tag, err := |
| 61 | if err != nil |
| 62 | return err |
| 63 | } |
| 64 | if tag.RowsAffected() |
| 65 | return errLeaseLost |
| 66 | } |
| 67 | return nil |
| 68 | } |
| 69 | |
| 70 | const failSQL = ` |
| 71 | UPDATE delivery_job SET |
| 72 | status = CASE WHEN created_at < now() - interval '3 days' |
| 73 | THEN 'dead'::delivery_job_status ELSE 'pending' END, |
| 74 | next_attempt_at = now() + $3 * interval '1 millisecond', |
| 75 | last_error = $4, locked_until = now(), updated_at = now() |
| 76 | WHERE id = $1 AND claim_token = $2 |
| 77 | ` |
| 78 | |
| 79 | func fail(ctx context |
| 80 | tag, err := |
| 81 | if err != nil |
| 82 | return err |
| 83 | } |
| 84 | if tag.RowsAffected() |
| 85 | return errLeaseLost |
| 86 | } |
| 87 | return nil |
| 88 | } |
| 89 | |
| 90 | const giveUpSQL = ` |
| 91 | UPDATE delivery_job |
| 92 | SET status = 'dead', last_error = $3, locked_until = now(), updated_at = now() |
| 93 | WHERE id = $1 AND claim_token = $2` |
| 94 | |
| 95 | // giveUp marks a job dead at once, for failures a retry cannot fix. |
| 96 | func giveUp(ctx context |
| 97 | tag, err := |
| 98 | if err != nil |
| 99 | return err |
| 100 | } |
| 101 | if tag.RowsAffected() |
| 102 | return errLeaseLost |
| 103 | } |
| 104 | return nil |
| 105 | } |
| 106 | |
| 107 | func backoff(attempt int |
| 108 | attempt = min( |
| 109 | d := min( |
| 110 | n := randN( |
| 111 | return time.Duration( |
| 112 | } |
| 113 | |
| 114 | // listen signals wake on every NOTIFY delivery until ctx is canceled, reconnecting when the connection drops. Polling in run covers any gap. |
| 115 | func listen(ctx context |
| 116 | for { |
| 117 | err := listenOnce( |
| 118 | if ctx.Err() |
| 119 | return |
| 120 | } |
| 121 | log.Printf("listen: |
| 122 | select { |
| 123 | case <-ctx.Done |
| 124 | return |
| 125 | case <-time.After |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | // listenOnce holds one connection and returns when it breaks. |
| 131 | func listenOnce(ctx context |
| 132 | conn, err := |
| 133 | if err != nil |
| 134 | return err |
| 135 | } |
| 136 | defer conn.Release() |
| 137 | |
| 138 | if _, err |
| 139 | return err |
| 140 | } |
| 141 | // Jobs inserted while we were disconnected got no NOTIFY. |
| 142 | notify(wake) |
| 143 | |
| 144 | for { |
| 145 | if _, err |
| 146 | return err |
| 147 | } |
| 148 | notify(wake) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | // notify sends on wake without blocking; a pending signal already covers this one. |
| 153 | func notify(wake chan |
| 154 | select { |
| 155 | case wake <- struct |
| 156 | default: |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | const ( |
| 161 | pollInterval = 5 * |
| 162 | sendTimeout = 10 * |
| 163 | ) |
| 164 | |
| 165 | // run keeps up to workers sends in flight until ctx is canceled, then waits |
| 166 | // for the in-flight sends to finish and record their result. |
| 167 | func run(ctx context |
| 168 | sem := make( |
| 169 | freed := make( |
| 170 | var wg sync |
| 171 | defer wg.Wait() |
| 172 | |
| 173 | // SIGTERM stops claiming, but a send already started must finish and be recorded. |
| 174 | jobCtx := context. |
| 175 | |
| 176 | tick := time. |
| 177 | defer tick.Stop() |
| 178 | |
| 179 | for { |
| 180 | // Claim until the queue is empty or every slot is busy. |
| 181 | for ctx.Err() |
| 182 | free := cap( |
| 183 | if free == 0 |
| 184 | break |
| 185 | } |
| 186 | jobs, err := |
| 187 | if err != nil |
| 188 | log.Printf("claim: |
| 189 | break |
| 190 | } |
| 191 | for _, j |
| 192 | sem <- struct{}{} |
| 193 | wg.Go(func() |
| 194 | defer func() { |
| 195 | <-sem |
| 196 | notify(freed) |
| 197 | }() |
| 198 | process(jobCtx, db |
| 199 | }) |
| 200 | } |
| 201 | if len(jobs) |
| 202 | break |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | select { |
| 207 | case <-ctx.Done |
| 208 | return |
| 209 | case <-wake: |
| 210 | case <-freed: |
| 211 | case <-tick.C |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | // process sends one job and records the result. |
| 217 | func process(ctx context |
| 218 | sendCtx, cancel := |
| 219 | err := send( |
| 220 | cancel() |
| 221 | |
| 222 | var ( |
| 223 | permanent permanentError |
| 224 | retryAfter retryAfterError |
| 225 | ) |
| 226 | switch { |
| 227 | case err == nil |
| 228 | err = complete( |
| 229 | case errors.As( |
| 230 | err = giveUp( |
| 231 | case errors.As( |
| 232 | err = fail( |
| 233 | default: |
| 234 | // attempts was already incremented by claim, so the first retry uses attempt 0. |
| 235 | err = fail( |
| 236 | } |
| 237 | if errors.Is( |
| 238 | log.Printf("job |
| 239 | } else if err |
| 240 | log.Printf("job |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | const ( |
| 245 | retention = 30 * |
| 246 | pruneInterval = time. |
| 247 | ) |
| 248 | |
| 249 | const pruneSQL = ` |
| 250 | DELETE FROM delivery_job |
| 251 | WHERE id IN ( |
| 252 | SELECT id FROM delivery_job |
| 253 | WHERE status <> 'pending' AND updated_at < now() - $1 * interval '1 millisecond' |
| 254 | LIMIT 1000 |
| 255 | )` |
| 256 | |
| 257 | type execer interface { |
| 258 | Exec(ctx context |
| 259 | } |
| 260 | |
| 261 | // prune deletes finished jobs older than the retention, and their attempts with |
| 262 | // them, in batches so no single statement holds locks for long. |
| 263 | func prune(ctx context |
| 264 | var total int64 |
| 265 | for { |
| 266 | tag, err := |
| 267 | if err != nil |
| 268 | return total, err |
| 269 | } |
| 270 | total += tag. |
| 271 | if tag.RowsAffected() |
| 272 | return total, nil |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | // pruneEvery runs prune until ctx is canceled. |
| 278 | func pruneEvery(ctx context |
| 279 | tick := time. |
| 280 | defer tick.Stop() |
| 281 | for { |
| 282 | if n, err |
| 283 | log.Printf("prune: |
| 284 | } else if n |
| 285 | log.Printf("pruned |
| 286 | } |
| 287 | select { |
| 288 | case <-ctx.Done |
| 289 | return |
| 290 | case <-tick.C |
| 291 | } |
| 292 | } |
| 293 | } |