wishforge-ide/scripts/tenant-admin.ts
eust-w b47a07e8d2 chore: baseline snapshot of the Codex-delivered code before review
Imports the previously untracked working tree as-is so that the review
changes that follow (requirements -> design -> implementation) can be
reviewed as diffs and reverted if needed. No content changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:18:04 +08:00

55 lines
7.2 KiB
TypeScript

import pg from 'pg';
import { randomUUID } from 'node:crypto';
import { pathToFileURL } from 'node:url';
import { z } from 'zod';
import { roles, type CommercialPlan, type TenantEntitlementSnapshot } from '@wishforge/contracts';
import { configuredPlans } from '../apps/api/src/domain/entitlements.js';
const tenantIdSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{2,62}$/);
const subject = z.string().trim().min(1).max(200);
function operator(value: string | undefined, env: NodeJS.ProcessEnv) { const id = subject.parse(value ?? env.WF_OPERATOR_SUBJECT); if (!(env.WF_BILLING_OPERATOR_SUBJECTS ?? '').split(',').map(s => s.trim()).includes(id)) throw new Error('The human operator subject must be explicitly listed in WF_BILLING_OPERATOR_SUBJECTS'); return id; }
function snapshot(plan: CommercialPlan, actorId: string): TenantEntitlementSnapshot { return { schemaVersion: 1, planId: plan.id, planVersion: plan.version, limits: structuredClone(plan.limits), assignedAt: new Date().toISOString(), assignedBy: actorId }; }
async function event(client: pg.Client, tenantId: string, actorId: string, action: string, fields: Record<string, unknown>) {
const id = randomUUID(), at = new Date().toISOString(); const data = { id, tenantId, version: 1, createdAt: at, updatedAt: at, actorId, action, source: 'operator-cli', ...fields };
await client.query('INSERT INTO entities(tenant_id,kind,id,version,data,created_at) VALUES($1,$2,$3,1,$4,$5)', [tenantId, 'entitlement_event', id, data, at]);
}
export async function runTenantAdmin(command: string, args: string[], env = process.env) {
if (!env.DATABASE_ADMIN_URL) throw new Error('Operator DATABASE_ADMIN_URL is required; runtime database credentials cannot change plans');
const tenantId = tenantIdSchema.parse(args[0]); let actorId: string; let plan: CommercialPlan | undefined;
if (command === 'provision') { actorId = operator(args[5], env); plan = (await configuredPlans(env)).find(value => value.id === args[4]); }
else if (command === 'plan') { actorId = operator(args[2], env); plan = (await configuredPlans(env)).find(value => value.id === args[1]); }
else if (command === 'member') actorId = operator(args[3], env);
else throw new Error('Use provision, plan or member');
if (command !== 'member' && !plan) throw new Error('Choose an existing configured planId; caller-defined quota numbers are not accepted');
const client = new pg.Client({ connectionString: env.DATABASE_ADMIN_URL }); await client.connect();
try {
await client.query('BEGIN'); await client.query("SELECT set_config('app.tenant_id',$1,true),set_config('app.actor_id',$2,true)", [tenantId, actorId]); await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [tenantId]);
if (command === 'provision') {
const name = z.string().min(1).max(120).parse(args[1]), region = z.string().min(1).max(120).parse(args[2]), owner = subject.parse(args[3]), entitlement = snapshot(plan!, actorId);
await client.query('INSERT INTO tenants(id,name,region,max_concurrent_runs,token_limit,plan_id,plan_version,entitlements) VALUES($1,$2,$3,$4,$5,$6,$7,$8)', [tenantId, name, region, plan!.limits.maxConcurrentRuns, plan!.limits.monthlyModelTokens, plan!.id, plan!.version, entitlement]);
await client.query("INSERT INTO memberships(tenant_id,user_id,role) VALUES($1,$2,'owner')", [tenantId, owner]); await event(client, tenantId, actorId, 'tenant.provisioned', { ownerSubject: owner, entitlements: entitlement });
} else {
const result = await client.query('SELECT * FROM tenants WHERE id=$1 FOR UPDATE', [tenantId]); if (!result.rowCount) throw new Error('Tenant does not exist'); const tenant = result.rows[0];
if (command === 'member') {
const userId = subject.parse(args[1]), role = z.enum(roles).parse(args[2]);
const members = await client.query('SELECT user_id,active FROM memberships WHERE tenant_id=$1', [tenantId]); const limit = Number(tenant.entitlements?.limits?.maxMembers ?? 10);
if (!members.rows.some(row => row.user_id === userId && row.active) && members.rows.filter(row => row.active).length >= limit) throw new Error('Tenant active-member allowance is exhausted');
await client.query('INSERT INTO memberships(tenant_id,user_id,role,active) VALUES($1,$2,$3,true) ON CONFLICT(tenant_id,user_id) DO UPDATE SET role=EXCLUDED.role,active=true', [tenantId, userId, role]); await event(client, tenantId, actorId, 'member.invited', { targetSubject: userId, role });
} else {
const members = await client.query('SELECT count(*)::integer AS count FROM memberships WHERE tenant_id=$1 AND active=true', [tenantId]);
const entities = await client.query("SELECT kind,data FROM entities WHERE tenant_id=$1 AND kind IN ('project','workspace','run')", [tenantId]);
const active = (kind: string) => entities.rows.filter(row => row.kind === kind && row.data.status !== 'deleted');
const held = active('run').filter(row => ['reserved', 'provisioned', 'unknown', 'releasing'].includes(row.data.resourceAllocation?.status) || (row.data.status === 'running' && Date.parse(row.data.lease?.expiresAt ?? '') > Date.now()));
if (members.rows[0].count > plan!.limits.maxMembers || active('project').length > plan!.limits.maxProjects || active('workspace').length > plan!.limits.maxWorkspaces || held.length > plan!.limits.maxConcurrentRuns) throw new Error('New plan is below existing allocations; reconcile them before downgrading');
if (held.some(row => { const grant = row.data.resourceAllocation?.grant; return grant && (grant.cpuMilli > plan!.limits.execution.cpuMilli || grant.memoryMiB > plan!.limits.execution.memoryMiB || grant.storageMiB > plan!.limits.execution.storageMiB); })) throw new Error('Existing execution grants exceed the new resource caps');
const date = new Date(), monthStart = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1)).toISOString(); const usage = await client.query('SELECT COALESCE(sum(tokens),0)::text AS tokens FROM usage_ledger WHERE tenant_id=$1 AND created_at >= $2', [tenantId, monthStart]);
if (Number(usage.rows[0].tokens) + active('run').reduce((sum, row) => sum + Number(row.data.reservedTokens ?? 0), 0) > plan!.limits.monthlyModelTokens) throw new Error('New model-token allowance is below measured/reserved usage');
const entitlement = snapshot(plan!, actorId);
await client.query('UPDATE tenants SET max_concurrent_runs=$2,token_limit=$3,plan_id=$4,plan_version=$5,entitlements=$6 WHERE id=$1', [tenantId, plan!.limits.maxConcurrentRuns, plan!.limits.monthlyModelTokens, plan!.id, plan!.version, entitlement]); await event(client, tenantId, actorId, 'plan.assigned', { previousPlanId: tenant.plan_id, previousPlanVersion: tenant.plan_version, entitlements: entitlement });
}
}
await client.query('COMMIT'); return { tenantId, operation: command, planId: plan?.id, planVersion: plan?.version, actorId, paymentProcessed: false };
} catch (error) { await client.query('ROLLBACK'); throw error; } finally { await client.end(); }
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { if (process.env.NODE_ENV !== 'production') { try { process.loadEnvFile('.env.local'); } catch {} } console.log(JSON.stringify(await runTenantAdmin(process.argv[2] ?? '', process.argv.slice(3)))); }