207 lines
6.7 KiB
Go
207 lines
6.7 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
|
|
}
|
|
// Usage under a staff preview grant is metered but never invoiced:
|
|
// tagged preview=true and kept out of the ERP outbox. A product not
|
|
// for sale yet is accepted only under such a grant.
|
|
preview := s.previewActive(ctx, in.TenantID, in.Product)
|
|
if !preview && !s.knownProduct(ctx, in.Product) {
|
|
rejected = append(rejected, map[string]any{"index": i, "reason": "unknown_product"})
|
|
continue
|
|
}
|
|
if preview {
|
|
props := map[string]interface{}{}
|
|
for k, v := range in.Properties {
|
|
props[k] = v
|
|
}
|
|
props["preview"] = true
|
|
in.Properties = props
|
|
}
|
|
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 preview {
|
|
continue
|
|
}
|
|
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})
|
|
}
|
|
|
|
// previewActive reports whether the tenant uses product under an unexpired
|
|
// staff preview grant. Lookup errors count as no: the event is then treated
|
|
// like any other and refused for a product not for sale.
|
|
func (s *Server) previewActive(ctx context.Context, tenantID, product string) bool {
|
|
tps, err := s.Store.ListTenantProducts(ctx, tenantID)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
now := s.now()
|
|
for _, tp := range tps {
|
|
if tp.Product == product && tp.PreviewActive(now) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|