Files
tenant-registry/internal/server/outbox.go
T
Sharang ParnerkarandClaude Opus 5.5 2f6fa5f3e8
ci / shared (pull_request) Successful in 11s
ci / test (pull_request) Failing after 38s
ci / image (pull_request) Skipped
feat(onprem): APP_ENV=onprem for a customer's own node
The registry on a customer's node must never reach a Breakpilot host and
must not run the cloud's commercial machinery.

- APP_ENV=onprem: no ERP (nothing queued, webhook off), no trial (new
  workspaces start active, the ladder never escalates by time), and the
  trial-offer, trial-terms, catalog/trial request and admin trial routes
  answer 404 not_available.
- PRODUCTS, PRODUCT_LAUNCH_URLS, PRODUCT_PROVISION_URLS: one store
  decorator applies the product list and URLs to every catalog read
  (catalog, activation, provisioning, entitlement checks). On-prem has no
  seeded URLs, so provisioning goes only to the local products. Checked at
  start ({id} in provision URLs, absolute http(s)).
- On-prem start fails when the values leave something to a cloud or dev
  default (auth off, no authz rules, ephemeral licence key, portal, invite,
  sender, LLM gateway) or set an ERP or contract documents.
- SMTP_TLS=starttls|tls|none: a plain relay inside the customer's network;
  no AUTH without encryption.
- Migration 0032: the Werkpilot text no longer names our LLM host.

Cloud behaviour is unchanged without the new variables (tested).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:35:53 +01:00

175 lines
5.8 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
// 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)
}
}