import { pollStorageUsageRemaining, type PollStorageUsage } from "./server-poll-storage-model.js" export type ServerPollCapacity = | Readonly<{ status: "unavailable" }> | Readonly<{ status: "observed"; owner: Readonly<{ used: number; limit: 8; remaining: number }>; global: Readonly<{ exhausted: boolean; usage: Readonly<{ used: number; limit: 128; remaining: number }> | null }>; retentionDays: number }> export interface ServerPollCapacitySql { query(text: string, values: unknown[]): Promise<{ rows: Record[] }> } // A single bounded MVCC snapshot. No admission enumeration, maintenance, locks // or claim/readiness mutation is part of this observation. const QUERY = `SELECT s.requests_retention_days AS retention_days, g.admissions AS global_admissions,g.compacted_admissions AS global_compacted_admissions,g.archive_bytes AS global_archive_bytes,g.reserved_rows AS global_reserved_rows,g.reserved_bytes AS global_reserved_bytes, o.admissions AS owner_admissions,o.compacted_admissions AS owner_compacted_admissions,o.archive_bytes AS owner_archive_bytes,o.reserved_rows AS owner_reserved_rows,o.reserved_bytes AS owner_reserved_bytes FROM public.mcp_settings s LEFT JOIN public.server_poll_storage_usage g ON g.scope='global' LEFT JOIN public.server_poll_storage_usage o ON o.scope=$1 WHERE s.id=1 LIMIT 2` const unavailable: ServerPollCapacity = Object.freeze({ status: "unavailable" }) function integer(value: unknown): number | undefined { if (typeof value === "number") return Number.isSafeInteger(value) && value >= 0 && !Object.is(value, -0) ? value : undefined if (typeof value !== "string" || !/^(?:0|[1-9][0-9]*)$/.test(value) || value.length > 16) return undefined const parsed = Number(value) return Number.isSafeInteger(parsed) ? parsed : undefined } function usage(admissions: unknown, rows: unknown, bytes: unknown, compacted:unknown, archive:unknown, scope:"global"|"owner") { const used=integer(admissions),reservedRows=integer(rows),reservedBytes=integer(bytes),compactedAttempts=integer(compacted),archiveBytes=integer(archive) if(used===undefined||reservedRows===undefined||reservedBytes===undefined||compactedAttempts===undefined||archiveBytes===undefined)return undefined const value:PollStorageUsage={attempts:used,rows:reservedRows,bytes:reservedBytes,compactedAttempts,archiveBytes} const remaining=pollStorageUsageRemaining(value,scope) return remaining===undefined?undefined:{value,remaining} } /** Read-only heavy reservation availability with paid retained history. Used * counts heavy slots; remaining also accounts for archive bytes/rows. This * observation does not verify archive MACs and is never an admission promise. * Missing or * inconsistent accounting is unavailable rather than a fabricated free slot. * Non-admin callers receive no global usage numbers or other owner identities. */ export async function readServerPollCapacity(sql: ServerPollCapacitySql, ownerId: string, admin: boolean): Promise { if (typeof ownerId !== "string" || ownerId.trim() !== ownerId || !ownerId.length || [...ownerId].length > 200 || /[\u0000-\u001f\u007f-\u009f]/.test(ownerId) || typeof admin !== "boolean") return unavailable try { const result = await sql.query(QUERY, ["owner:" + ownerId]) if (!Array.isArray(result.rows) || result.rows.length !== 1) return unavailable const row = result.rows[0] if (!row || typeof row !== "object" || Array.isArray(row)) return unavailable // Capture primitive fields synchronously. DTOs never alias mutable driver // rows and are frozen independently of the SQL adapter's result lifetime. const retentionDays = integer(row.retention_days) const globalUsed=usage(row.global_admissions,row.global_reserved_rows,row.global_reserved_bytes,row.global_compacted_admissions,row.global_archive_bytes,"global") const ownerFields=[row.owner_admissions,row.owner_reserved_rows,row.owner_reserved_bytes,row.owner_compacted_admissions,row.owner_archive_bytes] const ownerUsed=ownerFields.every(value=>value===null)?usage(0,0,0,0,0,"owner"):usage(...ownerFields as [unknown,unknown,unknown,unknown,unknown],"owner") if(retentionDays===undefined||retentionDays<1||retentionDays>365||!globalUsed||!ownerUsed)return unavailable for(const field of ["attempts","rows","bytes","compactedAttempts","archiveBytes"] as const) if(ownerUsed.value[field]! > globalUsed.value[field]!)return unavailable const otherCount=globalUsed.value.compactedAttempts!-ownerUsed.value.compactedAttempts!,otherBytes=globalUsed.value.archiveBytes!-ownerUsed.value.archiveBytes! if(otherBytesotherCount*131072)return unavailable return Object.freeze({status:"observed",owner:Object.freeze({used:ownerUsed.value.attempts,limit:8,remaining:ownerUsed.remaining}), global:Object.freeze({exhausted:globalUsed.remaining===0, usage:admin?Object.freeze({used:globalUsed.value.attempts,limit:128,remaining:globalUsed.remaining}):null}),retentionDays}) } catch { return unavailable } }