cache.go67 lines, 2.0 KB
| 1 | package idempotency |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "log/slog" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/redis/go-redis/v9" |
| 12 | ) |
| 13 | |
| 14 | // cacheTTL is how long Redis keeps a completed response. Most retries come |
| 15 | // within minutes. Older ones still work: they're answered by Postgres. |
| 16 | const cacheTTL = time.Hour |
| 17 | |
| 18 | // cachedResponse is a completed response as Redis holds it. It keeps the |
| 19 | // fingerprint, so a reused key is refused on the fast path too. |
| 20 | type cachedResponse struct { |
| 21 | Fingerprint []byte `json:"fingerprint"` |
| 22 | Status int `json:"status"` |
| 23 | Body []byte `json:"body"` |
| 24 | } |
| 25 | |
| 26 | func cacheKey(k Key) string { |
| 27 | return "idempotency:" + k.Scope + ":" + k.Value |
| 28 | } |
| 29 | |
| 30 | // cached looks k up in Redis, and returns the response to replay. When Redis |
| 31 | // doesn't know k, or is down, it returns nothing, and Postgres decides. |
| 32 | func (s *Store) cached(ctx context.Context, k Key) (Response, error) { |
| 33 | if s.cache == nil { |
| 34 | return Response{}, nil |
| 35 | } |
| 36 | data, err := s.cache.Get(ctx, cacheKey(k)).Bytes() |
| 37 | if err != nil { |
| 38 | if !errors.Is(err, redis.Nil) { |
| 39 | slog.WarnContext(ctx, "idempotency cache unavailable, using postgres", "err", err) |
| 40 | } |
| 41 | return Response{}, nil |
| 42 | } |
| 43 | var c cachedResponse |
| 44 | if err := json.Unmarshal(data, &c); err != nil { |
| 45 | slog.WarnContext(ctx, "idempotency cache: bad entry", "key", cacheKey(k), "err", err) |
| 46 | return Response{}, nil |
| 47 | } |
| 48 | if !bytes.Equal(c.Fingerprint, k.Fingerprint) { |
| 49 | return Response{}, ErrKeyReused |
| 50 | } |
| 51 | return Response{Status: c.Status, Body: c.Body, Replayed: true}, nil |
| 52 | } |
| 53 | |
| 54 | // remember stores a completed response in Redis. If that fails, we only lose |
| 55 | // the fast path, so the error is logged, never returned. |
| 56 | func (s *Store) remember(ctx context.Context, k Key, resp Response) { |
| 57 | if s.cache == nil { |
| 58 | return |
| 59 | } |
| 60 | data, err := json.Marshal(cachedResponse{Fingerprint: k.Fingerprint, Status: resp.Status, Body: resp.Body}) |
| 61 | if err == nil { |
| 62 | err = s.cache.Set(ctx, cacheKey(k), data, cacheTTL).Err() |
| 63 | } |
| 64 | if err != nil { |
| 65 | slog.WarnContext(ctx, "idempotency cache unavailable, response not cached", "err", err) |
| 66 | } |
| 67 | } |