From e5ed990bf7987e87a83887b9dda1810792b18218 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:21:01 +0100 Subject: [PATCH] fix(outbox): dead-letter after a week; ERP mock names unique per boot Stage logged ~11,100 failed usage.record items a day ('tenant has no ERP customer yet') behind 36 customer.upsert failures on the unique tenants_erp_customer_id_key (backlog t25). The ERP mock keeps its docs in memory and restarts with every registry deploy on stage: its counter began at CUST-00001 again and handed new tenants names older tenants are still linked to, so they never got linked and their usage waited forever. - erpmock: Config.NameToken goes into every assigned name; cmd/erpmock sets one per boot (CUST--00001). Tests keep plain names. - outbox: after maxOutboxAttempts (170, about a week at the 1 h cap) an item is dead-lettered instead of retried forever: done_at set, last_error 'dead letter: ', payload kept for a re-queue, and an ERROR line (the prod error alert sees it). Store gains DeadLetterOutbox (memory + postgres). Tests: dead letter after the last attempt and nothing claimed after, memory and postgres; mock names carry the token. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KYcAAeTw22GE9QPzDM8yc4 --- cmd/erpmock/main.go | 2 ++ internal/erpmock/server.go | 12 +++++++++- internal/erpmock/server_test.go | 11 +++++++++ internal/server/erp_test.go | 40 +++++++++++++++++++++++++++++++++ internal/server/export_test.go | 4 ++++ internal/server/outbox.go | 13 +++++++++++ internal/store/memory_erp.go | 15 +++++++++++++ internal/store/postgres_erp.go | 12 ++++++++++ internal/store/store.go | 3 +++ internal/store/types.go | 3 +++ 10 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 internal/server/export_test.go diff --git a/cmd/erpmock/main.go b/cmd/erpmock/main.go index 30d5a78..c56d946 100644 --- a/cmd/erpmock/main.go +++ b/cmd/erpmock/main.go @@ -29,6 +29,8 @@ func main() { APISecret: env("ERP_API_SECRET", "mock"), WebhookURL: os.Getenv("ERP_WEBHOOK_URL"), WebhookSecret: os.Getenv("ERP_WEBHOOK_SECRET"), + // One token per boot keeps assigned names unique across restarts. + NameToken: time.Now().UTC().Format("060102150405"), } addr := env("ERPMOCK_ADDR", ":8000") if cfg.WebhookURL == "" { diff --git a/internal/erpmock/server.go b/internal/erpmock/server.go index bd92602..c5ba439 100644 --- a/internal/erpmock/server.go +++ b/internal/erpmock/server.go @@ -47,6 +47,12 @@ type Config struct { WebhookSecret string // SKUs seeded as Item + Subscription Plan docs. SKUs []string + // NameToken goes into every name the mock assigns (CUST--00001). + // The mock keeps its docs in memory, so after a restart its counter + // starts again; without a token a new customer would get a name an older + // tenant in the registry is still linked to (unique erp_customer_id). + // Empty in tests: plain CUST-00001. + NameToken string } type Server struct { @@ -115,7 +121,11 @@ func (s *Server) put(doctype string, d Doc) Doc { name, _ := d["name"].(string) if name == "" { s.seq[doctype]++ - name = fmt.Sprintf("%s-%05d", prefix(doctype), s.seq[doctype]) + if s.cfg.NameToken != "" { + name = fmt.Sprintf("%s-%s-%05d", prefix(doctype), s.cfg.NameToken, s.seq[doctype]) + } else { + name = fmt.Sprintf("%s-%05d", prefix(doctype), s.seq[doctype]) + } d["name"] = name } now := time.Now().UTC().Format("2006-01-02 15:04:05.000000") diff --git a/internal/erpmock/server_test.go b/internal/erpmock/server_test.go index 66102e3..75074e1 100644 --- a/internal/erpmock/server_test.go +++ b/internal/erpmock/server_test.go @@ -155,3 +155,14 @@ func TestMock_noWebhookURL(t *testing.T) { t.Fatalf("got %d %s", code, raw) } } + +// TestNameToken: with a token, assigned names carry it, so a restarted mock +// (counter back at 1) never hands out a name it gave before. +func TestNameToken(t *testing.T) { + srv := httptest.NewServer(New(Config{APIKey: "k", APISecret: "s", NameToken: "boot1"})) + defer srv.Close() + code, raw := call(t, srv.URL, "POST", "/api/resource/Customer", map[string]any{"customer_name": "A"}, true) + if code != 200 || !bytes.Contains(raw, []byte(`"name":"CUST-boot1-00001"`)) { + t.Fatalf("create: %d %s", code, raw) + } +} diff --git a/internal/server/erp_test.go b/internal/server/erp_test.go index e9544a1..6814a36 100644 --- a/internal/server/erp_test.go +++ b/internal/server/erp_test.go @@ -11,6 +11,7 @@ import ( "git.breakpilot.com/platform/tenant-registry/internal/erp" "git.breakpilot.com/platform/tenant-registry/internal/erpmock" + "git.breakpilot.com/platform/tenant-registry/internal/server" "git.breakpilot.com/platform/tenant-registry/internal/store" ) @@ -445,3 +446,42 @@ func TestReconcile_overdueInvoicesDriveTheLadder(t *testing.T) { _ = paid }) } + +// TestOutbox_deadLettersAfterMaxAttempts: an item that keeps failing is +// retried with backoff, then given up after server.MaxOutboxAttempts (kept, with +// "dead letter: " in last_error) instead of being retried forever. +func TestOutbox_deadLettersAfterMaxAttempts(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, `{"exception":"down"}`, http.StatusInternalServerError) + })) + defer down.Close() + h.app.ERP = erp.New(erp.Config{BaseURL: down.URL, APIKey: "k", APISecret: "s"}) + newTenant(t, h, "dead-co") // enqueues the customer upsert + + start := time.Now() + defer func() { h.app.Now = nil }() + for i := 1; i <= server.MaxOutboxAttempts; i++ { + at := start.Add(time.Duration(i) * 2 * time.Hour) // always past the last backoff + h.app.Now = func() time.Time { return at } + if _, err := h.app.DrainOutbox(t.Context()); err != nil { + t.Fatal(err) + } + pending, err := h.app.Store.PendingOutbox(t.Context()) + if err != nil { + t.Fatal(err) + } + if want := 1; i < server.MaxOutboxAttempts && pending != want { + t.Fatalf("attempt %d: pending %d, want %d", i, pending, want) + } + if i == server.MaxOutboxAttempts && pending != 0 { + t.Fatalf("not dead-lettered after %d attempts: pending %d", i, pending) + } + } + // a later drain claims nothing: the item is done, not retried + h.app.Now = func() time.Time { return start.Add(1000 * time.Hour) } + if n, err := h.app.DrainOutbox(t.Context()); err != nil || n != 0 { + t.Fatalf("drain after dead letter: n=%d err=%v", n, err) + } + }) +} diff --git a/internal/server/export_test.go b/internal/server/export_test.go new file mode 100644 index 0000000..27bbabf --- /dev/null +++ b/internal/server/export_test.go @@ -0,0 +1,4 @@ +package server + +// MaxOutboxAttempts exposes the dead-letter threshold to the external tests. +const MaxOutboxAttempts = maxOutboxAttempts diff --git a/internal/server/outbox.go b/internal/server/outbox.go index 3b76d79..6d10a87 100644 --- a/internal/server/outbox.go +++ b/internal/server/outbox.go @@ -19,6 +19,12 @@ import ( var outboxBackoff = []time.Duration{time.Minute, 5 * time.Minute, 15 * time.Minute, time.Hour} +// maxOutboxAttempts: after that many failures (about a week at the 1 h cap) +// the item is dead-lettered instead of retried forever. Long enough that an +// ERP outage never drops usage; the ERROR line makes it an alert, and the row +// keeps its payload so it can be re-queued (done_at = NULL, attempts = 0). +const maxOutboxAttempts = 170 + // EnqueueCustomerUpsert is called on tenant creation. func (s *Server) EnqueueCustomerUpsert(ctx context.Context, t *store.Tenant) { if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{Kind: store.OutboxCustomerUpsert, TenantID: t.ID, @@ -62,6 +68,13 @@ func (s *Server) DrainOutbox(ctx context.Context) (int, error) { } for _, it := range items { if err := s.processOutbox(ctx, it); err != nil { + if it.Attempts+1 >= maxOutboxAttempts { + s.Log.Error("outbox item dead-lettered", "id", it.ID, "kind", it.Kind, "tenant_id", it.TenantID, "attempts", it.Attempts+1, "err", err) + if derr := s.Store.DeadLetterOutbox(ctx, it.ID, err.Error(), s.now()); derr != nil { + return len(items), derr + } + continue + } delay := outboxBackoff[min(it.Attempts, len(outboxBackoff)-1)] s.Log.Warn("outbox item failed", "id", it.ID, "kind", it.Kind, "attempt", it.Attempts+1, "retry_in", delay, "err", err) if ferr := s.Store.FailOutbox(ctx, it.ID, err.Error(), s.now().Add(delay)); ferr != nil { diff --git a/internal/store/memory_erp.go b/internal/store/memory_erp.go index 3b9331f..a59d8c4 100644 --- a/internal/store/memory_erp.go +++ b/internal/store/memory_erp.go @@ -201,6 +201,21 @@ func (m *Memory) CompleteOutbox(_ context.Context, id int64, at time.Time) error return ErrNotFound } +func (m *Memory) DeadLetterOutbox(_ context.Context, id int64, errMsg string, at time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + for _, o := range m.outbox { + if o.ID == id { + o.Attempts++ + o.LastError = DeadLetterPrefix + errMsg + t := at + o.DoneAt = &t + return nil + } + } + return ErrNotFound +} + func (m *Memory) FailOutbox(_ context.Context, id int64, errMsg string, nextAttempt time.Time) error { m.mu.Lock() defer m.mu.Unlock() diff --git a/internal/store/postgres_erp.go b/internal/store/postgres_erp.go index ba091ba..932f128 100644 --- a/internal/store/postgres_erp.go +++ b/internal/store/postgres_erp.go @@ -294,6 +294,18 @@ func (p *Postgres) CompleteOutbox(ctx context.Context, id int64, at time.Time) e return nil } +func (p *Postgres) DeadLetterOutbox(ctx context.Context, id int64, errMsg string, at time.Time) error { + tag, err := p.pool.Exec(ctx, `UPDATE erp_outbox SET attempts = attempts + 1, last_error = $2, done_at = $3 WHERE id = $1`, + id, DeadLetterPrefix+errMsg, at) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + return nil +} + func (p *Postgres) FailOutbox(ctx context.Context, id int64, errMsg string, nextAttempt time.Time) error { tag, err := p.pool.Exec(ctx, `UPDATE erp_outbox SET attempts = attempts + 1, last_error = $2, next_attempt_at = $3 WHERE id = $1`, id, errMsg, nextAttempt) if err != nil { diff --git a/internal/store/store.go b/internal/store/store.go index 780688b..998f06b 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -137,6 +137,9 @@ type Store interface { ClaimOutbox(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]OutboxItem, error) CompleteOutbox(ctx context.Context, id int64, at time.Time) error FailOutbox(ctx context.Context, id int64, errMsg string, nextAttempt time.Time) error + // DeadLetterOutbox gives up on an item: done, with the reason kept in + // last_error (prefixed "dead letter: ") so it can be found and re-queued. + DeadLetterOutbox(ctx context.Context, id int64, errMsg string, at time.Time) error PendingOutbox(ctx context.Context) (int, error) // Webhook idempotency: true when eventID was not seen before. diff --git a/internal/store/types.go b/internal/store/types.go index 6abe03e..5d31527 100644 --- a/internal/store/types.go +++ b/internal/store/types.go @@ -248,6 +248,9 @@ const ( OutboxLeadCreate = "lead.create" ) +// DeadLetterPrefix marks an outbox item the worker gave up on (last_error). +const DeadLetterPrefix = "dead letter: " + // Licence — revocation + heartbeat record of an issued CLI licence JWT. type Licence struct { ID string `json:"id"`