Files
tenant-registry/internal/store/memory_erp.go
T
sharang 209524e5ac
ci / shared (push) Successful in 14s
ci / test (push) Successful in 22m28s
ci / image (push) Successful in 28s
feat(erp): always-on ERP link, usage events, outbox, CLI licences (#25)
2026-09-12 08:35:13 +00:00

321 lines
6.9 KiB
Go

package store
import (
"context"
"sort"
"time"
"github.com/google/uuid"
)
// ─── M-MIG-7: subscriptions / usage / outbox / receipts / licences (Memory) ──
func (m *Memory) UpsertSubscription(_ context.Context, sub Subscription) (*Subscription, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[sub.TenantID]; !ok {
return nil, ErrNotFound
}
if sub.SKU == "" || sub.Product == "" {
return nil, ErrInvalidInput
}
now := time.Now().UTC()
var row *Subscription
for _, s := range m.subs {
if s.TenantID == sub.TenantID && s.SKU == sub.SKU && s.ErpSalesOrder == sub.ErpSalesOrder {
row = s
break
}
}
if row == nil {
row = &Subscription{ID: uuid.NewString(), TenantID: sub.TenantID, SKU: sub.SKU, ErpSalesOrder: sub.ErpSalesOrder, CreatedAt: now}
m.subs[row.ID] = row
}
row.Product = sub.Product
row.Plan = sub.Plan
row.Seats = sub.Seats
row.Status = firstNonEmpty(sub.Status, SubscriptionActive)
row.ErpSubscription = sub.ErpSubscription
row.PeriodStart = sub.PeriodStart
row.PeriodEnd = sub.PeriodEnd
row.UpdatedAt = now
cp := *row
return &cp, nil
}
func (m *Memory) ListSubscriptions(_ context.Context, tenantID string) ([]Subscription, error) {
m.mu.RLock()
defer m.mu.RUnlock()
if _, ok := m.tenants[tenantID]; !ok {
return nil, ErrNotFound
}
out := []Subscription{}
for _, s := range m.subs {
if s.TenantID == tenantID {
out = append(out, *s)
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].CreatedAt.Equal(out[j].CreatedAt) {
return out[i].ID < out[j].ID
}
return out[i].CreatedAt.Before(out[j].CreatedAt)
})
return out, nil
}
func (m *Memory) InsertUsageEvent(_ context.Context, ev UsageEvent) (*UsageEvent, bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[ev.TenantID]; !ok {
return nil, false, ErrNotFound
}
if ev.IdempotencyKey == "" || ev.Metric == "" || ev.Product == "" {
return nil, false, ErrInvalidInput
}
if id, dup := m.usageKey[ev.IdempotencyKey]; dup {
for _, u := range m.usage {
if u.ID == id {
cp := *u
return &cp, false, nil
}
}
}
m.usageID++
row := ev
row.ID = m.usageID
row.ReceivedAt = time.Now().UTC()
if row.OccurredAt.IsZero() {
row.OccurredAt = row.ReceivedAt
}
if row.Properties == nil {
row.Properties = map[string]interface{}{}
}
m.usage = append(m.usage, &row)
m.usageKey[ev.IdempotencyKey] = row.ID
cp := row
return &cp, true, nil
}
func (m *Memory) ListUsageEvents(_ context.Context, f UsageFilter) ([]UsageEvent, error) {
m.mu.RLock()
defer m.mu.RUnlock()
limit := f.Limit
if limit <= 0 || limit > 1000 {
limit = 200
}
out := []UsageEvent{}
for i := len(m.usage) - 1; i >= 0 && len(out) < limit; i-- {
u := m.usage[i]
if f.TenantID != "" && u.TenantID != f.TenantID {
continue
}
if f.Product != "" && u.Product != f.Product {
continue
}
if f.Metric != "" && u.Metric != f.Metric {
continue
}
if f.Since != nil && u.OccurredAt.Before(*f.Since) {
continue
}
if f.Until != nil && u.OccurredAt.After(*f.Until) {
continue
}
out = append(out, *u)
}
return out, nil
}
func (m *Memory) MarkUsageSynced(_ context.Context, ids []int64, at time.Time) error {
m.mu.Lock()
defer m.mu.Unlock()
set := map[int64]bool{}
for _, id := range ids {
set[id] = true
}
for _, u := range m.usage {
if set[u.ID] {
t := at
u.ErpSyncedAt = &t
}
}
return nil
}
func (m *Memory) EnqueueOutbox(_ context.Context, item OutboxItem) (*OutboxItem, error) {
m.mu.Lock()
defer m.mu.Unlock()
if item.Kind == "" {
return nil, ErrInvalidInput
}
m.outboxID++
row := item
row.ID = m.outboxID
row.Attempts = 0
row.DoneAt = nil
row.CreatedAt = time.Now().UTC()
if row.NextAttemptAt.IsZero() {
row.NextAttemptAt = row.CreatedAt
}
if row.Payload == nil {
row.Payload = map[string]interface{}{}
}
m.outbox = append(m.outbox, &row)
cp := row
return &cp, nil
}
func (m *Memory) ClaimOutbox(_ context.Context, limit int, now time.Time, lease time.Duration) ([]OutboxItem, error) {
m.mu.Lock()
defer m.mu.Unlock()
if limit <= 0 {
limit = 50
}
out := []OutboxItem{}
for _, o := range m.outbox {
if o.DoneAt != nil || o.NextAttemptAt.After(now) {
continue
}
o.NextAttemptAt = now.Add(lease)
out = append(out, *o)
if len(out) >= limit {
break
}
}
return out, nil
}
func (m *Memory) CompleteOutbox(_ context.Context, id int64, at time.Time) error {
m.mu.Lock()
defer m.mu.Unlock()
for _, o := range m.outbox {
if o.ID == id {
t := at
o.DoneAt = &t
o.Attempts++
o.LastError = ""
return nil
}
}
return ErrNotFound
}
func (m *Memory) FailOutbox(_ context.Context, id int64, errMsg string, nextAttempt time.Time) error {
m.mu.Lock()
defer m.mu.Unlock()
for _, o := range m.outbox {
if o.ID == id {
o.Attempts++
o.LastError = errMsg
o.NextAttemptAt = nextAttempt
return nil
}
}
return ErrNotFound
}
func (m *Memory) PendingOutbox(_ context.Context) (int, error) {
m.mu.RLock()
defer m.mu.RUnlock()
n := 0
for _, o := range m.outbox {
if o.DoneAt == nil {
n++
}
}
return n, nil
}
func (m *Memory) RecordWebhookReceipt(_ context.Context, eventID string) (bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
if eventID == "" {
return false, ErrInvalidInput
}
if _, seen := m.receipts[eventID]; seen {
return false, nil
}
m.receipts[eventID] = time.Now().UTC()
return true, nil
}
func (m *Memory) CreateLicence(_ context.Context, l Licence) (*Licence, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[l.TenantID]; !ok {
return nil, ErrNotFound
}
if l.Product == "" || l.Subject == "" || l.Kid == "" || l.ExpiresAt.IsZero() {
return nil, ErrInvalidInput
}
row := l
if row.ID == "" {
row.ID = uuid.NewString()
}
row.CreatedAt = time.Now().UTC()
row.RevokedAt = nil
row.LastSeenAt = nil
m.licences[row.ID] = &row
cp := row
return &cp, nil
}
func (m *Memory) GetLicence(_ context.Context, id string) (*Licence, error) {
m.mu.RLock()
defer m.mu.RUnlock()
l, ok := m.licences[id]
if !ok {
return nil, ErrNotFound
}
cp := *l
return &cp, nil
}
func (m *Memory) ListLicences(_ context.Context, tenantID string) ([]Licence, error) {
m.mu.RLock()
defer m.mu.RUnlock()
if _, ok := m.tenants[tenantID]; !ok {
return nil, ErrNotFound
}
out := []Licence{}
for _, l := range m.licences {
if l.TenantID == tenantID {
out = append(out, *l)
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].CreatedAt.Equal(out[j].CreatedAt) {
return out[i].ID < out[j].ID
}
return out[i].CreatedAt.Before(out[j].CreatedAt)
})
return out, nil
}
func (m *Memory) RevokeLicence(_ context.Context, id string, at time.Time) error {
m.mu.Lock()
defer m.mu.Unlock()
l, ok := m.licences[id]
if !ok {
return ErrNotFound
}
if l.RevokedAt == nil {
t := at
l.RevokedAt = &t
}
return nil
}
func (m *Memory) TouchLicence(_ context.Context, id string, at time.Time) error {
m.mu.Lock()
defer m.mu.Unlock()
l, ok := m.licences[id]
if !ok {
return ErrNotFound
}
t := at
l.LastSeenAt = &t
return nil
}