feat(store): module user counts and sealed git admin token (0031)

Migration 0031 adds managed_services.admin_token_enc (sealed, write-only),
module_user_days (Managed Git daily counts, month = peak day) and
module_users_seen (Werkpilot/Firmwerk people per month). Postgres and
Memory stores implement both.

Refs: t81

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-11-17 09:28:20 +01:00
1 parent 8a72469e18
commit 7b9ae37be7
10 files changed
+344 -4

No files matched your search

+7
View File
@@ -58,6 +58,9 @@ type Memory struct {
contractDocID int64
capRequests []CapabilityRequest // pending four-eyes grants, oldest first (0029)
moduleDays map[moduleDayKey]int // Managed Git daily counts (0031)
moduleSeen map[moduleSeenKey]time.Time // licence users per month (0031) → first seen
}
type apiKeyWithHash struct {
@@ -90,6 +93,9 @@ func NewMemory() *Memory {
documents: make(map[string]*Document),
prodSets: make(map[string]*TenantProductSettings),
moduleDays: make(map[moduleDayKey]int),
moduleSeen: make(map[moduleSeenKey]time.Time),
}
now := time.Now().UTC()
seed := &Tenant{
@@ -621,6 +627,7 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error {
m.contractDocs = kept
m.deleteIntake(id)
m.capRequests = slices.DeleteFunc(m.capRequests, func(r CapabilityRequest) bool { return r.TenantID == id })
m.deleteModuleUsers(id)
for kid, k := range m.apiKeys {
if k.TenantID == id {
delete(m.apiKeys, kid)
+110
View File
@@ -0,0 +1,110 @@
package store
import (
"context"
"sort"
"strings"
"time"
)
type moduleDayKey struct{ tenant, module, day string }
type moduleSeenKey struct{ tenant, module, month, subject string }
func (m *Memory) PutModuleUserDay(_ context.Context, d ModuleUserDay) error {
if d.Module == "" || d.Count < 0 || !validDay(d.Day) {
return ErrInvalidInput
}
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[d.TenantID]; !ok {
return ErrNotFound
}
m.moduleDays[moduleDayKey{d.TenantID, d.Module, d.Day}] = d.Count
return nil
}
func (m *Memory) AddModuleUsersSeen(_ context.Context, tenantID, module, month string, subjects []string) (int, error) {
if module == "" || !ValidMonth(month) {
return 0, ErrInvalidInput
}
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.tenants[tenantID]; !ok {
return 0, ErrNotFound
}
now, added := time.Now().UTC(), 0
for _, sub := range subjects {
if sub == "" {
continue
}
k := moduleSeenKey{tenantID, module, month, sub}
if _, ok := m.moduleSeen[k]; !ok {
m.moduleSeen[k] = now
added++
}
}
return added, nil
}
func (m *Memory) ModuleUserCounts(_ context.Context, tenantID, month string) ([]ModuleUserCount, error) {
if !ValidMonth(month) {
return nil, ErrInvalidInput
}
m.mu.RLock()
defer m.mu.RUnlock()
byModule := map[string]*ModuleUserCount{}
for k, n := range m.moduleDays {
if k.tenant != tenantID || !strings.HasPrefix(k.day, month+"-") {
continue
}
c, ok := byModule[k.module]
// The peak; on a tie the earliest day (as the Postgres query).
if !ok || n > c.Count || (n == c.Count && k.day < c.PeakDay) {
byModule[k.module] = &ModuleUserCount{Module: k.module, Count: n, PeakDay: k.day}
}
}
seen := map[string]int{}
for k := range m.moduleSeen {
if k.tenant == tenantID && k.month == month {
seen[k.module]++
}
}
for mod, n := range seen {
if _, ok := byModule[mod]; !ok { // a module is counted one way only
byModule[mod] = &ModuleUserCount{Module: mod, Count: n}
}
}
out := make([]ModuleUserCount, 0, len(byModule))
for _, c := range byModule {
out = append(out, *c)
}
sort.Slice(out, func(i, j int) bool { return out[i].Module < out[j].Module })
return out, nil
}
// deleteModuleUsers drops a purged tenant's counts (ON DELETE CASCADE in
// Postgres). Caller holds the lock.
func (m *Memory) deleteModuleUsers(tenantID string) {
for k := range m.moduleDays {
if k.tenant == tenantID {
delete(m.moduleDays, k)
}
}
for k := range m.moduleSeen {
if k.tenant == tenantID {
delete(m.moduleSeen, k)
}
}
}
// ValidMonth reports whether s is a calendar month "YYYY-MM".
func ValidMonth(s string) bool {
_, err := time.Parse("2006-01", s)
return err == nil && len(s) == 7
}
func validDay(s string) bool {
_, err := time.Parse("2006-01-02", s)
return err == nil && len(s) == 10
}
+17
View File
@@ -65,6 +65,7 @@ func (m *Memory) CreateManagedService(_ context.Context, ms ManagedService) (*Ma
return nil, ErrInvalidInput
}
ms.ID = uuid.NewString()
ms.AdminTokenSealed, ms.AdminTokenSet = nil, false
if m.serviceTaken(ms) {
return nil, ErrConflict
}
@@ -105,3 +106,19 @@ func (m *Memory) DeleteManagedService(_ context.Context, id string) error {
delete(m.services, id)
return nil
}
func (m *Memory) SetManagedServiceAdminToken(_ context.Context, id string, sealed []byte) error {
m.mu.Lock()
defer m.mu.Unlock()
ms, ok := m.services[id]
if !ok {
return ErrNotFound
}
ms.AdminTokenSealed = nil
if len(sealed) > 0 {
ms.AdminTokenSealed = append([]byte(nil), sealed...)
}
ms.AdminTokenSet = len(ms.AdminTokenSealed) > 0
ms.UpdatedAt = time.Now().UTC()
return nil
}
+111
View File
@@ -0,0 +1,111 @@
package store
import (
"context"
"sort"
)
func (p *Postgres) PutModuleUserDay(ctx context.Context, d ModuleUserDay) error {
if d.Module == "" || d.Count < 0 || !validDay(d.Day) {
return ErrInvalidInput
}
_, err := p.pool.Exec(ctx, `
INSERT INTO module_user_days (tenant_id, module, day, count)
VALUES ($1::uuid, $2, $3::date, $4)
ON CONFLICT (tenant_id, module, day) DO UPDATE SET count = EXCLUDED.count, counted_at = now()`,
d.TenantID, d.Module, d.Day, d.Count)
switch {
case isFKViolation(err), isInvalidUUID(err):
return ErrNotFound
case isCheckViolation(err):
return ErrInvalidInput
}
return err
}
func (p *Postgres) AddModuleUsersSeen(ctx context.Context, tenantID, module, month string, subjects []string) (int, error) {
if module == "" || !ValidMonth(month) {
return 0, ErrInvalidInput
}
subs := make([]string, 0, len(subjects))
for _, s := range subjects {
if s != "" {
subs = append(subs, s)
}
}
if len(subs) == 0 {
if _, err := p.GetTenant(ctx, tenantID); err != nil {
return 0, err
}
return 0, nil
}
tag, err := p.pool.Exec(ctx, `
INSERT INTO module_users_seen (tenant_id, module, month, subject)
SELECT $1::uuid, $2, $3, s FROM unnest($4::text[]) AS s
ON CONFLICT DO NOTHING`, tenantID, module, month, subs)
switch {
case isFKViolation(err), isInvalidUUID(err):
return 0, ErrNotFound
case isCheckViolation(err):
return 0, ErrInvalidInput
case err != nil:
return 0, err
}
return int(tag.RowsAffected()), nil
}
func (p *Postgres) ModuleUserCounts(ctx context.Context, tenantID, month string) ([]ModuleUserCount, error) {
if !ValidMonth(month) {
return nil, ErrInvalidInput
}
byModule := map[string]ModuleUserCount{}
// The peak day per module; on a tie the earliest day.
rows, err := p.pool.Query(ctx, `
SELECT DISTINCT ON (module) module, count, to_char(day, 'YYYY-MM-DD')
FROM module_user_days
WHERE tenant_id = $1::uuid AND day >= $2::date AND day < ($2::date + interval '1 month')
ORDER BY module, count DESC, day`, tenantID, month+"-01")
if isInvalidUUID(err) {
return []ModuleUserCount{}, nil
}
if err != nil {
return nil, err
}
for rows.Next() {
var c ModuleUserCount
if err := rows.Scan(&c.Module, &c.Count, &c.PeakDay); err != nil {
rows.Close()
return nil, err
}
byModule[c.Module] = c
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
rows, err = p.pool.Query(ctx, `
SELECT module, count(*) FROM module_users_seen
WHERE tenant_id = $1::uuid AND month = $2 GROUP BY module`, tenantID, month)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var c ModuleUserCount
if err := rows.Scan(&c.Module, &c.Count); err != nil {
return nil, err
}
if _, ok := byModule[c.Module]; !ok { // a module is counted one way only
byModule[c.Module] = c
}
}
if err := rows.Err(); err != nil {
return nil, err
}
out := make([]ModuleUserCount, 0, len(byModule))
for _, c := range byModule {
out = append(out, c)
}
sort.Slice(out, func(i, j int) bool { return out[i].Module < out[j].Module })
return out, nil
}
+20 -2
View File
@@ -8,18 +8,19 @@ import (
)
const serviceSelect = `
SELECT id::text, tenant_id::text, kind, name, url, sku, status, instance_id, notes, created_at, updated_at
SELECT id::text, tenant_id::text, kind, name, url, sku, status, instance_id, notes, created_at, updated_at, admin_token_enc
FROM managed_services `
func scanManagedService(row pgx.Row) (*ManagedService, error) {
var ms ManagedService
if err := row.Scan(&ms.ID, &ms.TenantID, &ms.Kind, &ms.Name, &ms.URL, &ms.SKU, &ms.Status,
&ms.InstanceID, &ms.Notes, &ms.CreatedAt, &ms.UpdatedAt); err != nil {
&ms.InstanceID, &ms.Notes, &ms.CreatedAt, &ms.UpdatedAt, &ms.AdminTokenSealed); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
ms.AdminTokenSet = len(ms.AdminTokenSealed) > 0
return &ms, nil
}
@@ -107,3 +108,20 @@ func (p *Postgres) DeleteManagedService(ctx context.Context, id string) error {
}
return nil
}
func (p *Postgres) SetManagedServiceAdminToken(ctx context.Context, id string, sealed []byte) error {
if len(sealed) == 0 {
sealed = nil
}
tag, err := p.pool.Exec(ctx, `UPDATE managed_services SET admin_token_enc = $2, updated_at = now() WHERE id = $1::uuid`, id, sealed)
if isInvalidUUID(err) {
return ErrNotFound
}
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
+12
View File
@@ -312,6 +312,18 @@ type Store interface {
// 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.
+29
View File
@@ -352,6 +352,10 @@ type ManagedService struct {
Notes string `json:"notes"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// AdminTokenSet: a sealed Gitea admin token is stored (0031, t81). The
// token itself (AdminTokenSealed) is never serialised.
AdminTokenSet bool `json:"admin_token_set"`
AdminTokenSealed []byte `json:"-"`
}
const (
@@ -364,6 +368,31 @@ const (
ManagedServiceHalted = "halted"
)
// Module users (0031, t81): the modules counted.
const (
ModuleManagedGit = "managed-git" // peak of the daily counts
ModuleWerkpilot = "werkpilot" // distinct users active in the month
ModuleFirmwerk = "firmwerk" // distinct users active in the month
)
// ModuleUserDay is one day's Managed Git count of a tenant. Day is
// "YYYY-MM-DD" (Europe/Berlin).
type ModuleUserDay struct {
TenantID string
Module string
Day string
Count int
}
// ModuleUserCount is a module's value for one month: the peak day's count
// (PeakDay set, the earliest day on a tie) or the number of distinct users
// seen in the month (PeakDay empty).
type ModuleUserCount struct {
Module string `json:"module"`
Count int `json:"count"`
PeakDay string `json:"peak_day,omitempty"`
}
// ValidManagedServiceKind and ValidManagedServiceStatus mirror the CHECK
// constraints of 0012 and 0013.
func ValidManagedServiceKind(k string) bool {
+3
View File
@@ -0,0 +1,3 @@
DROP TABLE module_users_seen;
DROP TABLE module_user_days;
ALTER TABLE managed_services DROP COLUMN admin_token_enc;
+31
View File
@@ -0,0 +1,31 @@
-- Module users per tenant and month (t81). Counting only; invoicing comes
-- later with t72.
--
-- managed_services.admin_token_enc: a Gitea token with read:admin scope per
-- Managed Git instance, AES-256-GCM sealed under SECRETS_ENCRYPTION_KEY and
-- bound to the service id (like licences.llm_key_secret_enc, 0017). Write
-- only: the API never returns it.
ALTER TABLE managed_services ADD COLUMN admin_token_enc BYTEA;
-- Managed Git: one count per Berlin day (workspace members who have signed
-- in to the tenant's instance). The month's value is the peak day.
CREATE TABLE module_user_days (
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
module TEXT NOT NULL,
day DATE NOT NULL,
count INTEGER NOT NULL CHECK (count >= 0),
counted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, module, day)
);
-- Werkpilot / Firmwerk: the people (Keycloak subjects) active in a Berlin
-- month. licences.last_seen_at keeps only the latest time, so the daily job
-- records them while the month runs. The month's value is the row count.
CREATE TABLE module_users_seen (
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
module TEXT NOT NULL,
month TEXT NOT NULL CHECK (month ~ '^[0-9]{4}-(0[1-9]|1[0-2])$'),
subject TEXT NOT NULL,
first_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, module, month, subject)
);
+4 -2
View File
@@ -109,6 +109,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
"role_dataset_revisions",
"tenant_product_settings",
"tenant_contract_documents",
"module_user_days",
"module_users_seen",
}
for _, table := range wantTables {
var exists bool
@@ -124,8 +126,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
}
}
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets; 0025: tenant_product_settings; 0027: tenant_contract_documents; 0028: intake).
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}, {"tenant_product_settings", "settings"}, {"tenant_contract_documents", "values_sha256"}, {"intake_reports", "danger"}, {"intake_entries", "content"}, {"intake_receipts", "handoff_id"}, {"intake_counters", "last"}} {
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets; 0025: tenant_product_settings; 0027: tenant_contract_documents; 0028: intake; 0031: module users).
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}, {"tenant_product_settings", "settings"}, {"tenant_contract_documents", "values_sha256"}, {"intake_reports", "danger"}, {"intake_entries", "content"}, {"intake_receipts", "handoff_id"}, {"intake_counters", "last"}, {"managed_services", "admin_token_enc"}, {"module_user_days", "count"}, {"module_users_seen", "subject"}} {
var exists bool
err := db.QueryRow(
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)",