Files
tenant-registry/internal/server/usage.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

175 lines
5.8 KiB
Go

package server
import (
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// ─── usage events (PRODUCT_INTEGRATION_SPEC 2.0 §9.2) ────────────────────
//
// Products push facts continuously; the registry stores them once
// (idempotency_key) and forwards each new one to ERPNext through the outbox
// as a Usage Record. Billing reads ERP; the portal reads the registry.
type usageEventIn struct {
IdempotencyKey string `json:"idempotency_key"`
TenantID string `json:"tenant_id"`
Product string `json:"product"`
Metric string `json:"metric"`
Quantity *float64 `json:"quantity"`
OccurredAt string `json:"occurred_at"`
Properties map[string]interface{} `json:"properties"`
}
type usageBatch struct {
Events []usageEventIn `json:"events"`
}
// postUsageEvents accepts one event, an array, or {"events": [...]}.
func (s *Server) postUsageEvents(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
var raw json.RawMessage
if err := dec.Decode(&raw); err != nil {
writeError(w, http.StatusBadRequest, "invalid_json", err.Error())
return
}
var events []usageEventIn
switch {
case len(raw) > 0 && raw[0] == '[':
if err := json.Unmarshal(raw, &events); err != nil {
writeError(w, http.StatusBadRequest, "invalid_json", err.Error())
return
}
default:
var b usageBatch
if err := json.Unmarshal(raw, &b); err != nil {
writeError(w, http.StatusBadRequest, "invalid_json", err.Error())
return
}
if b.Events == nil {
var one usageEventIn
if err := json.Unmarshal(raw, &one); err != nil {
writeError(w, http.StatusBadRequest, "invalid_json", err.Error())
return
}
events = []usageEventIn{one}
} else {
events = b.Events
}
}
if len(events) == 0 || len(events) > 500 {
writeError(w, http.StatusBadRequest, "invalid_input", "1..500 events per request")
return
}
p, _ := authn.PrincipalFrom(r.Context())
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
accepted, duplicates := 0, 0
rejected := []map[string]any{}
for i, in := range events {
if p.IsUser() {
in.TenantID = p.TenantID // users may only report for their own tenant
}
if in.IdempotencyKey == "" || in.TenantID == "" || in.Product == "" || in.Metric == "" {
rejected = append(rejected, map[string]any{"index": i, "reason": "idempotency_key, tenant_id, product and metric are required"})
continue
}
if !s.knownProduct(ctx, in.Product) {
rejected = append(rejected, map[string]any{"index": i, "reason": "unknown_product"})
continue
}
qty := 1.0
if in.Quantity != nil {
qty = *in.Quantity
}
occurred := s.now()
if in.OccurredAt != "" {
ts, err := time.Parse(time.RFC3339, in.OccurredAt)
if err != nil {
rejected = append(rejected, map[string]any{"index": i, "reason": "occurred_at must be RFC3339"})
continue
}
occurred = ts.UTC()
}
ev, inserted, err := s.Store.InsertUsageEvent(ctx, store.UsageEvent{
IdempotencyKey: in.IdempotencyKey, TenantID: in.TenantID, Product: in.Product, Metric: in.Metric,
Quantity: qty, OccurredAt: occurred, Properties: in.Properties,
})
if err != nil {
if errors.Is(err, store.ErrNotFound) {
rejected = append(rejected, map[string]any{"index": i, "reason": "tenant_not_found"})
continue
}
if errors.Is(err, store.ErrInvalidInput) {
rejected = append(rejected, map[string]any{"index": i, "reason": "invalid_input"})
continue
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if !inserted {
duplicates++
continue
}
accepted++
if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{
Kind: store.OutboxUsageRecord, TenantID: ev.TenantID,
Payload: map[string]interface{}{"usage_event_id": ev.ID, "idempotency_key": ev.IdempotencyKey, "product": ev.Product,
"metric": ev.Metric, "quantity": ev.Quantity, "occurred_at": ev.OccurredAt.Format(time.RFC3339)},
}); err != nil {
s.Log.Error("enqueue usage outbox failed", "err", err, "usage_event_id", ev.ID)
}
}
code := http.StatusAccepted
if accepted == 0 && duplicates == 0 {
code = http.StatusBadRequest
}
writeJSON(w, code, map[string]any{"accepted": accepted, "duplicates": duplicates, "rejected": rejected})
}
// listUsageEvents — GET /v1/usage/events?tenant_id=&product=&metric=&since=&until=&limit=
func (s *Server) listUsageEvents(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
f := store.UsageFilter{TenantID: q.Get("tenant_id"), Product: q.Get("product"), Metric: q.Get("metric")}
if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() {
f.TenantID = p.TenantID
}
if f.TenantID == "" {
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id query param is required")
return
}
for name, dst := range map[string]**time.Time{"since": &f.Since, "until": &f.Until} {
if v := q.Get(name); v != "" {
ts, err := time.Parse(time.RFC3339, v)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid_"+name, "must be RFC3339")
return
}
*dst = &ts
}
}
if v := q.Get("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n <= 0 || n > 1000 {
writeError(w, http.StatusBadRequest, "invalid_limit", "limit must be 1..1000")
return
}
f.Limit = n
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
items, err := s.Store.ListUsageEvents(ctx, f)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}