Demonstration plan, phase D6 (registry side). A prospect trialling Werkpilot had no model access until someone created a LiteLLM key by hand. The registry issues one with the licence, scoped and budgeted per tenant. **On issue** (`product=werkpilot`): `POST /key/generate` on LiteLLM with `key_alias = werkpilot-<slug>-<licence id>`, `metadata` carrying tenant id/slug/licence/product, the model list and the plan's budget (trial and default, USD per 30 days). LiteLLM's hashed token id goes on the `licences` row (migration `0007`, exposed as `llm_key_id` on `GET /v1/licences`); the `sk-…` secret is returned in that one response as `llm_api_key`, together with `llm_base_url`, and is never stored or returned again. **On renewal** (licence heartbeat): the existing key moves to the new licence row rather than a second key being generated — the secret cannot be re-read, and the CLI still holds the one it stored. **On revoke:** the key is deleted; a 404 from LiteLLM is treated as already gone. If the delete fails, the licence is still revoked and the key id stays on the row so it can be retried by hand. **Failure is never fatal:** with `LITELLM_MASTER_KEY` unset, LiteLLM unreachable or refusing, the licence is issued anyway and the grant carries `warnings: ["llm_key_unavailable"]` with no LLM fields. Also, a key that cannot be persisted is deleted again rather than handed out un-revocable. Config: `LITELLM_BASE_URL` (default `https://llm.breakpilot.com`), `LITELLM_MASTER_KEY`, `LITELLM_MODELS` (default `Qwen3-Coder-30B-A3B-Instruct,gpt-oss-120b`), `LITELLM_BUDGET_TRIAL` (5), `LITELLM_BUDGET_DEFAULT` (50). Startup logs whether provisioning is on. Note the migration is numbered `0007`: `0006` is taken by the members PR (#28), which is independent of this one — merge order does not matter. Verified locally: `go vet ./...`, `gofmt` clean, `go test ./...` green, CI coverage command at **74.4%** (gate 70%). `internal/llmkeys` is tested against an httptest fake; no live LiteLLM call was made. Pairs with a `bp-licence` bump (the Rust `Grant` gains the optional fields) and with `LITELLM_MASTER_KEY` on `tenant-registry-stage`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Reviewed-on: #29
332 lines
7.1 KiB
Go
332 lines
7.1 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
|
|
}
|
|
|
|
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
|
|
}
|