/** * Account administration on the shared subscription core, for any provider: * the workspace and organization pool projections, the provider's settings * (primary connection, rotation, workspace source) and the per-connection * writers (allocator, extra credits, rename). * * Every read and write runs under the caller's own row-level-security * context (organization, workspace and, for writes, the authenticated * subject), so the core tables' policies decide visibility and management * authority: an organization administrator, or a workspace administrator for * a connection or setting that workspace manages. Nothing here returns * credential material. Personal connections are read only through the * owner-only reader (`subscription_core_personal_connections`). * * The provider is data (the binding): its id selects rows and settings * keys, its registry column holds the primary connection, and its adapter's * display name fills operator-facing texts. Provider route shapes are * projected from the neutral rows here by the provider's own module. */ import { sql } from "drizzle-orm"; import { auditEvents } from "../schema"; import { withLosslessContentWriteVersion } from "../lossless-json"; import { rawRows, setSubjectRlsContext, withRlsContext, type Database } from "../database"; import { setSubscriptionAdministrationSubject } from "./account-administrator"; import { readSubscriptionEffectiveSettings, resolveSubscriptionConnectionId, subscriptionConnectionEffectiveLastError, subscriptionConnectionEffectiveStatus, } from "../subscription-core-repository"; import { organizationAdministeredConnection } from "./access"; import { SubscriptionCoreError } from "./errors"; import { lockSubscriptionSettings, SUBSCRIPTION_SETTINGS_TRANSACTION, subscriptionSettingLockRefusal, throwIfSubscriptionSettingLocked, } from "../subscription-settings-lock"; import { subscriptionCoreConnectionKind, subscriptionCoreProviderId, type SubscriptionCoreProvider, } from "./provider"; import { declarePersonalWorkspaceOwnerSettings, personalWorkspaceOwnerMayChangeSettings, type PersonalWorkspaceOwnerSettingsInput, } from "../personal-workspace-owner-settings"; /** A wake the caller delivers after its mutation committed. */ export type SubscriptionCoreWake = { accountId: string; reason: string; workspaceIds?: readonly string[]; /** Only these sessions' waiters (requires exactly one workspace). */ sessionIds?: readonly string[]; /** Only waiters of sessions owned by this organization membership. */ ownerMembershipId?: string; }; /** The wake reason for an administration event of this provider. */ export function subscriptionCoreWakeReason( provider: SubscriptionCoreProvider, event: string, ): string { return `core_${subscriptionCoreProviderId(provider)}_${event}`; } /** * One subscription connection as the administration projections read it. * `status` and `last_error` are effective: a quarantine that ended reads * `active` with no error (`subscriptionConnectionEffectiveStatus`). */ export type SubscriptionCoreConnectionRow = { id: string; label: string | null; account_email: string | null; plan_type: string | null; provider_account_id: string | null; status: string; last_error: string | null; extra_credits_enabled: boolean; extra_credits_version: number | string; extra_credits_updated_at: Date | string | null; allocator_enabled: boolean; allocator_version: number | string; allowed_model_ids: string[] | null; connected_by_subject_id: string | null; expires_at: Date | string | null; last_refresh_at: Date | string | null; /** When it was last signed in (1503); null when unknown, and on personal rows. */ signed_in_at?: Date | string | null; managed_by_workspace_id: string | null; provider_state: Record | null; updated_at: Date | string; quota: unknown; quota_revision: number | string | null; quota_observed_refresh_generation: number | string | null; quota_updated_at: Date | string | null; /** * The row version (moves on every connection change except a credential * refresh). Shared rows carry it; the owner reader of personal rows does * not (`readSubscriptionCorePersonalConnectionVersionsInTransaction`). */ version?: number | string; }; const CONNECTION_COLUMNS = sql`connection.id::text as id, connection.label, connection.account_email, connection.plan_type, connection.provider_account_id, ${subscriptionConnectionEffectiveStatus("connection")} as status, ${subscriptionConnectionEffectiveLastError("connection")} as last_error, connection.version, connection.allocator_enabled, connection.extra_credits_enabled, connection.extra_credits_version, connection.extra_credits_updated_at, connection.allocator_version, connection.allowed_model_ids, connection.connected_by_subject_id, connection.expires_at, connection.last_refresh_at, connection.signed_in_at, connection.managed_by_workspace_id::text as managed_by_workspace_id, connection.provider_state, connection.updated_at, quota.quota, quota.revision as quota_revision, quota.observed_refresh_generation as quota_observed_refresh_generation, quota.updated_at as quota_updated_at`; function date(value: Date | string | null | undefined): Date | null { return value === null || value === undefined ? null : new Date(value); } /** The provider's effective settings at one workspace. */ export type SubscriptionCoreProviderSettings = { enabled: boolean; rotationMode: "spread" | "primary_first"; rotationSource: "organization" | "workspace"; }; export function subscriptionCoreProviderSettings( provider: SubscriptionCoreProvider, effective: Awaited>, ): SubscriptionCoreProviderSettings { const id = subscriptionCoreProviderId(provider); const values = effective.values as unknown as { rotation?: Record; providers?: Record; }; const own = values.providers?.[id]; const rotationSources = effective.sources.rotation as Record; return { enabled: own?.enabled !== false, rotationMode: values.rotation?.[id]?.mode === "primary_first" ? "primary_first" : "spread", rotationSource: rotationSources[id] === "workspace" ? "workspace" : "organization", }; } /** The provider's primary column, or null for a provider without a primary setting. */ function primaryColumn(provider: SubscriptionCoreProvider) { const column = provider.settings.primaryColumn; return column === null ? null : sql.identifier(column); } /** Refusal of a primary write for a provider without a primary setting. */ function primaryUnsupported(provider: SubscriptionCoreProvider) { return new SubscriptionCoreError( "subscription_core_primary_unsupported", `${provider.adapter.displayName} has no primary connection setting`, ); } /** The primary column as a select expression (NULL for a provider without one). */ function primarySelect(provider: SubscriptionCoreProvider) { return primaryColumn(provider) ?? sql`null`; } export async function readSubscriptionCorePrimaryConnectionId( tx: Database, provider: SubscriptionCoreProvider, accountId: string, workspaceId: string | null, ): Promise { const [row] = await rawRows<{ primary_id: string | null }>( tx, sql`select ${primarySelect(provider)}::text as primary_id from subscription_settings where account_id = ${accountId}::uuid and workspace_id is not distinct from ${workspaceId}::uuid`, ); return row?.primary_id ?? null; } /** * Whether the provider is on in this workspace. `automatic` is on; the older * `workspace` and `organization` values are no longer stored (D-50). */ export type SubscriptionCoreWorkspaceSourceMode = "automatic" | "disabled"; /** * `disabled` when the provider is off here; otherwise `workspace` when the * workspace has its own connection, else `organization`. Every connection * that reaches the workspace serves either way (D-50). */ export type SubscriptionCoreEffectiveSource = "workspace" | "organization" | "disabled"; export type SubscriptionCoreWorkspaceSource = { accountId: string; workspaceId: string; workspaceKind: "personal" | "shared"; mode: SubscriptionCoreWorkspaceSourceMode; effectiveSource: SubscriptionCoreEffectiveSource; /** The workspace has a connection of its own. */ workspaceAvailable: boolean; /** An organization connection reaches the workspace. */ organizationAvailable: boolean; /** Always false: no connection is set aside (D-50). Kept for older clients. */ workspaceSetAside: false; /** * How many organization connections reach this workspace. Connections * limited to chosen people are not counted: they reach people, not * workspaces. */ organizationCount: number; }; /** One shared connection that reaches a workspace. */ export type SubscriptionCorePoolConnection = { row: SubscriptionCoreConnectionRow; /** `workspace` for the workspace's own connection, else `organization`. */ source: "workspace" | "organization"; }; export type SubscriptionCoreWorkspacePool = { connections: SubscriptionCorePoolConnection[]; primaryConnectionId: string | null; rotationMode: "spread" | "primary_first"; source: SubscriptionCoreWorkspaceSource; }; /** * The shared connections of this provider that reach the workspace, the * primary connection and whether the provider is on here. Requires the * workspace RLS context on `tx`. Only shared subscription connections in the * workspace's scope are listed; an administrator's wider visibility is * filtered explicitly. Nothing is listed while the provider is off here. */ export async function readSubscriptionCoreWorkspacePool( tx: Database, provider: SubscriptionCoreProvider, input: { accountId: string; workspaceId: string; /** Session picker only: include shared accounts assigned to the scoped caller. */ includeOwnPeopleScope?: boolean; /** Limits overview only: list the connections even while the provider is off here. */ includeAllAvailableConnections?: boolean; }, ): Promise { const providerId = subscriptionCoreProviderId(provider); const [workspace] = await rawRows<{ workspace_kind: "personal" | "shared" }>( tx, sql`select get_workspace_kind(${input.accountId}::uuid, ${input.workspaceId}::uuid) as workspace_kind`, ); const workspaceKind = workspace?.workspace_kind === "personal" ? "personal" : "shared"; const settings = subscriptionCoreProviderSettings( provider, await readSubscriptionEffectiveSettings(tx, input.accountId, input.workspaceId), ); const rows = await rawRows( tx, sql`select ${CONNECTION_COLUMNS}, connection.scope_kind from subscription_connections connection left join subscription_connection_quota quota on quota.account_id = connection.account_id and quota.connection_id = connection.id where connection.account_id = ${input.accountId}::uuid and connection.provider = ${providerId} and connection.kind = ${subscriptionCoreConnectionKind(provider)} and connection.disconnected_at is null and connection.ownership = 'shared' and (connection.scope_kind = 'organization' or (connection.scope_kind = 'workspaces' and ( exists (select 1 from subscription_connection_workspaces assignment where assignment.account_id = connection.account_id and assignment.connection_id = connection.id and assignment.workspace_id = ${input.workspaceId}::uuid) or (connection.allow_personal_workspaces and ${workspaceKind} = 'personal'))) or (${input.includeOwnPeopleScope === true} and connection.scope_kind = 'people' and exists (select 1 from subscription_connection_people assignment where assignment.account_id = connection.account_id and assignment.connection_id = connection.id and assignment.organization_membership_id = opengeni_private.subscription_own_person_membership_id(connection.account_id)))) order by connection.created_at, connection.id`, ); const reaching = rows.map(({ scope_kind: scopeKind, ...row }) => ({ row, people: scopeKind === "people", source: row.managed_by_workspace_id === input.workspaceId ? ("workspace" as const) : ("organization" as const), })); const workspaceAvailable = reaching.some((entry) => entry.source === "workspace"); const organizationAvailable = reaching.some((entry) => entry.source === "organization"); const effectiveSource: SubscriptionCoreEffectiveSource = !settings.enabled ? "disabled" : workspaceAvailable ? "workspace" : "organization"; let primaryConnectionId = await readSubscriptionCorePrimaryConnectionId( tx, provider, input.accountId, settings.rotationSource === "workspace" ? input.workspaceId : null, ); // Shared rows were already filtered for lifecycle and workspace scope above. // Personal primaries are checked only after the owner-only reader joins. if (workspaceKind === "shared" && !rows.some((row) => row.id === primaryConnectionId)) { primaryConnectionId = null; } return { // Callers with mere workspace read access must not see accounts that // cannot serve this workspace, so nothing is listed while it is off. connections: settings.enabled || input.includeAllAvailableConnections ? reaching.map(({ row, source }) => ({ row, source })) : [], primaryConnectionId, rotationMode: settings.rotationMode, source: { accountId: input.accountId, workspaceId: input.workspaceId, workspaceKind, mode: settings.enabled ? "automatic" : "disabled", effectiveSource, workspaceAvailable, organizationAvailable, workspaceSetAside: false, organizationCount: reaching.filter( (entry) => entry.source === "organization" && !entry.people, ).length, }, }; } /** * The viewing person's own personal connections of this provider (no * credential material), through the owner-only reader. Requires the * workspace RLS context on `tx`; sets the subject. Empty for anyone else or * for a workspace the person may not use. */ export async function listSubscriptionCorePersonalConnectionRowsInTransaction( tx: Database, provider: SubscriptionCoreProvider, input: { accountId: string; workspaceId: string; subjectId: string }, ): Promise { if (!input.subjectId.startsWith("user:")) return []; await setSubjectRlsContext(tx, input.subjectId); return await rawRows( tx, sql`select personal.id::text as id, personal.label, personal.account_email, personal.plan_type, personal.provider_account_id, personal.status, personal.last_error, personal.allocator_enabled, personal.allocator_version, personal.allowed_model_ids, personal.connected_by_subject_id, personal.expires_at, personal.last_refresh_at, null::text as managed_by_workspace_id, personal.provider_state, personal.updated_at, personal.quota, personal.quota_revision, personal.quota_observed_refresh_generation, personal.quota_updated_at, personal.extra_credits_enabled, personal.extra_credits_version, personal.extra_credits_updated_at from opengeni_private.subscription_core_personal_connections(${subscriptionCoreProviderId(provider)}, ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.subjectId} ) personal`, ); } /** * The row versions of the viewing person's own personal connections of this * provider, through the owner-only reader (0730), keyed by connection id. * Same context and visibility as * `listSubscriptionCorePersonalConnectionRowsInTransaction`. */ export async function readSubscriptionCorePersonalConnectionVersionsInTransaction( tx: Database, provider: SubscriptionCoreProvider, input: { accountId: string; workspaceId: string; subjectId: string }, ): Promise> { if (!input.subjectId.startsWith("user:")) return new Map(); await setSubjectRlsContext(tx, input.subjectId); const rows = await rawRows<{ id: string; version: number | string }>( tx, sql`select personal.id::text as id, personal.version from opengeni_private.subscription_core_personal_connection_versions(${subscriptionCoreProviderId(provider)}, ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.subjectId} ) personal`, ); return new Map(rows.map((row) => [row.id, Number(row.version)])); } /** * The organization's accounts of this provider (every shared connection the * organization administers, including ones a shared workspace manages, * design 5.4) and its rotation, for an organization administrator. * `null` for anyone else: the connection policy hides every row. */ export async function readSubscriptionCoreOrganizationPool( db: Database, provider: SubscriptionCoreProvider, input: { organizationId: string; subjectId: string; /** * Read only this connection, any organization account (also one a shared * workspace manages), for a route that just changed it. */ connectionId?: string; }, ): Promise<{ rows: SubscriptionCoreConnectionRow[]; /** * Per connection, the shared workspaces whose own accounts include it: its * workspace pool lists it there (scope reaches the workspace) classified as * the workspace's own, as `readSubscriptionCoreWorkspacePool` classifies it. */ ownInWorkspaceIds: Map; /** Per connection, who it reaches, so a list can say so without reading each one's access. */ reach: Map; primaryConnectionId: string | null; rotationMode: "spread" | "primary_first"; } | null> { const providerId = subscriptionCoreProviderId(provider); return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (tx) => { await setSubscriptionAdministrationSubject(tx, { accountId: input.organizationId, subjectId: input.subjectId, }); const [admin] = await rawRows<{ admin: boolean }>( tx, sql`select opengeni_private.subscription_organization_admin(${input.organizationId}::uuid) as admin`, ); if (admin?.admin !== true) return null; const [org] = await rawRows<{ mode: string | null; primary_id: string | null }>( tx, sql`select rotation->(${providerId}::text)->>'mode' as mode, ${primarySelect(provider)}::text as primary_id from subscription_settings where account_id = ${input.organizationId}::uuid and workspace_id is null`, ); let primaryConnectionId = org?.primary_id ?? null; const rows = await rawRows( tx, sql`select ${CONNECTION_COLUMNS} from subscription_connections connection left join subscription_connection_quota quota on quota.account_id = connection.account_id and quota.connection_id = connection.id where connection.account_id = ${input.organizationId}::uuid and connection.provider = ${providerId} and connection.kind = ${subscriptionCoreConnectionKind(provider)} and connection.disconnected_at is null and connection.ownership = 'shared' and ${ input.connectionId === undefined ? organizationAdministeredConnection("connection") : sql`connection.id = ${input.connectionId}::uuid and ${organizationAdministeredConnection("connection")}` } order by connection.created_at, connection.id`, ); if (!rows.some((row) => row.id === primaryConnectionId)) primaryConnectionId = null; // A workspace's own connection is that workspace's alone (D-50). const ownInWorkspaceIds = new Map(); for (const row of rows) if (row.managed_by_workspace_id !== null) ownInWorkspaceIds.set(row.id, [row.managed_by_workspace_id]); const reach = new Map(); if (rows.length > 0) { const reachRows = await rawRows<{ id: string; scope_kind: "organization" | "workspaces" | "people"; allow_personal_workspaces: boolean; managed_by_workspace_id: string | null; every_workspace: boolean | null; workspace_ids: string[] | null; people: number | string; }>( tx, sql`select connection.id::text as id, connection.scope_kind, connection.allow_personal_workspaces, connection.managed_by_workspace_id::text as managed_by_workspace_id, (opengeni_private.subscription_core_reach(${providerId}::text, connection.account_id, connection.id)->>'sharedWorkspaces')::boolean as every_workspace, array(select assignment.workspace_id::text from subscription_connection_workspaces assignment where assignment.account_id = connection.account_id and assignment.connection_id = connection.id and assignment.workspace_id in ( select inventory.workspace_id from list_organization_workspace_ids(connection.account_id) inventory) order by assignment.workspace_id) as workspace_ids, (select count(*) from subscription_connection_people person where person.account_id = connection.account_id and person.connection_id = connection.id) as people from subscription_connections connection where connection.account_id = ${input.organizationId}::uuid and connection.id in (select jsonb_array_elements_text( ${JSON.stringify(rows.map((row) => row.id))}::jsonb)::uuid)`, ); for (const row of reachRows) { const owner = row.managed_by_workspace_id; reach.set( row.id, row.scope_kind === "organization" ? { ownerWorkspaceId: owner, everyWorkspace: true, workspaceIds: [], personalWorkspaces: true, people: null, } : row.scope_kind === "people" ? { ownerWorkspaceId: owner, everyWorkspace: false, workspaceIds: [], personalWorkspaces: false, people: Number(row.people), } : { ownerWorkspaceId: owner, everyWorkspace: owner === null && row.every_workspace === true, workspaceIds: owner === null && row.every_workspace === true ? [] : (row.workspace_ids ?? []), personalWorkspaces: row.allow_personal_workspaces, people: null, }, ); } } return { rows, ownInWorkspaceIds, reach, primaryConnectionId, rotationMode: (org?.mode ?? "spread") === "primary_first" ? "primary_first" : "spread", }; }, ); } /** * Who an organization-listed connection reaches: its owning workspace (a * workspace's own account, used only there), every workspace including new * ones, chosen shared workspaces, Personal workspaces, or chosen people. */ export type SubscriptionCoreConnectionReach = { /** The workspace whose own account this is, or null for an organization account. */ ownerWorkspaceId: string | null; /** Every shared workspace, including ones created later. */ everyWorkspace: boolean; /** The shared workspaces it reaches, when not every one. */ workspaceIds: string[]; /** Every Personal workspace. */ personalWorkspaces: boolean; /** How many chosen people, or null when it is not limited to people. */ people: number | null; }; /** A workspace's pool as one person sees it: the shared pool plus, in their own Personal workspace, their personal connections. */ export type SubscriptionCoreWorkspaceView = { pool: SubscriptionCoreWorkspacePool; /** The viewer's own personal connections (Personal workspace only), through the owner-only reader. */ personal: SubscriptionCoreConnectionRow[]; /** * The primary connection as listed: when personal rows joined, a primary * that is neither a listed shared nor a listed personal connection is null * (personal rows are visible only through the owner reader). */ primaryConnectionId: string | null; }; /** * The workspace's pool of this provider for one viewer, under the workspace * RLS context. In the viewer's own Personal workspace their personal * connections are listed too; nobody else ever sees them. */ export async function readSubscriptionCoreWorkspaceView( db: Database, provider: SubscriptionCoreProvider, input: { accountId: string; workspaceId: string; viewerSubjectId?: string | null; /** Limits overview only; availability and canonical row visibility still apply. */ includeAllAvailableConnections?: boolean; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { const pool = await readSubscriptionCoreWorkspacePool(tx, provider, input); if (!input.viewerSubjectId || pool.source.workspaceKind !== "personal") { return { pool, personal: [], primaryConnectionId: pool.primaryConnectionId }; } const personal = await listSubscriptionCorePersonalConnectionRowsInTransaction(tx, provider, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.viewerSubjectId, }); const listed = [...pool.connections.map((entry) => entry.row), ...personal]; return { pool, personal, primaryConnectionId: listed.some((row) => row.id === pool.primaryConnectionId) ? pool.primaryConnectionId : null, }; }, ); } /** * A row-level security refusal (42501). The settings lock guard (0724) also * raises 42501; it is not a refusal to see the row, so it is excluded here and * surfaces as `SubscriptionSettingsLockedError`. */ export function isSubscriptionCoreRlsRefusal(error: unknown): boolean { if (subscriptionSettingLockRefusal(error) !== null) return false; const code = (error as { code?: unknown } | null)?.code; const causeCode = (error as { cause?: { code?: unknown } } | null)?.cause?.code; return code === "42501" || causeCode === "42501"; } export type SubscriptionCoreAdministration = { accountId: string; /** null: the organization route. */ workspaceId: string | null; subjectId: string; } & PersonalWorkspaceOwnerSettingsInput; export type SubscriptionCoreAllocatorResult = | { kind: "updated" | "unchanged" | "conflict"; allocatorEnabled: boolean; allocatorVersion: number; allocatorUpdatedAt: Date | null; } | { kind: "not_found" }; export type SubscriptionCoreExtraCreditsResult = | { kind: "updated" | "unchanged" | "conflict"; extraCreditsEnabled: boolean; extraCreditsVersion: number; extraCreditsUpdatedAt: Date | null; } | { kind: "not_found" }; async function managePersonalConnection( tx: Database, provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration & { connectionId: string }, action: "rename" | "allocator" | "primary", label: string | null = null, enabled: boolean | null = null, expectedVersion: number | null = null, ): Promise< ({ id: string } & Exclude) | null > { if (!input.workspaceId) return null; const [row] = await rawRows<{ result: | ({ id: string } & Exclude) | null; }>( tx, sql`select opengeni_private.manage_subscription_core_personal(${subscriptionCoreProviderId(provider)}, ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.subjectId}, ${input.connectionId}::uuid, ${action}, ${label}, ${enabled}::boolean, ${expectedVersion}::integer) as result`, ); return row?.result ?? null; } async function withAdministration( db: Database, input: SubscriptionCoreAdministration, fn: (tx: Database) => Promise, options: { writesSettings?: boolean } = {}, ): Promise { try { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { await setSubscriptionAdministrationSubject(tx, input); // A Personal workspace's own settings row admits its verified owner (1233). if (input.workspaceId !== null) await declarePersonalWorkspaceOwnerSettings(tx, input); // A workspace route that writes the workspace's settings row takes the // settings lock before any row lock (see lockSubscriptionSettings); // routes that never write settings do not queue behind a lock change. if (input.workspaceId !== null && options.writesSettings === true) { await lockSubscriptionSettings(tx, input.accountId, "shared"); } return await fn(tx); }, // These routines write settings rows: 0724 admits a widening write // only at READ COMMITTED, whatever the connection default. SUBSCRIPTION_SETTINGS_TRANSACTION, ); } catch (error) { // A write the organization's settings lock refused (0724), for example a // workspace rotation, primary or source change: nothing was written. throwIfSubscriptionSettingLocked(error); throw error; } } /** `withAdministration` for a route that may write a settings row. */ async function withSettingsAdministration( db: Database, input: SubscriptionCoreAdministration, fn: (tx: Database) => Promise, ): Promise { return await withAdministration(db, input, fn, { writesSettings: true }); } /** * Resolve a legacy or canonical id to a shared subscription connection of * this provider the route may manage, checked before anything is written. A * workspace route may name only a connection in the workspace's projected * pool (`readSubscriptionCoreWorkspacePool`), as legacy did; an organization * route any organization account (shared, managed by no workspace or by a * shared workspace, design 5.4). `organizationPoolOnly` keeps the organization * route to accounts no workspace manages, for settings that belong to the * organization pool itself (its primary). * Management authority itself is still the core tables' write policies. */ async function visibleSharedConnection( tx: Database, provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration, rawId: string, /** * `organizationPoolOnly`: on the organization's route, only the * organization's own accounts. `anyReaching`: on a workspace's route, any * account that reaches the workspace (a workspace setting such as its * primary may name the organization's accounts), not only its own. */ options: { organizationPoolOnly?: boolean; anyReaching?: boolean } = {}, ): Promise<{ id: string; allocatorEnabled: boolean; allocatorVersion: number; managedByWorkspaceId: string | null; } | null> { const providerId = subscriptionCoreProviderId(provider); const connectionId = await resolveSubscriptionConnectionId(tx, { accountId: input.accountId, provider: subscriptionCoreProviderId(provider), connectionId: rawId, }); if (!connectionId) return null; // Management must not accept a stale primary/allocator target after removal. // Use the same lifecycle order as disconnect before reading its current row. await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended( ${`subscription-refresh:${connectionId}`}, 0))`); const [row] = await rawRows<{ allocator_enabled: boolean; allocator_version: number | string; managed_by_workspace_id: string | null; }>( tx, sql`select allocator_enabled, allocator_version, managed_by_workspace_id::text from subscription_connections where account_id = ${input.accountId}::uuid and provider = ${providerId} and kind = ${subscriptionCoreConnectionKind(provider)} and ownership = 'shared' and id = ${connectionId}::uuid and disconnected_at is null and ${ input.workspaceId !== null ? options.anyReaching ? sql`true` : // A workspace's route manages only the workspace's own // accounts; the organization's are managed on its route (D-50). sql`managed_by_workspace_id = ${input.workspaceId}::uuid` : options.organizationPoolOnly ? sql`managed_by_workspace_id is null` : organizationAdministeredConnection() }`, ); if (!row) return null; if (input.workspaceId !== null) { const pool = await readSubscriptionCoreWorkspacePool(tx, provider, { accountId: input.accountId, workspaceId: input.workspaceId, includeAllAvailableConnections: true, }); if (!pool.connections.some((candidate) => candidate.row.id === connectionId)) return null; } return { id: connectionId, allocatorEnabled: row.allocator_enabled, allocatorVersion: Number(row.allocator_version), managedByWorkspaceId: row.managed_by_workspace_id, }; } function wakeFor( provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration, event: string, ): SubscriptionCoreWake { const reason = subscriptionCoreWakeReason(provider, event); return input.workspaceId ? { accountId: input.accountId, reason, workspaceIds: [input.workspaceId] } : { accountId: input.accountId, reason }; } /** * New-allocation eligibility of one connection, with the legacy optimistic * concurrency: the same state is idempotent even with a stale version; a * conflicting stale version returns the current one. A connection has one * switch (D-50): organization administrators may toggle any shared * connection, a workspace's administrators their workspace's own (the * connection write policy decides). */ export async function setSubscriptionCoreAllocator( db: Database, provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration & { connectionId: string; enabled: boolean; expectedVersion: number; }, ): Promise<{ result: SubscriptionCoreAllocatorResult; wake: SubscriptionCoreWake | null }> { return await withAdministration(db, input, async (tx) => { const personal = await managePersonalConnection( tx, provider, input, "allocator", null, input.enabled, input.expectedVersion, ); if (personal) return { result: { ...personal, allocatorUpdatedAt: date(personal.allocatorUpdatedAt) }, wake: personal.kind === "updated" ? wakeFor(provider, input, "allocator_changed") : null, }; const current = await visibleSharedConnection(tx, provider, input, input.connectionId); if (!current) return { result: { kind: "not_found" }, wake: null }; const projection = ( kind: "updated" | "unchanged" | "conflict", enabled: boolean, version: number, updatedAt: Date | string | null, ) => ({ kind, allocatorEnabled: enabled, allocatorVersion: version, allocatorUpdatedAt: date(updatedAt), }); const [stamp] = await rawRows<{ updated_at: Date | string }>( tx, sql`select updated_at from subscription_connections where account_id = ${input.accountId}::uuid and id = ${current.id}::uuid`, ); const shown = current.allocatorEnabled; if (current.allocatorEnabled === input.enabled) { return { result: projection("unchanged", shown, current.allocatorVersion, stamp?.updated_at ?? null), wake: null, }; } if (current.allocatorVersion !== input.expectedVersion) { return { result: projection("conflict", shown, current.allocatorVersion, stamp?.updated_at ?? null), wake: null, }; } let updated: { allocator_version: number | string; updated_at: Date | string } | undefined; try { updated = await tx.transaction(async (savepoint) => { const [row] = await rawRows<{ allocator_version: number | string; updated_at: Date | string; }>( savepoint as unknown as Database, sql`update subscription_connections set allocator_enabled = ${input.enabled}, allocator_version = allocator_version + 1, updated_at = clock_timestamp() where account_id = ${input.accountId}::uuid and id = ${current.id}::uuid and allocator_version = ${input.expectedVersion} returning allocator_version, updated_at`, ); return row; }); } catch (error) { if (isSubscriptionCoreRlsRefusal(error)) return { result: { kind: "not_found" }, wake: null }; throw error; } // The update policy hides a connection this subject may not manage. if (!updated) return { result: { kind: "not_found" }, wake: null }; return { result: projection( "updated", input.enabled, Number(updated.allocator_version), updated.updated_at, ), // Re-enabling can make a waiting turn placeable; disabling changes nothing // a waiter needs, but a single wake is cheap and keeps the rule simple. wake: { accountId: input.accountId, reason: subscriptionCoreWakeReason(provider, "allocator_changed"), }, }; }); } async function auditExtraCredits( tx: Database, provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration, connectionId: string, enabled: boolean, version: number, ): Promise { await tx.insert(auditEvents).values( withLosslessContentWriteVersion( { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, action: `${subscriptionCoreProviderId(provider)}.extra_credits.updated`, targetType: "subscription_connection", targetId: connectionId, metadata: { extraCreditsEnabled: enabled, extraCreditsVersion: version }, }, "metadata", "metadataCodecVersion", ), ); } /** * Consent to paid usage beyond the plan for one connection (providers with * the `extraCredits` capability), with the same optimistic concurrency as * the allocator switch. A provider without the capability finds nothing. */ export async function setSubscriptionCoreExtraCredits( db: Database, provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration & { connectionId: string; enabled: boolean; expectedVersion: number; }, ): Promise<{ result: SubscriptionCoreExtraCreditsResult; wake: SubscriptionCoreWake | null }> { if (!provider.adapter.capabilities.extraCredits) { return { result: { kind: "not_found" }, wake: null }; } return await withAdministration(db, input, async (tx) => { if (input.workspaceId) { const [personal] = await rawRows<{ result: | ({ id: string } & Exclude) | null; }>( tx, sql`select opengeni_private.manage_subscription_core_personal(${subscriptionCoreProviderId(provider)}, ${input.accountId}::uuid, ${input.workspaceId}::uuid, ${input.subjectId}, ${input.connectionId}::uuid, 'extra_credits', null, ${input.enabled}, ${input.expectedVersion}::integer) as result`, ); if (personal?.result) { const result = { ...personal.result, extraCreditsUpdatedAt: date(personal.result.extraCreditsUpdatedAt), }; if (result.kind === "updated") { await auditExtraCredits( tx, provider, input, result.id, result.extraCreditsEnabled, result.extraCreditsVersion, ); } return { result, wake: result.kind === "updated" ? { accountId: input.accountId, reason: subscriptionCoreWakeReason(provider, "extra_credits_changed"), } : null, }; } } const visible = await visibleSharedConnection(tx, provider, input, input.connectionId); if (!visible) return { result: { kind: "not_found" }, wake: null }; const [row] = await rawRows<{ enabled: boolean; version: number }>( tx, sql`select extra_credits_enabled as enabled, extra_credits_version as version from subscription_connections where account_id = ${input.accountId}::uuid and id = ${visible.id}::uuid for update`, ); const current = row ? { id: visible.id, extraCreditsEnabled: row.enabled, extraCreditsVersion: Number(row.version), } : null; if (!current) return { result: { kind: "not_found" }, wake: null }; const projection = ( kind: "updated" | "unchanged" | "conflict", enabled: boolean, version: number, updatedAt: Date | string | null, ) => ({ kind, extraCreditsEnabled: enabled, extraCreditsVersion: version, extraCreditsUpdatedAt: date(updatedAt), }); const [stamp] = await rawRows<{ updated_at: Date | string }>( tx, sql`select extra_credits_updated_at as updated_at from subscription_connections where account_id = ${input.accountId}::uuid and id = ${current.id}::uuid`, ); if (current.extraCreditsEnabled === input.enabled) { return { result: projection( "unchanged", current.extraCreditsEnabled, current.extraCreditsVersion, stamp?.updated_at ?? null, ), wake: null, }; } if (current.extraCreditsVersion !== input.expectedVersion) { return { result: projection( "conflict", current.extraCreditsEnabled, current.extraCreditsVersion, stamp?.updated_at ?? null, ), wake: null, }; } let updated: { extra_credits_version: number | string; updated_at: Date | string } | undefined; try { updated = await tx.transaction(async (savepoint) => { const [updatedRow] = await rawRows<{ extra_credits_version: number | string; updated_at: Date | string; }>( savepoint as unknown as Database, sql`update subscription_connections set extra_credits_enabled = ${input.enabled}, extra_credits_updated_by_subject_id = ${input.subjectId}, extra_credits_updated_at = clock_timestamp(), extra_credits_version = extra_credits_version + 1, updated_at = clock_timestamp() where account_id = ${input.accountId}::uuid and id = ${current.id}::uuid and extra_credits_version = ${input.expectedVersion} returning extra_credits_version, extra_credits_updated_at as updated_at`, ); return updatedRow; }); } catch (error) { if (isSubscriptionCoreRlsRefusal(error)) return { result: { kind: "not_found" }, wake: null }; throw error; } // The update policy hides a connection this subject may not manage. if (!updated) return { result: { kind: "not_found" }, wake: null }; await auditExtraCredits( tx, provider, input, current.id, input.enabled, Number(updated.extra_credits_version), ); return { result: projection( "updated", input.enabled, Number(updated.extra_credits_version), updated.updated_at, ), // Re-enabling can make a waiting turn placeable; disabling changes nothing // a waiter needs, but a single wake is cheap and keeps the rule simple. wake: { accountId: input.accountId, reason: subscriptionCoreWakeReason(provider, "extra_credits_changed"), }, }; }); } /** Rename one connection (label only). Returns null when it is not manageable. */ export async function renameSubscriptionCoreConnection( db: Database, provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration & { connectionId: string; label: string | null }, ): Promise { return await withAdministration(db, input, async (tx) => { const personal = await managePersonalConnection(tx, provider, input, "rename", input.label); if (personal) return personal.id; const current = await visibleSharedConnection(tx, provider, input, input.connectionId); if (!current) return null; const label = input.label === null ? null : input.label.trim().slice(0, 200) || null; try { const renamed = await tx.transaction(async (savepoint) => rawRows<{ id: string }>( savepoint as unknown as Database, sql`update subscription_connections set label = ${label}, version = version + 1, updated_at = clock_timestamp() where account_id = ${input.accountId}::uuid and id = ${current.id}::uuid returning id::text as id`, ), ); return renamed[0]?.id ?? null; } catch (error) { if (isSubscriptionCoreRlsRefusal(error)) return null; throw error; } }); } /** * Write one settings row (the organization row for a NULL workspace) through * the settings manager policy. Returns false when the subject may not write it. * * The existing row is updated in place. The organization row's CHECK requires * every organization default to be present, so an upsert's proposed insert * row (which sets only this provider's values) would be refused before ON * CONFLICT ran; a missing row is therefore inserted with the defaults the * settings resolver already applies to an absent value (empty rotation, * providers and fallback order, no cross-provider failover, personal * connections allowed, no personal fallback). A workspace override row may * leave them NULL. */ async function writeSettingsRow( tx: Database, provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration, patch: { rotationMode?: "spread" | "primary_first"; primaryConnectionId?: string | null; providerSettings?: Record | null; }, ): Promise { const providerId = subscriptionCoreProviderId(provider); const primary_column = primaryColumn(provider); const rotationJson = patch.rotationMode === undefined ? null : JSON.stringify({ [providerId]: { mode: patch.rotationMode } }); const providerJson = patch.providerSettings === undefined || patch.providerSettings === null ? null : JSON.stringify({ [providerId]: patch.providerSettings }); const clearProvider = patch.providerSettings === null; const setPrimary = patch.primaryConnectionId !== undefined; if (setPrimary && primary_column === null) throw primaryUnsupported(provider); const primary = setPrimary ? (patch.primaryConnectionId ?? null) : null; const primaryAssignment = primary_column === null ? sql`` : sql`${primary_column} = case when ${setPrimary} then ${primary}::uuid else ${primary_column} end,`; const primaryInsertColumn = primary_column === null ? sql`` : sql`${primary_column},`; const primaryInsertValue = primary_column === null ? sql`` : sql`${primary}::uuid,`; const organizationRow = input.workspaceId === null; const update = async (db: Database) => await rawRows<{ id: string }>( db, sql`update subscription_settings set rotation = case when ${rotationJson}::jsonb is null then rotation else coalesce(rotation, '{}'::jsonb) || ${rotationJson}::jsonb end, providers = case when ${clearProvider} then providers - (${providerId}::text) when ${providerJson}::jsonb is null then providers else coalesce(providers, '{}'::jsonb) || ${providerJson}::jsonb end, ${primaryAssignment} version = version + 1, updated_by_subject_id = ${input.subjectId}, updated_at = clock_timestamp() where account_id = ${input.accountId}::uuid and workspace_id is not distinct from ${input.workspaceId}::uuid returning id::text as id`, ); try { return await tx.transaction(async (savepoint) => { const scoped = savepoint as unknown as Database; if ((await update(scoped)).length > 0) return true; const inserted = await rawRows<{ id: string }>( scoped, sql`insert into subscription_settings ( account_id, workspace_id, rotation, providers, ${primaryInsertColumn} cross_provider_failover, fallback_order, personal_connections_allowed, personal_fallback_allowed, updated_by_subject_id, updated_at ) values ( ${input.accountId}::uuid, ${input.workspaceId}::uuid, case when ${organizationRow} then coalesce(${rotationJson}::jsonb, '{}'::jsonb) else ${rotationJson}::jsonb end, case when ${organizationRow} then coalesce(${providerJson}::jsonb, '{}'::jsonb) else ${providerJson}::jsonb end, ${primaryInsertValue} case when ${organizationRow} then false end, case when ${organizationRow} then '{}'::jsonb end, case when ${organizationRow} then true end, case when ${organizationRow} then false end, ${input.subjectId}, clock_timestamp() ) on conflict (account_id, workspace_id) do nothing returning id::text as id`, ); if (inserted.length > 0) return true; // A concurrent writer inserted the row first; update it. return (await update(scoped)).length > 0; }); } catch (error) { if (isSubscriptionCoreRlsRefusal(error)) return false; throw error; } } /** The rotation mode in effect at the row being written, for an override that keeps it. */ async function effectiveRotationMode( tx: Database, provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration, ): Promise<"spread" | "primary_first"> { if (input.workspaceId) { return subscriptionCoreProviderSettings( provider, await readSubscriptionEffectiveSettings(tx, input.accountId, input.workspaceId), ).rotationMode; } const [org] = await rawRows<{ mode: string | null }>( tx, sql`select rotation->(${subscriptionCoreProviderId(provider)}::text)->>'mode' as mode from subscription_settings where account_id = ${input.accountId}::uuid and workspace_id is null`, ); return org?.mode === "primary_first" ? "primary_first" : "spread"; } /** * The account unpinned sessions prefer: the primary connection of this * workspace (or the organization), keeping the rotation mode currently in * effect there. */ export async function setSubscriptionCorePrimary( db: Database, provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration & { connectionId: string }, ): Promise<{ activated: string | null; wake: SubscriptionCoreWake | null }> { // Refused up front, before any lock or read, for personal and shared // connections alike (after the binding's own checks). subscriptionCoreProviderId(provider); if (provider.settings.primaryColumn === null) throw primaryUnsupported(provider); return await withSettingsAdministration(db, input, async (tx) => { const personal = await managePersonalConnection(tx, provider, input, "primary"); if (personal) return { activated: personal.id, wake: wakeFor(provider, input, "primary_changed") }; // The organization primary stays within the organization pool: a // workspace-managed account keeps its workspace classification (5.4). const current = await visibleSharedConnection(tx, provider, input, input.connectionId, { organizationPoolOnly: true, anyReaching: true, }); if (!current) return { activated: null, wake: null }; const written = await writeSettingsRow(tx, provider, input, { rotationMode: await effectiveRotationMode(tx, provider, input), primaryConnectionId: current.id, }); return written ? { activated: current.id, wake: wakeFor(provider, input, "primary_changed") } : { activated: null, wake: null }; }); } /** * The primary a new or updated workspace rotation override must carry so the * effective primary does not change: the organization's while the workspace * inherits rotation from it, nothing to change while it already has its own. */ async function inheritedPrimaryForOverride( tx: Database, provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration, ): Promise<{ primaryConnectionId: string | null } | Record> { // A provider without a primary setting has nothing to carry. if (!input.workspaceId || provider.settings.primaryColumn === null) return {}; const settings = subscriptionCoreProviderSettings( provider, await readSubscriptionEffectiveSettings(tx, input.accountId, input.workspaceId), ); if (settings.rotationSource === "workspace") return {}; return { primaryConnectionId: await readSubscriptionCorePrimaryConnectionId( tx, provider, input.accountId, null, ), }; } /** * Rotation switch: on is `spread`, off is `primary_first` (D-13). A * workspace override carries the effective (inherited) primary, so toggling * rotation never drops the account unpinned sessions prefer. Returns null * when the subject may not write the row. */ export async function setSubscriptionCoreRotation( db: Database, provider: SubscriptionCoreProvider, input: SubscriptionCoreAdministration & { rotationEnabled: boolean }, ): Promise<{ primaryConnectionId: string | null; wake: SubscriptionCoreWake } | null> { return await withSettingsAdministration(db, input, async (tx) => { const written = await writeSettingsRow(tx, provider, input, { rotationMode: input.rotationEnabled ? "spread" : "primary_first", ...(await inheritedPrimaryForOverride(tx, provider, input)), }); if (!written) return null; return { primaryConnectionId: await readSubscriptionCorePrimaryConnectionId( tx, provider, input.accountId, input.workspaceId, ), wake: wakeFor(provider, input, "rotation_changed"), }; }); } /** * Whether the provider is on in a workspace, as the workspace's provider * override: `automatic` removes it, `disabled` sets `enabled = false`. Connection scope and the model allowlist are never * touched (design 5.2). Throws the provider's source-refused error. */ export async function setSubscriptionCoreWorkspaceSource( db: Database, provider: SubscriptionCoreProvider, input: { accountId: string; workspaceId: string; subjectId: string; mode: SubscriptionCoreWorkspaceSourceMode; } & PersonalWorkspaceOwnerSettingsInput, ): Promise<{ pool: SubscriptionCoreWorkspacePool; wake: SubscriptionCoreWake }> { return await withSettingsAdministration(db, input, async (tx) => { const [workspace] = await rawRows<{ workspace_kind: string }>( tx, sql`select get_workspace_kind(${input.accountId}::uuid, ${input.workspaceId}::uuid) as workspace_kind`, ); // Only its verified owner turns a provider off in a Personal workspace (1233). if ( workspace?.workspace_kind === "personal" && input.mode !== "automatic" && !(await personalWorkspaceOwnerMayChangeSettings(tx, input)) ) { throw provider.errors.sourceRefused( "personal_workspace", `${provider.adapter.displayName} source modes are not available for personal workspaces`, ); } const written = await writeSettingsRow(tx, provider, input, { providerSettings: input.mode === "automatic" ? null : { enabled: false }, }); if (!written) { throw provider.errors.sourceRefused( "forbidden", `You don't have permission to change this workspace's ${provider.adapter.displayName} source.`, ); } return { pool: await readSubscriptionCoreWorkspacePool(tx, provider, input), wake: wakeFor(provider, input, "source_changed"), }; }); }