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 // enqueueERP queues a write for the ERP. On-prem there is no ERP: nothing is // queued, so the outbox never fills with items no worker will drain. func (s *Server) enqueueERP(ctx context.Context, it store.OutboxItem) (*store.OutboxItem, error) { if s.onPrem() { return nil, nil } return s.Store.EnqueueOutbox(ctx, it) } // EnqueueCustomerUpsert is called on tenant creation. func (s *Server) EnqueueCustomerUpsert(ctx context.Context, t *store.Tenant) { if _, err := s.enqueueERP(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) } }