Files
tenant-registry/internal/store/store.go
T
sharangandClaude Opus 5.5 85934567f1
ci / shared (push) Successful in 13s
ci / test (push) Successful in 24m12s
ci / image (push) Successful in 35s
ci / shared (pull_request) Successful in 14s
ci / test (pull_request) Successful in 24m17s
ci / image (pull_request) Skipped
feat(services): managed services per tenant for the portal (#77) (#61)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-04 19:33:20 +00:00

197 lines
9.3 KiB
Go

// Package store hides the persistence layer behind a Store interface.
// Two implementations: Memory (dev convenience, used when DATABASE_URL is
// empty) and Postgres (production via pgx). Handlers depend on the
// interface — never on a concrete type.
package store
import (
"context"
"errors"
"time"
)
// Sentinel errors.
var (
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
ErrInvalidInput = errors.New("invalid input")
)
// TenantCreate is the input shape for Store.CreateTenant.
type TenantCreate struct {
Slug string
Name string
Plan string // optional, defaults to "starter"
Kind string // optional, defaults to "customer"
SalesOwner string // optional
AdminEmail string // optional — the first admin invited at creation
}
// TenantUpdate captures partial mutations. Nil fields are left untouched.
type TenantUpdate struct {
Status *string
Plan *string
ErpCustomerID *string
StripeCustID *string
TrialEndsAt *time.Time
ContractStart *time.Time
ContractEnd *time.Time
SalesOwner *string
AdminEmail *string
}
// APIKeyCreate is the input shape for Store.CreateAPIKey.
type APIKeyCreate struct {
TenantID string
Product string // empty = applies to all products
Name string
Scopes []string
Prefix string
Hash string // argon2id encoded
CreatedBy string
}
// AuditFilter narrows /v1/audit GET results.
type AuditFilter struct {
TenantID string
Product string
ActorID string
Action string
Since *time.Time
Until *time.Time
Limit int
Cursor int64 // id > Cursor (ascending) is the next page anchor
}
// Store is the persistence contract. Implementations:
// - Memory — in-process, used when DATABASE_URL is empty (dev convenience).
// - Postgres — pgxpool-backed, used in stage + prod.
type Store interface {
// Tenants
CreateTenant(ctx context.Context, in TenantCreate) (*Tenant, error)
GetTenant(ctx context.Context, id string) (*Tenant, error)
GetTenantBySlug(ctx context.Context, slug string) (*Tenant, error)
GetTenantByErpCustomerID(ctx context.Context, erpCustomerID string) (*Tenant, error)
UpdateTenant(ctx context.Context, id string, in TenantUpdate) (*Tenant, error)
ListTenants(ctx context.Context, f TenantFilter) ([]Tenant, string, error) // rows + next cursor ("" = none)
// TenantActivity returns usage totals since `since` and the latest audit
// time for each of the given tenants (tenants without either are absent).
TenantActivity(ctx context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error)
// Products (catalog)
ListProducts(ctx context.Context, includeDisabled bool) ([]Product, error)
GetProduct(ctx context.Context, key string) (*Product, error)
// Entitlements
UpsertTenantProduct(ctx context.Context, tp TenantProduct) (*TenantProduct, error)
ListTenantProducts(ctx context.Context, tenantID string) ([]TenantProduct, error)
// API keys
CreateAPIKey(ctx context.Context, in APIKeyCreate) (*APIKey, error)
FindAPIKeyByPrefix(ctx context.Context, prefix string) (*APIKey, string, error) // returns key + hash
TouchAPIKeyUsed(ctx context.Context, id string) error
RevokeAPIKey(ctx context.Context, id string) error
ListAPIKeys(ctx context.Context, tenantID string) ([]APIKey, error)
// Audit
AppendAudit(ctx context.Context, ev AuditEvent) (*AuditEvent, error)
ListAudit(ctx context.Context, f AuditFilter) ([]AuditEvent, int64, error) // returns rows + next cursor (0 = none)
// Subscriptions (M-MIG-7, mirrored from ERPNext Sales Orders)
UpsertSubscription(ctx context.Context, sub Subscription) (*Subscription, error) // key (tenant_id, sku, erp_sales_order)
ListSubscriptions(ctx context.Context, tenantID string) ([]Subscription, error)
// Usage events (§9.2). Inserted reports false when the idempotency key
// was already stored (the existing row is returned).
InsertUsageEvent(ctx context.Context, ev UsageEvent) (*UsageEvent, bool, error)
ListUsageEvents(ctx context.Context, f UsageFilter) ([]UsageEvent, error)
MarkUsageSynced(ctx context.Context, ids []int64, at time.Time) error
// ERP outbox. ClaimOutbox returns due rows (next_attempt_at <= now) and
// pushes their next_attempt_at by lease so a second worker skips them.
EnqueueOutbox(ctx context.Context, item OutboxItem) (*OutboxItem, error)
ClaimOutbox(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]OutboxItem, error)
CompleteOutbox(ctx context.Context, id int64, at time.Time) error
FailOutbox(ctx context.Context, id int64, errMsg string, nextAttempt time.Time) error
PendingOutbox(ctx context.Context) (int, error)
// Webhook idempotency: true when eventID was not seen before.
RecordWebhookReceipt(ctx context.Context, eventID string) (bool, error)
// Licences
CreateLicence(ctx context.Context, l Licence) (*Licence, error)
GetLicence(ctx context.Context, id string) (*Licence, error)
ListLicences(ctx context.Context, tenantID string) ([]Licence, error)
RevokeLicence(ctx context.Context, id string, at time.Time) error
TouchLicence(ctx context.Context, id string, at time.Time) error
// SetLicenceLLMKey records (or clears, with "") the LiteLLM key id.
SetLicenceLLMKey(ctx context.Context, id string, keyID string) error
// Documents (0008). ID and ObjectKey are chosen by the caller (the object
// is stored before the row). ListDocuments with publishedOnly hides drafts.
CreateDocument(ctx context.Context, d Document) (*Document, error)
GetDocument(ctx context.Context, id string) (*Document, error)
ListDocuments(ctx context.Context, tenantID string, publishedOnly bool) ([]Document, error)
// DeleteTenant removes the tenant and everything that belongs to it
// (entitlements, keys, subscriptions, usage, licences, outbox, documents,
// projects, managed services, mail). Audit events stay, with the tenant reference cleared.
// ErrNotFound when there is no such tenant.
DeleteTenant(ctx context.Context, id string) error
PublishDocument(ctx context.Context, id, by string, at time.Time) (*Document, error)
DeleteDocument(ctx context.Context, id string) error
// SetDocumentProjects replaces a document's projects; every project must
// belong to the document's tenant (ErrInvalidInput otherwise).
SetDocumentProjects(ctx context.Context, docID string, projectIDs []string) (*Document, error)
SetDocumentOwn(ctx context.Context, docID string, own bool) (*Document, error)
// Trial offers (0011, portal#64). Only the state moves; the snapshot is
// written by CreateTrialOffer and never changed.
CreateTrialOffer(ctx context.Context, o TrialOffer) (*TrialOffer, error)
GetTrialOffer(ctx context.Context, id string) (*TrialOffer, error)
GetTrialOfferByToken(ctx context.Context, tokenHash string) (*TrialOffer, error)
GetTrialOfferByTenant(ctx context.Context, tenantID string) (*TrialOffer, error)
// LatestTrialOffer is the newest offer for the address (case-insensitive).
LatestTrialOffer(ctx context.Context, email string) (*TrialOffer, error)
// SetTrialOfferToken replaces the confirmation token of a pending offer
// (ErrConflict once it is verified).
SetTrialOfferToken(ctx context.Context, id, tokenHash string, expires time.Time) (*TrialOffer, error)
// VerifyTrialOffer moves a pending offer to verified (ErrConflict when it
// is not pending), so only one confirmation click activates.
VerifyTrialOffer(ctx context.Context, id string, at time.Time) (*TrialOffer, error)
// ActivateTrialOffer records the acceptance: tenant, contract and trial
// times; only from verified (ErrConflict otherwise).
ActivateTrialOffer(ctx context.Context, id, tenantID string, acceptedAt, expiresAt time.Time) (*TrialOffer, error)
// MarkTrialOfferMail sets receipt_mail_sent_at ("receipt") or
// activation_mail_sent_at ("activation").
MarkTrialOfferMail(ctx context.Context, id, which string, at time.Time) error
// Projects (0010). Names are unique per tenant, case-insensitively
// (ErrConflict). Deleting a project removes it from its documents.
ListProjects(ctx context.Context, tenantID string) ([]Project, error)
GetProject(ctx context.Context, id string) (*Project, error)
CreateProject(ctx context.Context, p Project) (*Project, error)
UpdateProject(ctx context.Context, p Project) (*Project, error)
DeleteProject(ctx context.Context, id string) error
// Managed services (0012, portal#77), listed by created_at. One row per
// (tenant, kind, url): ErrConflict otherwise.
ListManagedServices(ctx context.Context, tenantID string) ([]ManagedService, error)
GetManagedService(ctx context.Context, id string) (*ManagedService, error)
CreateManagedService(ctx context.Context, ms ManagedService) (*ManagedService, error)
// UpdateManagedService writes name, url, sku, status, instance_id, notes.
UpdateManagedService(ctx context.Context, ms ManagedService) (*ManagedService, error)
DeleteManagedService(ctx context.Context, id string) error
// Mail outbox (0009). EnqueueMail is idempotent on IdempotencyKey
// (false when the key existed). ClaimMail leases due unsent rows.
EnqueueMail(ctx context.Context, m MailItem) (bool, error)
ClaimMail(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]MailItem, error)
CompleteMail(ctx context.Context, id int64, at time.Time) error
FailMail(ctx context.Context, id int64, errMsg string, next time.Time) error
// Lifecycle
Close()
Ping(ctx context.Context) error
}