store.go215 lines, 6.9 KB
| 1 | package idempotency |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "log/slog" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/fiston-user/payments/internal/platform/postgres" |
| 12 | "github.com/jackc/pgx/v5" |
| 13 | "github.com/jackc/pgx/v5/pgxpool" |
| 14 | "github.com/redis/go-redis/v9" |
| 15 | ) |
| 16 | |
| 17 | const ( |
| 18 | // TTL is how long we remember a key. Most retries come within seconds; a |
| 19 | // day also covers a phone that was offline overnight. |
| 20 | TTL = 24 * time.Hour |
| 21 | // lease is how long a claim lasts. A request that holds a key for longer |
| 22 | // died before it could finish, or let go. |
| 23 | lease = time.Minute |
| 24 | ) |
| 25 | |
| 26 | // Store keeps idempotency keys in Postgres, the source of truth, with an |
| 27 | // optional Redis cache of completed responses in front of it. |
| 28 | type Store struct { |
| 29 | pool *pgxpool.Pool |
| 30 | cache *redis.Client // nil: no cache |
| 31 | } |
| 32 | |
| 33 | // NewStore returns a Store that keeps keys in the idempotency_keys table of |
| 34 | // pool's database. cache may be nil. |
| 35 | func NewStore(pool *pgxpool.Pool, cache *redis.Client) *Store { |
| 36 | return &Store{pool: pool, cache: cache} |
| 37 | } |
| 38 | |
| 39 | // Run runs work once per key. The first request with a key runs work inside a |
| 40 | // database transaction, and stores its response in that same transaction, so |
| 41 | // both commit, or neither does. A retry with the same key and request gets |
| 42 | // the stored response back, and work doesn't run again. |
| 43 | func (s *Store) Run(ctx context.Context, k Key, work func(tx pgx.Tx) (Response, error)) (Response, error) { |
| 44 | // The fast path: a retry of a request that completed recently. |
| 45 | if resp, err := s.cached(ctx, k); resp.Replayed || err != nil { |
| 46 | return resp, err |
| 47 | } |
| 48 | |
| 49 | resp, err := s.claim(ctx, k) |
| 50 | switch { |
| 51 | case err != nil: |
| 52 | return Response{}, err |
| 53 | case resp.Replayed: |
| 54 | s.remember(ctx, k, resp) // so the next retry takes the fast path |
| 55 | return resp, nil |
| 56 | } |
| 57 | |
| 58 | err = postgres.Retry(ctx, func() error { |
| 59 | var err error |
| 60 | resp, err = s.attempt(ctx, k, work) |
| 61 | return err |
| 62 | }) |
| 63 | if err != nil { |
| 64 | // The transaction rolled back, so nothing happened. Let go of the key, |
| 65 | // so the client can fix the request, and send it again with that key. |
| 66 | s.release(ctx, k) |
| 67 | return Response{}, err |
| 68 | } |
| 69 | s.remember(ctx, k, resp) |
| 70 | return resp, nil |
| 71 | } |
| 72 | |
| 73 | // claim marks k as in progress, so that this request can run it. If k exists, |
| 74 | // it returns the response to replay, or the reason this request can't run. |
| 75 | func (s *Store) claim(ctx context.Context, k Key) (Response, error) { |
| 76 | tx, err := s.pool.Begin(ctx) |
| 77 | if err != nil { |
| 78 | return Response{}, fmt.Errorf("claim key: %w", err) |
| 79 | } |
| 80 | defer tx.Rollback(ctx) |
| 81 | |
| 82 | // A new key goes in as in progress. If another request is inserting the |
| 83 | // same key right now, the primary key makes us wait until it commits. |
| 84 | tag, err := tx.Exec(ctx, ` |
| 85 | INSERT INTO idempotency_keys (scope, key, fingerprint, expires_at) |
| 86 | VALUES ($1, $2, $3, now() + $4::interval) |
| 87 | ON CONFLICT (scope, key) DO NOTHING`, |
| 88 | k.Scope, k.Value, k.Fingerprint, TTL) |
| 89 | if err != nil { |
| 90 | return Response{}, fmt.Errorf("claim key: %w", err) |
| 91 | } |
| 92 | if tag.RowsAffected() == 0 { |
| 93 | // The key exists: lock its row, and look at it. |
| 94 | if resp, err := s.existing(ctx, tx, k); resp.Replayed || err != nil { |
| 95 | return resp, err |
| 96 | } |
| 97 | } |
| 98 | if err := tx.Commit(ctx); err != nil { |
| 99 | return Response{}, fmt.Errorf("claim key: %w", err) |
| 100 | } |
| 101 | return Response{}, nil |
| 102 | } |
| 103 | |
| 104 | // existing locks the row of a key that's already there, and decides. It |
| 105 | // returns the response to replay, or an error, or neither: then the key was |
| 106 | // abandoned, and this request takes it over. |
| 107 | func (s *Store) existing(ctx context.Context, tx pgx.Tx, k Key) (Response, error) { |
| 108 | var ( |
| 109 | fingerprint, body []byte |
| 110 | status string |
| 111 | code *int |
| 112 | abandoned bool |
| 113 | ) |
| 114 | err := tx.QueryRow(ctx, ` |
| 115 | SELECT fingerprint, status, response_code, response_body, |
| 116 | locked_at < now() - $3::interval |
| 117 | FROM idempotency_keys |
| 118 | WHERE scope = $1 AND key = $2 |
| 119 | FOR UPDATE`, |
| 120 | k.Scope, k.Value, lease).Scan(&fingerprint, &status, &code, &body, &abandoned) |
| 121 | if errors.Is(err, pgx.ErrNoRows) { |
| 122 | // A request that failed released it a moment ago. A retry can claim it. |
| 123 | return Response{}, ErrInProgress |
| 124 | } |
| 125 | if err != nil { |
| 126 | return Response{}, fmt.Errorf("get key: %w", err) |
| 127 | } |
| 128 | |
| 129 | switch { |
| 130 | case !bytes.Equal(fingerprint, k.Fingerprint): |
| 131 | return Response{}, ErrKeyReused |
| 132 | case status == "completed": |
| 133 | return Response{Status: *code, Body: body, Replayed: true}, nil |
| 134 | case !abandoned: |
| 135 | return Response{}, ErrInProgress |
| 136 | } |
| 137 | // In progress for longer than any request takes: the request that claimed |
| 138 | // it died, and its transaction never committed. Take it over. |
| 139 | _, err = tx.Exec(ctx, ` |
| 140 | UPDATE idempotency_keys SET locked_at = now() |
| 141 | WHERE scope = $1 AND key = $2`, |
| 142 | k.Scope, k.Value) |
| 143 | if err != nil { |
| 144 | return Response{}, fmt.Errorf("take over key: %w", err) |
| 145 | } |
| 146 | return Response{}, nil |
| 147 | } |
| 148 | |
| 149 | // attempt runs work and completes k, in one database transaction. |
| 150 | func (s *Store) attempt(ctx context.Context, k Key, work func(tx pgx.Tx) (Response, error)) (Response, error) { |
| 151 | // READ COMMITTED, like the wallet's own transactions: the row locks that |
| 152 | // work takes rely on it. |
| 153 | tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted}) |
| 154 | if err != nil { |
| 155 | return Response{}, fmt.Errorf("begin: %w", err) |
| 156 | } |
| 157 | defer tx.Rollback(ctx) |
| 158 | |
| 159 | resp, err := work(tx) |
| 160 | if err != nil { |
| 161 | return Response{}, err |
| 162 | } |
| 163 | // Complete the key in the same transaction as the work. The status check |
| 164 | // proves the key is still ours: if another request completed it first, we |
| 165 | // roll back, and our work never happened. |
| 166 | tag, err := tx.Exec(ctx, ` |
| 167 | UPDATE idempotency_keys |
| 168 | SET status = 'completed', response_code = $3, response_body = $4, completed_at = now() |
| 169 | WHERE scope = $1 AND key = $2 AND status = 'in_progress'`, |
| 170 | k.Scope, k.Value, resp.Status, resp.Body) |
| 171 | if err != nil { |
| 172 | return Response{}, fmt.Errorf("complete key: %w", err) |
| 173 | } |
| 174 | if tag.RowsAffected() == 0 { |
| 175 | return Response{}, ErrInProgress |
| 176 | } |
| 177 | if err := tx.Commit(ctx); err != nil { |
| 178 | return Response{}, fmt.Errorf("commit: %w", err) |
| 179 | } |
| 180 | return resp, nil |
| 181 | } |
| 182 | |
| 183 | // release deletes k's claim after its work failed, so the key can run again. |
| 184 | func (s *Store) release(ctx context.Context, k Key) { |
| 185 | // Release it even if the client hung up, which cancels ctx. |
| 186 | ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) |
| 187 | defer cancel() |
| 188 | _, err := s.pool.Exec(ctx, ` |
| 189 | DELETE FROM idempotency_keys |
| 190 | WHERE scope = $1 AND key = $2 AND status = 'in_progress'`, |
| 191 | k.Scope, k.Value) |
| 192 | if err != nil { |
| 193 | // Not fatal: the lease runs out, and a retry takes the key over. |
| 194 | slog.WarnContext(ctx, "release idempotency key", "err", err) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | // Cleanup deletes expired keys every interval, until ctx is canceled. |
| 199 | func (s *Store) Cleanup(ctx context.Context, interval time.Duration) { |
| 200 | ticker := time.NewTicker(interval) |
| 201 | defer ticker.Stop() |
| 202 | for { |
| 203 | select { |
| 204 | case <-ctx.Done(): |
| 205 | return |
| 206 | case <-ticker.C: |
| 207 | } |
| 208 | tag, err := s.pool.Exec(ctx, `DELETE FROM idempotency_keys WHERE expires_at < now()`) |
| 209 | if err != nil { |
| 210 | slog.WarnContext(ctx, "delete expired idempotency keys", "err", err) |
| 211 | continue |
| 212 | } |
| 213 | slog.InfoContext(ctx, "deleted expired idempotency keys", "count", tag.RowsAffected()) |
| 214 | } |
| 215 | } |