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) DeadLetterOutbox(_ context.Context, id int64, errMsg string, at time.Time) error { m.mu.Lock() defer m.mu.Unlock() for _, o := range m.outbox { if o.ID == id { o.Attempts++ o.LastError = DeadLetterPrefix + errMsg t := at o.DoneAt = &t 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) FindReusableLicence(_ context.Context, tenantID, product, subject, device string, since, now time.Time) (*Licence, error) { m.mu.RLock() defer m.mu.RUnlock() var best *Licence for _, l := range m.licences { if l.TenantID != tenantID || l.Product != product || l.Subject != subject || l.Device != device || l.CreatedAt.Before(since) || !l.ExpiresAt.After(now) || l.RevokedAt != nil { continue } if best == nil || l.CreatedAt.After(best.CreatedAt) { best = l } } if best == nil { return nil, ErrNotFound } cp := *best 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 } func (m *Memory) SetLicenceLLMSecret(_ context.Context, id string, sealed []byte) error { m.mu.Lock() defer m.mu.Unlock() l, ok := m.licences[id] if !ok { return ErrNotFound } l.LLMKeySecret = append([]byte(nil), sealed...) return nil } func (m *Memory) SetLicenceLLMKey(_ context.Context, id string, keyID string) error { m.mu.Lock() defer m.mu.Unlock() l, ok := m.licences[id] if !ok { return ErrNotFound } l.LLMKeyID = keyID return nil }