Files
tenant-registry/internal/server/outbox.go
T
Sharang ParnerkarandClaude Opus 5.5 e5ed990bf7
ci / shared (pull_request) Successful in 11s
ci / test (pull_request) Successful in 25m15s
ci / image (pull_request) Skipped
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-<yymmddHHMMSS>-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: <err>', 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KYcAAeTw22GE9QPzDM8yc4
2026-10-29 18:21:01 +01:00

166 lines
5.5 KiB
Go

package server
import (
"context"
"errors"
"fmt"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/erp"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// ─── ERP outbox worker (M-MIG-7) ───────────────────────────────────────────
//
// Every ERP write is a row in erp_outbox; the worker drains due rows, calls
// ERPNext and marks them done or schedules a retry with backoff
// (1m, 5m, 15m, 1h, 1h…). Nothing is lost when ERP is down; the reconcile
// job is the safety net for the other direction.
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,
Payload: map[string]interface{}{"name": t.Name, "slug": t.Slug}}); err != nil {
s.Log.Error("enqueue customer upsert failed", "tenant_id", t.ID, "err", err)
}
}
// RunOutbox drains the outbox until ctx is done. No-op when ERP is not
// configured (items accumulate and are drained once it is).
func (s *Server) RunOutbox(ctx context.Context, every time.Duration) {
if !s.ERP.Enabled() {
s.Log.Warn("ERP_BASE_URL not set — outbox worker idle (ERP writes accumulate)")
return
}
if every <= 0 {
every = 15 * time.Second
}
t := time.NewTicker(every)
defer t.Stop()
for {
if n, err := s.DrainOutbox(ctx); err != nil {
s.Log.Error("outbox drain failed", "err", err)
} else if n > 0 {
s.Log.Info("outbox drained", "processed", n)
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
// DrainOutbox processes one batch; returns the number of items attempted.
func (s *Server) DrainOutbox(ctx context.Context) (int, error) {
now := s.now()
items, err := s.Store.ClaimOutbox(ctx, 50, now, 2*time.Minute)
if err != nil {
return 0, err
}
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 {
return len(items), ferr
}
continue
}
if cerr := s.Store.CompleteOutbox(ctx, it.ID, s.now()); cerr != nil {
return len(items), cerr
}
}
return len(items), nil
}
func (s *Server) processOutbox(ctx context.Context, it store.OutboxItem) error {
switch it.Kind {
case store.OutboxCustomerUpsert:
t, err := s.Store.GetTenant(ctx, it.TenantID)
if err != nil {
return err
}
if t.ErpCustomerID != "" {
return nil
}
name, err := s.ERP.UpsertCustomer(ctx, erp.Customer{CustomerName: t.Name, TenantID: t.ID, TenantSlug: t.Slug})
if err != nil {
return err
}
if _, err := s.Store.UpdateTenant(ctx, t.ID, store.TenantUpdate{ErpCustomerID: &name}); err != nil {
return err
}
s.emitAudit(ctx, nil, store.AuditEvent{TenantID: t.ID, Action: "erp.customer_linked", TargetID: name, TargetType: "customer", ActorType: "service"})
return nil
case store.OutboxUsageRecord:
t, err := s.Store.GetTenant(ctx, it.TenantID)
if err != nil {
return err
}
if t.ErpCustomerID == "" {
// customer.upsert is still pending — retry later
return errors.New("tenant has no ERP customer yet")
}
id := toFloat(it.Payload["usage_event_id"])
if _, err := s.ERP.CreateUsageRecord(ctx, erp.UsageRecord{
Customer: t.ErpCustomerID, TenantID: t.ID,
Product: str(it.Payload["product"]), Metric: str(it.Payload["metric"]), Qty: toFloat(it.Payload["quantity"]),
OccurredAt: str(it.Payload["occurred_at"]), IdempotencyKey: str(it.Payload["idempotency_key"]),
}); err != nil {
return err
}
if id > 0 {
return s.Store.MarkUsageSynced(ctx, []int64{int64(id)}, s.now())
}
return nil
case store.OutboxLeadCreate:
_, err := s.ERP.CreateLead(ctx, erp.Lead{
LeadName: str(it.Payload["lead_name"]), CompanyName: str(it.Payload["company_name"]), EmailID: str(it.Payload["email"]),
Source: "Platform catalog", Notes: str(it.Payload["notes"]), TenantID: it.TenantID, Product: str(it.Payload["product"]),
})
return err
}
return fmt.Errorf("unknown outbox kind %q", it.Kind)
}
func str(v interface{}) string {
s, _ := v.(string)
return s
}
// RunReconcile runs Reconcile every `every` until ctx is done.
func (s *Server) RunReconcile(ctx context.Context, every time.Duration) {
if every <= 0 {
every = 15 * time.Minute
}
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
rep := s.Reconcile(ctx)
s.Log.Info("reconcile", "tenants", rep.Tenants, "erp_checked", rep.ErpChecked, "changed", rep.Changed, "escalated", rep.Escalated, "errors", rep.Errors)
}
}