Files
tenant-registry/internal/server/outbox.go
T
Sharang ParnerkarandClaude Fable 5.1 7b02cd1c21
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Failing after 14m32s
ci / image (pull_request) Skipped
feat(erp): always-on ERP link, usage events, outbox, CLI licences
M-MIG-7 (ERP/02, decisions 3, 12, 13, 18):

- migration 0004: subscriptions, usage_events, erp_outbox,
  erp_webhook_receipts, licences; tenants.status_changed_at (trigger)
- internal/erp: Frappe REST client (Customer upsert by tenant_id,
  Subscription list, Usage Record, Lead) + webhook signing/verification
- internal/erpmock + cmd/erpmock: ERPNext stand-in for staging —
  /api/resource/{doctype} with token auth, request log, /_mock/fire/*
  triggers that mutate docs and deliver signed webhooks
- POST /v1/internal/erp/webhook (HMAC, idempotent by event id):
  sales_order.submit → subscriptions + entitlements (SKU → product/plan,
  add-on SKUs → limits) + active; sales_invoice.overdue → warning /
  restricted / halted by days overdue; payment_entry.submit → active;
  subscription.cancel → halted
- outbox worker (customer.upsert on tenant create, usage.record,
  lead.create on catalog request) with backoff; reconcile job mirrors
  ERP subscriptions and applies the time-based ladder (trial expiry,
  warning→restricted 14 d, restricted→halted 30 d, halted→archived 30 d)
- POST/GET /v1/usage/events (idempotency_key, batch), GET
  /v1/subscriptions, GET /v1/internal/erp/status, POST
  /v1/internal/erp/reconcile
- CLI licences: Ed25519 signer (LICENCE_SIGNING_KEY), POST /v1/licences
  (entitlement-gated, expiry capped by the entitlement), GET
  /.well-known/licence-keys.json, POST /v1/licences/heartbeat (grace
  ladder, renewal past half-life, revoked), revoke/list
- authn Principal carries tenant-context claims (user tokens scope usage
  and licence calls to their own tenant); authz groups usage(.read)
- tests for every path (both stores), erpmock, erp client, licence pkg;
  openapi.yaml + README updated; Dockerfile ships /erpmock

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-12 09:45:05 +02:00

153 lines
4.9 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}
// 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 {
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)
}
}