Files
tenant-registry/internal/store/store.go
sharangandSharang Parnerkar c6de35858e
ci / shared (push) Successful in 12s
ci / test (push) Successful in 6m30s
ci / image (push) Successful in 38s
feat(connections): connect two workspaces by code (#138) (#145)
## What

- **Codes:** two workspaces connect by code. One administrator creates a code; another workspace's administrator enters it, and the two are connected at once. Each side sees only the other's display name.
- **Ending:** either side can end a connection. Archiving a workspace ends all of its connections. When a workspace is purged, the other side keeps the ended connection under the name it knew.
- **Product routes:** products (Prüfwerk's supplier SBOM releases first) list a tenant's active connections and check one before each delivery, under a new route group `connections.read`.

## Why

Closes #138. This is phase 4 of platform/pruefwerk#1028. Prüfwerk's agent is on stage and already calls the two internal routes; without them the release screen warns that connections can't be read (see the comment on #138).

Linked milestone: **n/a** (Prüfwerk #1028, phase 4)

## How

**Routes:**

| Call | Group | Answer |
|---|---|---|
| `POST /v1/tenants/{id}/connection-invites` | tenants.write | `201 {id, code, created_at, expires_at}`; the code is in this answer only |
| `GET /v1/tenants/{id}/connection-invites` | tenants.read | open codes, without the codes |
| `DELETE /v1/tenants/{id}/connection-invites/{invite}` | tenants.write | `204`, withdraws an unused code |
| `POST /v1/tenants/{id}/connections` `{code}` | tenants.write | `201 {id, peer_name, state, created_at, ended_by_us}` |
| `GET /v1/tenants/{id}/connections` | tenants.read | `{items: [...]}`, newest first |
| `POST /v1/tenants/{id}/connections/{connection}/end` | tenants.write | `200`; ending one that has ended answers it unchanged |
| `GET /v1/internal/tenants/{id}/connections?state=active` | **connections.read** | `{items: [{id, peer_tenant_id, peer_name}]}`; 404 for an unknown tenant |
| `GET /v1/internal/connections/{connection}` | **connections.read** | `{active, tenant_ids}`; 404 for an unknown id |

The two internal answers match what `compliance-agent/src/registry.rs` reads. A test pins the `items` key, because the agent defaults a missing key to "no connections".

**Codes:**
- 160 random bits (`crypto/rand`), shown as eight groups of four base32 letters.
- Stored as SHA-256 only, looked up by hash; case, spaces and dashes don't matter.
- Valid for 14 days, single use, at most 20 open per workspace.
- Every code that doesn't work gets the same 404 `invalid_code`: unknown, used, expired, withdrawn, the workspace's own, or either workspace archived.
- 409 `already_connected` when the two are connected already; the code then stays open.
- Entering codes is limited to 20 per hour per workspace, and per person when the call names one (`keyRateLimiter` now takes its limit as an argument; CI licences keep theirs). A call from the portal's own client that names nobody has only the workspace limit. Otherwise every workspace would share one limit through that client. **portal#201 must send `X-Portal-User-Subject`.**

**Redeeming** is one transaction. `SELECT … FOR UPDATE` on the code, insert the connection, then mark the code used. A partial unique index allows at most one connection per pair of workspaces that hasn't ended. A race test has two workspaces enter one code at the same time: exactly one connects.

**Active** is derived on every read: not ended, both workspaces exist, and neither is archived. So no delivery can go to an archived workspace, even if writing the end failed.

**Ending on archive:** every status change passes through `syncTenantStatus`, which now ends an archived workspace's connections. The admin purge calls the same step again before `DeleteTenant`, as a safety net. The foreign keys are `ON DELETE SET NULL`, with name snapshots, so the other side keeps its history.

**Audit:** `connection.invite_created`, `connection.invite_withdrawn`, `connection.created` and `connection.ended` go into both workspaces' logs.
- The acting side's entry names the actor.
- The other side's entry is a system entry with `by: peer`: no person, IP or user agent, only the connection id and the acting side's display name.
- Ends caused by archiving carry `reason: tenant_archived`.

**Product routes refuse user tokens** (403 `FORBIDDEN_CLIENT`), whatever groups the token's client holds, because they carry the peer's tenant id.

**Who may:** user tokens need IT_ADMIN or OWNER in their own workspace (the existing team gate, `IsTenantAdmin`). Another workspace's administrator gets a 404. The portal calls as its service client, naming the person in `X-Portal-User-*`.

**Side fix:** the Postgres `GetTenant` now answers a non-UUID id as not found (404), as the memory store does. It was a 500, which the new internal route hit.

## Test plan

- [x] Unit tests: route groups in `authz_test`, roles and cross-tenant scoping in `connections_scope_test`, and the OpenAPI contract cases.
- [x] Integration tests on memory **and Postgres (testcontainers)** in `connections_test.go`, run locally:
  - connect, list, product view, check, and the re-connect after end;
  - every invalid code gives the same answer, including expiry with an injected clock;
  - archive, then purge;
  - unknown ids;
  - the rate limit;
  - the redeem race.
- [x] The whole `internal/server` suite runs against Postgres locally (`go test -count=1 ./internal/server/`, 236 s, green). `-race` is green on the connection tests. `go vet` and `golangci-lint` v2.12.2: 0 issues.
- [ ] Playwright e2e: n/a, there's no UI here (portal#201).
- [ ] Manual smoke on stage after deploy, once `AUTHZ_RULES` carries the grant below. Prüfwerk's release screen should then show no warning.

## Risk

**Blast radius:** new tables and routes only. Existing routes change in two small ways: the `GetTenant` 500→404 for non-UUID ids, and the archive path now also ends connections.

**What could break:**
- **Migration number:** `0032` is also used by the open onprem PRs (#142/#143, `0032_werkpilot_description`). Whichever merges second must renumber. A duplicate version fails the migrations test loudly. I didn't pick 0033, because golang-migrate would silently skip a 0032 that merges after it.
- **Deployment grant:** the new group needs a grant in stage and prod `AUTHZ_RULES`. That config isn't in this repo: `pruefwerk-svc-stage:…,connections.read`, and the same for prod. Until it's added, Prüfwerk keeps getting 403.

**Rollback plan:** revert the PR and redeploy. The down migration drops both tables.

## Decided (2026-11-20, by the product owner)

- **Archived only** ends connections. A `halted` workspace keeps them, so a returning customer finds them again. Active stays false while a side is archived.
- **IT_ADMIN or OWNER** may create, enter and end, using the existing team gate rather than a new catalogue right.

## Open points for review

1. **Retention:** a purged workspace's display name stays visible to its former peers through the name snapshot, with no time limit. Should it be dropped after a while?
2. **Additions to the sketch:** the create answer now carries the invite `id`, which the withdraw route needs, and there's a list of open codes, without the codes.

## Checklist

- [x] Docs updated: the OpenAPI spec and the package doc in `connections.go` (no separate docs page for registry routes)
- [x] Audit events emitted for state changes
- [x] Secrets via Infisical, never in repo (none involved)
- [x] Migration is forward-only (new tables; down drops them)
- [x] Tenant scoping enforced on every DB query
- [x] OpenAPI spec updated
- [ ] `featureFlags.evaluate()`: n/a (nothing toggleable)
- [ ] CHANGELOG entry: n/a (generated by git-cliff on release)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #145
2026-11-20 08:54:44 +00:00

370 lines
21 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"
"encoding/json"
"errors"
"time"
)
// Sentinel errors.
var (
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
ErrInvalidInput = errors.New("invalid input")
// ErrHasChildren: a project with sub-projects cannot be deleted (0020).
ErrHasChildren = errors.New("has children")
)
// 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; keys created before migration 0015 only
HashSHA256 []byte // sha256 of the plaintext; every new key
Kind string // user | ci | integration; empty = user
Holder string // integration keys only
ExpiresAt *time.Time
CreatedBy string
}
// APIKeyCandidate is an active key found by its display prefix, with the
// stored argon2id hash the caller must check.
type APIKeyCandidate struct {
APIKey
Hash 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)
// SetPreviewGrant grants (or extends) a preview of product until
// expiresAt; ErrConflict when the tenant has really booked it.
SetPreviewGrant(ctx context.Context, tenantID, product string, expiresAt time.Time) (*TenantProduct, error)
// RevokePreviewGrant removes a preview grant; ErrNotFound when there is
// none (a real booking is never removed this way).
RevokePreviewGrant(ctx context.Context, tenantID, product string) error
// API keys
CreateAPIKey(ctx context.Context, in APIKeyCreate) (*APIKey, error)
// FindAPIKeyBySHA256 returns the active (not revoked) key with this hash.
FindAPIKeyBySHA256(ctx context.Context, sum []byte) (*APIKey, error)
// FindAPIKeysByPrefix returns every active argon2id key with this prefix;
// prefixes are not unique, the caller checks each hash.
FindAPIKeysByPrefix(ctx context.Context, prefix string) ([]APIKeyCandidate, error)
TouchAPIKeyUsed(ctx context.Context, id string) error
// RevokeAPIKey revokes key id; a non-empty tenantID must own it, else ErrNotFound.
RevokeAPIKey(ctx context.Context, id, tenantID 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)
// SummarizeUsage aggregates every matching event (f.Limit is ignored).
// Totals are ordered by product, metric; Daily by day, metric.
SummarizeUsage(ctx context.Context, f UsageFilter) (*UsageSummary, 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
// DeadLetterOutbox gives up on an item: done, with the reason kept in
// last_error (prefixed "dead letter: ") so it can be found and re-queued.
DeadLetterOutbox(ctx context.Context, id int64, errMsg string, at 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)
// FindReusableLicence returns the newest licence for (tenant, product,
// subject, device) created at or after since that is neither revoked
// nor expired at now; ErrNotFound otherwise. CI licences are reused
// per key, device and UTC day instead of one row per job.
FindReusableLicence(ctx context.Context, tenantID, product, subject, device string, since, now time.Time) (*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
// SetLicenceLLMSecret stores the sealed LiteLLM secret of a CI licence.
SetLicenceLLMSecret(ctx context.Context, id string, sealed []byte) 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; ErrConflict while it has
// security reports, which outlive it (docgen#6 decision Nr. 17).
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)
// Dokumentenablage (0022, 0023). ListDocuments returns every document of
// the tenant; ListStoreDocuments the published ones as the store shows
// them: by area (BreakPilot's deliveries, no area, last), legal folder and
// title. GetDocumentByExternalID
// finds a document by the Factory's id (ErrNotFound when none).
ListStoreDocuments(ctx context.Context, tenantID string) ([]Document, error)
GetDocumentByExternalID(ctx context.Context, tenantID, externalID string) (*Document, error)
SetDocumentProcessing(ctx context.Context, docID, status, errMsg string) (*Document, error)
// SaveDocumentPreparation stores the delivered parts (a chunk part and/or a
// consent part; a part left empty keeps what is stored) and marks the
// document ready when it has a chunk part.
SaveDocumentPreparation(ctx context.Context, p Preparation) (*Preparation, error)
// GetDocumentPreparation is ErrNotFound when nothing was delivered.
GetDocumentPreparation(ctx context.Context, docID string) (*Preparation, error)
// ListDocumentPreparations maps document id → preparation for a tenant.
ListDocumentPreparations(ctx context.Context, tenantID string) (map[string]Preparation, error)
// PutStoreAsset is idempotent on (tenant, sha256); GetStoreAsset is
// ErrNotFound for an asset the tenant does not hold.
PutStoreAsset(ctx context.Context, a StoreAsset) (*StoreAsset, error)
GetStoreAsset(ctx context.Context, tenantID, sha256 string) (*StoreAsset, 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
// Company profile (0021): one per tenant. GetCompanyProfile is
// ErrNotFound when the tenant has none. SaveCompanyProfile writes a new
// revision unless data and schema version are unchanged (changed=false);
// the status stays as it was. SubmitCompanyProfile marks the current
// state submitted as a new revision. Both return a *RevisionConflict
// (matches ErrConflict) when the expected revision is not the stored one.
GetCompanyProfile(ctx context.Context, tenantID string) (*CompanyProfile, error)
SaveCompanyProfile(ctx context.Context, w CompanyProfileWrite) (profile *CompanyProfile, changed bool, err error)
SubmitCompanyProfile(ctx context.Context, tenantID string, expectedRevision int, by string, at time.Time) (*CompanyProfile, error)
// Role and authority dataset (0024): one per tenant, versioned like the
// company profile. GetRoleDataset is ErrNotFound when the tenant has
// none; SaveRoleDataset writes a new revision unless data and catalogue
// version are unchanged (changed=false) and returns a *RevisionConflict
// when the expected revision is not the stored one.
// GetRoleDatasetRevision returns one stored revision (ErrNotFound).
GetRoleDataset(ctx context.Context, tenantID string) (*RoleDataset, error)
SaveRoleDataset(ctx context.Context, w RoleDatasetWrite) (dataset *RoleDataset, changed bool, err error)
GetRoleDatasetRevision(ctx context.Context, tenantID string, revision int) (*RoleDataset, error)
// R1 intake (0028): CreateIntakeReport records a report and its capture
// entry under the tenant's next reference (ErrNotFound for an unknown
// tenant, ErrInvalidInput for a value out of range). GetIntakeReport and
// IntakeEntries are ErrNotFound for an unknown reference;
// ListIntakeReports lists one reporter's reports, newest first.
// AddIntakeSupplement adds a supplement. PendingIntake lists entries not
// settled yet with an id above after, oldest first, across tenants. AddIntakeReceipt adds a
// receipt unless it repeats the newest one (added=false); ErrConflict
// once the entry is settled, ErrNotFound for an unknown entry.
CreateIntakeReport(ctx context.Context, c IntakeCapture) (*IntakeReport, *IntakeEntry, error)
GetIntakeReport(ctx context.Context, tenantID, reference string) (*IntakeReport, error)
ListIntakeReports(ctx context.Context, tenantID, reporterSub string) ([]IntakeReport, error)
// CountIntakeReports: how many security reports the tenant has. A tenant
// with reports is never deleted (docgen#6 decision Nr. 17).
CountIntakeReports(ctx context.Context, tenantID string) (int, error)
IntakeEntries(ctx context.Context, tenantID, reference string) ([]IntakeEntry, error)
AddIntakeSupplement(ctx context.Context, tenantID, reference, by string, content json.RawMessage, at time.Time) (*IntakeEntry, error)
PendingIntake(ctx context.Context, after int64, limit int) ([]PendingIntake, error)
AddIntakeReceipt(ctx context.Context, r IntakeReceipt) (added bool, err error)
// Capability requests (0029, RBAC step 3): grants of an administration
// capability waiting for a second person. CreateCapabilityRequest
// returns the open request for the same member and capability instead
// of a second one (created=false); ErrNotFound for an unknown tenant,
// ErrInvalidInput for a malformed row. ListCapabilityRequests lists a
// tenant's open requests, oldest first. GetCapabilityRequest and
// DeleteCapabilityRequest are ErrNotFound for an unknown id.
// DeleteMemberCapabilityRequests drops a member's open requests for
// capability, or all of them when capability is "".
CreateCapabilityRequest(ctx context.Context, r CapabilityRequest) (req *CapabilityRequest, created bool, err error)
ListCapabilityRequests(ctx context.Context, tenantID string) ([]CapabilityRequest, error)
GetCapabilityRequest(ctx context.Context, tenantID, id string) (*CapabilityRequest, error)
DeleteCapabilityRequest(ctx context.Context, tenantID, id string) error
DeleteMemberCapabilityRequests(ctx context.Context, tenantID, userID, capability string) (int, error)
// Connections between tenants (0032, #138).
//
// CreateConnectionInvite stores a code (ErrNotFound for an unknown
// tenant, ErrInvalidInput for a malformed row). ListConnectionInvites
// lists a tenant's open codes (unused, not expired at now), oldest
// first. DeleteConnectionInvite withdraws an unused code; ErrNotFound
// otherwise.
//
// RedeemConnectionInvite connects tenantID to the tenant whose code
// hashes to codeHash, and uses the code up. ErrNotFound for every code
// that does not work: unknown, used, expired, the tenant's own, or
// either tenant archived or unknown. ErrConflict when the two are
// connected already; the code then stays unused.
//
// ListConnections lists a tenant's connections, newest first.
// GetConnection is ErrNotFound for an unknown id. EndConnection ends an
// open connection of tenantID (ended=false when it had ended already;
// ErrNotFound when tenantID is not a side). EndTenantConnections ends
// every open connection of a tenant, by the registry, and returns them.
CreateConnectionInvite(ctx context.Context, inv ConnectionInvite) (*ConnectionInvite, error)
ListConnectionInvites(ctx context.Context, tenantID string, now time.Time) ([]ConnectionInvite, error)
DeleteConnectionInvite(ctx context.Context, tenantID, id string) error
RedeemConnectionInvite(ctx context.Context, codeHash []byte, tenantID string, now time.Time) (*Connection, error)
ListConnections(ctx context.Context, tenantID string) ([]Connection, error)
GetConnection(ctx context.Context, id string) (*Connection, error)
EndConnection(ctx context.Context, tenantID, id string, at time.Time) (conn *Connection, ended bool, err error)
EndTenantConnections(ctx context.Context, tenantID string, at time.Time) ([]Connection, error)
// Product settings (0025): the workspace's own choices per product,
// untouched by the ERP recompute. GetTenantProductSettings is
// ErrNotFound when none were saved; PutTenantProductSettings replaces
// the document (ErrNotFound for an unknown tenant, ErrInvalidInput when
// settings is not a JSON object).
GetTenantProductSettings(ctx context.Context, tenantID, product string) (*TenantProductSettings, error)
PutTenantProductSettings(ctx context.Context, ps TenantProductSettings) (*TenantProductSettings, error)
// Contract documents of a tenant (0027): its own filled copies, for now
// the AVV. Rows are never changed; the newest per tenant and kind is the
// current one. CreateContractDocument returns ErrNotFound for an unknown
// tenant and ErrInvalidInput for a malformed row; CurrentContractDocument
// is ErrNotFound when the tenant has none of that kind;
// ListContractDocuments returns every row, oldest first.
CreateContractDocument(ctx context.Context, d ContractDocument) (*ContractDocument, error)
CurrentContractDocument(ctx context.Context, tenantID, kind string) (*ContractDocument, error)
ListContractDocuments(ctx context.Context, tenantID string) ([]ContractDocument, 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
// SetManagedServiceAdminToken stores the sealed Gitea admin token of a
// service (0031, t81); nil or empty clears it. ErrNotFound for no row.
SetManagedServiceAdminToken(ctx context.Context, id string, sealed []byte) error
// Module users (0031, t81). PutModuleUserDay writes (overwrites) one
// day's count; AddModuleUsersSeen adds subjects to a month's set and
// returns how many were new; ModuleUserCounts returns the month's value
// per module (peak day or set size), sorted by module. ErrNotFound for
// an unknown tenant on the writes.
PutModuleUserDay(ctx context.Context, d ModuleUserDay) error
AddModuleUsersSeen(ctx context.Context, tenantID, module, month string, subjects []string) (int, error)
ModuleUserCounts(ctx context.Context, tenantID, month string) ([]ModuleUserCount, 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
}