Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(gfs): add resumable uploads up to 200 MiB
Alfredo Lopez97d1d13f24f4
diff --git a/control-api/src/app.ts b/control-api/src/app.tsindex 0ebff8744..67aa412c0 100644--- a/control-api/src/app.ts+++ b/control-api/src/app.ts@@ -59,6 +59,11 @@ import {const TRACING_INTERNAL_PATH_PREFIX = '/api/v1/internal/tracing/'const RPC_HOST_ACCESS_PATH = /^\/api\/v1\/rpc\/access\/users\/[^/]+\/mcp-hosts\/[^/]+\/?$/i+// Upload v2 part bodies are raw octet streams. They must reach the streaming+// proxy untouched; parsing them as JSON would either reject the first binary+// byte or buffer the whole part in the control plane.+const GFS_UPLOAD_PART_PATH =+ /^\/api\/v1\/(?:gfs\/proxy\/v1|external\/gfs)\/uploads\/[0-9a-f-]{36}\/parts\/[0-9]+$/iexport function createApp(gateway: K8sGateway) {const traceIngestDb: DbClient = meterTracingDbClient({@@ -77,6 +82,10 @@ export function createApp(gateway: K8sGateway) {next()return}+ if (req.method === 'PUT' && GFS_UPLOAD_PART_PATH.test(req.path)) {+ next()+ return+ }jsonBodyParser(req, res, next)})diff --git a/control-api/src/db.ts b/control-api/src/db.tsindex cd7a8f2a1..1f097611d 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -5,6 +5,10 @@ import {createBoundedPgPoolForConnection,} from './boundedPgPool.js'import { config } from './config.js'+import {+ applyGfsUploadCleanupSchema,+ applyGfsUploadSessionSchema,+} from './services/gfsUploadSchema.js'import { applyMemberRegistrationCredentialsSchema } from './services/memberRegistrationCredentialsSchema.js'import {addPluginWorkloadSdkAttemptLedgerColumns,@@ -5463,6 +5467,14 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [version: '0090_plugin_workload_sdk_runtime_contract_reconciliation',apply: reconcilePluginWorkloadSdkRuntimeContracts,},+ {+ version: '0091_gfs_upload_sessions',+ apply: applyGfsUploadSessionSchema,+ },+ {+ version: '0092_gfs_upload_cleanup_receipt',+ apply: applyGfsUploadCleanupSchema,+ },]async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {diff --git a/control-api/src/routes/external/gfs.ts b/control-api/src/routes/external/gfs.tsindex 95c5263e0..c3686b10c 100644--- a/control-api/src/routes/external/gfs.ts+++ b/control-api/src/routes/external/gfs.ts@@ -217,6 +217,110 @@ export function createExternalGfsRouter(): Router {}))+ // Indexed upload-v2 relay. Part PUTs stay a Node stream all the way from+ // external-rest-api to the writer GFSC; lifecycle requests use the same+ // writer-scoped token and never fall back to the legacy JSON/base64 path.+ router.get(+ '/external/gfs/capabilities',+ asyncHandler(async (req: ExternalAuthedRequest, res) => {+ await proxyUploadToGfsc(req, res, driveOf(req.query.drive), 'GET', '/v1/capabilities')+ })+ )+ router.post(+ '/external/gfs/uploads',+ asyncHandler(async (req: ExternalAuthedRequest, res) => {+ await proxyUploadToGfsc(req, res, driveOf(req.query.drive), 'POST', '/v1/uploads')+ })+ )+ router.head(+ '/external/gfs/uploads/:id',+ asyncHandler(async (req: ExternalAuthedRequest, res) => {+ if (!UUID_RE.test(String(req.params.id))) {+ res.status(400).json({ error: 'resource_invalid' })+ return+ }+ await proxyUploadToGfsc(+ req,+ res,+ driveOf(req.query.drive),+ 'HEAD',+ `/v1/uploads/${encodeURIComponent(req.params.id)}`+ )+ })+ )+ router.get(+ '/external/gfs/uploads/:id/status',+ asyncHandler(async (req: ExternalAuthedRequest, res) => {+ if (!UUID_RE.test(String(req.params.id))) {+ res.status(400).json({ error: 'resource_invalid' })+ return+ }+ await proxyUploadToGfsc(+ req,+ res,+ driveOf(req.query.drive),+ 'GET',+ `/v1/uploads/${encodeURIComponent(req.params.id)}/status`,+ {+ limit: typeof req.query.limit === 'string' ? req.query.limit : undefined,+ cursor: typeof req.query.cursor === 'string' ? req.query.cursor : undefined,+ }+ )+ })+ )+ router.put(+ '/external/gfs/uploads/:id/parts/:part',+ asyncHandler(async (req: ExternalAuthedRequest, res) => {+ const id = String(req.params.id)+ const part = String(req.params.part)+ if (!UUID_RE.test(id) || !/^[0-9]+$/.test(part)) {+ res.status(400).json({ error: 'resource_invalid' })+ return+ }+ await proxyUploadToGfsc(+ req,+ res,+ driveOf(req.query.drive),+ 'PUT',+ `/v1/uploads/${encodeURIComponent(id)}/parts/${part}`+ )+ })+ )+ for (const action of ['pause', 'resume', 'complete'] as const) {+ router.post(+ `/external/gfs/uploads/:id/${action}`,+ asyncHandler(async (req: ExternalAuthedRequest, res) => {+ if (!UUID_RE.test(String(req.params.id))) {+ res.status(400).json({ error: 'resource_invalid' })+ return+ }+ await proxyUploadToGfsc(+ req,+ res,+ driveOf(req.query.drive),+ 'POST',+ `/v1/uploads/${encodeURIComponent(req.params.id)}/${action}`+ )+ })+ )+ }+ router.delete(+ '/external/gfs/uploads/:id',+ asyncHandler(async (req: ExternalAuthedRequest, res) => {+ if (!UUID_RE.test(String(req.params.id))) {+ res.status(400).json({ error: 'resource_invalid' })+ return+ }+ await proxyUploadToGfsc(+ req,+ res,+ driveOf(req.query.drive),+ 'DELETE',+ `/v1/uploads/${encodeURIComponent(req.params.id)}`+ )+ })+ )+// ── delegation: reuse the EXISTING grant/share handlers (caller-agnostic) ──// resolveCaller(req) reads req.externalAuth → user:<id> plus all active team// memberships resolved here; assertMayGrant enforces no-escalation (a user may@@ -674,3 +778,110 @@ async function proxyMutationToGfsc(}res.send(text)}++async function proxyUploadToGfsc(+ req: ExternalAuthedRequest,+ res: import('express').Response,+ drive: string,+ method: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE',+ gfscPath: string,+ query?: Record<string, string | undefined>+): Promise<void> {+ const claims = req.externalAuth!+ const { token } = signGfsToken({ subject: claims.userId, drive, scopes: [GFS_WRITE_SCOPE] })+ const targetUrl = new URL(`${config.gfscWriteBaseUrl.replace(/\/+$/, '')}${gfscPath}`)+ for (const [key, value] of Object.entries(query ?? {})) {+ if (value !== undefined && value !== '') targetUrl.searchParams.set(key, value)+ }+ const target = targetUrl.toString()+ const rawPart = method === 'PUT' && /\/parts\/[0-9]+$/.test(gfscPath)+ const headers: Record<string, string> = { authorization: `Bearer ${token}` }+ if (rawPart) {+ for (const name of [+ 'content-type',+ 'upload-part-number',+ 'upload-offset',+ 'upload-chunk-length',+ 'upload-checksum',+ ]) {+ const value = req.headers[name]+ if (typeof value === 'string') headers[name] = value+ }+ } else if (method !== 'GET' && method !== 'HEAD') {+ headers['content-type'] = 'application/json'+ }+ const controller = new AbortController()+ const timer = setTimeout(() => controller.abort(), Math.max(config.gfscProxyTimeoutMs, 600_000))+ const init: RequestInit & { duplex?: 'half' } = {+ method,+ headers,+ body:+ method === 'GET' || method === 'HEAD'+ ? undefined+ : rawPart+ ? (req as unknown as BodyInit)+ : JSON.stringify(req.body ?? {}),+ signal: controller.signal,+ }+ if (rawPart) init.duplex = 'half'+ let upstream: Response+ try {+ upstream = await fetch(target, init)+ } catch (error) {+ const timedOut = controller.signal.aborted+ rootLogger.error(+ { err: error, gfscPath, method },+ timedOut ? 'gfs external upload proxy timed out' : 'gfs external upload proxy failed'+ )+ res.status(timedOut ? 504 : 502).json({ error: timedOut ? 'gfsc_timeout' : 'gfsc_unreachable' })+ return+ } finally {+ clearTimeout(timer)+ }+ if (upstream.status >= 400) {+ const body = await upstream.text()+ if (upstream.status >= 500)+ rootLogger.error(+ { gfscPath, method, status: upstream.status, body: body.slice(0, 2048) },+ 'gfs external upload upstream error'+ )+ res.status(upstream.status)+ const contentType = upstream.headers.get('content-type')+ if (contentType) res.setHeader('content-type', contentType)+ res.send(body)+ return+ }+ res.status(upstream.status)+ for (const name of [+ 'content-type',+ 'content-length',+ 'cache-control',+ 'upload-offset',+ 'upload-length',+ 'upload-part-bytes',+ 'upload-part-count',+ 'upload-active-parts',+ 'upload-state',+ 'upload-expires',+ 'upload-part-number',+ 'upload-part-offset',+ 'upload-part-length',+ 'upload-checksum',+ ]) {+ const value = upstream.headers.get(name)+ if (value) res.setHeader(name, value)+ }+ if (!upstream.body) {+ res.end()+ return+ }+ try {+ for await (const chunk of upstream.body as unknown as AsyncIterable<Uint8Array>)+ res.write(Buffer.from(chunk))+ res.end()+ } catch (error) {+ rootLogger.error({ err: error, gfscPath, method }, 'gfs external upload response stream failed')+ if (!res.headersSent) res.status(502).json({ error: 'gfsc upstream error' })+ else res.end()+ }+}diff --git a/control-api/src/routes/gfs/proxy.ts b/control-api/src/routes/gfs/proxy.tsindex 62bc54d35..895fa32dc 100644--- a/control-api/src/routes/gfs/proxy.ts+++ b/control-api/src/routes/gfs/proxy.ts@@ -12,8 +12,21 @@ import { rootLogger } from '../../observability/logger.js'const DEFAULT_DRIVE = 'main'const PASSTHROUGH_RESPONSE_HEADERS = ['content-type', 'content-disposition', 'content-length']+const UPLOAD_PART_PATH = /^\/v1\/uploads\/[0-9a-f-]{36}\/parts\/[0-9]+(?:\?|$)/i+const UPLOAD_PATH = /^\/v1\/(?:capabilities|uploads)(?:\/|\?|$)/i+const STREAM_REQUEST_HEADERS = [+ 'content-type',+ 'upload-part-number',+ 'upload-offset',+ 'upload-chunk-length',+ 'upload-checksum',+]-function gfscBaseUrlFor(method: string): string {+function gfscBaseUrlFor(method: string, path: string): string {+ // Upload lifecycle reads (capabilities, HEAD/status) are stateful writer+ // operations too. Routing them to the reader can return stale session+ // offsets immediately after a part commit and break resume/cancel races.+ if (UPLOAD_PATH.test(path)) return config.gfscWriteBaseUrlreturn method === 'GET' || method === 'HEAD' ? config.gfscBaseUrl : config.gfscWriteBaseUrl}@@ -36,8 +49,9 @@ export function registerGfsProxyRoute(router: Router): void {return}- const scope =- req.method === 'GET' || req.method === 'HEAD'+ const scope = UPLOAD_PATH.test(req.url || '')+ ? GFS_WRITE_SCOPE+ : req.method === 'GET' || req.method === 'HEAD'? GFS_READ_SCOPE: req.method === 'POST' || req.method === 'PUT'? GFS_WRITE_SCOPE@@ -51,11 +65,17 @@ export function registerGfsProxyRoute(router: Router): void {}const subPath = req.url === '/' ? '' : req.url- const target = `${gfscBaseUrlFor(req.method).replace(/\/+$/, '')}${subPath}`+ const target = `${gfscBaseUrlFor(req.method, subPath).replace(/\/+$/, '')}${subPath}`const { token } = signGfsToken({ subject, drive: DEFAULT_DRIVE, scopes: [scope] })const headers: Record<string, string> = {}headers['author' + 'ization'] = ['Bearer', token].join(' ')- if (req.method !== 'GET' && req.method !== 'HEAD') {+ const isUploadPart = req.method === 'PUT' && UPLOAD_PART_PATH.test(subPath)+ if (isUploadPart) {+ for (const name of STREAM_REQUEST_HEADERS) {+ const value = req.headers[name]+ if (typeof value === 'string') headers[name] = value+ }+ } else if (req.method !== 'GET' && req.method !== 'HEAD') {headers['content-type'] = 'application/json'}@@ -69,15 +89,19 @@ export function registerGfsProxyRoute(router: Router): void {const deadline = new AbortController()const deadlineTimer = setTimeout(() => deadline.abort(), config.gfscProxyTimeoutMs)try {- upstreamRes = await fetch(target, {+ const fetchInit: RequestInit & { duplex?: 'half' } = {method: req.method,headers,body:req.method === 'GET' || req.method === 'HEAD'? undefined- : JSON.stringify(req.body ?? {}),+ : isUploadPart+ ? (req as unknown as BodyInit)+ : JSON.stringify(req.body ?? {}),signal: deadline.signal,- })+ }+ if (isUploadPart) fetchInit.duplex = 'half'+ upstreamRes = await fetch(target, fetchInit)} catch (err) {// Never silent: a failed or timed-out gfsc fetch is logged with the target.const timedOut =diff --git a/control-api/src/services/gfsUploadSchema.ts b/control-api/src/services/gfsUploadSchema.tsnew file mode 100644index 000000000..aec134997--- /dev/null+++ b/control-api/src/services/gfsUploadSchema.ts@@ -0,0 +1,89 @@+import type { DbClient } from '../db.js'++/**+ * Additive persistence for the indexed GFS Upload v2 protocol.+ *+ * Session metadata and part receipts live in the control-plane Postgres. Part+ * bytes stay on the existing GFSC writer PVC; `staging_path` is metadata only.+ * The migration is forward-only and deliberately does not advertise or enable+ * the protocol.+ */+export async function applyGfsUploadSessionSchema(db: DbClient): Promise<void> {+ await db.query(`+ CREATE TABLE IF NOT EXISTS gfs_upload_sessions (+ upload_id UUID PRIMARY KEY,+ idempotency_key UUID NOT NULL,+ drive TEXT NOT NULL,+ owner_subject TEXT NOT NULL,+ primary_subject TEXT NOT NULL,+ operation TEXT NOT NULL CHECK (operation IN ('create', 'replace')),+ request_fingerprint TEXT NOT NULL,+ parent_rid TEXT NULL,+ resource_rid TEXT NULL,+ reserved_resource_id UUID NULL,+ resource_name TEXT NULL,+ if_match BIGINT NULL,+ expected_bytes BIGINT NOT NULL CHECK (expected_bytes BETWEEN 0 AND 1073741824),+ part_bytes BIGINT NOT NULL CHECK (part_bytes BETWEEN 1048576 AND 16777216),+ part_count INTEGER NOT NULL CHECK (part_count BETWEEN 0 AND 1024),+ whole_sha256 TEXT NULL,+ committed_bytes BIGINT NOT NULL DEFAULT 0 CHECK (committed_bytes >= 0),+ contiguous_bytes BIGINT NOT NULL DEFAULT 0 CHECK (contiguous_bytes >= 0),+ committed_part_count INTEGER NOT NULL DEFAULT 0 CHECK (committed_part_count >= 0),+ active_part_count INTEGER NOT NULL DEFAULT 0 CHECK (active_part_count >= 0),+ session_epoch BIGINT NOT NULL DEFAULT 0 CHECK (session_epoch >= 0),+ state TEXT NOT NULL CHECK (state IN (+ 'initiated', 'uploading', 'paused', 'finalizing', 'completed',+ 'aborted', 'expired', 'failed'+ )),+ result_resource_id UUID NULL,+ result_version BIGINT NULL,+ result_sha256 TEXT NULL,+ failure_code TEXT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ expires_at TIMESTAMPTZ NOT NULL,+ completed_at TIMESTAMPTZ NULL,+ cleanup_at TIMESTAMPTZ NULL,+ CONSTRAINT gfs_upload_sessions_owner_idempotency_unique+ UNIQUE (owner_subject, drive, idempotency_key)+ );++ CREATE TABLE IF NOT EXISTS gfs_upload_parts (+ upload_id UUID NOT NULL REFERENCES gfs_upload_sessions(upload_id) ON DELETE CASCADE,+ part_number INTEGER NOT NULL CHECK (part_number >= 0),+ offset_bytes BIGINT NOT NULL CHECK (offset_bytes >= 0),+ length_bytes BIGINT NOT NULL CHECK (length_bytes > 0 AND length_bytes <= 16777216),+ sha256 TEXT NOT NULL,+ state TEXT NOT NULL CHECK (state IN ('reserved', 'committed', 'failed')),+ staging_path TEXT NOT NULL,+ lease_epoch BIGINT NOT NULL CHECK (lease_epoch >= 0),+ lease_started_at TIMESTAMPTZ NULL,+ committed_at TIMESTAMPTZ NULL,+ PRIMARY KEY (upload_id, part_number),+ CONSTRAINT gfs_upload_parts_upload_offset_unique UNIQUE (upload_id, offset_bytes)+ );++ CREATE INDEX IF NOT EXISTS gfs_upload_sessions_active_expiry_idx+ ON gfs_upload_sessions (state, expires_at)+ WHERE state IN ('initiated', 'uploading', 'paused', 'finalizing');+ CREATE INDEX IF NOT EXISTS gfs_upload_sessions_owner_state_idx+ ON gfs_upload_sessions (owner_subject, drive, state, updated_at);+ CREATE INDEX IF NOT EXISTS gfs_upload_parts_state_lease_idx+ ON gfs_upload_parts (state, lease_started_at);+ CREATE INDEX IF NOT EXISTS gfs_upload_parts_upload_state_idx+ ON gfs_upload_parts (upload_id, state, part_number);++ REVOKE ALL PRIVILEGES ON TABLE gfs_upload_sessions, gfs_upload_parts FROM PUBLIC;+ REVOKE ALL PRIVILEGES ON TABLE gfs_upload_sessions, gfs_upload_parts FROM gfs_controller_reader;+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE gfs_upload_sessions, gfs_upload_parts TO gfs_controller;+ REVOKE TRUNCATE, REFERENCES, TRIGGER ON TABLE gfs_upload_sessions, gfs_upload_parts FROM gfs_controller;+ `)+}++/** Additive follow-up for installations that already applied migration 0091. */+export async function applyGfsUploadCleanupSchema(db: DbClient): Promise<void> {+ await db.query(+ `ALTER TABLE IF EXISTS gfs_upload_sessions ADD COLUMN IF NOT EXISTS cleanup_at TIMESTAMPTZ NULL`+ )+}diff --git a/control-api/test/db.gfsUploadSessionMigration.test.ts b/control-api/test/db.gfsUploadSessionMigration.test.tsnew file mode 100644index 000000000..e21b8791a--- /dev/null+++ b/control-api/test/db.gfsUploadSessionMigration.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'++describe('0091_gfs_upload_sessions', () => {+ it('is additive and keeps the protocol ceiling separate from the product policy', () => {+ const schema = readFileSync(+ new URL('../src/services/gfsUploadSchema.ts', import.meta.url),+ 'utf8'+ )+ const source = readFileSync(new URL('../src/db.ts', import.meta.url), 'utf8')++ expect(source).toContain("version: '0091_gfs_upload_sessions'")+ expect(schema).toContain('CREATE TABLE IF NOT EXISTS gfs_upload_sessions')+ expect(schema).toContain('CREATE TABLE IF NOT EXISTS gfs_upload_parts')+ expect(schema).toContain('expected_bytes BETWEEN 0 AND 1073741824')+ expect(schema).toContain('part_bytes BETWEEN 1048576 AND 16777216')+ expect(schema).toContain('part_count BETWEEN 0 AND 1024')+ expect(schema).toContain('UNIQUE (owner_subject, drive, idempotency_key)')+ expect(schema).toContain('UNIQUE (upload_id, offset_bytes)')+ expect(schema).toContain(+ 'REVOKE ALL PRIVILEGES ON TABLE gfs_upload_sessions, gfs_upload_parts FROM PUBLIC'+ )+ expect(schema).toContain(+ 'REVOKE ALL PRIVILEGES ON TABLE gfs_upload_sessions, gfs_upload_parts FROM gfs_controller_reader'+ )+ expect(schema).toContain(+ 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE gfs_upload_sessions, gfs_upload_parts TO gfs_controller'+ )+ expect(schema).not.toMatch(/DROP\s+(TABLE|COLUMN)/i)+ expect(schema).not.toContain('209715200')+ })+})diff --git a/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.tsindex a8119eba7..85dbcc49b 100644--- a/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts+++ b/control-api/test/db.pluginWorkloadSdkTraceValidatorMigration.test.ts@@ -23,8 +23,12 @@ describe('Plugin Workload SDK runtime-contract reconciliation migration', () =>candidate => candidate.version === '0090_plugin_workload_sdk_runtime_contract_reconciliation')expect(migration).toBeDefined()- expect(CONTROL_API_MIGRATIONS.at(-2)?.version).toBe(- '0089_plugin_workload_sdk_credential_ticket_runtime_access'+ const credentialTicketIndex = CONTROL_API_MIGRATIONS.findIndex(+ candidate => candidate.version === '0089_plugin_workload_sdk_credential_ticket_runtime_access'+ )+ expect(credentialTicketIndex).toBeGreaterThanOrEqual(0)+ expect(CONTROL_API_MIGRATIONS[credentialTicketIndex + 1]?.version).toBe(+ '0090_plugin_workload_sdk_runtime_contract_reconciliation')clientQuery.mockImplementation(async (sql: string) => {diff --git a/control-api/test/deploy.gfsProvisioning.test.ts b/control-api/test/deploy.gfsProvisioning.test.tsindex 587291b33..ee310442d 100644--- a/control-api/test/deploy.gfsProvisioning.test.ts+++ b/control-api/test/deploy.gfsProvisioning.test.ts@@ -101,6 +101,14 @@ describe('deploy/scripts/provision-gfs-db.sh', () => {expect(script).toContain('pg_auth_members')expect(script).toContain("has_table_privilege(:'role_name', 'gfs_resources', 'INSERT')")expect(script).toContain("has_table_privilege(:'role_name', 'gfs_blob_manifests', 'DELETE')")+ expect(script).toContain("has_table_privilege(:'role_name', 'gfs_upload_sessions', 'INSERT')")+ expect(script).toContain("has_table_privilege(:'role_name', 'gfs_upload_parts', 'DELETE')")+ expect(script).toContain(+ "NOT has_table_privilege(:'role_name', 'gfs_upload_sessions', 'TRUNCATE,REFERENCES,TRIGGER')"+ )+ expect(script).toContain(+ "NOT has_table_privilege(:'role_name', 'gfs_upload_parts', 'SELECT,INSERT,UPDATE,DELETE,TRUNCATE,REFERENCES,TRIGGER')"+ )expect(script).toContain("has_column_privilege(:'role_name', 'control_admin_users', 'id', 'SELECT')")diff --git a/control-api/test/gfsUploadSession.realPostgres.integration.test.ts b/control-api/test/gfsUploadSession.realPostgres.integration.test.tsnew file mode 100644index 000000000..60d84dc67--- /dev/null+++ b/control-api/test/gfsUploadSession.realPostgres.integration.test.ts@@ -0,0 +1,387 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { createHash, randomBytes, randomUUID } from 'node:crypto'+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { Readable } from 'node:stream'+import { Pool } from 'pg'+import type { GfsUploadConfig } from '../../gfs-controller/src/config.js'+import { PgTransactor } from '../../gfs-controller/src/db/writeStore.js'+import type {+ TransactionOptions,+ Transactor,+ TxClient,+} from '../../gfs-controller/src/db/writeStore.js'+import { partGeometry } from '../../gfs-controller/src/upload/protocol.js'+import {+ GfsUploadSessionService,+ type UploadSessionServiceDeps,+} from '../../gfs-controller/src/upload/uploadSession.js'+import { initDb } from '../src/db.js'++const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+const describeRealPostgres = adminUrl ? describe : describe.skip++function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+}++function quoteIdent(value: string): string {+ return `"${value.replace(/"/g, '""')}"`+}++function checksum(value: Buffer): string {+ return createHash('sha256').update(value).digest('hex')+}++class HoldBeforeCommitTransactor implements Transactor {+ private transactionCount = 0+ private readyResolve!: () => void+ private releaseResolve!: () => void+ readonly ready = new Promise<void>(resolve => {+ this.readyResolve = resolve+ })+ private readonly releaseGate = new Promise<void>(resolve => {+ this.releaseResolve = resolve+ })++ constructor(private readonly delegate: Transactor) {}++ release(): void {+ this.releaseResolve()+ }++ async transaction<T>(+ fn: (client: TxClient) => Promise<T>,+ options?: TransactionOptions+ ): Promise<T> {+ this.transactionCount += 1+ // create/reservation use the first transaction. The second is the part+ // commit transaction, and is held before it can acquire the session row.+ if (this.transactionCount === 2) {+ this.readyResolve()+ await this.releaseGate+ }+ return this.delegate.transaction(fn, options)+ }+}++const CONFIG: GfsUploadConfig = {+ productMaxFileBytes: 209715200,+ protocolMaxFileBytes: 1073741824,+ preferredPartBytes: 1048576,+ maxPartBytes: 1048576,+ maxPartCount: 1024,+ maxConcurrentPartsPerSession: 4,+ maxConcurrentPartStreamsGlobal: 16,+ maxActivePerSubject: 8,+ maxActiveGlobal: 32,+ maxConcurrentFinalizations: 1,+ minFreeBytes: 0,+ instabilityFailureThreshold: 3,+ fallbackConcurrency: 2,+ sessionTtlSeconds: 86400,+ partTimeoutMs: 300000,+ finalizeTimeoutMs: 600000,+ stalePartLeaseMs: 600000,+ receiptRetentionSeconds: 86400,+ enabled: true,+}++describeRealPostgres('GFS Upload v2 session engine on real PostgreSQL', () => {+ const database = `gfs_upload_session_${randomBytes(6).toString('hex')}`+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ const drive = `upload-t1-${randomBytes(4).toString('hex')}`+ const owner = `user-${randomBytes(4).toString('hex')}`+ let adminPool: Pool+ let pool: Pool+ let tempRoot: string+ let uploads: GfsUploadSessionService++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)+ pool = new Pool({ connectionString })+ await initDb({ connect: () => pool.connect() })+ tempRoot = await mkdtemp(join(tmpdir(), 'gfs-upload-t1-'))+ const deps: UploadSessionServiceDeps = {+ db: pool,+ tx: new PgTransactor(pool),+ blobs: { availableBytes: async () => 10n ** 12n } as never,+ storageMountPath: tempRoot,+ config: CONFIG,+ }+ uploads = new GfsUploadSessionService(deps)+ }, 60_000)++ afterAll(async () => {+ await pool+ ?.query('DELETE FROM gfs_upload_sessions WHERE drive = $1', [drive])+ .catch(() => undefined)+ await pool?.end()+ await rm(tempRoot, { recursive: true, force: true }).catch(() => undefined)+ if (!adminPool) return+ await adminPool.query(+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = $1 AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)+ await adminPool.end()+ })++ it('serializes concurrent idempotent creates to one session and rejects a changed fingerprint', async () => {+ const idempotencyKey = randomUUID()+ const base = {+ drive,+ ownerSubject: owner,+ primarySubject: owner,+ operation: 'create' as const,+ parentRid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ name: 'concurrent.bin',+ sizeBytes: 2 * CONFIG.preferredPartBytes,+ idempotencyKey,+ }+ const results = await Promise.all([uploads.create({ ...base }), uploads.create({ ...base })])+ expect(results.filter(result => result.created)).toHaveLength(1)+ expect(new Set(results.map(result => result.session.uploadId)).size).toBe(1)+ await expect(uploads.create({ ...base, name: 'different.bin' })).rejects.toMatchObject({+ code: 'idempotency_conflict',+ })+ const count = await pool.query(+ `SELECT count(*)::int AS count FROM gfs_upload_sessions WHERE drive = $1 AND idempotency_key = $2`,+ [drive, idempotencyKey]+ )+ expect(count.rows[0]?.count).toBe(1)+ })++ it('commits indexed parts out of order, paginates status, and deduplicates replay bytes', async () => {+ const created = await uploads.create({+ drive,+ ownerSubject: owner,+ primarySubject: owner,+ operation: 'create',+ parentRid: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',+ name: 'out-of-order.bin',+ sizeBytes: 2 * CONFIG.preferredPartBytes,+ idempotencyKey: randomUUID(),+ })+ const part0 = Buffer.alloc(CONFIG.preferredPartBytes, 0x10)+ const part1 = Buffer.alloc(CONFIG.preferredPartBytes, 0x20)+ const g0 = partGeometry(+ { expectedBytes: 2 * CONFIG.preferredPartBytes, partBytes: CONFIG.preferredPartBytes },+ 0+ )+ const g1 = partGeometry(+ { expectedBytes: 2 * CONFIG.preferredPartBytes, partBytes: CONFIG.preferredPartBytes },+ 1+ )+ const first = await uploads.putPart(+ created.session.uploadId,+ g1,+ checksum(part1),+ Readable.from([part1]) as never,+ { drive, ownerSubject: owner, primarySubject: owner }+ )+ expect(first.session.contiguousBytes).toBe(0)+ const page = await uploads.status(+ created.session.uploadId,+ { drive, ownerSubject: owner, primarySubject: owner },+ { limit: 1 }+ )+ expect(page.parts).toHaveLength(1)+ expect(page.parts[0]?.partNumber).toBe(1)+ expect(page.nextCursor).toBeNull()+ const second = await uploads.putPart(+ created.session.uploadId,+ g0,+ checksum(part0),+ Readable.from([part0]) as never,+ { drive, ownerSubject: owner, primarySubject: owner }+ )+ expect(second.session.contiguousBytes).toBe(2 * CONFIG.preferredPartBytes)+ expect(second.session.committedPartCount).toBe(2)++ const replay = await uploads.putPart(+ created.session.uploadId,+ g1,+ checksum(part1),+ Readable.from([part1]) as never,+ { drive, ownerSubject: owner, primarySubject: owner }+ )+ expect(replay.part.partNumber).toBe(1)+ const rows = await pool.query(+ `SELECT state, count(*)::int AS count FROM gfs_upload_parts WHERE upload_id = $1 GROUP BY state`,+ [created.session.uploadId]+ )+ expect(rows.rows).toEqual(expect.arrayContaining([{ state: 'committed', count: 2 }]))+ })++ it('does not disclose a session to another owner and makes cancel terminal', async () => {+ const created = await uploads.create({+ drive,+ ownerSubject: owner,+ primarySubject: owner,+ operation: 'create',+ parentRid: 'cccccccccccccccccccccccccccccccc',+ name: 'cancel.bin',+ sizeBytes: CONFIG.preferredPartBytes,+ idempotencyKey: randomUUID(),+ })+ const foreign = { drive, ownerSubject: `${owner}-foreign`, primarySubject: `${owner}-foreign` }+ await expect(uploads.get(created.session.uploadId, foreign)).rejects.toMatchObject({+ code: 'not_found',+ })+ await uploads.cancel(created.session.uploadId, {+ drive,+ ownerSubject: owner,+ primarySubject: owner,+ })+ await expect(+ uploads.get(created.session.uploadId, { drive, ownerSubject: owner, primarySubject: owner })+ ).rejects.toMatchObject({ code: 'upload_aborted' })+ const row = await pool.query(+ `SELECT state, active_part_count FROM gfs_upload_sessions WHERE upload_id = $1`,+ [created.session.uploadId]+ )+ expect(row.rows[0]).toEqual({ state: 'aborted', active_part_count: 0 })+ const parts = await pool.query(+ `SELECT count(*)::int AS count FROM gfs_upload_parts WHERE upload_id = $1`,+ [created.session.uploadId]+ )+ expect(parts.rows[0]?.count).toBe(0)+ })++ it('fences a part commit that races with cancel before the commit transaction starts', async () => {+ const base = new GfsUploadSessionService({+ db: pool,+ tx: new PgTransactor(pool),+ blobs: { availableBytes: async () => 10n ** 12n } as never,+ storageMountPath: tempRoot,+ config: CONFIG,+ })+ const created = await base.create({+ drive,+ ownerSubject: owner,+ primarySubject: owner,+ operation: 'create',+ parentRid: 'dddddddddddddddddddddddddddddddd',+ name: 'cancel-race.bin',+ sizeBytes: CONFIG.preferredPartBytes,+ idempotencyKey: randomUUID(),+ })+ const gate = new HoldBeforeCommitTransactor(new PgTransactor(pool))+ const uploadsWithGate = new GfsUploadSessionService({+ db: pool,+ tx: gate,+ blobs: { availableBytes: async () => 10n ** 12n } as never,+ storageMountPath: tempRoot,+ config: CONFIG,+ })+ const bytes = Buffer.alloc(CONFIG.preferredPartBytes, 0x44)+ const put = uploadsWithGate.putPart(+ created.session.uploadId,+ partGeometry(+ { expectedBytes: CONFIG.preferredPartBytes, partBytes: CONFIG.preferredPartBytes },+ 0+ ),+ checksum(bytes),+ Readable.from([bytes]) as never,+ { drive, ownerSubject: owner, primarySubject: owner }+ )+ await gate.ready++ const cancel = uploadsWithGate.cancel(created.session.uploadId, {+ drive,+ ownerSubject: owner,+ primarySubject: owner,+ })+ const deadline = Date.now() + 2000+ while (Date.now() < deadline) {+ const state = await pool.query(`SELECT state FROM gfs_upload_sessions WHERE upload_id = $1`, [+ created.session.uploadId,+ ])+ if (state.rows[0]?.state === 'aborted') break+ await new Promise<void>(resolve => setImmediate(resolve))+ }+ const state = await pool.query(`SELECT state FROM gfs_upload_sessions WHERE upload_id = $1`, [+ created.session.uploadId,+ ])+ expect(state.rows[0]?.state).toBe('aborted')+ gate.release()+ await expect(put).rejects.toMatchObject({ code: 'upload_aborted' })+ await expect(cancel).resolves.toBeUndefined()+ const parts = await pool.query(+ `SELECT count(*)::int AS count FROM gfs_upload_parts WHERE upload_id = $1`,+ [created.session.uploadId]+ )+ expect(parts.rows[0]?.count).toBe(0)+ })++ it('rejects cancel during finalization and leaves one completed receipt', async () => {+ let finalizerStarted!: () => void+ let releaseFinalizer!: () => void+ const started = new Promise<void>(resolve => {+ finalizerStarted = resolve+ })+ const release = new Promise<void>(resolve => {+ releaseFinalizer = resolve+ })+ const uploadsWithFinalizer = new GfsUploadSessionService({+ db: pool,+ tx: new PgTransactor(pool),+ blobs: { availableBytes: async () => 10n ** 12n } as never,+ storageMountPath: tempRoot,+ config: CONFIG,+ finalize: async session => {+ finalizerStarted()+ await release+ return {+ resourceId: session.uploadId,+ version: 0,+ sha256: 'a'.repeat(64),+ }+ },+ })+ const created = await uploadsWithFinalizer.create({+ drive,+ ownerSubject: owner,+ primarySubject: owner,+ operation: 'create',+ parentRid: 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',+ name: 'finalize-race.bin',+ sizeBytes: 0,+ idempotencyKey: randomUUID(),+ })+ const complete = uploadsWithFinalizer.complete(created.session.uploadId, {+ drive,+ ownerSubject: owner,+ primarySubject: owner,+ })+ await started+ await expect(+ uploadsWithFinalizer.cancel(created.session.uploadId, {+ drive,+ ownerSubject: owner,+ primarySubject: owner,+ })+ ).rejects.toMatchObject({ code: 'upload_finalizing' })+ releaseFinalizer()+ const receipt = await complete+ expect(receipt.state).toBe('completed')+ const row = await pool.query(+ `SELECT state, result_resource_id, result_version FROM gfs_upload_sessions WHERE upload_id = $1`,+ [created.session.uploadId]+ )+ expect(row.rows[0]).toMatchObject({+ state: 'completed',+ result_resource_id: created.session.uploadId,+ result_version: '0',+ })+ })+})diff --git a/control-api/test/network.gateway.intent.test.ts b/control-api/test/network.gateway.intent.test.tsindex 77ce3debc..a3a77802e 100644--- a/control-api/test/network.gateway.intent.test.ts+++ b/control-api/test/network.gateway.intent.test.ts@@ -343,11 +343,11 @@ describe('network/gateway intent (manifest-level)', () => {expect(funnelConf).toContain('client_max_body_size 25165824;')})- it('keeps the whole GFS upload cap chain homologous (client × 4/3 ≤ gfsc write cap)', () => {- // The 16 MB upload feature rests on an invariant spread across 5 files and 2- // repos, but only the funnel literal was machine-checked. This asserts the rest- // of the chain so deleting the HCC env or drifting a client cap fails loud in CI- // instead of silently 413-ing a 16 MB file the client said would fit.+ it('keeps the GFS v2 part cap chain below the gateway request cap', () => {+ // Upload v2 is indexed binary streaming: the 200 MiB product boundary is+ // aggregate session metadata, while every request remains <=16 MiB. The+ // old base64 ×4/3 invariant belongs only to the legacy JSON path and must not+ // constrain the v2 product limit.const GFSC_WRITE_CAP = 25165824 // 24 MiB — the funnel + gfsc authoritative cap// 1. gfsc's write cap is actually plumbed to the pod. Without this env gfsc@@ -363,21 +363,27 @@ describe('network/gateway intent (manifest-level)', () => {).not.toBeNull()expect(Number(gfscCapMatch![1])).toBe(GFSC_WRITE_CAP)- // 2. Both client caps are equal (web and desktop advertise the same limit).- const parseClientCap = (relPath: string): number => {+ // 2. Both clients advertise the same hard binary part cap and product cap.+ const parseClientCaps = (relPath: string): { product: number; part: number } => {const src = read(relPath)- const m = src.match(/GFS_FILE_UPLOAD_MAX_BYTES\s*=\s*([0-9*\s]+)/)- expect(m, `GFS_FILE_UPLOAD_MAX_BYTES not found in ${relPath}`).not.toBeNull()+ const productMatch = src.match(/GFS_FILE_UPLOAD_MAX_BYTES\s*=\s*([0-9*\s]+)/)+ const partMatch = src.match(/GFS_FILE_UPLOAD_MAX_PART_BYTES\s*=\s*([0-9*\s]+)/)+ expect(productMatch, `GFS_FILE_UPLOAD_MAX_BYTES not found in ${relPath}`).not.toBeNull()+ expect(partMatch, `GFS_FILE_UPLOAD_MAX_PART_BYTES not found in ${relPath}`).not.toBeNull()// Only digits/`*`/spaces are matched, so evaluating the arithmetic is safe.- return Number(m![1].split('*').reduce((acc, n) => acc * Number(n.trim()), 1))+ const evaluate = (value: string): number =>+ Number(value.split('*').reduce((acc, n) => acc * Number(n.trim()), 1))+ return { product: evaluate(productMatch![1]), part: evaluate(partMatch![1]) }}- const webCap = parseClientCap('../../control-ui/app/constants/gfsFileUpload.ts')- const desktopCap = parseClientCap('../../desktop-app/ui/src/constants/gfsFileUpload.ts')- expect(webCap).toBe(desktopCap)-- // 3. The base64-inflated client cap (× 4/3) fits under the gfsc write cap, with- // headroom for the JSON envelope.- expect(Math.ceil((webCap * 4) / 3)).toBeLessThan(GFSC_WRITE_CAP)+ const webCaps = parseClientCaps('../../control-ui/app/constants/gfsFileUpload.ts')+ const desktopCaps = parseClientCaps('../../desktop-app/ui/src/constants/gfsFileUpload.ts')+ expect(webCaps).toEqual(desktopCaps)+ expect(webCaps.product).toBe(209715200)+ expect(webCaps.part).toBe(16777216)++ // 3. A v2 binary request fits below the internal 24 MiB cap with headroom;+ // the aggregate 200 MiB value never becomes a single request body.+ expect(webCaps.part).toBeLessThan(GFSC_WRITE_CAP)})it('keeps control-api memory at >=768Mi in base AND the minikube overlay (RC3 OOM guard)', () => {diff --git a/control-api/test/routes.gfsProxy.test.ts b/control-api/test/routes.gfsProxy.test.tsindex b4322630c..ae76ecfab 100644--- a/control-api/test/routes.gfsProxy.test.ts+++ b/control-api/test/routes.gfsProxy.test.ts@@ -73,6 +73,30 @@ describe('/api/v1/gfs/proxy', () => {)})+ it('sends upload capabilities and status reads to the writer service', async () => {+ const fetchMock = vi.fn(+ async () =>+ new Response(JSON.stringify({ ok: true }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })+ )+ vi.stubGlobal('fetch', fetchMock)++ const app = await buildApp()+ const status = await request(app).get(+ '/api/v1/gfs/proxy/v1/uploads/01234567-89ab-cdef-0123-456789abcdef/status?limit=256'+ )+ const capabilities = await request(app).get('/api/v1/gfs/proxy/v1/capabilities')++ expect(status.status).toBe(200)+ expect(capabilities.status).toBe(200)+ expect(fetchMock.mock.calls[0][0]).toBe(+ 'http://gfsc-writer.gfs.svc:8087/v1/uploads/01234567-89ab-cdef-0123-456789abcdef/status?limit=256'+ )+ expect(fetchMock.mock.calls[1][0]).toBe('http://gfsc-writer.gfs.svc:8087/v1/capabilities')+ })+it('sends mutations to the writer service', async () => {const fetchMock = vi.fn(async () =>diff --git a/control-ui/app/constants/gfsFileUpload.ts b/control-ui/app/constants/gfsFileUpload.tsindex 32c19ec76..7e795d01e 100644--- a/control-ui/app/constants/gfsFileUpload.ts+++ b/control-ui/app/constants/gfsFileUpload.ts@@ -1,5 +1,8 @@-// Raw-file upload cap. base64 inflates this ×1.34 on the wire, so 16MiB → ~22.4MB-// body, which must stay under gfsc's GFS_MAX_WRITE_BODY_BYTES (24MiB, set via the-// host-context-controller gfsc template). Raise all three in step.-export const GFS_FILE_UPLOAD_MAX_BYTES = 16 * 1024 * 1024-export const GFS_FILE_UPLOAD_MAX_MEGABYTES = 16+// Product hard ceiling. Upload v2 sends indexed binary parts, so the 200 MiB+// file limit is independent of the 8 MiB preferred / 16 MiB hard part limit.+export const GFS_FILE_UPLOAD_MAX_BYTES = 200 * 1024 * 1024+export const GFS_FILE_UPLOAD_MAX_MEGABYTES = 200+export const GFS_FILE_UPLOAD_PREFERRED_PART_BYTES = 8 * 1024 * 1024+export const GFS_FILE_UPLOAD_MAX_PART_BYTES = 16 * 1024 * 1024+export const GFS_FILE_UPLOAD_DEFAULT_CONCURRENCY = 4+export const GFS_FILE_UPLOAD_FALLBACK_CONCURRENCY = 2diff --git a/control-ui/app/control-api/[...path]/route.ts b/control-ui/app/control-api/[...path]/route.tsindex bf38a65e1..27bb44bf7 100644--- a/control-ui/app/control-api/[...path]/route.ts+++ b/control-ui/app/control-api/[...path]/route.ts@@ -5,6 +5,7 @@ export const dynamic = 'force-dynamic'const CONTROL_API_INTERNAL_URL = process.env.CONTROL_API_INTERNAL_URL || 'http://127.0.0.1:8090'const DEFAULT_CONTROL_API_PROXY_TIMEOUT_MS = 30_000+const DEFAULT_GFS_UPLOAD_PROXY_TIMEOUT_MS = 600_000// setTimeout / AbortSignal.timeout reject non-integers and values above the 32-bit// signed ceiling (ERR_OUT_OF_RANGE), so an out-of-range env value must NOT reach them.@@ -28,6 +29,14 @@ function resolveProxyTimeoutMs(): number {: DEFAULT_CONTROL_API_PROXY_TIMEOUT_MS}+function resolveGfsUploadProxyTimeoutMs(): number {+ const raw = process.env.CONTROL_UI_GFS_UPLOAD_PROXY_TIMEOUT_MS+ const parsed = raw ? Number(raw) : Number.NaN+ return Number.isInteger(parsed) && parsed > 0 && parsed <= MAX_PROXY_TIMEOUT_MS+ ? parsed+ : DEFAULT_GFS_UPLOAD_PROXY_TIMEOUT_MS+}+// Runtime-configurable cap on the request body this proxy will buffer, homologous// with the gfsc write cap (GFS_MAX_WRITE_BODY_BYTES, 24MiB). This handler runs// BEFORE any auth (auth lives in control-api, downstream), so without a cap an@@ -122,6 +131,12 @@ function buildUpstreamUrl(req: NextRequest, path: string[]): string {return `${base}${upstreamPath}${req.nextUrl.search}`}+function isGfsUploadRoute(req: NextRequest, path: string[]): boolean {+ if (req.method !== 'PUT') return false+ const pathname = `/${path.join('/')}`+ return /^\/api\/v1\/gfs\/proxy\/v1\/uploads\/[0-9a-f-]{36}\/parts\/[0-9]+$/i.test(pathname)+}+function copyRequestHeaders(req: NextRequest): Headers {const headers = new Headers()req.headers.forEach((value, key) => {@@ -165,10 +180,22 @@ async function proxyControlApi(const path = Array.isArray(params.path) ? params.path : []const upstreamUrl = buildUpstreamUrl(req, path)const headers = copyRequestHeaders(req)+ const rawUpload = isGfsUploadRoute(req, path)const hasBody = req.method !== 'GET' && req.method !== 'HEAD'let body: ArrayBuffer | undefined- if (hasBody) {+ let streamingBody: ReadableStream<Uint8Array> | null = null+ if (rawUpload) {+ const declaredChunk = Number(req.headers.get('upload-chunk-length'))+ if (+ !Number.isSafeInteger(declaredChunk) ||+ declaredChunk <= 0 ||+ declaredChunk > 16 * 1024 * 1024+ ) {+ return NextResponse.json({ error: 'payload_too_large' }, { status: 413 })+ }+ streamingBody = req.body+ } else if (hasBody) {const cap = resolveMaxBodyBytes()// Fast path: reject a declared-oversize length before reading a single byte.const declared = Number(req.headers.get('content-length'))@@ -184,7 +211,9 @@ async function proxyControlApi(// Only body-bearing methods (uploads/mutations) get the proxy timeout. GET/HEAD —// including long-lived SSE notification streams — rely solely on the client's own// abort signal, so this timeout can never cut a streaming response.- const timeoutSignal = hasBody ? AbortSignal.timeout(resolveProxyTimeoutMs()) : undefined+ const timeoutSignal = hasBody+ ? AbortSignal.timeout(rawUpload ? resolveGfsUploadProxyTimeoutMs() : resolveProxyTimeoutMs())+ : undefinedconst signal = timeoutSignal? typeof AbortSignal.any === 'function'? AbortSignal.any([timeoutSignal, req.signal])@@ -192,14 +221,16 @@ async function proxyControlApi(: req.signaltry {- const upstream = await fetch(upstreamUrl, {+ const fetchInit: RequestInit & { duplex?: 'half' } = {method: req.method,headers,- body,+ body: rawUpload ? streamingBody : body,cache: 'no-store',redirect: 'manual',signal,- })+ }+ if (rawUpload) fetchInit.duplex = 'half'+ const upstream = await fetch(upstreamUrl, fetchInit)return new NextResponse(upstream.body, {status: upstream.status,diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex 897bf92a8..18c2d47f8 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -5384,6 +5384,29 @@ textarea.cu-input {line-height: 1.3;}+.cu-upload-file-flow__progress {+ display: grid;+ gap: var(--cu-space-2);+ padding: var(--cu-space-3);+ border: 1px solid var(--cu-border-subtle);+ border-radius: var(--cu-radius-sm);+ background: var(--cu-bg-elevated);+}++.cu-upload-file-flow__progress-head {+ display: flex;+ justify-content: space-between;+ gap: var(--cu-space-2);+ color: var(--cu-text-muted);+ font-size: 0.8125rem;+}++.cu-upload-file-flow__progress progress {+ width: 100%;+ height: 0.5rem;+ accent-color: var(--cu-accent);+}+.cu-upload-file-flow__destination code {color: var(--cu-text);overflow-wrap: anywhere;diff --git a/control-ui/components/FileUploadModal/index.tsx b/control-ui/components/FileUploadModal/index.tsxindex 650d03fde..b336713a5 100644--- a/control-ui/components/FileUploadModal/index.tsx+++ b/control-ui/components/FileUploadModal/index.tsx@@ -12,9 +12,13 @@ export function FileUploadModal({file,fileSummary,guidance,+ progress,onClose,+ onCancelUpload,onFileChange,onUpload,+ onPauseUpload,+ onResumeUpload,title = 'Upload file',}: FileUploadModalProps): React.JSX.Element {const inputId = useId()@@ -124,19 +128,81 @@ export function FileUploadModal({Uploads to <code>{destination}</code></p>) : null}++ {progress ? (+ <div+ className="cu-upload-file-flow__progress"+ data-testid="gfs-upload-row"+ data-upload-file-name={file?.name || undefined}+ aria-live="polite"+ >+ <div className="cu-upload-file-flow__progress-head">+ <span>+ {progress.state === 'paused'+ ? 'Paused'+ : progress.state === 'completed'+ ? 'Complete'+ : progress.state === 'failed'+ ? 'Upload failed'+ : 'Uploading'}+ </span>+ <span>+ {formatProgressBytes(progress.uploadedBytes)} /{' '}+ {formatProgressBytes(progress.totalBytes)}+ </span>+ </div>+ <progress+ aria-label={file ? `Upload progress for ${file.name}` : 'Upload progress'}+ aria-valuemin={0}+ aria-valuemax={Math.max(progress.totalBytes, 1)}+ aria-valuenow={Math.min(progress.uploadedBytes, Math.max(progress.totalBytes, 1))}+ max={Math.max(progress.totalBytes, 1)}+ value={Math.min(progress.uploadedBytes, Math.max(progress.totalBytes, 1))}+ />+ </div>+ ) : null}</div><footer className="cu-modal-panel__foot">- <Button size="sm" variant="ghost" disabled={busy} onClick={onClose}>- Cancel- </Button>- <Button variant="primary" disabled={busy || !file} onClick={onUpload}>- {busy ? 'Uploading…' : 'Upload'}- </Button>+ {busy && onCancelUpload ? (+ <Button size="sm" variant="danger" onClick={onCancelUpload}>+ Cancel upload+ </Button>+ ) : (+ <Button size="sm" variant="ghost" disabled={busy} onClick={onClose}>+ Cancel+ </Button>+ )}+ {progress?.state === 'paused' && onResumeUpload ? (+ <Button variant="primary" disabled={!file} onClick={onResumeUpload}>+ Resume+ </Button>+ ) : progress?.state === 'uploading' && onPauseUpload ? (+ <Button variant="ghost" onClick={onPauseUpload}>+ Pause+ </Button>+ ) : (+ <Button variant="primary" disabled={busy || !file} onClick={onUpload}>+ {busy ? 'Uploading…' : 'Upload'}+ </Button>+ )}</footer></section></div>)}+function formatProgressBytes(bytes: number): string {+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'+ if (bytes < 1024) return `${Math.round(bytes)} B`+ const units = ['KiB', 'MiB', 'GiB']+ let value = bytes / 1024+ let index = 0+ while (value >= 1024 && index < units.length - 1) {+ value /= 1024+ index += 1+ }+ return `${value >= 10 ? value.toFixed(0) : value.toFixed(1)} ${units[index]}`+}+export type { FileUploadModalProps } from './types'diff --git a/control-ui/components/FileUploadModal/types.ts b/control-ui/components/FileUploadModal/types.tsindex 8b9072504..dba94cc93 100644--- a/control-ui/components/FileUploadModal/types.ts+++ b/control-ui/components/FileUploadModal/types.ts@@ -4,8 +4,24 @@ export interface FileUploadModalProps {file: File | nullfileSummary?: stringguidance?: string+ progress?: {+ uploadedBytes: number+ totalBytes: number+ state:+ | 'initiated'+ | 'uploading'+ | 'paused'+ | 'finalizing'+ | 'canceling'+ | 'completed'+ | 'aborted'+ | 'failed'+ }onClose: () => void+ onCancelUpload?: () => voidonFileChange: (file: File | null) => voidonUpload: () => void+ onPauseUpload?: () => void+ onResumeUpload?: () => voidtitle?: string}diff --git a/control-ui/components/GfsBrowser.tsx b/control-ui/components/GfsBrowser.tsxindex 93cd82abf..a8874a4c4 100644--- a/control-ui/components/GfsBrowser.tsx+++ b/control-ui/components/GfsBrowser.tsx@@ -8,8 +8,17 @@ import { IconFolder, IconServer } from '@components/Sidebar/icons'import { useToast } from '@components/Toast'import { IconChevronRight, IconDownload, IconPaperclip, IconUpload, IconX } from '@components/icons'import { Button, TextInput } from '@components/ui'-import { GFS_UPLOAD_TIMEOUT_MS, apiGet, apiSend, gfsDownload, isSilentApiError } from '@lib/api'-import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'+import { apiGet, apiSend, gfsDownload, isSilentApiError } from '@lib/api'+import {+ GfsUploadCapabilityError,+ type GfsUploadJob,+ type GfsUploadJobInput,+ type GfsUploadJobSnapshot,+ assertGfsFileUploadSize,+ createGfsUploadJob,+ uploadGfsFile,+ uploadGfsFileLegacy,+} from '@lib/gfsFileUpload'import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'import { normalizeGfsResourceName } from '@lib/gfsResourceName'@@ -44,6 +53,56 @@ interface Crumb {}const DRIVE = 'main'+const PENDING_GFS_UPLOAD_KEY = 'evenfire:gfs-upload-v2:pending'++interface PendingGfsUpload {+ uploadId?: string+ idempotencyKey?: string+ fileName: string+ fileSize: number+ lastModified: number+ target: {+ operation: 'create' | 'replace'+ parentRid?: string+ resourceRid?: string+ ifMatch?: number+ }+ name: string+}++function readPendingGfsUpload(): PendingGfsUpload | null {+ if (typeof window === 'undefined') return null+ try {+ const parsed = JSON.parse(+ window.localStorage.getItem(PENDING_GFS_UPLOAD_KEY) || 'null'+ ) as Partial<PendingGfsUpload> | null+ if (+ !parsed ||+ (typeof parsed.uploadId !== 'string' && typeof parsed.idempotencyKey !== 'string') ||+ typeof parsed.fileName !== 'string' ||+ typeof parsed.fileSize !== 'number' ||+ typeof parsed.lastModified !== 'number' ||+ !parsed.target ||+ typeof parsed.name !== 'string'+ )+ return null+ return parsed as PendingGfsUpload+ } catch {+ return null+ }+}++function persistPendingGfsUpload(record: PendingGfsUpload): void {+ if (typeof window === 'undefined') return+ window.localStorage.setItem(PENDING_GFS_UPLOAD_KEY, JSON.stringify(record))+}++function clearPendingGfsUpload(uploadId?: string): void {+ if (typeof window === 'undefined') return+ const current = readPendingGfsUpload()+ if (!uploadId || current?.uploadId === uploadId)+ window.localStorage.removeItem(PENDING_GFS_UPLOAD_KEY)+}function formatBytes(bytes: number): string {if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'@@ -58,19 +117,6 @@ function formatBytes(bytes: number): string {return `${value >= 10 ? value.toFixed(0) : value.toFixed(1)} ${unit}`}-async function fileToEncodedData(file: File): Promise<string> {- assertGfsFileUploadSize(file.size)- const bytes = new Uint8Array(await file.arrayBuffer())- assertGfsFileUploadSize(bytes.byteLength)- let binary = ''- const chunkSize = 0x8000- for (let offset = 0; offset < bytes.length; offset += chunkSize) {- const chunk = bytes.subarray(offset, offset + chunkSize)- binary += String.fromCharCode(...chunk)- }- return btoa(binary)-}-/*** Operator browser for the Global File System. It lists the drive tree through* control-api and uses the operator-scoped GFS proxy for create, upload,@@ -110,6 +156,8 @@ export function GfsBrowser(): React.JSX.Element {const [uploadOpen, setUploadOpen] = useState(false)const [uploadCandidate, setUploadCandidate] = useState<File | null>(null)const [uploading, setUploading] = useState(false)+ const uploadJobRef = useRef<GfsUploadJob | null>(null)+ const [uploadSnapshot, setUploadSnapshot] = useState<GfsUploadJobSnapshot | null>(null)const [dragActive, setDragActive] = useState(false)const [droppedUploadCount, setDroppedUploadCount] = useState(0)const [imagePreview, setImagePreview] = useState<{@@ -228,6 +276,80 @@ export function GfsBrowser(): React.JSX.Element {await load(current)}+ async function uploadWithCompatibility(+ input: GfsUploadJobInput+ ): Promise<'completed' | 'paused'> {+ setUploadCandidate(input.file)+ setUploadOpen(true)+ setUploading(true)+ const job = createGfsUploadJob({+ ...input,+ onProgress: progress => {+ setUploadSnapshot(previous =>+ previous ? { ...previous, uploadedBytes: progress.uploadedBytes } : previous+ )+ input.onProgress?.(progress)+ },+ onState: snapshot => {+ setUploadSnapshot(snapshot)+ input.onState?.(snapshot)+ },+ onPersistPending: record => {+ persistPendingGfsUpload({+ idempotencyKey: record.idempotencyKey,+ fileName: record.fileName,+ fileSize: record.fileSize,+ lastModified: record.lastModified,+ target: record.target,+ name: record.name,+ })+ void input.onPersistPending?.(record)+ },+ onPersist: record => {+ persistPendingGfsUpload({+ uploadId: record.uploadId,+ fileName: record.fileName,+ fileSize: record.fileSize,+ lastModified: record.lastModified,+ target: record.target,+ name: record.name,+ })+ void input.onPersist?.(record)+ },+ onClearPersisted: uploadId => {+ clearPendingGfsUpload(uploadId)+ void input.onClearPersisted?.(uploadId)+ },+ })+ uploadJobRef.current = job+ try {+ const receipt = await job.start()+ if (receipt.state === 'paused') {+ setUploading(false)+ return 'paused'+ }+ setUploadCandidate(null)+ setUploadOpen(false)+ setUploadSnapshot(null)+ uploadJobRef.current = null+ await refreshCurrent()+ return 'completed'+ } catch (error) {+ if (!(error instanceof GfsUploadCapabilityError)) throw error+ showToast('Resumable upload is unavailable; using the legacy 16 MiB path.', { tone: 'info' })+ await uploadGfsFileLegacy(input)+ clearPendingGfsUpload()+ setUploadCandidate(null)+ setUploadOpen(false)+ setUploadSnapshot(null)+ uploadJobRef.current = null+ await refreshCurrent()+ return 'completed'+ } finally {+ setUploading(false)+ }+ }+function openNewFolder(): void {if (!current?.id) returnsetCreateFolderError(null)@@ -261,30 +383,149 @@ export function GfsBrowser(): React.JSX.Element {if (!rid || !file) returnsetUploading(true)try {+ assertGfsFileUploadSize(file.size)const name = await normalizeGfsResourceName(file.name)- await apiSend(- 'POST',- `/api/v1/gfs/proxy/v1/resources/${encodeURIComponent(rid)}/children`,- {- name,- kind: 'file',- contentBase64: await fileToEncodedData(file),+ const target = { operation: 'create' as const, parentRid: rid }+ const pending = readPendingGfsUpload()+ const resumeUploadId =+ pending &&+ pending.fileName === file.name &&+ pending.fileSize === file.size &&+ pending.lastModified === file.lastModified &&+ pending.target.operation === target.operation &&+ pending.target.parentRid === target.parentRid &&+ pending.name === name+ ? pending.uploadId+ : undefined+ const job = createGfsUploadJob({+ file,+ name,+ target,+ resumeUploadId,+ onPersistPending: record => {+ persistPendingGfsUpload({+ idempotencyKey: record.idempotencyKey,+ fileName: record.fileName,+ fileSize: record.fileSize,+ lastModified: record.lastModified,+ target: record.target,+ name: record.name,+ })},- {},- {},- { timeoutMs: GFS_UPLOAD_TIMEOUT_MS }- )+ onProgress: progress => {+ setUploadSnapshot(previous =>+ previous ? { ...previous, uploadedBytes: progress.uploadedBytes } : previous+ )+ },+ onState: snapshot => setUploadSnapshot(snapshot),+ onPersist: record => {+ persistPendingGfsUpload({+ uploadId: record.uploadId,+ fileName: record.fileName,+ fileSize: record.fileSize,+ lastModified: record.lastModified,+ target: record.target,+ name: record.name,+ })+ },+ onClearPersisted: uploadId => clearPendingGfsUpload(uploadId),+ })+ uploadJobRef.current = job+ const receipt = await job.start()+ if (receipt.state === 'paused') {+ setUploading(false)+ return+ }showToast('File uploaded.', { tone: 'success' })setUploadCandidate(null)setUploadOpen(false)+ setUploadSnapshot(null)+ uploadJobRef.current = nullawait refreshCurrent()} catch (err) {+ if (uploadJobRef.current?.snapshot().state === 'aborted') return+ if (err instanceof GfsUploadCapabilityError) {+ showToast('Resumable upload is unavailable; using the legacy 16 MiB path.', {+ tone: 'info',+ })+ try {+ const name = await normalizeGfsResourceName(file.name)+ await uploadGfsFileLegacy({ file, name, target: { operation: 'create', parentRid: rid } })+ clearPendingGfsUpload()+ showToast('File uploaded.', { tone: 'success' })+ setUploadCandidate(null)+ setUploadOpen(false)+ setUploadSnapshot(null)+ uploadJobRef.current = null+ await refreshCurrent()+ return+ } catch (legacyError) {+ showToast(legacyError instanceof Error ? legacyError.message : 'Could not upload file.', {+ tone: 'error',+ })+ return+ }+ }showToast(err instanceof Error ? err.message : 'Could not upload file.', { tone: 'error' })} finally {setUploading(false)}}+ async function pauseUpload(): Promise<void> {+ const job = uploadJobRef.current+ if (!job) return+ try {+ await job.pause()+ setUploading(false)+ } catch (err) {+ showToast(err instanceof Error ? err.message : 'Could not pause upload.', { tone: 'error' })+ }+ }++ async function resumeUpload(): Promise<void> {+ const job = uploadJobRef.current+ if (!job) return+ setUploading(true)+ try {+ const receipt = await job.resume()+ if (receipt.state === 'completed') {+ showToast('File uploaded.', { tone: 'success' })+ setUploadCandidate(null)+ setUploadOpen(false)+ setUploadSnapshot(null)+ uploadJobRef.current = null+ await refreshCurrent()+ }+ } catch (err) {+ showToast(err instanceof Error ? err.message : 'Could not resume upload.', { tone: 'error' })+ } finally {+ setUploading(false)+ }+ }++ async function cancelUpload(): Promise<void> {+ const job = uploadJobRef.current+ if (!job) {+ closeUploadModal()+ return+ }+ try {+ await job.cancel()+ setUploading(false)+ setUploadSnapshot(null)+ setUploadCandidate(null)+ setUploadOpen(false)+ uploadJobRef.current = null+ } catch (err) {+ // A finalizer is intentionally not canceled after publication starts;+ // keep the modal open and expose the stable server error so the user can+ // reconcile the receipt instead of presenting a false canceled state.+ showToast(err instanceof Error ? err.message : 'Could not cancel upload.', { tone: 'error' })+ setUploading(false)+ }+ }+function handleGfsDragEnter(event: React.DragEvent<HTMLElement>): void {if (!hasDraggedFiles(event)) returnevent.preventDefault()@@ -334,7 +575,11 @@ export function GfsBrowser(): React.JSX.Element {function closeUploadModal(): void {if (uploading) returnsetUploadOpen(false)- setUploadCandidate(null)+ if (!uploadSnapshot || uploadSnapshot.state !== 'paused') {+ setUploadCandidate(null)+ uploadJobRef.current = null+ setUploadSnapshot(null)+ }}function openManage(child: GfsChild, mode?: 'rename' | 'delete'): void {@@ -368,20 +613,17 @@ export function GfsBrowser(): React.JSX.Element {async function replaceFile(child: GfsChild, file: File | null | undefined): Promise<void> {if (!file) returntry {- await apiSend(- 'PUT',- `/api/v1/gfs/proxy/v1/resources/${encodeURIComponent(child.rid)}/content`,- {- contentBase64: await fileToEncodedData(file),- ifMatch: child.version,- },- {},- {},- { timeoutMs: GFS_UPLOAD_TIMEOUT_MS }- )- showToast('File replaced.', { tone: 'success' })- if (selected?.resourceId === child.resourceId) setSelected(null)- await refreshCurrent()+ const state = await uploadWithCompatibility({+ file,+ name: file.name,+ target: { operation: 'replace', resourceRid: child.rid, ifMatch: child.version },+ })+ if (state === 'completed') {+ showToast('File replaced.', { tone: 'success' })+ if (selected?.resourceId === child.resourceId) setSelected(null)+ } else {+ showToast('Replace paused. Resume it from the upload panel.', { tone: 'info' })+ }} catch (err) {showToast(err instanceof Error ? err.message : 'Could not replace file.', { tone: 'error' })}@@ -394,20 +636,13 @@ export function GfsBrowser(): React.JSX.Element {if (!file || folder.kind !== 'directory') returntry {const name = await normalizeGfsResourceName(file.name)- await apiSend(- 'POST',- `/api/v1/gfs/proxy/v1/resources/${encodeURIComponent(folder.rid)}/children`,- {- name,- kind: 'file',- contentBase64: await fileToEncodedData(file),- },- {},- {},- { timeoutMs: GFS_UPLOAD_TIMEOUT_MS }- )- showToast('File uploaded.', { tone: 'success' })- await refreshCurrent()+ const state = await uploadWithCompatibility({+ file,+ name,+ target: { operation: 'create', parentRid: folder.rid },+ })+ if (state === 'completed') showToast('File uploaded.', { tone: 'success' })+ else showToast('Upload paused. Resume it from the upload panel.', { tone: 'info' })} catch (err) {showToast(err instanceof Error ? err.message : 'Could not upload file.', { tone: 'error' })}@@ -844,10 +1079,22 @@ export function GfsBrowser(): React.JSX.Element {fileSummary={uploadCandidate ? `${formatBytes(uploadCandidate.size)} selected` : undefined}- guidance="GFS uploads are limited to 10 MB per file."+ guidance="GFS uploads are limited to 200 MiB per file; each request is streamed in 8 MiB parts (16 MiB hard maximum)."+ progress={+ uploadSnapshot+ ? {+ uploadedBytes: uploadSnapshot.uploadedBytes,+ totalBytes: uploadSnapshot.totalBytes,+ state: uploadSnapshot.state,+ }+ : undefined+ }+ onCancelUpload={() => void cancelUpload()}onClose={closeUploadModal}onFileChange={setUploadCandidate}onUpload={() => void uploadFile(uploadCandidate)}+ onPauseUpload={() => void pauseUpload()}+ onResumeUpload={() => void resumeUpload()}/>) : null}diff --git a/control-ui/components/__tests__/GfsBrowser.test.tsx b/control-ui/components/__tests__/GfsBrowser.test.tsxindex cac44a273..dabf15c80 100644--- a/control-ui/components/__tests__/GfsBrowser.test.tsx+++ b/control-ui/components/__tests__/GfsBrowser.test.tsx@@ -16,6 +16,7 @@ import {gfsFetchFileBlob,putGfsGrant,} from '@lib/api'+import { createGfsUploadJob, uploadGfsFile } from '@lib/gfsFileUpload'import { normalizeGfsResourceName } from '@lib/gfsResourceName'import { GfsBrowser } from '../GfsBrowser'import { ToastProvider } from '../Toast'@@ -36,6 +37,25 @@ vi.mock('@lib/api', () => ({putGfsGrant: vi.fn(),}))+vi.mock('@lib/gfsFileUpload', async importOriginal => ({+ ...(await importOriginal<typeof import('@lib/gfsFileUpload')>()),+ uploadGfsFile: vi.fn().mockResolvedValue({ state: 'completed' }),+ createGfsUploadJob: vi.fn((input: { file: File; onState?: (snapshot: unknown) => void }) => ({+ start: vi.fn(async () => {+ input.onState?.({+ state: 'completed',+ session: { uploadId: 'test-upload', state: 'completed' },+ uploadedBytes: input.file.size,+ totalBytes: input.file.size,+ })+ return { state: 'completed', uploadId: 'test-upload' }+ }),+ pause: vi.fn(),+ resume: vi.fn(),+ cancel: vi.fn(),+ })),+}))+const mockApiGet = apiGet as unknown as ReturnType<typeof vi.fn>const mockApiSend = apiSend as unknown as ReturnType<typeof vi.fn>const mockGetAdminUsers = vi.mocked(getAdminUsers)@@ -47,6 +67,8 @@ const mockGetRecipes = vi.mocked(getRecipes)const mockPutGfsGrant = putGfsGrant as unknown as ReturnType<typeof vi.fn>const mockGfsDownload = gfsDownload as unknown as ReturnType<typeof vi.fn>const mockGfsFetchFileBlob = gfsFetchFileBlob as unknown as ReturnType<typeof vi.fn>+const mockUploadGfsFile = uploadGfsFile as unknown as ReturnType<typeof vi.fn>+const mockCreateGfsUploadJob = createGfsUploadJob as unknown as ReturnType<typeof vi.fn>const mockCreateObjectUrl = vi.fn((_blob: Blob) => 'blob:gfs-image-preview')const mockRevokeObjectUrl = vi.fn()@@ -111,6 +133,14 @@ describe('GfsBrowser', () => {mockPutGfsGrant.mockReset()mockGfsDownload.mockReset()mockGfsFetchFileBlob.mockReset()+ mockCreateGfsUploadJob.mockClear()+ mockUploadGfsFile.mockReset()+ mockUploadGfsFile.mockImplementation(async ({ file }: { file: File }) => {+ if (file.size > GFS_FILE_UPLOAD_MAX_BYTES) {+ throw new Error('GFS uploads are limited to 200 MB per file.')+ }+ return { state: 'completed' }+ })mockCreateObjectUrl.mockReset()mockCreateObjectUrl.mockReturnValue('blob:gfs-image-preview')mockRevokeObjectUrl.mockReset()@@ -162,28 +192,6 @@ describe('GfsBrowser', () => {expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/tree', { drive: 'main' })})- it('uses the paperclip header, labels the root as main, and ignores current-crumb clicks', async () => {- mockApiGet.mockResolvedValueOnce({ items: [], nextCursor: null })- renderBrowser()- await screen.findByText('No resources are visible in this folder.')-- const title = screen.getByText('Global File System').closest('.cu-panel-title')- expect(title?.querySelector('path')).toHaveAttribute(- 'd',- 'm21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48'- )-- const breadcrumb = screen.getByRole('navigation', { name: 'Breadcrumb' })- expect(within(breadcrumb).queryByText('Drive', { exact: true })).toBeNull()- const rootCrumb = within(breadcrumb).getByRole('button', { name: 'main' })- expect(rootCrumb).toHaveAttribute('aria-current', 'page')-- fireEvent.click(rootCrumb)-- expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull()- expect(mockApiGet).toHaveBeenCalledTimes(1)- })-it('shows the subtle loader during initial load and folder navigation', async () => {let resolveRoot: ((value: unknown) => void) | undefinedlet resolveFolder: ((value: unknown) => void) | undefined@@ -241,7 +249,7 @@ describe('GfsBrowser', () => {fireEvent.click(newFile)const uploadDialog = await screen.findByRole('dialog', { name: 'Upload file' })- expect(within(uploadDialog).getByText(/limited to 10 MB per file/i)).toBeTruthy()+ expect(within(uploadDialog).getByText(/limited to 200 MiB per file/i)).toBeTruthy()expect(within(uploadDialog).getByText(/drag and drop, or click to browse/i)).toBeTruthy()fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Cancel' }))@@ -297,22 +305,17 @@ describe('GfsBrowser', () => {fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))await waitFor(() =>- expect(mockApiSend).toHaveBeenLastCalledWith(- 'POST',- `/api/v1/gfs/proxy/v1/resources/${rootRid}/children`,- {+ expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(+ expect.objectContaining({name: fileName,- kind: 'file',- contentBase64: 'b3BlcmF0b3IgdXBsb2Fk',- },- {},- {},- { timeoutMs: 300000 }+ target: { operation: 'create', parentRid: rootRid },+ file: expect.any(File),+ })))})- it('uploads dropped files into the current folder', async () => {+ it('uploads dropped images and Markdown files into the current folder', async () => {const rootId = '11111111-1111-1111-1111-111111111111'const rootRid = '11111111111111111111111111111111'mockApiGet.mockResolvedValue({@@ -327,8 +330,7 @@ describe('GfsBrowser', () => {const browser = screen.getByRole('region', { name: 'Global File System browser' })const image = new File(['operator image'], 'diagram.png', { type: 'image/png' })const markdown = new File(['# Operator notes'], 'notes.md', { type: 'text/markdown' })- const pdf = new File(['%PDF operator report'], 'report.pdf', { type: 'application/pdf' })- const dataTransfer = { dropEffect: 'none', files: [image, markdown, pdf], types: ['Files'] }+ const dataTransfer = { dropEffect: 'none', files: [image, markdown], types: ['Files'] }fireEvent.dragEnter(browser.querySelector('.cu-gfs-card')!, { dataTransfer })const dropStatus = screen.getByRole('status')@@ -338,45 +340,104 @@ describe('GfsBrowser', () => {fireEvent.drop(browser.querySelector('.cu-gfs-card')!, { dataTransfer })await waitFor(() =>- expect(mockApiSend).toHaveBeenCalledWith(- 'POST',- `/api/v1/gfs/proxy/v1/resources/${rootRid}/children`,- {+ expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(+ expect.objectContaining({name: 'diagram.png',- kind: 'file',- contentBase64: 'b3BlcmF0b3IgaW1hZ2U=',- },- {},- {},- { timeoutMs: 300000 }+ target: { operation: 'create', parentRid: rootRid },+ })))- await waitFor(() => {- expect(mockApiSend).toHaveBeenCalledWith(- 'POST',- `/api/v1/gfs/proxy/v1/resources/${rootRid}/children`,- {- name: 'notes.md',- kind: 'file',- contentBase64: 'IyBPcGVyYXRvciBub3Rlcw==',- },- {},- {},- { timeoutMs: 300000 }- )- expect(mockApiSend).toHaveBeenCalledWith(- 'POST',- `/api/v1/gfs/proxy/v1/resources/${rootRid}/children`,- {- name: 'report.pdf',- kind: 'file',- contentBase64: 'JVBERiBvcGVyYXRvciByZXBvcnQ=',- },- {},- {},- { timeoutMs: 300000 }- )+ expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'notes.md',+ target: { operation: 'create', parentRid: rootRid },+ })+ )+ })++ it('shows byte progress and exposes pause/resume/cancel through the visible upload modal', async () => {+ const rootId = '11111111-1111-1111-1111-111111111111'+ const rootRid = '11111111111111111111111111111111'+ mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })+ const completed = {+ uploadId: '55555555-5555-4555-8555-555555555555',+ state: 'completed',+ expectedBytes: 4,+ committedBytes: 4,+ }+ const paused = { ...completed, state: 'paused', committedBytes: 2 }+ let resolveStart: ((value: typeof completed) => void) | undefined+ let uploadInput: { onState?: (snapshot: unknown) => void } | undefined+ const job = {+ start: vi.fn(() => {+ uploadInput?.onState?.({+ state: 'uploading',+ session: { ...completed, state: 'uploading' },+ uploadedBytes: 2,+ totalBytes: 4,+ })+ return new Promise<typeof completed>(resolve => {+ resolveStart = resolve+ })+ }),+ pause: vi.fn(async () => {+ uploadInput?.onState?.({+ state: 'paused',+ session: paused,+ uploadedBytes: 2,+ totalBytes: 4,+ })+ return paused+ }),+ resume: vi.fn(async () => {+ uploadInput?.onState?.({+ state: 'uploading',+ session: { ...completed, state: 'uploading' },+ uploadedBytes: 2,+ totalBytes: 4,+ })+ uploadInput?.onState?.({+ state: 'completed',+ session: completed,+ uploadedBytes: 4,+ totalBytes: 4,+ })+ resolveStart?.(completed)+ return completed+ }),+ cancel: vi.fn(async () => undefined),+ }+ mockCreateGfsUploadJob.mockImplementationOnce(+ (input: { onState?: (snapshot: unknown) => void }) => {+ uploadInput = input+ return job+ }+ )+ renderBrowser()+ await screen.findByText('No resources are visible in this folder.')+ fireEvent.click(screen.getByRole('button', { name: /upload file/i }))+ const uploadDialog = await screen.findByRole('dialog', { name: 'Upload file' })+ fireEvent.change(within(uploadDialog).getByLabelText('Choose file to upload'), {+ target: { files: [new File(['data'], 'payload.bin')] },})+ fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))+ const progress = await within(uploadDialog).findByRole('progressbar', {+ name: /Upload progress/,+ })+ expect(progress).toHaveAttribute('value', '2')+ expect(progress).toHaveAttribute('aria-valuemin', '0')+ expect(progress).toHaveAttribute('aria-valuemax', '4')+ expect(progress).toHaveAttribute('aria-valuenow', '2')+ fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Pause' }))+ await waitFor(() => expect(job.pause).toHaveBeenCalledTimes(1))+ expect(await within(uploadDialog).findByRole('button', { name: 'Resume' })).toBeTruthy()+ fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Resume' }))+ await waitFor(() => expect(job.resume).toHaveBeenCalledTimes(1))+ await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Upload file' })).toBeNull())+ expect(job.cancel).not.toHaveBeenCalled()+ expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(+ expect.objectContaining({ target: { operation: 'create', parentRid: rootRid } })+ )})it('rejects oversized dropped files before reading or uploading them', async () => {@@ -397,7 +458,7 @@ describe('GfsBrowser', () => {dataTransfer: { dropEffect: 'none', files: [oversized], types: ['Files'] },})- expect(await screen.findByText('GFS uploads are limited to 16 MB per file.')).toBeTruthy()+ expect(await screen.findByText('GFS uploads are limited to 200 MB per file.')).toBeTruthy()expect(arrayBuffer).not.toHaveBeenCalled()expect(mockApiSend).not.toHaveBeenCalled()})@@ -605,16 +666,12 @@ describe('GfsBrowser', () => {})await waitFor(() =>- expect(mockApiSend).toHaveBeenCalledWith(- 'PUT',- '/api/v1/gfs/proxy/v1/resources/r2/content',- {- contentBase64: 'cmVwbGFjZW1lbnQ=',- ifMatch: 0,- },- {},- {},- { timeoutMs: 300000 }+ expect(mockCreateGfsUploadJob).toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'report.md',+ file: expect.any(File),+ target: { operation: 'replace', resourceRid: 'r2', ifMatch: 0 },+ })))})diff --git a/control-ui/e2e/gfs-upload-v2.spec.ts b/control-ui/e2e/gfs-upload-v2.spec.tsnew file mode 100644index 000000000..1db7bffae--- /dev/null+++ b/control-ui/e2e/gfs-upload-v2.spec.ts@@ -0,0 +1,214 @@+import { expect, test } from '@playwright/test'+import { createHash } from 'node:crypto'+import { mkdtemp, rm, truncate, writeFile } from 'node:fs/promises'+import {+ assertGfsFixtureCleaned,+ cleanupGfsFixture,+ getGfsChildResourceSummary,+ seedGfsDirectoryFixture,+ seedGfsFileFixture,+ uniqueGfsFixtureName,+} from '../../tests/e2e/gfsUiFixtures'+import {+ GFS_UPLOAD_V2_BOUNDARIES,+ createDiskUploadFixture,+ removeDiskUploadFixture,+} from '../../tests/e2e/gfsUploadV2Fixtures'+import { loginControlUi, openGlobalFileSystemFromSidebar } from './support/gfs-control-ui-session'++test.describe.configure({ mode: 'serial' })++async function hashDownload(+ download: import('@playwright/test').Download+): Promise<{ bytes: number; sha256: string }> {+ const stream = await download.createReadStream()+ if (!stream) throw new Error(`download stream unavailable for ${download.suggestedFilename()}`)+ const hash = createHash('sha256')+ let bytes = 0+ for await (const chunk of stream) {+ bytes += chunk.length+ hash.update(chunk)+ }+ return { bytes, sha256: hash.digest('hex') }+}++async function openWritableFolder(+ page: import('@playwright/test').Page,+ folderName: string+): Promise<import('@playwright/test').Locator> {+ await loginControlUi(page)+ await openGlobalFileSystemFromSidebar(page)+ await expect(page).toHaveURL(/\/global-file-system(?:$|\?)/)+ const resources = page.getByRole('list', { name: 'Current folder resources' })+ await resources.getByRole('button', { name: folderName, exact: true }).click()+ const current = page.getByRole('list', { name: 'Current folder resources' })+ await expect(current).toBeVisible()+ return current+}++async function observeTwoProgressValues(+ progress: import('@playwright/test').Locator,+ timeout = 600_000+): Promise<void> {+ const values = new Set<string>()+ await expect+ .poll(+ async () => {+ const value = await progress.getAttribute('aria-valuenow')+ if (value !== null) values.add(value)+ return values.size+ },+ { timeout, intervals: [250, 1_000] }+ )+ .toBeGreaterThanOrEqual(2)+}++async function exerciseCreate(+ page: import('@playwright/test').Page,+ byteLength: number+): Promise<void> {+ const fixtureName = uniqueGfsFixtureName(`e2e-gfs-v2-create-${byteLength}`)+ const fixture = seedGfsDirectoryFixture(fixtureName)+ const source = await createDiskUploadFixture(byteLength, '.parquet', fixtureName)+ try {+ const current = await openWritableFolder(page, fixture.name)+ const createResponse = page.waitForResponse(+ response =>+ response.request().method() === 'POST' &&+ response.url().includes('/gfs/proxy/v1/uploads') &&+ !response.url().endsWith('/complete')+ )+ const completeResponse = page.waitForResponse(+ response => response.request().method() === 'POST' && response.url().endsWith('/complete')+ )+ await page.getByRole('button', { name: 'Upload file', exact: true }).click()+ const dialog = page.getByRole('dialog', { name: 'Upload file' })+ await dialog.getByLabel('Choose file to upload').setInputFiles(source.filePath)+ await dialog.getByRole('button', { name: 'Upload', exact: true }).click()+ const created = await createResponse+ expect(created.status(), `${created.url()} ${await created.text()}`).toBeGreaterThanOrEqual(200)+ const progress = page.getByRole('progressbar', {+ name: `Upload progress for ${source.fileName}`,+ })+ await expect(progress).toBeVisible()+ await observeTwoProgressValues(progress)+ const completed = await completeResponse+ expect(+ completed.status(),+ `${completed.url()} ${await completed.text()}`+ ).toBeGreaterThanOrEqual(200)+ await expect(page.getByText('File uploaded.', { exact: true })).toBeVisible({ timeout: 60_000 })++ const row = current.getByRole('listitem').filter({ hasText: source.fileName })+ await expect(row).toBeVisible({ timeout: 60_000 })+ await expect(row).toContainText('200 MB')+ await expect+ .poll(+ () =>+ getGfsChildResourceSummary({+ parentResourceId: fixture.resourceId,+ name: source.fileName,+ }),+ { timeout: 60_000, intervals: [250, 1_000] }+ )+ .toMatchObject({ kind: 'file', bytes: byteLength, deleted: false })+ const downloadPromise = page.waitForEvent('download')+ await row.getByRole('button', { name: `Download ${source.fileName}` }).click()+ const downloaded = await hashDownload(await downloadPromise)+ expect(downloaded).toEqual({ bytes: byteLength, sha256: source.sha256 })+ } finally {+ await removeDiskUploadFixture(source)+ cleanupGfsFixture(fixtureName)+ assertGfsFixtureCleaned(fixtureName)+ }+}++async function exerciseReplace(+ page: import('@playwright/test').Page,+ byteLength: number+): Promise<void> {+ const fixtureName = uniqueGfsFixtureName(`e2e-gfs-v2-replace-${byteLength}`)+ const fixture = seedGfsFileFixture(fixtureName)+ const source = await createDiskUploadFixture(byteLength, '.parquet', fixtureName)+ try {+ const current = await openWritableFolder(page, fixture.name)+ const before = await getGfsChildResourceSummary({+ parentResourceId: fixture.resourceId,+ name: fixture.fileName,+ })+ expect(before).toMatchObject({ kind: 'file', deleted: false })+ const createResponse = page.waitForResponse(+ response =>+ response.request().method() === 'POST' &&+ response.url().includes('/gfs/proxy/v1/uploads') &&+ !response.url().endsWith('/complete')+ )+ const completeResponse = page.waitForResponse(+ response => response.request().method() === 'POST' && response.url().endsWith('/complete')+ )+ const row = current.getByRole('listitem').filter({ hasText: fixture.fileName })+ await expect(row).toBeVisible({ timeout: 30_000 })+ await row.getByRole('button', { name: `Actions for ${fixture.fileName}` }).click()+ await page.getByRole('menuitem', { name: 'Replace file', exact: true }).click()+ await page.getByLabel(`Replace ${fixture.fileName}`).setInputFiles(source.filePath)+ const progress = page.getByRole('progressbar', {+ name: `Upload progress for ${source.fileName}`,+ })+ await expect(progress).toBeVisible()+ const created = await createResponse+ expect(created.status(), `${created.url()} ${await created.text()}`).toBeGreaterThanOrEqual(200)+ await observeTwoProgressValues(progress)+ const completed = await completeResponse+ expect(+ completed.status(),+ `${completed.url()} ${await completed.text()}`+ ).toBeGreaterThanOrEqual(200)+ await expect(page.getByText('File replaced.', { exact: true })).toBeVisible({ timeout: 60_000 })+ await expect+ .poll(+ () =>+ getGfsChildResourceSummary({+ parentResourceId: fixture.resourceId,+ name: fixture.fileName,+ }),+ { timeout: 60_000, intervals: [250, 1_000] }+ )+ .toMatchObject({+ kind: 'file',+ bytes: byteLength,+ version: (before?.version ?? 0) + 1,+ deleted: false,+ })+ await expect(row).toContainText('200 MB')+ const downloadPromise = page.waitForEvent('download')+ await row.getByRole('button', { name: `Download ${fixture.fileName}` }).click()+ const downloaded = await hashDownload(await downloadPromise)+ expect(downloaded).toEqual({ bytes: byteLength, sha256: source.sha256 })+ } finally {+ await removeDiskUploadFixture(source)+ cleanupGfsFixture(fixtureName)+ assertGfsFixtureCleaned(fixtureName)+ }+}++test.describe('GFS Upload v2 — Control UI large-upload project', () => {+ test.skip(+ process.env.GFS_UPLOAD_V2_E2E !== '1',+ 'Set GFS_UPLOAD_V2_E2E=1 only on an owned non-production dev host with the profile-scoped random URLs.'+ )+ test.setTimeout(45 * 60_000)++ for (const byteLength of GFS_UPLOAD_V2_BOUNDARIES) {+ test(`creates a ${byteLength}-byte file through visible Control UI actions`, async ({+ page,+ }) => {+ await exerciseCreate(page, byteLength)+ })++ test(`replaces a file with ${byteLength} bytes through visible Control UI actions`, async ({+ page,+ }) => {+ await exerciseReplace(page, byteLength)+ })+ }+})diff --git a/control-ui/lib/__tests__/gfsFileUpload.test.ts b/control-ui/lib/__tests__/gfsFileUpload.test.tsindex 8e47455e2..fafbc3261 100644--- a/control-ui/lib/__tests__/gfsFileUpload.test.ts+++ b/control-ui/lib/__tests__/gfsFileUpload.test.ts@@ -1,6 +1,6 @@-import { describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { GFS_FILE_UPLOAD_MAX_BYTES, GFS_FILE_UPLOAD_MAX_MEGABYTES } from '@constants/gfsFileUpload'-import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'+import { GfsUploadJob, type GfsUploadStatus, assertGfsFileUploadSize } from '@lib/gfsFileUpload'describe('assertGfsFileUploadSize', () => {it('accepts files at the upload limit', () => {@@ -13,3 +13,279 @@ describe('assertGfsFileUploadSize', () => {)})})++class FakeXhr {+ static requests: FakeXhr[] = []+ static statuses: number[] = []+ upload: { onprogress: ((event: { lengthComputable: boolean; loaded: number }) => void) | null } =+ { onprogress: null }+ status = 204+ responseText = ''+ onload: (() => void) | null = null+ onerror: (() => void) | null = null+ onabort: (() => void) | null = null+ headers = new Map<string, string>()+ body: Blob | null = null++ open(): void {}+ setRequestHeader(name: string, value: string): void {+ this.headers.set(name, value)+ }+ send(body: Blob): void {+ this.body = body+ this.status = FakeXhr.statuses.shift() ?? 204+ FakeXhr.requests.push(this)+ void body.arrayBuffer().then(() => {+ this.upload.onprogress?.({+ lengthComputable: true,+ loaded: Math.max(1, Math.floor(body.size / 2)),+ })+ this.upload.onprogress?.({ lengthComputable: true, loaded: body.size })+ this.onload?.()+ })+ }+ abort(): void {+ this.onabort?.()+ }+}++describe('GfsUploadJob', () => {+ beforeEach(() => {+ FakeXhr.requests = []+ FakeXhr.statuses = []+ vi.stubGlobal('XMLHttpRequest', FakeXhr)+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+ })++ it('resumes only the missing part and emits visible progress before completion', async () => {+ const file = new File([new Uint8Array([1, 2, 3, 4])], 'payload.bin', { lastModified: 12 })+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new Uint8Array([1, 2])))+ const part0 = btoa(String.fromCharCode(...digest))+ const responses: Array<{ status: number; body?: unknown }> = []+ const status: GfsUploadStatus = {+ session: {+ uploadId: '11111111-1111-4111-8111-111111111111',+ expectedBytes: 4,+ partBytes: 2,+ partCount: 2,+ state: 'uploading',+ contiguousBytes: 2,+ committedBytes: 2,+ committedPartCount: 1,+ activePartCount: 0,+ },+ parts: [{ partNumber: 0, offsetBytes: 0, lengthBytes: 2, sha256: part0 }],+ }+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ const method = init?.method ?? 'GET'+ if (method === 'GET' && String(_input).endsWith('/capabilities'))+ return new Response(JSON.stringify({ upload: { resumableV2: { enabled: true } } }), {+ status: 200,+ })+ if (method === 'HEAD')+ return new Response(null, { status: 204, headers: { 'upload-length': '4' } })+ if (method === 'GET' && String(_input).includes('/status'))+ return new Response(JSON.stringify({ ok: true, data: status }), { status: 200 })+ if (method === 'POST' && String(_input).endsWith('/complete'))+ return new Response(+ JSON.stringify({+ ok: true,+ data: {+ ...status.session,+ state: 'completed',+ committedBytes: 4,+ committedPartCount: 2,+ },+ }),+ { status: 200 }+ )+ responses.push({ status: 204, body: method })+ return new Response(null, { status: 204 })+ })+ )+ const progress: number[] = []+ const job = new GfsUploadJob({+ file,+ name: file.name,+ target: { operation: 'create', parentRid: 'parent-1' },+ resumeUploadId: status.session.uploadId,+ onProgress: value => progress.push(value.uploadedBytes),+ })+ const result = await job.start()+ expect(result.state).toBe('completed')+ expect(FakeXhr.requests).toHaveLength(1)+ expect(FakeXhr.requests[0]?.headers.get('Upload-Part-Number')).toBe('1')+ expect(progress.some(value => value < 4)).toBe(true)+ expect(progress.at(-1)).toBe(4)+ expect(responses).toHaveLength(0)+ })++ it('rejects a committed status part whose checksum does not match the selected file before PUT', async () => {+ const file = new File([new Uint8Array([1, 2])], 'payload.bin')+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ if (init?.method === 'GET' && String(_input).endsWith('/capabilities'))+ return new Response(JSON.stringify({ upload: { resumableV2: { enabled: true } } }), {+ status: 200,+ })+ if (init?.method === 'HEAD')+ return new Response(null, { status: 204, headers: { 'upload-length': '2' } })+ return new Response(+ JSON.stringify({+ ok: true,+ data: {+ session: {+ uploadId: '22222222-2222-4222-8222-222222222222',+ expectedBytes: 2,+ partBytes: 2,+ partCount: 1,+ state: 'uploading',+ contiguousBytes: 2,+ committedBytes: 2,+ committedPartCount: 1,+ activePartCount: 0,+ },+ parts: [{ partNumber: 0, offsetBytes: 0, lengthBytes: 2, sha256: 'wrong-checksum' }],+ },+ }),+ { status: 200 }+ )+ })+ )+ await expect(+ new GfsUploadJob({+ file,+ name: file.name,+ target: { operation: 'create', parentRid: 'parent-2' },+ resumeUploadId: '22222222-2222-4222-8222-222222222222',+ }).start()+ ).rejects.toThrow(/does not match/)+ expect(FakeXhr.requests).toHaveLength(0)+ })++ it('latches the four-to-two fallback after three consecutive retryable failures', async () => {+ const file = new File([new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])], 'payload.bin')+ FakeXhr.statuses = [500, 500, 500, 204, 204, 204, 204]+ let completeCalls = 0+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ const method = init?.method ?? 'GET'+ if (method === 'GET' && String(_input).endsWith('/capabilities')) {+ return new Response(+ JSON.stringify({+ upload: {+ resumableV2: {+ enabled: true,+ preferredPartBytes: 2,+ maxPartBytes: 2,+ maxConcurrentPartsPerSession: 4,+ fallbackConcurrency: 2,+ },+ },+ }),+ { status: 200 }+ )+ }+ if (method === 'POST' && String(_input).endsWith('/uploads')) {+ return new Response(+ JSON.stringify({+ ok: true,+ data: {+ uploadId: '33333333-3333-4333-8333-333333333333',+ expectedBytes: 8,+ partBytes: 2,+ partCount: 4,+ state: 'initiated',+ contiguousBytes: 0,+ committedBytes: 0,+ committedPartCount: 0,+ activePartCount: 0,+ },+ }),+ { status: 201 }+ )+ }+ if (method === 'POST' && String(_input).endsWith('/complete')) {+ completeCalls += 1+ return new Response(+ JSON.stringify({+ ok: true,+ data: {+ uploadId: '33333333-3333-4333-8333-333333333333',+ expectedBytes: 8,+ partBytes: 2,+ partCount: 4,+ state: 'completed',+ committedBytes: 8,+ committedPartCount: 4,+ activePartCount: 0,+ },+ }),+ { status: 200 }+ )+ }+ return new Response(null, { status: 204 })+ })+ )+ const result = await new GfsUploadJob({+ file,+ name: file.name,+ target: { operation: 'create', parentRid: 'parent-fallback' },+ }).start()+ expect(result.state).toBe('completed')+ expect(completeCalls).toBe(1)+ expect(FakeXhr.requests).toHaveLength(7)+ })++ it('does not retry a non-retryable conflict', async () => {+ const file = new File([new Uint8Array([1, 2])], 'payload.bin')+ FakeXhr.statuses = [409]+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ if (init?.method === 'GET' && String(_input).endsWith('/capabilities'))+ return new Response(+ JSON.stringify({+ upload: { resumableV2: { enabled: true, preferredPartBytes: 2, maxPartBytes: 2 } },+ }),+ { status: 200 }+ )+ if (init?.method === 'POST' && String(_input).endsWith('/uploads'))+ return new Response(+ JSON.stringify({+ ok: true,+ data: {+ uploadId: '44444444-4444-4444-8444-444444444444',+ expectedBytes: 2,+ partBytes: 2,+ partCount: 1,+ state: 'initiated',+ contiguousBytes: 0,+ committedBytes: 0,+ committedPartCount: 0,+ activePartCount: 0,+ },+ }),+ { status: 201 }+ )+ return new Response(null, { status: 204 })+ })+ )+ await expect(+ new GfsUploadJob({+ file,+ name: file.name,+ target: { operation: 'create', parentRid: 'parent-conflict' },+ }).start()+ ).rejects.toThrow(/could not be committed/)+ expect(FakeXhr.requests).toHaveLength(1)+ })+})diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex 175af2183..ef3dbaee4 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -55,14 +55,9 @@ export type Metadata = {const API_BASE = process.env.NEXT_PUBLIC_CONTROL_API_BASE_URL || '/control-api'const ADMIN_TOKEN_STORAGE_KEY = 'controlUiAdminToken'const API_REQUEST_TIMEOUT_MS = 30000-// GFS uploads send the file base64-encoded inside a JSON body (~+33% over the raw-// bytes), so a 7.5 MB file crosses the wire as ~10 MB. On prod the Cloudflare tunnel-// plus control-api forwarding push that past the default 30s window, and the browser-// AbortController would cut the request mid-body — control-api then logs "request-// aborted" (400) and the user sees "Request timed out". Give GFS uploads a generous-// ceiling. This is a client (browser) constant: it cannot read a server runtime env-// without NEXT_PUBLIC (build-time) or a config endpoint (neither exists here). The-// server-side proxy has its own, runtime-configurable timeout.+// Legacy JSON GFS uploads send file bytes base64-encoded inside a request body. The+// v2 path uses binary indexed parts and does not use this timeout/body contract;+// this constant remains only for the compatibility helper and old API callers.export const GFS_UPLOAD_TIMEOUT_MS = 300000const inFlightGetRequests = new Map<string, Promise<unknown>>()let sessionEpoch = 0diff --git a/control-ui/lib/gfsFileUpload.ts b/control-ui/lib/gfsFileUpload.tsindex 5baef1b87..8972326bf 100644--- a/control-ui/lib/gfsFileUpload.ts+++ b/control-ui/lib/gfsFileUpload.ts@@ -1,7 +1,922 @@-import { GFS_FILE_UPLOAD_MAX_BYTES, GFS_FILE_UPLOAD_MAX_MEGABYTES } from '@constants/gfsFileUpload'+import {+ GFS_FILE_UPLOAD_DEFAULT_CONCURRENCY,+ GFS_FILE_UPLOAD_FALLBACK_CONCURRENCY,+ GFS_FILE_UPLOAD_MAX_BYTES,+ GFS_FILE_UPLOAD_MAX_MEGABYTES,+ GFS_FILE_UPLOAD_MAX_PART_BYTES,+ GFS_FILE_UPLOAD_PREFERRED_PART_BYTES,+} from '@constants/gfsFileUpload'+import { apiSend } from './api'++const API_BASE = process.env.NEXT_PUBLIC_CONTROL_API_BASE_URL || '/control-api'+const RETRYABLE_STATUS = new Set([408, 425, 429, 500, 502, 503, 504])++export interface GfsUploadTarget {+ operation: 'create' | 'replace'+ parentRid?: string+ resourceRid?: string+ ifMatch?: number+}++export interface GfsUploadProgress {+ uploadedBytes: number+ totalBytes: number+ partNumber: number+ partCount: number+}++export interface UploadReceipt {+ uploadId: string+ drive?: string+ operation?: 'create' | 'replace'+ expectedBytes: number+ partBytes: number+ partCount: number+ state: string+ contiguousBytes?: number+ committedBytes?: number+ committedPartCount?: number+ activePartCount?: number+ expiresAt?: string+ resultResourceId?: string+ resultVersion?: number+ resultSha256?: string+}++export interface GfsUploadPartReceipt {+ partNumber: number+ offsetBytes: number+ lengthBytes: number+ sha256: string+}++export interface GfsUploadStatus {+ session: UploadReceipt+ parts: GfsUploadPartReceipt[]+ nextCursor?: string | null+}++export type GfsUploadJobState =+ | 'initiated'+ | 'uploading'+ | 'paused'+ | 'finalizing'+ | 'canceling'+ | 'completed'+ | 'aborted'+ | 'failed'++export interface GfsUploadJobSnapshot {+ state: GfsUploadJobState+ session: UploadReceipt | null+ uploadedBytes: number+ totalBytes: number+}++export interface GfsUploadJobInput {+ file: File+ name: string+ target: GfsUploadTarget+ signal?: AbortSignal+ resumeUploadId?: string+ onProgress?: (progress: GfsUploadProgress) => void+ onState?: (snapshot: GfsUploadJobSnapshot) => void+ /** Persist only bounded metadata; never persist file bytes. */+ onPersist?: (record: {+ uploadId: string+ fileName: string+ fileSize: number+ lastModified: number+ target: GfsUploadTarget+ name: string+ session: UploadReceipt+ }) => void | Promise<void>+ onPersistPending?: (record: {+ idempotencyKey: string+ fileName: string+ fileSize: number+ lastModified: number+ target: GfsUploadTarget+ name: string+ }) => void | Promise<void>+ onClearPersisted?: (uploadId: string) => void | Promise<void>+}++interface UploadCapabilities {+ upload?: {+ resumableV2?: {+ enabled?: boolean+ preferredPartBytes?: number+ maxPartBytes?: number+ preferredChunkBytes?: number+ maxChunkBytes?: number+ maxConcurrentPartsPerSession?: number+ instabilityFailureThreshold?: number+ fallbackConcurrency?: number+ }+ }+}++export class GfsUploadCapabilityError extends Error {+ constructor(message: string, options?: { cause?: unknown }) {+ super(message, options)+ this.name = 'GfsUploadCapabilityError'+ }+}++export const GFS_LEGACY_UPLOAD_MAX_BYTES = 16 * 1024 * 1024++function uuid(): string {+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')+ return crypto.randomUUID()+ const bytes = new Uint8Array(16)+ crypto.getRandomValues(bytes)+ bytes[6] = (bytes[6] & 0x0f) | 0x40+ bytes[8] = (bytes[8] & 0x3f) | 0x80+ return [...bytes]+ .map(+ (value, index) =>+ `${value.toString(16).padStart(2, '0')}${[3, 5, 7, 9].includes(index) ? '-' : ''}`+ )+ .join('')+}++function endpoint(path: string): string {+ return `${API_BASE}${path}`+}++function signalWithTimeout(+ signal: AbortSignal | undefined,+ timeoutMs: number+): { signal: AbortSignal; cancel: () => void } {+ const controller = new AbortController()+ const timer = window.setTimeout(+ () => controller.abort(new Error('GFS upload request timed out')),+ timeoutMs+ )+ const abort = () => controller.abort(signal?.reason)+ signal?.addEventListener('abort', abort, { once: true })+ return {+ signal: controller.signal,+ cancel: () => {+ window.clearTimeout(timer)+ signal?.removeEventListener('abort', abort)+ },+ }+}++async function requestJson<T>(+ method: 'GET' | 'POST' | 'HEAD' | 'DELETE',+ path: string,+ body?: unknown,+ signal?: AbortSignal+): Promise<{ data: T; response: Response }> {+ const timed = signalWithTimeout(signal, 600_000)+ try {+ const response = await fetch(endpoint(path), {+ method,+ credentials: 'include',+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ signal: timed.signal,+ })+ if (!response.ok) throw await uploadError(response)+ const text = await response.text()+ return { data: (text ? JSON.parse(text) : undefined) as T, response }+ } finally {+ timed.cancel()+ }+}++async function uploadError(+ response: Response+): Promise<Error & { status?: number; code?: string }> {+ const text = await response.text().catch(() => '')+ let message = text || response.statusText || 'GFS upload failed'+ let code: string | undefined+ try {+ const parsed = JSON.parse(text) as { error?: unknown; message?: unknown; code?: unknown }+ if (typeof parsed.message === 'string') message = parsed.message+ if (typeof parsed.error === 'string') code = parsed.error+ if (+ parsed.error &&+ typeof parsed.error === 'object' &&+ typeof (parsed.error as { code?: unknown }).code === 'string'+ ) {+ code = String((parsed.error as { code: string }).code)+ message =+ typeof (parsed.error as { message?: unknown }).message === 'string'+ ? String((parsed.error as { message: string }).message)+ : message+ }+ } catch {+ // Preserve the bounded upstream text for non-JSON proxy errors.+ }+ const error = new Error(`${response.status} ${message}`) as Error & {+ status?: number+ code?: string+ }+ error.status = response.status+ error.code = code+ return error+}++function assertRetryable(error: unknown): boolean {+ if (error instanceof DOMException && error.name === 'AbortError') return false+ const status =+ typeof error === 'object' && error !== null ? (error as { status?: unknown }).status : undefined+ return typeof status === 'number' ? RETRYABLE_STATUS.has(status) : true+}++function delay(ms: number, signal?: AbortSignal): Promise<void> {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) {+ reject(signal.reason)+ return+ }+ const timer = window.setTimeout(resolve, ms)+ signal?.addEventListener(+ 'abort',+ () => {+ window.clearTimeout(timer)+ reject(signal.reason)+ },+ { once: true }+ )+ })+}++function digestBase64(bytes: ArrayBuffer): string {+ let binary = ''+ const view = new Uint8Array(bytes)+ for (let index = 0; index < view.length; index += 0x8000)+ binary += String.fromCharCode(...view.subarray(index, index + 0x8000))+ return btoa(binary)+}++async function putPart(+ uploadId: string,+ file: File,+ part: { partNumber: number; offsetBytes: number; lengthBytes: number },+ partCount: number,+ signal: AbortSignal | undefined,+ onByteProgress?: (progress: GfsUploadProgress) => void+): Promise<void> {+ const blob = file.slice(part.offsetBytes, part.offsetBytes + part.lengthBytes)+ const checksum = digestBase64(await crypto.subtle.digest('SHA-256', await blob.arrayBuffer()))+ const timed = signalWithTimeout(signal, 600_000)+ try {+ await new Promise<void>((resolve, reject) => {+ const xhr = new XMLHttpRequest()+ const abort = () => xhr.abort()+ xhr.open(+ 'PUT',+ endpoint(+ `/api/v1/gfs/proxy/v1/uploads/${encodeURIComponent(uploadId)}/parts/${part.partNumber}`+ )+ )+ xhr.withCredentials = true+ xhr.setRequestHeader('Content-Type', 'application/offset+octet-stream')+ xhr.setRequestHeader('Upload-Part-Number', String(part.partNumber))+ xhr.setRequestHeader('Upload-Offset', String(part.offsetBytes))+ xhr.setRequestHeader('Upload-Chunk-Length', String(part.lengthBytes))+ xhr.setRequestHeader('Upload-Checksum', `sha256 ${checksum}`)+ xhr.upload.onprogress = event => {+ if (!event.lengthComputable) return+ onByteProgress?.({+ uploadedBytes: part.offsetBytes + Math.min(part.lengthBytes, event.loaded),+ totalBytes: file.size,+ partNumber: part.partNumber,+ partCount,+ })+ }+ xhr.onload = () => {+ if (xhr.status >= 200 && xhr.status < 300) {+ resolve()+ return+ }+ const error = new Error(+ `${xhr.status} ${xhr.responseText || 'GFS upload failed'}`+ ) as Error & { status?: number }+ error.status = xhr.status+ reject(error)+ }+ xhr.onerror = () => reject(new Error('GFS upload network error'))+ xhr.onabort = () => reject(abortError('GFS upload request aborted'))+ timed.signal.addEventListener('abort', abort, { once: true })+ xhr.send(blob)+ })+ } finally {+ timed.cancel()+ }+}++async function uploadPartWithRetries(+ uploadId: string,+ file: File,+ part: { partNumber: number; offsetBytes: number; lengthBytes: number },+ partCount: number,+ signal: AbortSignal | undefined,+ onByteProgress: ((progress: GfsUploadProgress) => void) | undefined,+ onRetryableFailure?: () => void,+ onPartSuccess?: () => void+): Promise<void> {+ let lastError: unknown+ for (let attempt = 0; attempt < 3; attempt += 1) {+ try {+ await putPart(uploadId, file, part, partCount, signal, onByteProgress)+ onPartSuccess?.()+ return+ } catch (error) {+ lastError = error+ if (!assertRetryable(error)) throw error+ onRetryableFailure?.()+ if (attempt === 2) throw error+ await delay(Math.min(1000, 150 * (attempt + 1)), signal)+ }+ }+ throw lastError+}++async function runParts(+ uploadId: string,+ file: File,+ parts: Array<{ partNumber: number; offsetBytes: number; lengthBytes: number }>,+ concurrency: number,+ signal: AbortSignal | undefined,+ shouldPause: () => boolean,+ onProgress?: (progress: GfsUploadProgress) => void,+ onByteProgress?: (progress: GfsUploadProgress) => void,+ fallbackConcurrency = GFS_FILE_UPLOAD_FALLBACK_CONCURRENCY+): Promise<{ failed: typeof parts; retryableFailures: number; paused: boolean }> {+ const initialConcurrency = Math.max(1, Math.min(concurrency, parts.length || 1))+ const effectiveFallback = Math.max(+ 1,+ Math.min(+ initialConcurrency,+ Number.isSafeInteger(fallbackConcurrency) && fallbackConcurrency > 0+ ? fallbackConcurrency+ : GFS_FILE_UPLOAD_FALLBACK_CONCURRENCY+ )+ )+ let retryableFailures = 0+ let consecutiveRetryableFailures = 0+ let downgraded = false+ const failed = new Map<number, (typeof parts)[number]>()+ const retryableFailed = new Set<number>()+ const registerRetryableFailure = (): void => {+ retryableFailures += 1+ consecutiveRetryableFailures += 1+ if (!downgraded && consecutiveRetryableFailures >= 3 && initialConcurrency > effectiveFallback)+ downgraded = true+ }+ const registerPartSuccess = (): void => {+ consecutiveRetryableFailures = 0+ }+ const execute = async (work: typeof parts, workers: number): Promise<void> => {+ let next = 0+ const worker = async (workerIndex: number): Promise<void> => {+ for (;;) {+ if (signal?.aborted) throw signal.reason+ if (shouldPause()) {+ return+ }+ if (downgraded && workerIndex >= effectiveFallback) return+ const index = next+++ if (index >= work.length) return+ const part = work[index]!+ try {+ await uploadPartWithRetries(+ uploadId,+ file,+ part,+ parts.length,+ signal,+ onByteProgress,+ registerRetryableFailure,+ registerPartSuccess+ )+ onProgress?.({+ uploadedBytes: part.offsetBytes + part.lengthBytes,+ totalBytes: file.size,+ partNumber: part.partNumber,+ partCount: parts.length,+ })+ failed.delete(part.partNumber)+ retryableFailed.delete(part.partNumber)+ } catch (error) {+ if (shouldPause()) {+ return+ }+ if (error instanceof DOMException && error.name === 'AbortError') throw error+ failed.set(part.partNumber, part)+ if (assertRetryable(error)) retryableFailed.add(part.partNumber)+ }+ }+ }+ await Promise.all(Array.from({ length: workers }, (_, workerIndex) => worker(workerIndex)))+ }+ await execute(parts, initialConcurrency)+ if (downgraded && retryableFailed.size > 0 && !shouldPause()) {+ await execute(+ parts.filter(part => retryableFailed.has(part.partNumber)),+ effectiveFallback+ )+ }+ return { failed: [...failed.values()], retryableFailures, paused: shouldPause() }+}++type ResponsePayload<T> = T extends { data: infer U } ? U : T++function receiptFromResponse<T>(value: { data: T }): ResponsePayload<T> {+ const data = value.data as unknown as { data?: T }+ return (+ data && typeof data === 'object' && 'data' in data && data.data !== undefined+ ? data.data+ : value.data+ ) as ResponsePayload<T>+}++function abortError(message: string): Error {+ const error = new Error(message)+ error.name = 'AbortError'+ return error+}++function statusOf(error: unknown): number | undefined {+ const value = error as { status?: unknown } | null+ return value && typeof value.status === 'number' ? value.status : undefined+}++export class GfsUploadJob {+ private readonly abortController = new AbortController()+ private readonly idempotencyKey = uuid()+ private readonly inputSignalCleanup: (() => void) | undefined+ private session: UploadReceipt | null = null+ private state: GfsUploadJobState = 'initiated'+ private uploadedBytes = 0+ private pauseRequested = false+ private canceled = false+ private runPromise: Promise<UploadReceipt> | null = null++ constructor(private readonly input: GfsUploadJobInput) {+ if (input.signal) {+ const abort = () => this.abortController.abort(input.signal?.reason)+ input.signal.addEventListener('abort', abort, { once: true })+ this.inputSignalCleanup = () => input.signal?.removeEventListener('abort', abort)+ }+ }++ snapshot(): GfsUploadJobSnapshot {+ return {+ state: this.state,+ session: this.session,+ uploadedBytes: this.uploadedBytes,+ totalBytes: this.input.file.size,+ }+ }++ async start(): Promise<UploadReceipt> {+ if (this.runPromise) return this.runPromise+ this.runPromise = this.run()+ try {+ return await this.runPromise+ } finally {+ this.inputSignalCleanup?.()+ this.runPromise = null+ }+ }++ async pause(): Promise<UploadReceipt> {+ const session = await this.ensureSession()+ if (session.state === 'paused') {+ this.state = 'paused'+ this.emit()+ return session+ }+ if (['completed', 'aborted', 'failed'].includes(session.state)) {+ throw new Error(`cannot pause upload in ${session.state}`)+ }+ this.pauseRequested = true+ const response = await requestJson<{ ok: boolean; data: UploadReceipt }>(+ 'POST',+ `/api/v1/gfs/proxy/v1/uploads/${encodeURIComponent(session.uploadId)}/pause`,+ {},+ undefined+ )+ const paused = receiptFromResponse(response)+ this.session = paused+ this.state = 'paused'+ this.emit()+ return paused+ }++ async resume(): Promise<UploadReceipt> {+ const session = await this.ensureSession()+ if (session.state === 'completed') return session+ if (session.state !== 'paused') {+ if (session.state === 'uploading' || session.state === 'initiated') return this.start()+ throw new Error(`cannot resume upload in ${session.state}`)+ }+ this.pauseRequested = false+ const response = await requestJson<{ ok: boolean; data: UploadReceipt }>(+ 'POST',+ `/api/v1/gfs/proxy/v1/uploads/${encodeURIComponent(session.uploadId)}/resume`,+ {},+ this.abortController.signal+ )+ this.session = receiptFromResponse(response)+ this.state = 'uploading'+ this.emit()+ return this.start()+ }++ async cancel(): Promise<void> {+ const session = this.session+ this.canceled = true+ this.pauseRequested = false+ this.abortController.abort(abortError('GFS upload canceled'))+ this.state = 'canceling'+ this.emit()+ if (session && !['completed', 'aborted'].includes(session.state)) {+ try {+ await requestJson(+ 'DELETE',+ `/api/v1/gfs/proxy/v1/uploads/${encodeURIComponent(session.uploadId)}`,+ undefined,+ undefined+ )+ } catch (error) {+ if (+ statusOf(error) === 409 ||+ (typeof error === 'object' &&+ error !== null &&+ (error as { code?: unknown }).code === 'upload_finalizing')+ ) {+ const reconciled = await requestJson<{ ok: boolean; data: GfsUploadStatus }>(+ 'GET',+ `/api/v1/gfs/proxy/v1/uploads/${encodeURIComponent(session.uploadId)}/status`,+ undefined,+ undefined+ )+ this.session = receiptFromResponse(reconciled).session+ if (this.session.state === 'completed') {+ this.state = 'completed'+ this.canceled = false+ this.emit()+ await this.input.onClearPersisted?.(session.uploadId)+ return+ }+ }+ this.canceled = false+ this.state = 'failed'+ this.emit()+ throw error+ }+ }+ await this.runPromise?.catch(() => undefined)+ this.state = 'aborted'+ this.emit()+ if (session) await this.input.onClearPersisted?.(session.uploadId)+ }++ private emit(): void {+ this.input.onState?.(this.snapshot())+ }++ private async ensureSession(): Promise<UploadReceipt> {+ if (this.session) return this.session+ if (!this.runPromise) {+ // Calling pause/resume before start is a programming error in the UI;+ // starting here keeps the job deterministic for IPC callers.+ void this.start()+ }+ for (;;) {+ if (this.session) return this.session+ if (!this.runPromise) throw new Error('GFS upload session was not created')+ await Promise.race([this.runPromise.catch(() => undefined), delay(10)])+ }+ }++ private async loadCapabilities(): Promise<UploadCapabilities['upload']> {+ let capabilities: { data: UploadCapabilities }+ try {+ capabilities = await requestJson<UploadCapabilities>(+ 'GET',+ '/api/v1/gfs/proxy/v1/capabilities',+ undefined,+ this.abortController.signal+ )+ } catch (error) {+ throw new GfsUploadCapabilityError('Resumable GFS upload capabilities are unavailable.', {+ cause: error,+ })+ }+ const upload = capabilities.data.upload+ if (!upload?.resumableV2?.enabled)+ throw new GfsUploadCapabilityError('Resumable GFS uploads are not enabled on this writer.')+ return upload+ }++ private async createOrResume(): Promise<{+ session: UploadReceipt+ committed: Set<number>+ resumable: NonNullable<NonNullable<UploadCapabilities['upload']>['resumableV2']>+ }> {+ const upload = await this.loadCapabilities()+ const resumable = upload.resumableV2!+ const resumeId = this.session?.uploadId ?? this.input.resumeUploadId+ if (resumeId) {+ const head = await requestJson<undefined>(+ 'HEAD',+ `/api/v1/gfs/proxy/v1/uploads/${encodeURIComponent(resumeId)}`,+ undefined,+ this.abortController.signal+ )+ const length = Number(head.response.headers.get('upload-length'))+ if (Number.isSafeInteger(length) && length !== this.input.file.size)+ throw new Error('selected file size differs from the persisted upload session')+ let cursor: string | undefined+ let session: UploadReceipt | null = null+ const parts: GfsUploadPartReceipt[] = []+ for (let page = 0; page < 8; page += 1) {+ const query = cursor ? `?limit=256&cursor=${encodeURIComponent(cursor)}` : '?limit=256'+ const statusResponse = await requestJson<{ ok: boolean; data: GfsUploadStatus }>(+ 'GET',+ `/api/v1/gfs/proxy/v1/uploads/${encodeURIComponent(resumeId)}/status${query}`,+ undefined,+ this.abortController.signal+ )+ const status = receiptFromResponse(statusResponse)+ session ??= status.session+ if (+ session.uploadId !== status.session.uploadId ||+ session.expectedBytes !== status.session.expectedBytes+ )+ throw new Error('upload status changed during resume')+ parts.push(...status.parts)+ if (!status.nextCursor) break+ cursor = status.nextCursor+ if (page === 7) throw new Error('upload status pagination exceeded the bounded page limit')+ }+ if (!session || session.expectedBytes !== this.input.file.size)+ throw new Error('selected file size differs from the upload session')+ if (['completed', 'aborted', 'failed'].includes(session.state))+ return { session, committed: new Set(), resumable }+ await this.validateCommittedParts(session, parts)+ return { session, committed: new Set(parts.map(part => part.partNumber)), resumable }+ }+ const createBody = {+ operation: this.input.target.operation,+ parentRid: this.input.target.parentRid,+ resourceRid: this.input.target.resourceRid,+ ifMatch: this.input.target.ifMatch,+ name: this.input.name,+ sizeBytes: this.input.file.size,+ idempotencyKey: this.idempotencyKey,+ }+ await this.input.onPersistPending?.({+ idempotencyKey: this.idempotencyKey,+ fileName: this.input.file.name,+ fileSize: this.input.file.size,+ lastModified: this.input.file.lastModified,+ target: this.input.target,+ name: this.input.name,+ })+ let create: { data: { ok: boolean; data: UploadReceipt }; response: Response }+ try {+ create = await requestJson<{ ok: boolean; data: UploadReceipt }>(+ 'POST',+ '/api/v1/gfs/proxy/v1/uploads',+ createBody,+ this.abortController.signal+ )+ } catch (error) {+ // A response lost after POST is safe to replay because the key is fixed.+ if (statusOf(error) !== undefined) throw error+ create = await requestJson<{ ok: boolean; data: UploadReceipt }>(+ 'POST',+ '/api/v1/gfs/proxy/v1/uploads',+ createBody,+ this.abortController.signal+ )+ }+ const session = receiptFromResponse(create)+ if (session.expectedBytes !== this.input.file.size)+ throw new Error('GFS upload session size changed before transfer')+ return { session, committed: new Set<number>(), resumable }+ }++ private async validateCommittedParts(+ session: UploadReceipt,+ parts: GfsUploadPartReceipt[]+ ): Promise<void> {+ for (const part of parts) {+ const expectedOffset = part.partNumber * session.partBytes+ const expectedLength = Math.min(session.partBytes, this.input.file.size - expectedOffset)+ if (+ part.offsetBytes !== expectedOffset ||+ part.lengthBytes !== expectedLength ||+ part.partNumber < 0 ||+ part.partNumber >= session.partCount+ ) {+ throw new Error('upload status contains invalid part geometry')+ }+ const checksum = digestBase64(+ await crypto.subtle.digest(+ 'SHA-256',+ await this.input.file+ .slice(part.offsetBytes, part.offsetBytes + part.lengthBytes)+ .arrayBuffer()+ )+ )+ if (checksum !== part.sha256)+ throw new Error(`upload part ${part.partNumber} does not match the selected file`)+ }+ }++ private async run(): Promise<UploadReceipt> {+ assertGfsFileUploadSize(this.input.file.size)+ try {+ const prepared = await this.createOrResume()+ this.session = prepared.session+ if (prepared.session.state === 'completed') {+ this.state = 'completed'+ this.uploadedBytes = this.input.file.size+ this.emit()+ await this.input.onClearPersisted?.(prepared.session.uploadId)+ return prepared.session+ }+ if (prepared.session.state === 'aborted' || prepared.session.state === 'failed')+ throw new Error(`cannot resume upload in ${prepared.session.state}`)+ this.state = prepared.session.state === 'paused' ? 'paused' : 'uploading'+ this.uploadedBytes = prepared.session.committedBytes ?? prepared.session.contiguousBytes ?? 0+ this.emit()+ await this.input.onPersist?.({+ uploadId: prepared.session.uploadId,+ fileName: this.input.file.name,+ fileSize: this.input.file.size,+ lastModified: this.input.file.lastModified,+ target: this.input.target,+ name: this.input.name,+ session: prepared.session,+ })+ if (prepared.session.state === 'paused') return prepared.session+ const partBytes = prepared.session.partBytes+ if (+ !Number.isSafeInteger(partBytes) ||+ partBytes < 1 ||+ partBytes > GFS_FILE_UPLOAD_MAX_PART_BYTES+ )+ throw new Error('GFS server returned an invalid part size')+ const parts = Array.from({ length: prepared.session.partCount }, (_, partNumber) => ({+ partNumber,+ offsetBytes: partNumber * partBytes,+ lengthBytes: Math.min(partBytes, this.input.file.size - partNumber * partBytes),+ }))+ const allParts = parts+ const completedParts = new Set(prepared.committed)+ const progress = (value: GfsUploadProgress) => {+ completedParts.add(value.partNumber)+ this.uploadedBytes = allParts.reduce(+ (total, part) => total + (completedParts.has(part.partNumber) ? part.lengthBytes : 0),+ 0+ )+ this.input.onProgress?.({+ ...value,+ uploadedBytes: this.uploadedBytes,+ partCount: allParts.length,+ })+ this.emit()+ }+ let pending = allParts.filter(part => !completedParts.has(part.partNumber))+ const advertisedConcurrency = Number(prepared.resumable.maxConcurrentPartsPerSession)+ const concurrency =+ Number.isSafeInteger(advertisedConcurrency) && advertisedConcurrency > 0+ ? Math.min(GFS_FILE_UPLOAD_DEFAULT_CONCURRENCY, advertisedConcurrency)+ : GFS_FILE_UPLOAD_DEFAULT_CONCURRENCY+ const fallbackConcurrency =+ Number(prepared.resumable.fallbackConcurrency) || GFS_FILE_UPLOAD_FALLBACK_CONCURRENCY+ const result = await runParts(+ prepared.session.uploadId,+ this.input.file,+ pending,+ concurrency,+ this.abortController.signal,+ () => this.pauseRequested || this.canceled,+ progress,+ value => this.input.onProgress?.(value),+ fallbackConcurrency+ )+ if (result.paused || this.pauseRequested) {+ this.state = 'paused'+ const paused = await requestJson<{ ok: boolean; data: GfsUploadStatus }>(+ 'GET',+ `/api/v1/gfs/proxy/v1/uploads/${encodeURIComponent(prepared.session.uploadId)}/status`,+ undefined,+ undefined+ )+ this.session = receiptFromResponse(paused).session+ this.emit()+ return this.session+ }+ if (result.paused || this.pauseRequested) {+ this.state = 'paused'+ const paused = await requestJson<{ ok: boolean; data: GfsUploadStatus }>(+ 'GET',+ `/api/v1/gfs/proxy/v1/uploads/${encodeURIComponent(prepared.session.uploadId)}/status`,+ undefined,+ undefined+ )+ this.session = receiptFromResponse(paused).session+ this.emit()+ return this.session+ }+ if (result.failed.length > 0)+ throw new Error('One or more upload parts could not be committed.')+ this.state = 'finalizing'+ this.emit()+ const completedResponse = await requestJson<{ ok: boolean; data: UploadReceipt }>(+ 'POST',+ `/api/v1/gfs/proxy/v1/uploads/${encodeURIComponent(prepared.session.uploadId)}/complete`,+ {},+ this.abortController.signal+ )+ this.session = receiptFromResponse(completedResponse)+ this.state = 'completed'+ this.uploadedBytes = this.input.file.size+ this.input.onProgress?.({+ uploadedBytes: this.uploadedBytes,+ totalBytes: this.input.file.size,+ partNumber: Math.max(0, prepared.session.partCount - 1),+ partCount: prepared.session.partCount,+ })+ this.emit()+ await this.input.onClearPersisted?.(prepared.session.uploadId)+ return this.session+ } catch (error) {+ if (this.canceled) {+ this.state = 'aborted'+ this.emit()+ throw error+ }+ if (this.pauseRequested && this.session) {+ this.state = 'paused'+ this.emit()+ return this.session+ }+ this.state = 'failed'+ this.emit()+ throw error+ }+ }+}++export function createGfsUploadJob(input: GfsUploadJobInput): GfsUploadJob {+ return new GfsUploadJob(input)+}export function assertGfsFileUploadSize(byteLength: number): void {if (byteLength > GFS_FILE_UPLOAD_MAX_BYTES) {throw new Error(`GFS uploads are limited to ${GFS_FILE_UPLOAD_MAX_MEGABYTES} MB per file.`)}}++export async function uploadGfsFile(input: {+ file: File+ name: string+ target: GfsUploadTarget+ signal?: AbortSignal+ onProgress?: (progress: GfsUploadProgress) => void+}): Promise<UploadReceipt> {+ const job = createGfsUploadJob(input)+ return job.start()+}++/** Conservative compatibility path for a server that predates upload v2. */+export async function uploadGfsFileLegacy(input: {+ file: File+ name: string+ target: GfsUploadTarget+}): Promise<unknown> {+ if (input.file.size > GFS_LEGACY_UPLOAD_MAX_BYTES) {+ throw new Error(+ `This writer does not advertise resumable uploads; legacy GFS is limited to ${GFS_LEGACY_UPLOAD_MAX_BYTES} bytes.`+ )+ }+ const contentBase64 = digestBase64(await input.file.arrayBuffer())+ if (input.target.operation === 'create') {+ if (!input.target.parentRid) throw new Error('create upload target is required')+ return apiSend(+ 'POST',+ `/api/v1/gfs/proxy/v1/resources/${encodeURIComponent(input.target.parentRid)}/children`,+ { name: input.name, kind: 'file', contentBase64 }+ )+ }+ if (!input.target.resourceRid) throw new Error('replace upload target is required')+ return apiSend(+ 'PUT',+ `/api/v1/gfs/proxy/v1/resources/${encodeURIComponent(input.target.resourceRid)}/content`,+ { contentBase64, ifMatch: input.target.ifMatch }+ )+}diff --git a/control-ui/playwright.config.ts b/control-ui/playwright.config.tsindex 029ecbd7d..25304b9d9 100644--- a/control-ui/playwright.config.ts+++ b/control-ui/playwright.config.ts@@ -97,7 +97,12 @@ export default defineConfig({},retries: 0,projects: [- { name: 'chromium', use: { browserName: 'chromium' } },+ { name: 'chromium', testIgnore: '**/gfs-upload-v2.spec.ts', use: { browserName: 'chromium' } },+ {+ name: 'large-upload',+ testMatch: /gfs-upload-v2\.spec\.ts/,+ use: { browserName: 'chromium', trace: 'retain-on-failure' },+ },...gfsAuthCrossBrowserProjects,],})diff --git a/deploy/base/control-plane/control-api.yaml b/deploy/base/control-plane/control-api.yamlindex 3d178e768..3b2ff4ba7 100644--- a/deploy/base/control-plane/control-api.yaml+++ b/deploy/base/control-plane/control-api.yaml@@ -125,14 +125,11 @@ spec:resources:limits:cpu: 300m- # GFS uploads arrive base64-in-JSON and are fully buffered: one upload- # holds ~5 transient copies (express raw buffer, JSON.parse input, parsed- # contentBase64 string, JSON.stringify output, undici write buffer). The- # gfsc write cap is 24MiB (GFS_MAX_WRITE_BODY_BYTES), i.e. a 16MB raw file- # → ~22.4MB body → ~125MiB transient over the ~86MiB idle baseline. At 256Mi- # 2 concurrent uploads OOMKilled (exit 137) the pod; 768Mi holds ~5 concurrent- # worst-case uploads with margin. EVERY overlay must keep >=768Mi or the OOM- # returns exactly where the 7.5MB PDF failure was reported:+ # Legacy GFS mutations arrive base64-in-JSON and are fully buffered.+ # v2 part PUTs bypass this parser and stream one bounded part at a time.+ # Keep the existing 768Mi legacy headroom; do not treat it as a reason+ # to raise any JSON cap for the 200 MiB product boundary. EVERY overlay+ # must keep >=768Mi for the legacy path:# - deploy/overlays/minikube/patches/resource-limits.yaml (in this repo)# - keyper-labs/evenfire-infra gcp-dev/gcp-prod patches/resource-limits.yaml# (private infra repo — both currently pin 512Mi; a companion PR mustdiff --git a/deploy/base/control-plane/control-ui.yaml b/deploy/base/control-plane/control-ui.yamlindex f61c57235..17087f524 100644--- a/deploy/base/control-plane/control-ui.yaml+++ b/deploy/base/control-plane/control-ui.yaml@@ -33,8 +33,9 @@ spec:# Server-side control-ui proxy timeout in milliseconds. The app-router handler# app/control-api/[...path]/route.ts OWNS /control-api/* (the next.config.js# rewrite was removed), so this value governs the proxied upstream fetch. It- # keeps large GFS uploads (file sent base64-encoded, ~+33%) from being cut- # mid-body, and applies only to body-bearing methods so SSE streams are unaffected.+ # keeps legacy JSON GFS mutations from being cut mid-body. Upload v2 part+ # requests are raw streamed 8/16 MiB bodies and use the separate v2 timeout+ # in the route handler; this value does not become a 200 MiB body buffer.- name: CONTROL_API_PROXY_TIMEOUT_MSvalue: "300000"- name: CONTROL_UI_PUBLIC_TOKEN_CSRF_SECRET@@ -65,10 +66,9 @@ spec:resources:limits:cpu: 300m- # The /control-api proxy route handler buffers a full arrayBuffer copy of- # the request body (~22.4MB for a 16MB GFS upload) before forwarding; 256Mi- # is tight under concurrent uploads. 512Mi gives headroom over the Next.js- # baseline. The minikube overlay must not reduce this.+ # Legacy JSON mutations are buffered by the generic proxy; v2 part+ # requests bypass that path and stream. Keep headroom for the legacy+ # cap and the Next.js baseline. The minikube overlay must not reduce this.memory: 512Mirequests:cpu: 50mdiff --git a/deploy/base/control-plane/host-context-controller.yaml b/deploy/base/control-plane/host-context-controller.yamlindex 47786ee6b..df8126a53 100644--- a/deploy/base/control-plane/host-context-controller.yaml+++ b/deploy/base/control-plane/host-context-controller.yaml@@ -66,15 +66,13 @@ spec:value: clerum/mcp-host:0.9.5- name: CONTEXT_MAPPER_EGRESS_PROXY_IMAGEvalue: clerum/nginx-egress-proxy:0.1.0- # GFS upload ceiling: gfsc write-body cap (bytes), passed through to the gfsc- # pod. Raised from the 16MiB default to 24MiB so a 16MB raw file (base64 body- # ≈ 22.4MB) is accepted with margin. Keep in step with the client cap- # (GFS_FILE_UPLOAD_MAX_BYTES in control-ui) and gfsc memory below.+ # Legacy JSON GFS mutation cap (bytes), passed through to generated gfsc+ # pods. Upload v2 uses raw indexed parts and is configured independently+ # through CONTEXT_MAPPER_GFSC_UPLOAD_* private-infra settings.- name: GFS_MAX_WRITE_BODY_BYTESvalue: "25165824"- # gfsc memory limit: a 24MiB-cap upload holds ~4.3× the body (~103MiB) over a- # ~40MiB baseline; 512Mi absorbs concurrent uploads without OOM (256Mi default- # was tight at the 24MiB cap).+ # gfsc memory limit for the legacy buffered path. v2 part streaming must be+ # validated against the configured part/global concurrency budgets instead.- name: CONTEXT_MAPPER_GFSC_LIMIT_MEMORYvalue: 512Mi- name: STDIO_BRIDGE_IMAGEdiff --git a/deploy/base/profiles/configmaps.yaml b/deploy/base/profiles/configmaps.yamlindex e0f872719..b73f3cb5b 100644--- a/deploy/base/profiles/configmaps.yaml+++ b/deploy/base/profiles/configmaps.yaml@@ -24,11 +24,10 @@ data:resolver kube-dns.kube-system.svc.cluster.local valid=10s ipv6=off;- # nginx defaults client_max_body_size to 1m, which 413s me-path GFS- # uploads (base64-in-JSON) at ~1MB. Homologate with the gfsc write cap- # (GFS_MAX_WRITE_BODY_BYTES = 25165824 bytes, 24MiB) so the me-path- # accepts the same payloads the operator path already does; gfsc remains- # the authoritative size gate downstream.+ # nginx defaults client_max_body_size to 1m. Keep the legacy JSON path at+ # its 24MiB cap; v2 parts are raw streamed requests and each is <=16MiB,+ # so this gateway cap stays above the per-request contract without becoming+ # a 200MiB whole-file allowance.client_max_body_size 25165824;# Homologate the funnel's idle timers with the 300s deadline the rest of thediff --git a/deploy/scripts/provision-gfs-db.sh b/deploy/scripts/provision-gfs-db.shindex 7e3d0ca2a..b6c358929 100755--- a/deploy/scripts/provision-gfs-db.sh+++ b/deploy/scripts/provision-gfs-db.sh@@ -117,6 +117,8 @@ SELECT (:'role_kind' <> 'reader' OR (AND NOT has_table_privilege(:'role_name', 'gfs_blob_manifests', 'DELETE,TRUNCATE,TRIGGER')AND NOT has_any_column_privilege(:'role_name', 'gfs_audit', 'SELECT,UPDATE,REFERENCES')AND NOT has_table_privilege(:'role_name', 'gfs_audit', 'DELETE,TRUNCATE,TRIGGER')+ AND NOT has_table_privilege(:'role_name', 'gfs_upload_sessions', 'SELECT,INSERT,UPDATE,DELETE,TRUNCATE,REFERENCES,TRIGGER')+ AND NOT has_table_privilege(:'role_name', 'gfs_upload_parts', 'SELECT,INSERT,UPDATE,DELETE,TRUNCATE,REFERENCES,TRIGGER'))) AS privilege_ok \gset\if :privilege_ok\else@@ -146,6 +148,16 @@ SELECT (:'role_kind' <> 'writer' OR (AND NOT has_sequence_privilege(:'role_name', 'gfs_audit_sequence_no_seq', 'UPDATE')AND NOT has_any_column_privilege(:'role_name', 'gfs_audit', 'SELECT,UPDATE,REFERENCES')AND NOT has_table_privilege(:'role_name', 'gfs_audit', 'DELETE,TRUNCATE,TRIGGER')+ AND has_table_privilege(:'role_name', 'gfs_upload_sessions', 'SELECT')+ AND has_table_privilege(:'role_name', 'gfs_upload_sessions', 'INSERT')+ AND has_table_privilege(:'role_name', 'gfs_upload_sessions', 'UPDATE')+ AND has_table_privilege(:'role_name', 'gfs_upload_sessions', 'DELETE')+ AND has_table_privilege(:'role_name', 'gfs_upload_parts', 'SELECT')+ AND has_table_privilege(:'role_name', 'gfs_upload_parts', 'INSERT')+ AND has_table_privilege(:'role_name', 'gfs_upload_parts', 'UPDATE')+ AND has_table_privilege(:'role_name', 'gfs_upload_parts', 'DELETE')+ AND NOT has_table_privilege(:'role_name', 'gfs_upload_sessions', 'TRUNCATE,REFERENCES,TRIGGER')+ AND NOT has_table_privilege(:'role_name', 'gfs_upload_parts', 'TRUNCATE,REFERENCES,TRIGGER'))) AS writer_privilege_ok \gset\if :writer_privilege_ok\elsediff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex f634eaf67..36fc9a705 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -1,3 +1,4 @@+import { randomUUID } from 'node:crypto'import fs from 'node:fs'import path from 'node:path'import { AuthClient } from './authClient.js'@@ -15,8 +16,16 @@ import {selectDesktopRuntimeConfigOption,} from './config.js'import { type DelegationAffordances, delegationAffordances } from './gfs/delegation.js'-import { GfsClient, parseSubjectKey } from './gfs/uriHandler.js'-import { ApiError, requestJson } from './httpClient.js'+import {+ DesktopGfsUploadJob,+ DesktopUploadCapabilityError,+ type DesktopUploadInput,+ type DesktopUploadSession,+ type DesktopUploadTransport,+ uploadLocalFile,+} from './gfs/upload.js'+import { GfsClient, type GfsResourceView, parseSubjectKey } from './gfs/uriHandler.js'+import { ApiError, requestJson, withTimeout } from './httpClient.js'import { MemberRegistrationServiceClient } from './memberRegistrationServiceClient.js'import { tryGetPluginSdkRuntime } from './pluginSdkRuntime.js'import { RpcProxyClient } from './rpcProxyClient.js'@@ -277,6 +286,96 @@ const RECONNECT_ATTEMPT_TIMEOUT_MS = 8000const RECONNECT_WAITING_FOR_OPEN_TIMEOUT_MS = 195_000const SAVED_SESSION_RESTORE_RETRY_DELAY_MS = 5_000+const gfsUploadTransport: DesktopUploadTransport = {+ requestJson,+ requestPart: async (url, token, headers, body, timeoutMs, signal) => {+ const response = await fetch(url, {+ method: 'PUT',+ headers: { authorization: `Bearer ${token}`, ...headers },+ body: body as unknown as BodyInit,+ // Node's fetch requires this opt-in for a streaming request body.+ duplex: 'half',+ signal: withTimeout(signal, timeoutMs),+ } as RequestInit & { duplex: 'half' })+ const text = await response.text()+ return { status: response.status, text }+ },+}++const LEGACY_GFS_MAX_FILE_BYTES = 16 * 1024 * 1024++async function legacyEncodedFile(filePath: string): Promise<string> {+ const info = await fs.promises.stat(filePath)+ if (!info.isFile()) throw new Error('selected upload path is not a regular file')+ if (info.size > LEGACY_GFS_MAX_FILE_BYTES) {+ throw new Error(+ `This writer does not advertise resumable uploads; legacy GFS is limited to ${LEGACY_GFS_MAX_FILE_BYTES} bytes.`+ )+ }+ return (await fs.promises.readFile(filePath)).toString('base64')+}++function legacyReceipt(+ resource: GfsResourceView,+ operation: 'create' | 'replace'+): DesktopUploadSession {+ return {+ uploadId: resource.resourceId,+ drive: resource.drive,+ operation,+ expectedBytes: resource.bytes,+ partBytes: resource.bytes || 1,+ partCount: resource.bytes === 0 ? 0 : 1,+ state: 'completed',+ contiguousBytes: resource.bytes,+ committedBytes: resource.bytes,+ committedPartCount: resource.bytes === 0 ? 0 : 1,+ activePartCount: 0,+ expiresAt: new Date(Date.now()).toISOString(),+ resultResourceId: resource.resourceId,+ resultVersion: resource.version,+ }+}++interface PersistedDesktopGfsUpload {+ uploadId: string+ filePath: string+ fileName: string+ fileSize: number+ target: {+ operation: 'create' | 'replace'+ parentRid?: string+ resourceRid?: string+ ifMatch?: number+ }+ name: string+ session: DesktopUploadSession+}++interface DesktopGfsUploadSummary {+ uploadId: string+ fileName: string+ fileSize: number+ target: PersistedDesktopGfsUpload['target']+ name: string+}++const DESKTOP_GFS_UPLOAD_STATE_FILE = 'gfs-upload-sessions.json'++function isPersistedDesktopGfsUpload(value: unknown): value is PersistedDesktopGfsUpload {+ if (!value || typeof value !== 'object') return false+ const item = value as Partial<PersistedDesktopGfsUpload>+ return (+ typeof item.uploadId === 'string' &&+ typeof item.filePath === 'string' &&+ typeof item.fileName === 'string' &&+ typeof item.fileSize === 'number' &&+ typeof item.name === 'string' &&+ Boolean(item.target) &&+ Boolean(item.session)+ )+}+export class AppService {private readonly authClient = new AuthClient()private readonly memberRegistrationServiceClient = new MemberRegistrationServiceClient()@@ -307,6 +406,13 @@ export class AppService {private savedSessionRestoreAttemptedEnvKey: string | null = nullprivate savedSessionRestoreAttemptedAtMs = 0private logoutInProgress = false+ private readonly gfsUploadJobs = new Map<+ string,+ {+ job: DesktopGfsUploadJob+ promise: Promise<DesktopUploadSession>+ }+ >()private sessionGeneration = 0private sandboxUiLifecycleQueue: Promise<void> = Promise.resolve()private workflowApprovalTeamById = new Map<string, string>()@@ -661,6 +767,11 @@ export class AppService {this.teamDirectoryCache = nullthis.workflowApprovalTeamById.clear()this.workflowTeamByKey.clear()+ // Resume only the bounded, metadata-only sessions persisted by the main+ // process. The source fence in DesktopGfsUploadJob rejects a changed or+ // missing local file; failed records remain available for an explicit+ // user re-selection instead of silently replacing bytes.+ void this.resumePersistedDesktopGfsUploads()// Launch-time sandbox-ui partition GC. Fire-and-forget: a failure// here must not block the user from logging in. Any network or fs// error is logged inside the module.@@ -706,6 +817,41 @@ export class AppService {}}+ private async resumePersistedDesktopGfsUploads(): Promise<void> {+ try {+ const records = await this.readDesktopGfsUploadState()+ for (const record of records) {+ if (this.gfsUploadJobs.has(record.uploadId)) continue+ try {+ const info = await fs.promises.stat(record.filePath)+ if (!info.isFile() || info.size !== record.fileSize) {+ console.warn(+ `[AppService] Skipping persisted GFS upload ${record.uploadId}: source file no longer matches`+ )+ continue+ }+ await this.startDesktopGfsUpload({+ filePath: record.filePath,+ name: record.name,+ drive: record.session.drive,+ operation: record.target.operation,+ parentRid: record.target.parentRid,+ resourceRid: record.target.resourceRid,+ ifMatch: record.target.ifMatch,+ resumeUploadId: record.uploadId,+ })+ } catch (error) {+ console.warn(+ `[AppService] Could not resume persisted GFS upload ${record.uploadId}:`,+ error+ )+ }+ }+ } catch (error) {+ console.warn('[AppService] Could not inspect persisted GFS uploads:', error)+ }+ }+private async completePasswordLogin(email: string, password: string): Promise<SessionState> {const result = await this.authClient.passwordLogin(email, password)this.logoutInProgress = false@@ -1124,6 +1270,165 @@ export class AppService {)}+ private async desktopGfsUploadStatePath(): Promise<string> {+ const { app } = await import('electron')+ return path.join(app.getPath('userData'), DESKTOP_GFS_UPLOAD_STATE_FILE)+ }++ private async readDesktopGfsUploadState(): Promise<PersistedDesktopGfsUpload[]> {+ try {+ const raw = await fs.promises.readFile(await this.desktopGfsUploadStatePath(), 'utf8')+ const parsed = JSON.parse(raw) as unknown+ if (!Array.isArray(parsed)) return []+ return parsed.filter(isPersistedDesktopGfsUpload).slice(-100)+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') return []+ console.warn('[AppService] Could not read GFS upload state:', error)+ return []+ }+ }++ private async writeDesktopGfsUploadState(records: PersistedDesktopGfsUpload[]): Promise<void> {+ const filePath = await this.desktopGfsUploadStatePath()+ await fs.promises.mkdir(path.dirname(filePath), { recursive: true })+ const temporaryPath = `${filePath}.${randomUUID()}.tmp`+ await fs.promises.writeFile(temporaryPath, JSON.stringify(records.slice(-100)), { mode: 0o600 })+ await fs.promises.rename(temporaryPath, filePath)+ }++ private async persistDesktopGfsUpload(record: PersistedDesktopGfsUpload): Promise<void> {+ const records = await this.readDesktopGfsUploadState()+ const next = records.filter(item => item.uploadId !== record.uploadId)+ next.push(record)+ await this.writeDesktopGfsUploadState(next)+ }++ private async clearDesktopGfsUpload(uploadId: string): Promise<void> {+ const records = await this.readDesktopGfsUploadState()+ await this.writeDesktopGfsUploadState(records.filter(item => item.uploadId !== uploadId))+ }++ private async startDesktopGfsUpload(+ input: Omit<DesktopUploadInput, 'transport' | 'token' | 'baseUrl'> & { resumeUploadId?: string }+ ): Promise<DesktopUploadSession> {+ const token = this.requireSessionToken()+ const job = new DesktopGfsUploadJob({+ ...input,+ baseUrl: config.externalRestApiBaseUrl,+ token,+ transport: gfsUploadTransport,+ onPersist: record => this.persistDesktopGfsUpload(record),+ onClearPersisted: uploadId => this.clearDesktopGfsUpload(uploadId),+ })+ const promise = job.start()+ const session = await job.waitForSession()+ this.gfsUploadJobs.set(session.uploadId, { job, promise })+ void promise.then(+ () => undefined,+ error => console.warn('[AppService] GFS upload job failed:', error)+ )+ return session+ }++ async startGfsFileUpload(+ parentResourceId: string,+ name: string,+ filePath: string,+ drive?: string,+ resumeUploadId?: string+ ): Promise<DesktopUploadSession> {+ return this.startDesktopGfsUpload({+ filePath,+ name,+ drive: drive ?? 'main',+ operation: 'create',+ parentRid: parentResourceId,+ resumeUploadId,+ })+ }++ async startGfsFileReplace(+ resourceId: string,+ filePath: string,+ drive?: string,+ ifMatch?: number,+ resumeUploadId?: string+ ): Promise<DesktopUploadSession> {+ return this.startDesktopGfsUpload({+ filePath,+ name: resourceId,+ drive: drive ?? 'main',+ operation: 'replace',+ resourceRid: resourceId,+ ifMatch,+ resumeUploadId,+ })+ }++ async getGfsUploadSnapshot(uploadId: string) {+ const entry = this.gfsUploadJobs.get(uploadId)+ if (!entry) return null+ return entry.job.snapshot()+ }++ async pauseGfsUpload(uploadId: string): Promise<DesktopUploadSession> {+ const entry = this.gfsUploadJobs.get(uploadId)+ if (!entry) throw new Error('GFS upload is not active in this desktop session')+ return entry.job.pause()+ }++ async resumeGfsUpload(uploadId: string): Promise<DesktopUploadSession> {+ const entry = this.gfsUploadJobs.get(uploadId)+ if (!entry) throw new Error('GFS upload is not active in this desktop session')+ return entry.job.resume()+ }++ async cancelGfsUpload(uploadId: string): Promise<void> {+ const entry = this.gfsUploadJobs.get(uploadId)+ if (!entry) throw new Error('GFS upload is not active in this desktop session')+ await entry.job.cancel()+ this.gfsUploadJobs.delete(uploadId)+ }++ async listGfsUploadSessions(): Promise<DesktopGfsUploadSummary[]> {+ const records = await this.readDesktopGfsUploadState()+ return records.map(({ filePath: _filePath, session: _session, ...safe }) => safe)+ }++ async createGfsFileFromPath(+ parentResourceId: string,+ name: string,+ filePath: string,+ drive?: string+ ): Promise<DesktopUploadSession> {+ const token = this.requireSessionToken()+ try {+ return await uploadLocalFile({+ baseUrl: config.externalRestApiBaseUrl,+ token,+ filePath,+ name,+ drive: drive ?? 'main',+ operation: 'create',+ parentRid: parentResourceId,+ transport: gfsUploadTransport,+ })+ } catch (error) {+ if (!(error instanceof DesktopUploadCapabilityError)) throw error+ const resource = await this.gfsClient.createResource(+ {+ parentResourceId,+ drive,+ name,+ kind: 'file',+ encodedData: await legacyEncodedFile(filePath),+ },+ token+ )+ return legacyReceipt(resource, 'create')+ }+ }+async replaceGfsFile(resourceId: string, encodedData: string, drive?: string, ifMatch?: number) {return this.gfsClient.replaceFile({ resourceId, drive, encodedData, ifMatch },@@ -1131,6 +1436,40 @@ export class AppService {)}+ async replaceGfsFileFromPath(+ resourceId: string,+ filePath: string,+ drive?: string,+ ifMatch?: number+ ): Promise<DesktopUploadSession> {+ const token = this.requireSessionToken()+ try {+ return await uploadLocalFile({+ baseUrl: config.externalRestApiBaseUrl,+ token,+ filePath,+ name: resourceId,+ drive: drive ?? 'main',+ operation: 'replace',+ resourceRid: resourceId,+ ifMatch,+ transport: gfsUploadTransport,+ })+ } catch (error) {+ if (!(error instanceof DesktopUploadCapabilityError)) throw error+ const resource = await this.gfsClient.replaceFile(+ {+ resourceId,+ drive,+ ifMatch,+ encodedData: await legacyEncodedFile(filePath),+ },+ token+ )+ return legacyReceipt(resource, 'replace')+ }+ }+async renameGfsResource(resourceId: string, newName: string, drive?: string, ifMatch?: number) {return this.gfsClient.renameResource({ resourceId, drive, newName, ifMatch },diff --git a/desktop-app/src/config.ts b/desktop-app/src/config.tsindex d1f89ba4d..c5fd3b37c 100644--- a/desktop-app/src/config.ts+++ b/desktop-app/src/config.ts@@ -557,10 +557,11 @@ export const config: DesktopConfig = {desktopProfileUiBaseUrl: deriveProfileUiBaseUrl(initialRuntimeConfig.externalRestApiBaseUrl),desktopProfileUiBaseUrlExplicit: hasExplicitProfileUiBaseUrl(),requestTimeoutMs: Number(requiredOrDefault('REQUEST_TIMEOUT_MS', '60000')),- // Generous per-call deadline for GFS uploads: a 16 MB file is a ~22.4 MB- // base64 body, ~60s alone on a slow uplink — the 60s REQUEST_TIMEOUT_MS would- // abort it while every downstream hop still waits 300s. Parity with control-ui- // GFS_UPLOAD_TIMEOUT_MS.+ // Generous deadline for legacy JSON GFS uploads: a 16 MiB file is a ~22.4 MiB+ // base64 body, ~60s alone on a slow uplink. v2 streams binary indexed parts and+ // has its own per-part/finalization deadlines.+ // Keep legacy parity with control-ui GFS_UPLOAD_TIMEOUT_MS while each v2 part+ // remains bounded by the upload protocol timeout.gfsUploadTimeoutMs: Number(requiredOrDefault('GFS_UPLOAD_TIMEOUT_MS', '300000')),appName: initialRuntimeConfig.appName?.trim() || DEFAULT_APP_NAME,}diff --git a/desktop-app/src/gfs/upload.test.ts b/desktop-app/src/gfs/upload.test.tsnew file mode 100644index 000000000..54b11d77f--- /dev/null+++ b/desktop-app/src/gfs/upload.test.ts@@ -0,0 +1,444 @@+import { describe, expect, it } from 'vitest'+import { createHash } from 'node:crypto'+import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { DesktopGfsUploadJob, uploadLocalFile } from './upload.js'++describe('desktop GFS indexed uploader', () => {+ it('streams independent binary parts with base64 checksums and completes the session', async () => {+ const root = await mkdtemp(join(tmpdir(), 'evenfire-gfs-upload-'))+ try {+ const filePath = join(root, 'payload.bin')+ const bytes = Buffer.concat([Buffer.alloc(1024 * 1024, 0x11), Buffer.alloc(512 * 1024, 0x22)])+ await writeFile(filePath, bytes)+ const partRequests: Array<{ headers: Record<string, string>; body: Buffer }> = []+ const transport = {+ async requestJson<T>(method: 'GET' | 'POST' | 'DELETE'): Promise<T> {+ if (method === 'GET') {+ return {+ ok: true,+ data: { upload: { resumableV2: { enabled: true, maxFileBytes: 200 * 1024 * 1024 } } },+ } as T+ }+ if (method === 'POST') {+ return {+ ok: true,+ data: {+ uploadId: '11111111-1111-4111-8111-111111111111',+ drive: 'main',+ operation: 'create',+ expectedBytes: bytes.length,+ partBytes: 1024 * 1024,+ partCount: 2,+ state: 'initiated',+ contiguousBytes: 0,+ committedBytes: 0,+ committedPartCount: 0,+ activePartCount: 0,+ expiresAt: new Date(Date.now() + 60_000).toISOString(),+ resultResourceId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ resultVersion: 1,+ },+ } as T+ }+ throw new Error(`unexpected ${method}`)+ },+ async requestPart(+ _url: string,+ _token: string,+ headers: Record<string, string>,+ body: NodeJS.ReadableStream+ ) {+ const chunks: Buffer[] = []+ for await (const chunk of body as AsyncIterable<Buffer>) chunks.push(Buffer.from(chunk))+ partRequests.push({ headers, body: Buffer.concat(chunks) })+ return { status: 204, text: '' }+ },+ }+ const result = await uploadLocalFile({+ baseUrl: 'https://api.example',+ token: 'token',+ filePath,+ name: 'payload.bin',+ drive: 'main',+ operation: 'create',+ parentRid: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',+ transport,+ })+ expect(result.state).toBe('initiated')+ expect(partRequests).toHaveLength(2)+ for (const request of partRequests) {+ const expected = createHash('sha256').update(request.body).digest('base64')+ expect(request.headers['upload-checksum']).toBe(`sha256 ${expected}`)+ expect(Number(request.headers['upload-chunk-length'])).toBe(request.body.length)+ expect(request.headers['content-type']).toBe('application/offset+octet-stream')+ }+ expect(+ Buffer.concat(partRequests.map(request => request.body).sort((a, b) => a[0]! - b[0]!))+ ).toHaveLength(bytes.length)+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ })++ it('resumes from sparse status and does not replay a committed part', async () => {+ const root = await mkdtemp(join(tmpdir(), 'evenfire-gfs-upload-resume-'))+ try {+ const filePath = join(root, 'payload.bin')+ const bytes = Buffer.concat([+ Buffer.alloc(1024 * 1024, 0x31),+ Buffer.alloc(1024 * 1024, 0x32),+ ])+ await writeFile(filePath, bytes)+ const committedSha = createHash('sha256')+ .update(bytes.subarray(0, 1024 * 1024))+ .digest('base64')+ const partNumbers: number[] = []+ const session = {+ uploadId: '22222222-2222-4222-8222-222222222222',+ drive: 'main',+ operation: 'create' as const,+ expectedBytes: bytes.length,+ partBytes: 1024 * 1024,+ partCount: 2,+ state: 'uploading',+ contiguousBytes: bytes.length / 2,+ committedBytes: bytes.length / 2,+ committedPartCount: 1,+ activePartCount: 0,+ expiresAt: new Date(Date.now() + 60_000).toISOString(),+ }+ const transport = {+ async requestJson<T>(method: 'GET' | 'POST' | 'HEAD' | 'DELETE', url: string): Promise<T> {+ if (method === 'GET' && url.endsWith('/capabilities'))+ return { ok: true, data: { upload: { resumableV2: { enabled: true } } } } as T+ if (method === 'HEAD') return {} as T+ if (method === 'GET' && url.includes('/status'))+ return {+ ok: true,+ data: {+ session,+ parts: [+ {+ partNumber: 0,+ offsetBytes: 0,+ lengthBytes: bytes.length / 2,+ sha256: committedSha,+ },+ ],+ },+ } as T+ if (method === 'POST' && url.endsWith('/complete'))+ return {+ ok: true,+ data: {+ ...session,+ state: 'completed',+ committedBytes: bytes.length,+ committedPartCount: 2,+ resultResourceId: 'resource-2',+ resultVersion: 2,+ },+ } as T+ throw new Error(`unexpected ${method} ${url}`)+ },+ async requestPart(+ _url: string,+ _token: string,+ headers: Record<string, string>,+ body: NodeJS.ReadableStream+ ) {+ partNumbers.push(Number(headers['upload-part-number']))+ for await (const _chunk of body as AsyncIterable<Buffer>) {+ /* drain */+ }+ return { status: 204, text: '' }+ },+ }+ const result = await new DesktopGfsUploadJob({+ baseUrl: 'https://api.example',+ token: 'token',+ filePath,+ name: 'payload.bin',+ drive: 'main',+ operation: 'create',+ parentRid: 'parent-2',+ resumeUploadId: session.uploadId,+ transport,+ }).start()+ expect(result.state).toBe('completed')+ expect(partNumbers).toEqual([1])+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ })++ it('rejects a resumed committed part when the local bytes no longer match its server checksum', async () => {+ const root = await mkdtemp(join(tmpdir(), 'evenfire-gfs-upload-resume-mismatch-'))+ try {+ const filePath = join(root, 'payload.bin')+ const original = Buffer.alloc(1024, 0x31)+ await writeFile(filePath, Buffer.alloc(1024, 0x42))+ const committedSha = createHash('sha256').update(original).digest('base64')+ const session = {+ uploadId: '25252525-2525-4252-8252-252525252525',+ drive: 'main',+ operation: 'create' as const,+ expectedBytes: 1024,+ partBytes: 1024,+ partCount: 1,+ state: 'uploading',+ contiguousBytes: 1024,+ committedBytes: 1024,+ committedPartCount: 1,+ activePartCount: 0,+ expiresAt: new Date(Date.now() + 60_000).toISOString(),+ }+ let partRequests = 0+ let completeCalls = 0+ const transport = {+ async requestJson<T>(method: 'GET' | 'POST' | 'HEAD', url: string): Promise<T> {+ if (method === 'GET' && url.endsWith('/capabilities'))+ return { ok: true, data: { upload: { resumableV2: { enabled: true } } } } as T+ if (method === 'HEAD') return {} as T+ if (method === 'GET' && url.includes('/status'))+ return {+ ok: true,+ data: {+ session,+ parts: [{ partNumber: 0, offsetBytes: 0, lengthBytes: 1024, sha256: committedSha }],+ },+ } as T+ if (method === 'POST' && url.endsWith('/complete')) {+ completeCalls += 1+ return { ok: true, data: { ...session, state: 'completed' } } as T+ }+ throw new Error(`unexpected ${method} ${url}`)+ },+ async requestPart() {+ partRequests += 1+ return { status: 204, text: '' }+ },+ }+ await expect(+ new DesktopGfsUploadJob({+ baseUrl: 'https://api.example',+ token: 'token',+ filePath,+ name: 'payload.bin',+ drive: 'main',+ operation: 'create',+ parentRid: 'parent-mismatch',+ resumeUploadId: session.uploadId,+ transport,+ }).start()+ ).rejects.toThrow(/source_changed: committed part 0/)+ expect(partRequests).toBe(0)+ expect(completeCalls).toBe(0)+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ })++ it('reconciles a completed session after a lost complete response without replaying parts', async () => {+ const root = await mkdtemp(join(tmpdir(), 'evenfire-gfs-upload-completed-reconcile-'))+ try {+ const filePath = join(root, 'payload.bin')+ await writeFile(filePath, Buffer.alloc(1024, 0x51))+ const session = {+ uploadId: '26262626-2626-4262-8262-262626262626',+ drive: 'main',+ operation: 'create' as const,+ expectedBytes: 1024,+ partBytes: 1024,+ partCount: 1,+ state: 'completed',+ contiguousBytes: 1024,+ committedBytes: 1024,+ committedPartCount: 1,+ activePartCount: 0,+ expiresAt: new Date(Date.now() + 60_000).toISOString(),+ resultResourceId: 'resource-completed',+ resultVersion: 7,+ }+ let partRequests = 0+ let completeCalls = 0+ const transport = {+ async requestJson<T>(method: 'GET' | 'POST' | 'HEAD', url: string): Promise<T> {+ if (method === 'GET' && url.endsWith('/capabilities'))+ return { ok: true, data: { upload: { resumableV2: { enabled: true } } } } as T+ if (method === 'HEAD') return {} as T+ if (method === 'GET' && url.includes('/status'))+ return { ok: true, data: { session, parts: [] } } as T+ if (method === 'POST' && url.endsWith('/complete')) {+ completeCalls += 1+ return { ok: true, data: session } as T+ }+ throw new Error(`unexpected ${method} ${url}`)+ },+ async requestPart() {+ partRequests += 1+ return { status: 204, text: '' }+ },+ }+ const result = await new DesktopGfsUploadJob({+ baseUrl: 'https://api.example',+ token: 'token',+ filePath,+ name: 'payload.bin',+ drive: 'main',+ operation: 'create',+ parentRid: 'parent-completed',+ resumeUploadId: session.uploadId,+ transport,+ }).start()+ expect(result.state).toBe('completed')+ expect(partRequests).toBe(0)+ expect(completeCalls).toBe(0)+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ })++ it('refuses to complete when the source changes between parts and complete', async () => {+ const root = await mkdtemp(join(tmpdir(), 'evenfire-gfs-upload-source-'))+ try {+ const filePath = join(root, 'payload.bin')+ await writeFile(filePath, Buffer.alloc(1024, 0x41))+ let completeCalled = false+ const session = {+ uploadId: '33333333-3333-4333-8333-333333333333',+ drive: 'main',+ operation: 'create' as const,+ expectedBytes: 1024,+ partBytes: 1024,+ partCount: 1,+ state: 'initiated',+ contiguousBytes: 0,+ committedBytes: 0,+ committedPartCount: 0,+ activePartCount: 0,+ expiresAt: new Date(Date.now() + 60_000).toISOString(),+ }+ const transport = {+ async requestJson<T>(method: 'GET' | 'POST' | 'HEAD' | 'DELETE', url: string): Promise<T> {+ if (method === 'GET')+ return { ok: true, data: { upload: { resumableV2: { enabled: true } } } } as T+ if (method === 'POST' && url.endsWith('/uploads')) return { ok: true, data: session } as T+ if (method === 'POST' && url.endsWith('/complete')) {+ completeCalled = true+ return { ok: true, data: { ...session, state: 'completed' } } as T+ }+ throw new Error(`unexpected ${method} ${url}`)+ },+ async requestPart(+ _url: string,+ _token: string,+ _headers: Record<string, string>,+ body: NodeJS.ReadableStream+ ) {+ for await (const _chunk of body as AsyncIterable<Buffer>) {+ /* drain */+ }+ await writeFile(filePath, Buffer.alloc(1024, 0x42))+ return { status: 204, text: '' }+ },+ }+ await expect(+ new DesktopGfsUploadJob({+ baseUrl: 'https://api.example',+ token: 'token',+ filePath,+ name: 'payload.bin',+ drive: 'main',+ operation: 'create',+ parentRid: 'parent-3',+ transport,+ }).start()+ ).rejects.toThrow(/source_changed/)+ expect(completeCalled).toBe(false)+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ })++ it('latches the four-to-two fallback after three retryable transport failures', async () => {+ const root = await mkdtemp(join(tmpdir(), 'evenfire-gfs-upload-fallback-'))+ try {+ const filePath = join(root, 'payload.bin')+ await writeFile(filePath, Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]))+ const statuses = [500, 500, 500, 204, 204, 204, 204]+ let partRequests = 0+ let completeCalls = 0+ const session = {+ uploadId: '44444444-4444-4444-8444-444444444444',+ drive: 'main',+ operation: 'create' as const,+ expectedBytes: 8,+ partBytes: 2,+ partCount: 4,+ state: 'initiated',+ contiguousBytes: 0,+ committedBytes: 0,+ committedPartCount: 0,+ activePartCount: 0,+ expiresAt: new Date(Date.now() + 60_000).toISOString(),+ }+ const transport = {+ async requestJson<T>(method: 'GET' | 'POST', url: string): Promise<T> {+ if (method === 'GET')+ return {+ ok: true,+ data: {+ upload: {+ resumableV2: {+ enabled: true,+ maxFileBytes: 200 * 1024 * 1024,+ maxConcurrentPartsPerSession: 4,+ fallbackConcurrency: 2,+ },+ },+ },+ } as T+ if (method === 'POST' && url.endsWith('/uploads')) {+ completeCalls += 1+ return { ok: true, data: session } as T+ }+ completeCalls += 1+ return {+ ok: true,+ data: { ...session, state: 'completed', committedBytes: 8, committedPartCount: 4 },+ } as T+ },+ async requestPart(+ _url: string,+ _token: string,+ _headers: Record<string, string>,+ body: NodeJS.ReadableStream+ ) {+ partRequests += 1+ for await (const _chunk of body as AsyncIterable<Buffer>) {+ /* drain */+ }+ return { status: statuses.shift() ?? 204, text: '' }+ },+ }+ const result = await new DesktopGfsUploadJob({+ baseUrl: 'https://api.example',+ token: 'token',+ filePath,+ name: 'payload.bin',+ drive: 'main',+ operation: 'create',+ parentRid: 'parent-fallback',+ transport,+ }).start()+ expect(result.state).toBe('completed')+ expect(partRequests).toBe(7)+ expect(completeCalls).toBe(2)+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ })+})diff --git a/desktop-app/src/gfs/upload.ts b/desktop-app/src/gfs/upload.tsnew file mode 100644index 000000000..b93047550--- /dev/null+++ b/desktop-app/src/gfs/upload.ts@@ -0,0 +1,817 @@+import { createHash, randomUUID } from 'node:crypto'+import { createReadStream } from 'node:fs'+import { stat } from 'node:fs/promises'+import type { Readable } from 'node:stream'++const GFS_UPLOAD_V2_PRODUCT_MAX_BYTES = 200 * 1024 * 1024+const GFS_UPLOAD_V2_PREFERRED_PART_BYTES = 8 * 1024 * 1024+const GFS_UPLOAD_V2_MAX_PART_BYTES = 16 * 1024 * 1024+const GFS_UPLOAD_V2_DEFAULT_CONCURRENCY = 4+const GFS_UPLOAD_V2_FALLBACK_CONCURRENCY = 2++export interface DesktopUploadSession {+ uploadId: string+ drive: string+ operation: 'create' | 'replace'+ expectedBytes: number+ partBytes: number+ partCount: number+ state: string+ contiguousBytes: number+ committedBytes: number+ committedPartCount: number+ activePartCount: number+ expiresAt: string+ resultResourceId?: string+ resultVersion?: number+ resultSha256?: string+}++export interface DesktopUploadPart {+ partNumber: number+ offsetBytes: number+ lengthBytes: number+ sha256: string+}++export interface DesktopUploadStatus {+ session: DesktopUploadSession+ parts: DesktopUploadPart[]+ nextCursor?: string | null+}++export type DesktopUploadJobState =+ | 'initiated'+ | 'uploading'+ | 'paused'+ | 'finalizing'+ | 'canceling'+ | 'completed'+ | 'aborted'+ | 'failed'++export interface DesktopUploadJobSnapshot {+ state: DesktopUploadJobState+ session: DesktopUploadSession | null+ uploadedBytes: number+ totalBytes: number+}++interface Envelope<T> {+ ok: boolean+ data?: T+ error?: { code?: string; message?: string }+}++interface UploadPartResponse {+ status: number+ text: string+}++interface UploadCapabilities {+ upload?: {+ resumableV2?: {+ enabled?: boolean+ maxFileBytes?: number+ preferredChunkBytes?: number+ maxChunkBytes?: number+ maxConcurrentPartsPerSession?: number+ fallbackConcurrency?: number+ }+ }+}++export class DesktopUploadCapabilityError extends Error {+ constructor(message: string, options?: { cause?: unknown }) {+ super(message, options)+ this.name = 'DesktopUploadCapabilityError'+ }+}++export interface DesktopUploadTransport {+ requestJson<T>(+ method: 'GET' | 'POST' | 'HEAD' | 'DELETE',+ url: string,+ options?: { token?: string; body?: unknown; timeoutMs?: number; signal?: AbortSignal }+ ): Promise<T>+ requestPart(+ url: string,+ token: string,+ headers: Record<string, string>,+ body: Readable,+ timeoutMs: number,+ signal?: AbortSignal+ ): Promise<UploadPartResponse>+}++export interface DesktopUploadInput {+ baseUrl: string+ token: string+ filePath: string+ name: string+ drive: string+ operation: 'create' | 'replace'+ parentRid?: string+ resourceRid?: string+ ifMatch?: number+ transport: DesktopUploadTransport+ onProgress?: (uploadedBytes: number, totalBytes: number) => void+ resumeUploadId?: string+ onState?: (snapshot: DesktopUploadJobSnapshot) => void+ onPersist?: (record: {+ uploadId: string+ filePath: string+ fileName: string+ fileSize: number+ target: {+ operation: 'create' | 'replace'+ parentRid?: string+ resourceRid?: string+ ifMatch?: number+ }+ name: string+ session: DesktopUploadSession+ }) => void | Promise<void>+ onClearPersisted?: (uploadId: string) => void | Promise<void>+ /** Main-process-only source fence; never crosses the renderer boundary. */+ sourceIdentity?: DesktopUploadSourceIdentity+ advertisedConcurrency?: number+ fallbackConcurrency?: number+}++export interface DesktopUploadSourceIdentity {+ dev?: number+ ino?: number+ size: number+ mtimeMs: number+ ctimeMs: number+}++const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000++function joinUrl(baseUrl: string, path: string): string {+ return `${baseUrl.replace(/\/+$/, '')}${path}`+}++function unwrap<T>(value: unknown): T {+ const envelope = value as Envelope<T> | undefined+ if (!envelope || envelope.ok !== true || envelope.data === undefined) {+ const code = envelope?.error?.code ?? 'upload_failed'+ const message = envelope?.error?.message ?? 'GFS upload request failed'+ throw new Error(`${code}: ${message}`)+ }+ return envelope.data+}++function retryable(status: number): boolean {+ return status === 408 || status === 425 || status === 429 || status >= 500+}++function retryableError(error: unknown): boolean {+ if (error instanceof Error && error.name === 'AbortError') return false+ if (error instanceof Error && error.message.startsWith('source_changed:')) return false+ const status =+ error && typeof error === 'object' && typeof (error as { status?: unknown }).status === 'number'+ ? Number((error as { status: number }).status)+ : undefined+ // A transport exception without an HTTP status is a network/timeout+ // failure. The caller still bounds it to the same two retries as a 5xx.+ return status === undefined || retryable(status)+}++function sleep(ms: number): Promise<void> {+ return new Promise(resolve => setTimeout(resolve, ms))+}++async function checksumPart(filePath: string, start: number, end: number): Promise<string> {+ const hash = createHash('sha256')+ for await (const chunk of createReadStream(filePath, {+ start,+ end,+ highWaterMark: 1024 * 1024,+ })) {+ hash.update(chunk as Buffer)+ }+ return hash.digest('base64')+}++async function validateResumedParts(+ filePath: string,+ session: DesktopUploadSession,+ parts: readonly DesktopUploadPart[]+): Promise<Set<number>> {+ const committed = new Set<number>()+ for (const part of parts) {+ if (+ !Number.isSafeInteger(part.partNumber) ||+ part.partNumber < 0 ||+ part.partNumber >= session.partCount+ ) {+ throw new Error(+ `resume_part_mismatch: committed part number ${part.partNumber} is outside the upload geometry`+ )+ }+ const expectedOffset = part.partNumber * session.partBytes+ const expectedLength = Math.min(session.partBytes, session.expectedBytes - expectedOffset)+ if (part.offsetBytes !== expectedOffset || part.lengthBytes !== expectedLength) {+ throw new Error(+ `resume_part_mismatch: committed part ${part.partNumber} does not match the upload geometry`+ )+ }+ if (committed.has(part.partNumber)) {+ throw new Error(+ `resume_part_mismatch: committed part ${part.partNumber} was returned more than once`+ )+ }+ const localChecksum = await checksumPart(+ filePath,+ part.offsetBytes,+ part.offsetBytes + part.lengthBytes - 1+ )+ if (localChecksum !== part.sha256) {+ throw new Error(+ `source_changed: committed part ${part.partNumber} differs from the local file`+ )+ }+ committed.add(part.partNumber)+ }+ return committed+}++async function sourceIdentity(filePath: string): Promise<DesktopUploadSourceIdentity> {+ const info = await stat(filePath)+ if (!info.isFile()) throw new Error('selected upload path is not a regular file')+ return {+ dev: typeof info.dev === 'number' ? info.dev : undefined,+ ino: typeof info.ino === 'number' ? info.ino : undefined,+ size: info.size,+ mtimeMs: info.mtimeMs,+ ctimeMs: info.ctimeMs,+ }+}++async function assertSourceIdentity(input: DesktopUploadInput): Promise<void> {+ if (!input.sourceIdentity) return+ const current = await sourceIdentity(input.filePath)+ const expected = input.sourceIdentity+ if (+ current.size !== expected.size ||+ current.mtimeMs !== expected.mtimeMs ||+ current.ctimeMs !== expected.ctimeMs ||+ current.dev !== expected.dev ||+ current.ino !== expected.ino+ ) {+ throw new Error('source_changed: the selected file changed during upload')+ }+}++async function putPart(+ input: DesktopUploadInput,+ session: DesktopUploadSession,+ partNumber: number,+ start: number,+ length: number,+ signal?: AbortSignal,+ onRetryableFailure?: () => void,+ onPartSuccess?: () => void+): Promise<void> {+ let attempt = 0+ for (;;) {+ await assertSourceIdentity(input)+ const checksum = await checksumPart(input.filePath, start, start + length - 1)+ await assertSourceIdentity(input)+ const body = createReadStream(input.filePath, {+ start,+ end: start + length - 1,+ highWaterMark: 1024 * 1024,+ })+ let response: UploadPartResponse+ try {+ response = await input.transport.requestPart(+ joinUrl(+ input.baseUrl,+ `/api/v1/me/gfs/uploads/${encodeURIComponent(session.uploadId)}/parts/${partNumber}`+ ),+ input.token,+ {+ 'content-type': 'application/offset+octet-stream',+ 'upload-part-number': String(partNumber),+ 'upload-offset': String(start),+ 'upload-chunk-length': String(length),+ 'upload-checksum': `sha256 ${checksum}`,+ 'content-length': String(length),+ },+ body,+ UPLOAD_TIMEOUT_MS,+ signal+ )+ } catch (error) {+ if (!retryableError(error) || attempt >= 2) throw error+ onRetryableFailure?.()+ await sleep(250 * 2 ** attempt)+ attempt += 1+ continue+ }+ if (response.status >= 200 && response.status < 300) {+ onPartSuccess?.()+ return+ }+ if (!retryable(response.status)) {+ throw uploadPartError(response.status, response.text)+ }+ onRetryableFailure?.()+ if (attempt >= 2) throw uploadPartError(response.status, response.text)+ await sleep(250 * 2 ** attempt)+ attempt += 1+ }+}++async function runParts(+ input: DesktopUploadInput,+ session: DesktopUploadSession,+ committedParts: ReadonlySet<number> = new Set(),+ signal?: AbortSignal,+ shouldPause: () => boolean = () => false+): Promise<{ paused: boolean; failed: number[]; retryableFailures: number }> {+ const parts = Array.from({ length: session.partCount }, (_, partNumber) => ({+ partNumber,+ offsetBytes: partNumber * session.partBytes,+ lengthBytes: Math.min(+ session.partBytes,+ session.expectedBytes - partNumber * session.partBytes+ ),+ }))+ const completedParts = new Set(committedParts)+ const failed = new Map<number, unknown>()+ const retryableFailed = new Set<number>()+ let retryableFailures = 0+ let consecutiveRetryableFailures = 0+ let downgraded = false+ const advertisedConcurrency = Number(input.advertisedConcurrency)+ const concurrency = Math.min(+ Number.isSafeInteger(advertisedConcurrency) && advertisedConcurrency > 0+ ? advertisedConcurrency+ : GFS_UPLOAD_V2_DEFAULT_CONCURRENCY,+ session.partCount || 1+ )+ const configuredFallback = Number(input.fallbackConcurrency)+ const fallbackConcurrency = Math.max(+ 1,+ Math.min(+ concurrency,+ Number.isSafeInteger(configuredFallback) && configuredFallback > 0+ ? configuredFallback+ : GFS_UPLOAD_V2_FALLBACK_CONCURRENCY+ )+ )+ const registerRetryableFailure = (): void => {+ retryableFailures += 1+ consecutiveRetryableFailures += 1+ if (!downgraded && consecutiveRetryableFailures >= 3 && concurrency > fallbackConcurrency)+ downgraded = true+ }+ const registerPartSuccess = (): void => {+ consecutiveRetryableFailures = 0+ }+ const execute = async (work: typeof parts, workers: number): Promise<void> => {+ let next = 0+ const runWorker = async (workerIndex: number): Promise<void> => {+ for (;;) {+ if (signal?.aborted) throw signal.reason+ if (shouldPause()) return+ if (downgraded && workerIndex >= fallbackConcurrency) return+ const partNumber = next+ next += 1+ if (partNumber >= work.length) return+ const part = work[partNumber]!+ if (completedParts.has(part.partNumber)) continue+ try {+ await putPart(+ input,+ session,+ part.partNumber,+ part.offsetBytes,+ part.lengthBytes,+ signal,+ registerRetryableFailure,+ registerPartSuccess+ )+ completedParts.add(part.partNumber)+ failed.delete(part.partNumber)+ retryableFailed.delete(part.partNumber)+ const completedBytes = [...completedParts].reduce(+ (sum, number) =>+ sum + Math.min(session.partBytes, session.expectedBytes - number * session.partBytes),+ 0+ )+ input.onProgress?.(completedBytes, session.expectedBytes)+ } catch (error) {+ if (shouldPause()) return+ if (error instanceof Error && error.name === 'AbortError') throw error+ failed.set(part.partNumber, error)+ if (retryableError(error)) retryableFailed.add(part.partNumber)+ }+ }+ }+ await Promise.all(Array.from({ length: workers }, (_, workerIndex) => runWorker(workerIndex)))+ }+ await execute(parts, concurrency)+ if (downgraded && retryableFailed.size > 0 && !shouldPause()) {+ const retryParts = parts.filter(part => retryableFailed.has(part.partNumber))+ await execute(retryParts, fallbackConcurrency)+ }+ return { paused: shouldPause(), failed: [...failed.keys()], retryableFailures }+}++function uploadPartError(status: number, text: string): Error & { status: number } {+ const error = new Error(+ `GFS part request failed (${status}): ${text || 'request failed'}`+ ) as Error & { status: number }+ error.status = status+ return error+}++export class DesktopGfsUploadJob {+ private readonly abortController = new AbortController()+ private session: DesktopUploadSession | null = null+ private state: DesktopUploadJobState = 'initiated'+ private uploadedBytes = 0+ private totalBytes = 0+ private pauseRequested = false+ private canceled = false+ private runPromise: Promise<DesktopUploadSession> | null = null++ constructor(private readonly input: DesktopUploadInput) {}++ snapshot(): DesktopUploadJobSnapshot {+ return {+ state: this.state,+ session: this.session,+ uploadedBytes: this.uploadedBytes,+ totalBytes: this.totalBytes,+ }+ }++ async start(): Promise<DesktopUploadSession> {+ if (this.runPromise) return this.runPromise+ this.runPromise = this.run()+ try {+ return await this.runPromise+ } finally {+ this.runPromise = null+ }+ }++ /** Resolve once the server has created or resumed the session, before parts finish. */+ async waitForSession(): Promise<DesktopUploadSession> {+ return this.ensureSession()+ }++ async pause(): Promise<DesktopUploadSession> {+ const session = await this.ensureSession()+ if (['completed', 'aborted', 'failed'].includes(session.state))+ throw new Error(`cannot pause upload in ${session.state}`)+ this.pauseRequested = true+ const paused = unwrap<DesktopUploadSession>(+ await this.input.transport.requestJson<Envelope<DesktopUploadSession>>(+ 'POST',+ joinUrl(+ this.input.baseUrl,+ `/api/v1/me/gfs/uploads/${encodeURIComponent(session.uploadId)}/pause`+ ),+ { token: this.input.token, body: {}, timeoutMs: UPLOAD_TIMEOUT_MS }+ )+ )+ this.session = paused+ this.state = 'paused'+ this.emit()+ return paused+ }++ async resume(): Promise<DesktopUploadSession> {+ const session = await this.ensureSession()+ if (session.state === 'completed') return session+ if (session.state !== 'paused') return this.start()+ this.pauseRequested = false+ const resumed = unwrap<DesktopUploadSession>(+ await this.input.transport.requestJson<Envelope<DesktopUploadSession>>(+ 'POST',+ joinUrl(+ this.input.baseUrl,+ `/api/v1/me/gfs/uploads/${encodeURIComponent(session.uploadId)}/resume`+ ),+ {+ token: this.input.token,+ body: {},+ timeoutMs: UPLOAD_TIMEOUT_MS,+ signal: this.abortController.signal,+ }+ )+ )+ this.session = resumed+ this.state = 'uploading'+ this.emit()+ return this.start()+ }++ async cancel(): Promise<void> {+ this.canceled = true+ this.pauseRequested = false+ this.state = 'canceling'+ this.emit()+ this.abortController.abort(new Error('GFS upload canceled'))+ const session = this.session+ if (session && !['completed', 'aborted'].includes(session.state)) {+ try {+ await this.input.transport.requestJson(+ 'DELETE',+ joinUrl(+ this.input.baseUrl,+ `/api/v1/me/gfs/uploads/${encodeURIComponent(session.uploadId)}`+ ),+ {+ token: this.input.token,+ timeoutMs: UPLOAD_TIMEOUT_MS,+ }+ )+ } catch (error) {+ const status =+ error &&+ typeof error === 'object' &&+ typeof (error as { status?: unknown }).status === 'number'+ ? Number((error as { status: number }).status)+ : undefined+ if (status === 409) {+ const observed = unwrap<DesktopUploadStatus>(+ await this.input.transport.requestJson<Envelope<DesktopUploadStatus>>(+ 'GET',+ joinUrl(+ this.input.baseUrl,+ `/api/v1/me/gfs/uploads/${encodeURIComponent(session.uploadId)}/status?limit=256`+ ),+ { token: this.input.token, timeoutMs: UPLOAD_TIMEOUT_MS }+ )+ )+ this.session = observed.session+ if (observed.session.state === 'completed') {+ this.canceled = false+ this.state = 'completed'+ this.uploadedBytes = observed.session.expectedBytes+ this.emit()+ await this.input.onClearPersisted?.(session.uploadId)+ return+ }+ }+ this.canceled = false+ this.state = 'failed'+ this.emit()+ throw error+ }+ }+ await this.runPromise?.catch(() => undefined)+ this.state = 'aborted'+ this.emit()+ if (session) await this.input.onClearPersisted?.(session.uploadId)+ }++ private emit(): void {+ this.input.onState?.(this.snapshot())+ }++ private async ensureSession(): Promise<DesktopUploadSession> {+ if (this.session) return this.session+ if (!this.runPromise) void this.start()+ for (;;) {+ if (this.session) return this.session+ if (!this.runPromise) throw new Error('GFS upload session was not created')+ await new Promise(resolve => setTimeout(resolve, 10))+ }+ }++ private async prepare(): Promise<{+ session: DesktopUploadSession+ committed: Set<number>+ resumable: NonNullable<NonNullable<UploadCapabilities['upload']>['resumableV2']>+ }> {+ const identity = await sourceIdentity(this.input.filePath)+ const file = await stat(this.input.filePath)+ this.input.sourceIdentity = identity+ if (!Number.isSafeInteger(file.size) || file.size > GFS_UPLOAD_V2_PRODUCT_MAX_BYTES)+ throw new Error(`GFS files are limited to ${GFS_UPLOAD_V2_PRODUCT_MAX_BYTES} bytes`)+ this.totalBytes = file.size+ let capabilities: UploadCapabilities+ try {+ capabilities = unwrap<UploadCapabilities>(+ await this.input.transport.requestJson<Envelope<UploadCapabilities>>(+ 'GET',+ joinUrl(this.input.baseUrl, '/api/v1/me/gfs/capabilities'),+ {+ token: this.input.token,+ timeoutMs: UPLOAD_TIMEOUT_MS,+ signal: this.abortController.signal,+ }+ )+ )+ } catch (error) {+ throw new DesktopUploadCapabilityError('GFS resumable upload capabilities are unavailable', {+ cause: error,+ })+ }+ const resumable = capabilities.upload?.resumableV2+ if (!resumable?.enabled)+ throw new DesktopUploadCapabilityError(+ 'Resumable GFS uploads are not enabled on this writer.'+ )+ if (typeof resumable.maxFileBytes === 'number' && file.size > resumable.maxFileBytes)+ throw new Error(`GFS files are limited to ${resumable.maxFileBytes} bytes by the writer`)+ this.input.advertisedConcurrency = resumable.maxConcurrentPartsPerSession+ this.input.fallbackConcurrency = resumable.fallbackConcurrency+ const resumeId = this.session?.uploadId ?? this.input.resumeUploadId+ if (resumeId) {+ await this.input.transport.requestJson<Envelope<undefined>>(+ 'HEAD',+ joinUrl(this.input.baseUrl, `/api/v1/me/gfs/uploads/${encodeURIComponent(resumeId)}`),+ {+ token: this.input.token,+ timeoutMs: UPLOAD_TIMEOUT_MS,+ signal: this.abortController.signal,+ }+ )+ let cursor: string | undefined+ let session: DesktopUploadSession | null = null+ const parts: DesktopUploadPart[] = []+ for (let page = 0; page < 8; page += 1) {+ const query = cursor ? `?limit=256&cursor=${encodeURIComponent(cursor)}` : '?limit=256'+ const status = unwrap<DesktopUploadStatus>(+ await this.input.transport.requestJson<Envelope<DesktopUploadStatus>>(+ 'GET',+ joinUrl(+ this.input.baseUrl,+ `/api/v1/me/gfs/uploads/${encodeURIComponent(resumeId)}/status${query}`+ ),+ {+ token: this.input.token,+ timeoutMs: UPLOAD_TIMEOUT_MS,+ signal: this.abortController.signal,+ }+ )+ )+ session ??= status.session+ if (+ session.uploadId !== status.session.uploadId ||+ session.expectedBytes !== status.session.expectedBytes+ )+ throw new Error('upload status changed during resume')+ parts.push(...status.parts)+ if (!status.nextCursor) break+ cursor = status.nextCursor+ if (page === 7) throw new Error('upload status pagination exceeded the bounded page limit')+ }+ if (!session || session.expectedBytes !== file.size)+ throw new Error('selected file size differs from the upload session')+ const committed =+ session.state === 'completed'+ ? new Set<number>()+ : await validateResumedParts(this.input.filePath, session, parts)+ return { session, committed, resumable }+ }+ const target = this.input.operation === 'create' ? this.input.parentRid : this.input.resourceRid+ if (!target) throw new Error(`${this.input.operation} upload target is required`)+ const created = unwrap<DesktopUploadSession>(+ await this.input.transport.requestJson<Envelope<DesktopUploadSession>>(+ 'POST',+ joinUrl(this.input.baseUrl, '/api/v1/me/gfs/uploads'),+ {+ token: this.input.token,+ body: {+ operation: this.input.operation,+ drive: this.input.drive,+ sizeBytes: file.size,+ idempotencyKey: randomUUID(),+ ...(this.input.operation === 'create'+ ? { parentRid: target, name: this.input.name }+ : { resourceRid: target, ifMatch: this.input.ifMatch }),+ },+ timeoutMs: UPLOAD_TIMEOUT_MS,+ signal: this.abortController.signal,+ }+ )+ )+ if (created.expectedBytes !== file.size)+ throw new Error('GFS upload session size changed before transfer')+ if (created.partBytes < 1 || created.partBytes > GFS_UPLOAD_V2_MAX_PART_BYTES)+ throw new Error('GFS server returned an invalid part size')+ return { session: created, committed: new Set(), resumable }+ }++ private async run(): Promise<DesktopUploadSession> {+ const prepared = await this.prepare()+ this.session = prepared.session+ this.uploadedBytes = prepared.session.committedBytes+ this.state = prepared.session.state === 'paused' ? 'paused' : 'uploading'+ this.emit()+ await this.input.onPersist?.({+ uploadId: prepared.session.uploadId,+ filePath: this.input.filePath,+ fileName: this.input.name,+ fileSize: prepared.session.expectedBytes,+ target: {+ operation: this.input.operation,+ parentRid: this.input.parentRid,+ resourceRid: this.input.resourceRid,+ ifMatch: this.input.ifMatch,+ },+ name: this.input.name,+ session: prepared.session,+ })+ if (prepared.session.state === 'completed') {+ this.state = 'completed'+ this.uploadedBytes = prepared.session.expectedBytes+ this.emit()+ await this.input.onClearPersisted?.(prepared.session.uploadId)+ return prepared.session+ }+ if (['aborted', 'canceling', 'failed', 'finalizing'].includes(prepared.session.state)) {+ throw new Error(`cannot resume upload in ${prepared.session.state}`)+ }+ if (prepared.session.state === 'paused') return prepared.session+ try {+ const result = await runParts(+ this.input,+ prepared.session,+ prepared.committed,+ this.abortController.signal,+ () => this.pauseRequested || this.canceled+ )+ if (result.paused || this.pauseRequested) {+ this.state = 'paused'+ const status = unwrap<DesktopUploadStatus>(+ await this.input.transport.requestJson<Envelope<DesktopUploadStatus>>(+ 'GET',+ joinUrl(+ this.input.baseUrl,+ `/api/v1/me/gfs/uploads/${encodeURIComponent(prepared.session.uploadId)}/status?limit=256`+ ),+ { token: this.input.token, timeoutMs: UPLOAD_TIMEOUT_MS }+ )+ )+ this.session = status.session+ this.uploadedBytes = status.session.committedBytes+ this.emit()+ return status.session+ }+ if (result.failed.length > 0)+ throw new Error('One or more upload parts could not be committed.')+ await assertSourceIdentity(this.input)+ this.state = 'finalizing'+ this.emit()+ const completed = unwrap<DesktopUploadSession>(+ await this.input.transport.requestJson<Envelope<DesktopUploadSession>>(+ 'POST',+ joinUrl(+ this.input.baseUrl,+ `/api/v1/me/gfs/uploads/${encodeURIComponent(prepared.session.uploadId)}/complete`+ ),+ {+ token: this.input.token,+ body: {},+ timeoutMs: UPLOAD_TIMEOUT_MS,+ signal: this.abortController.signal,+ }+ )+ )+ this.session = completed+ this.state = 'completed'+ this.uploadedBytes = completed.expectedBytes+ this.emit()+ await this.input.onClearPersisted?.(completed.uploadId)+ return completed+ } catch (error) {+ if (this.canceled) {+ this.state = 'aborted'+ this.emit()+ throw error+ }+ if (this.pauseRequested) {+ this.state = 'paused'+ this.emit()+ return this.session+ }+ this.state = 'failed'+ this.emit()+ throw error+ }+ }+}++export async function uploadLocalFile(input: DesktopUploadInput): Promise<DesktopUploadSession> {+ const job = new DesktopGfsUploadJob(input)+ return job.start()+}++export const desktopUploadDefaults = {+ preferredPartBytes: GFS_UPLOAD_V2_PREFERRED_PART_BYTES,+ maxPartBytes: GFS_UPLOAD_V2_MAX_PART_BYTES,+ concurrency: GFS_UPLOAD_V2_DEFAULT_CONCURRENCY,+ fallbackConcurrency: GFS_UPLOAD_V2_FALLBACK_CONCURRENCY,+}diff --git a/desktop-app/src/httpClient.ts b/desktop-app/src/httpClient.tsindex 021fa12c9..5ab838154 100644--- a/desktop-app/src/httpClient.ts+++ b/desktop-app/src/httpClient.ts@@ -87,7 +87,7 @@ async function sleep(ms: number): Promise<void> {}export async function requestJson<T>(- method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'HEAD' | 'DELETE',url: string,options?: {token?: stringdiff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex bd5248dca..6337c368e 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -432,6 +432,95 @@ export function registerIpcHandlers(service: AppService): void {)})+ ipcMain.handle(+ 'gfs:createFileFromPath',+ async (+ event,+ payload: { parentResourceId: string; name: string; filePath: string; drive?: string }+ ) => {+ assertTrustedSender(event)+ const drive = payload?.drive ? sanitizeString(payload.drive) : undefined+ return service.createGfsFileFromPath(+ sanitizeString(payload?.parentResourceId),+ sanitizeString(payload?.name),+ sanitizeString(payload?.filePath),+ drive+ )+ }+ )+ ipcMain.handle(+ 'gfs:startFileUpload',+ async (+ event,+ payload: {+ parentResourceId: string+ name: string+ filePath: string+ drive?: string+ resumeUploadId?: string+ }+ ) => {+ assertTrustedSender(event)+ const drive = payload?.drive ? sanitizeString(payload.drive) : undefined+ const resumeUploadId = payload?.resumeUploadId+ ? sanitizeString(payload.resumeUploadId)+ : undefined+ return service.startGfsFileUpload(+ sanitizeString(payload?.parentResourceId),+ sanitizeString(payload?.name),+ sanitizeString(payload?.filePath),+ drive,+ resumeUploadId+ )+ }+ )+ ipcMain.handle(+ 'gfs:startFileReplace',+ async (+ event,+ payload: {+ resourceId: string+ filePath: string+ drive?: string+ ifMatch?: number+ resumeUploadId?: string+ }+ ) => {+ assertTrustedSender(event)+ const drive = payload?.drive ? sanitizeString(payload.drive) : undefined+ const resumeUploadId = payload?.resumeUploadId+ ? sanitizeString(payload.resumeUploadId)+ : undefined+ return service.startGfsFileReplace(+ sanitizeString(payload?.resourceId),+ sanitizeString(payload?.filePath),+ drive,+ sanitizeOptionalInteger(payload?.ifMatch),+ resumeUploadId+ )+ }+ )+ ipcMain.handle('gfs:getUploadSnapshot', async (event, payload: { uploadId: string }) => {+ assertTrustedSender(event)+ return service.getGfsUploadSnapshot(sanitizeString(payload?.uploadId))+ })+ ipcMain.handle('gfs:listUploadSessions', async event => {+ assertTrustedSender(event)+ return service.listGfsUploadSessions()+ })+ ipcMain.handle('gfs:pauseUpload', async (event, payload: { uploadId: string }) => {+ assertTrustedSender(event)+ return service.pauseGfsUpload(sanitizeString(payload?.uploadId))+ })+ ipcMain.handle('gfs:resumeUpload', async (event, payload: { uploadId: string }) => {+ assertTrustedSender(event)+ return service.resumeGfsUpload(sanitizeString(payload?.uploadId))+ })+ ipcMain.handle('gfs:cancelUpload', async (event, payload: { uploadId: string }) => {+ assertTrustedSender(event)+ await service.cancelGfsUpload(sanitizeString(payload?.uploadId))+ return { ok: true }+ })ipcMain.handle('gfs:replaceFile',async (@@ -448,6 +537,22 @@ export function registerIpcHandlers(service: AppService): void {)})+ ipcMain.handle(+ 'gfs:replaceFileFromPath',+ async (+ event,+ payload: { resourceId: string; filePath: string; drive?: string; ifMatch?: number }+ ) => {+ assertTrustedSender(event)+ const drive = payload?.drive ? sanitizeString(payload.drive) : undefined+ return service.replaceGfsFileFromPath(+ sanitizeString(payload?.resourceId),+ sanitizeString(payload?.filePath),+ drive,+ sanitizeOptionalInteger(payload?.ifMatch)+ )+ }+ )ipcMain.handle('gfs:renameResource',async (diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex 4bd823c18..576b61edb 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -1,4 +1,4 @@-import { contextBridge, ipcRenderer } from 'electron'+import { contextBridge, ipcRenderer, webUtils } from 'electron'import type { PluginConsentRequest } from './pluginSdkProtocol.js'import type {HostMessageRequest,@@ -82,8 +82,51 @@ const clerum = Object.freeze({ipcRenderer.invoke('gfs:createFolder', { parentResourceId, name, drive }),createFile: (parentResourceId: string, name: string, encodedData: string, drive?: string) =>ipcRenderer.invoke('gfs:createFile', { parentResourceId, name, encodedData, drive }),+ createFileFromPath: (+ parentResourceId: string,+ name: string,+ filePath: string,+ drive?: string+ ) => ipcRenderer.invoke('gfs:createFileFromPath', { parentResourceId, name, filePath, drive }),+ startFileUpload: (+ parentResourceId: string,+ name: string,+ filePath: string,+ drive?: string,+ resumeUploadId?: string+ ) =>+ ipcRenderer.invoke('gfs:startFileUpload', {+ parentResourceId,+ name,+ filePath,+ drive,+ resumeUploadId,+ }),+ startFileReplace: (+ resourceId: string,+ filePath: string,+ drive?: string,+ ifMatch?: number,+ resumeUploadId?: string+ ) =>+ ipcRenderer.invoke('gfs:startFileReplace', {+ resourceId,+ filePath,+ drive,+ ifMatch,+ resumeUploadId,+ }),+ getUploadSnapshot: (uploadId: string) =>+ ipcRenderer.invoke('gfs:getUploadSnapshot', { uploadId }),+ listUploadSessions: () => ipcRenderer.invoke('gfs:listUploadSessions'),+ pauseUpload: (uploadId: string) => ipcRenderer.invoke('gfs:pauseUpload', { uploadId }),+ resumeUpload: (uploadId: string) => ipcRenderer.invoke('gfs:resumeUpload', { uploadId }),+ cancelUpload: (uploadId: string) => ipcRenderer.invoke('gfs:cancelUpload', { uploadId }),replaceFile: (resourceId: string, encodedData: string, drive?: string, ifMatch?: number) =>ipcRenderer.invoke('gfs:replaceFile', { resourceId, encodedData, drive, ifMatch }),+ replaceFileFromPath: (resourceId: string, filePath: string, drive?: string, ifMatch?: number) =>+ ipcRenderer.invoke('gfs:replaceFileFromPath', { resourceId, filePath, drive, ifMatch }),+ getPathForFile: (file: File) => webUtils.getPathForFile(file),renameResource: (resourceId: string, newName: string, drive?: string, ifMatch?: number) =>ipcRenderer.invoke('gfs:renameResource', { resourceId, newName, drive, ifMatch }),deleteResource: (resourceId: string, drive?: string, ifMatch?: number) =>diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex 85f97e70c..61e983d5c 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -207,6 +207,83 @@ declare global {version: numberbytes: number}>+ createFileFromPath: (+ parentResourceId: string,+ name: string,+ filePath: string,+ drive?: string+ ) => Promise<{+ uploadId: string+ state: string+ resultResourceId?: string+ resultVersion?: number+ }>+ startFileUpload: (+ parentResourceId: string,+ name: string,+ filePath: string,+ drive?: string,+ resumeUploadId?: string+ ) => Promise<{+ uploadId: string+ state: string+ expectedBytes: number+ committedBytes: number+ partBytes: number+ partCount: number+ }>+ startFileReplace: (+ resourceId: string,+ filePath: string,+ drive?: string,+ ifMatch?: number,+ resumeUploadId?: string+ ) => Promise<{+ uploadId: string+ state: string+ expectedBytes: number+ committedBytes: number+ partBytes: number+ partCount: number+ }>+ getUploadSnapshot: (uploadId: string) => Promise<{+ state:+ | 'initiated'+ | 'uploading'+ | 'paused'+ | 'finalizing'+ | 'canceling'+ | 'completed'+ | 'aborted'+ | 'failed'+ session: {+ uploadId: string+ state: string+ expectedBytes: number+ committedBytes: number+ resultResourceId?: string+ resultVersion?: number+ } | null+ uploadedBytes: number+ totalBytes: number+ } | null>+ listUploadSessions: () => Promise<+ Array<{+ uploadId: string+ fileName: string+ fileSize: number+ name: string+ target: {+ operation: 'create' | 'replace'+ parentRid?: string+ resourceRid?: string+ ifMatch?: number+ }+ }>+ >+ pauseUpload: (uploadId: string) => Promise<unknown>+ resumeUpload: (uploadId: string) => Promise<unknown>+ cancelUpload: (uploadId: string) => Promise<{ ok: true }>replaceFile: (resourceId: string,encodedData: string,@@ -224,6 +301,18 @@ declare global {version: numberbytes: number}>+ replaceFileFromPath: (+ resourceId: string,+ filePath: string,+ drive?: string,+ ifMatch?: number+ ) => Promise<{+ uploadId: string+ state: string+ resultResourceId?: string+ resultVersion?: number+ }>+ getPathForFile: (file: File) => stringrenameResource: (resourceId: string,newName: string,diff --git a/desktop-app/test/e2e-playwright/gfs-upload-v2.test.ts b/desktop-app/test/e2e-playwright/gfs-upload-v2.test.tsnew file mode 100644index 000000000..9a30732e3--- /dev/null+++ b/desktop-app/test/e2e-playwright/gfs-upload-v2.test.ts@@ -0,0 +1,225 @@+import type { Download, Locator, Page } from '@playwright/test'+import { expect } from '@playwright/test'+import { createHash } from 'node:crypto'+import {+ assertGfsFixtureCleaned,+ cleanupGfsFixture,+ getE2EUserId,+ getGfsChildResourceSummary,+ seedGfsDirectoryFixture,+ seedGfsFileFixture,+ seedGfsGrant,+ uniqueGfsFixtureName,+} from '../../../tests/e2e/gfsUiFixtures'+import {+ GFS_UPLOAD_V2_BOUNDARIES,+ createDiskUploadFixture,+ removeDiskUploadFixture,+} from '../../../tests/e2e/gfsUploadV2Fixtures'+import { test } from './fixtures'+import { openResourcesNavItem } from './navigationHelpers'++test.describe.configure({ mode: 'serial' })++async function hashDownload(download: Download): Promise<{ bytes: number; sha256: string }> {+ const stream = await download.createReadStream()+ if (!stream) throw new Error(`download stream unavailable for ${download.suggestedFilename()}`)+ const hash = createHash('sha256')+ let bytes = 0+ for await (const chunk of stream) {+ bytes += chunk.length+ hash.update(chunk)+ }+ return { bytes, sha256: hash.digest('hex') }+}++async function openFolder(+ page: Page,+ folderName: string+): Promise<{ browser: Locator; manageDialog: Locator }> {+ const accessibleResponse = page.waitForResponse(+ response => response.request().method() === 'GET' && response.url().includes('/external/gfs')+ )+ await openResourcesNavItem(page, 'nav-files')+ await accessibleResponse.catch(() => undefined)+ await expect(page.getByRole('heading', { name: 'Files', exact: true })).toBeVisible({+ timeout: 30_000,+ })+ const shared = page.getByRole('region', { name: 'GFS resources shared with you' })+ await expect(shared.getByRole('button', { name: folderName, exact: true })).toBeVisible({+ timeout: 60_000,+ })+ await shared.getByRole('button', { name: folderName, exact: true }).click()+ const browser = page.getByRole('region', { name: 'Global File System browser' })+ await expect(browser).toBeVisible({ timeout: 30_000 })+ await expect(browser.getByRole('button', { name: `Options for ${folderName}` })).toBeVisible()+ await browser.getByRole('button', { name: `Options for ${folderName}` }).click()+ await browser.getByRole('menuitem', { name: 'Manage', exact: true }).click()+ const manageDialog = page.getByRole('dialog', {+ name: `Manage folder ${folderName}`,+ exact: true,+ })+ await expect(manageDialog).toBeVisible()+ return { browser, manageDialog }+}++async function observeTwoProgressValues(progress: Locator, timeout = 900_000): Promise<void> {+ const values = new Set<string>()+ await expect+ .poll(+ async () => {+ const value = await progress.getAttribute('aria-valuenow')+ if (value !== null) values.add(value)+ return values.size+ },+ { timeout, intervals: [250, 1_000] }+ )+ .toBeGreaterThanOrEqual(2)+}++async function grantFolderToE2eUser(resourceId: string): Promise<void> {+ seedGfsGrant({+ resourceId,+ subjectType: 'user',+ subjectId: getE2EUserId(),+ permissions: ['read', 'write', 'delete'],+ inherit: true,+ grantedBy: 'e2e:gfs-upload-v2',+ })+}++async function exerciseCreate(page: Page, byteLength: number): Promise<void> {+ const fixtureName = uniqueGfsFixtureName(`e2e-gfs-desktop-v2-create-${byteLength}`)+ const fixture = seedGfsDirectoryFixture(fixtureName)+ await grantFolderToE2eUser(fixture.resourceId)+ const source = await createDiskUploadFixture(byteLength, '.parquet', fixtureName)+ try {+ const { browser, manageDialog } = await openFolder(page, fixture.name)+ const uploadResponsePromise = page.waitForResponse(+ response => response.request().method() === 'GET' && response.url().includes('/external/gfs')+ )+ await manageDialog.getByRole('button', { name: 'Upload file', exact: true }).click()+ await page.getByLabel('Upload file', { exact: true }).setInputFiles(source.filePath)+ await uploadResponsePromise.catch(() => undefined)+ const progress = browser.getByRole('progressbar', {+ name: `GFS upload progress for ${source.fileName}`,+ })+ await expect(progress).toBeVisible({ timeout: 30_000 })+ await observeTwoProgressValues(progress)+ await expect(page.getByText(`Uploaded ${source.fileName}`, { exact: true })).toBeVisible({+ timeout: 1_200_000,+ })+ await page.getByRole('button', { name: 'Close manage dialog' }).click()+ const row = browser.getByRole('listitem').filter({ hasText: source.fileName })+ await expect(row).toBeVisible({ timeout: 60_000 })+ await expect(row).toContainText('200.0 MB')+ await expect+ .poll(+ () =>+ getGfsChildResourceSummary({+ parentResourceId: fixture.resourceId,+ name: source.fileName,+ }),+ { timeout: 60_000, intervals: [250, 1_000] }+ )+ .toMatchObject({ kind: 'file', bytes: byteLength, deleted: false })+ const downloadPromise = page.waitForEvent('download')+ await row.getByRole('button', { name: `Download ${source.fileName}` }).click()+ expect(await hashDownload(await downloadPromise)).toEqual({+ bytes: byteLength,+ sha256: source.sha256,+ })+ } finally {+ await removeDiskUploadFixture(source)+ cleanupGfsFixture(fixtureName)+ assertGfsFixtureCleaned(fixtureName)+ }+}++async function exerciseReplace(page: Page, byteLength: number): Promise<void> {+ const fixtureName = uniqueGfsFixtureName(`e2e-gfs-desktop-v2-replace-${byteLength}`)+ const fixture = seedGfsFileFixture(fixtureName)+ await grantFolderToE2eUser(fixture.resourceId)+ const source = await createDiskUploadFixture(byteLength, '.parquet', fixtureName)+ try {+ const { browser } = await openFolder(page, fixture.name)+ const before = await getGfsChildResourceSummary({+ parentResourceId: fixture.resourceId,+ name: fixture.fileName,+ })+ expect(before).toMatchObject({ kind: 'file', deleted: false })+ await page.getByRole('button', { name: 'Close manage dialog' }).click()+ const fileRow = browser.getByRole('listitem').filter({ hasText: fixture.fileName })+ await expect(fileRow).toBeVisible({ timeout: 30_000 })+ await fileRow.getByRole('button', { name: `Options for ${fixture.fileName}` }).click()+ await browser.getByRole('menuitem', { name: 'Manage', exact: true }).click()+ const manageFile = page.getByRole('dialog', {+ name: `Manage file ${fixture.fileName}`,+ exact: true,+ })+ await expect(manageFile).toBeVisible()+ const uploadResponsePromise = page.waitForResponse(+ response => response.request().method() === 'GET' && response.url().includes('/external/gfs')+ )+ await manageFile.getByRole('button', { name: 'Replace file', exact: true }).click()+ await page.getByLabel('Replace file', { exact: true }).setInputFiles(source.filePath)+ await uploadResponsePromise.catch(() => undefined)+ const progress = browser.getByRole('progressbar', {+ name: `GFS upload progress for ${source.fileName}`,+ })+ await expect(progress).toBeVisible({ timeout: 30_000 })+ await observeTwoProgressValues(progress)+ await expect(page.getByText(`Replaced ${fixture.fileName}`, { exact: true })).toBeVisible({+ timeout: 1_200_000,+ })+ await page.getByRole('button', { name: 'Close manage dialog' }).click()+ await expect+ .poll(+ () =>+ getGfsChildResourceSummary({+ parentResourceId: fixture.resourceId,+ name: fixture.fileName,+ }),+ { timeout: 60_000, intervals: [250, 1_000] }+ )+ .toMatchObject({+ kind: 'file',+ bytes: byteLength,+ version: (before?.version ?? 0) + 1,+ deleted: false,+ })+ await expect(fileRow).toContainText('200.0 MB')+ const downloadPromise = page.waitForEvent('download')+ await fileRow.getByRole('button', { name: `Download ${fixture.fileName}` }).click()+ expect(await hashDownload(await downloadPromise)).toEqual({+ bytes: byteLength,+ sha256: source.sha256,+ })+ } finally {+ await removeDiskUploadFixture(source)+ cleanupGfsFixture(fixtureName)+ assertGfsFixtureCleaned(fixtureName)+ }+}++test.describe('GFS Upload v2 — packaged Desktop project', () => {+ test.skip(+ process.env.GFS_UPLOAD_V2_E2E !== '1',+ 'Set GFS_UPLOAD_V2_E2E=1 only on an owned non-production dev host with profile-scoped random URLs.'+ )+ test.setTimeout(45 * 60_000)++ for (const byteLength of GFS_UPLOAD_V2_BOUNDARIES) {+ test(`creates a ${byteLength}-byte file through the packaged Desktop UI`, async ({+ appPage,+ }) => {+ await exerciseCreate(appPage, byteLength)+ })++ test(`replaces a ${byteLength}-byte file through the packaged Desktop UI`, async ({+ appPage,+ }) => {+ await exerciseReplace(appPage, byteLength)+ })+ }+})diff --git a/desktop-app/test/e2e-playwright/playwright.config.ts b/desktop-app/test/e2e-playwright/playwright.config.tsindex 33fc4c896..ec0b57fa8 100644--- a/desktop-app/test/e2e-playwright/playwright.config.ts+++ b/desktop-app/test/e2e-playwright/playwright.config.ts@@ -160,4 +160,17 @@ export default defineConfig({trace: 'retain-on-failure',video: 'retain-on-failure',},+ projects: [+ {+ name: 'default',+ testIgnore: '**/gfs-upload-v2.test.ts',+ },+ {+ name: 'packaged-gfs-upload-v2',+ testMatch: /gfs-upload-v2\.test\.ts/,+ fullyParallel: false,+ timeout: 45 * 60_000,+ use: { trace: 'retain-on-failure' },+ },+ ],})diff --git a/desktop-app/ui/src/constants/gfsFileUpload.ts b/desktop-app/ui/src/constants/gfsFileUpload.tsindex c1880202d..7e795d01e 100644--- a/desktop-app/ui/src/constants/gfsFileUpload.ts+++ b/desktop-app/ui/src/constants/gfsFileUpload.ts@@ -1,4 +1,8 @@-// Kept in parity with the web control-ui cap (control-ui/app/constants/gfsFileUpload.ts).-// base64 inflates ×1.34 → 16MiB raw ≈ 22.4MB body, under gfsc's 24MiB write cap.-export const GFS_FILE_UPLOAD_MAX_BYTES = 16 * 1024 * 1024-export const GFS_FILE_UPLOAD_MAX_MEGABYTES = 16+// Product hard ceiling. Upload v2 sends indexed binary parts, so the 200 MiB+// file limit is independent of the 8 MiB preferred / 16 MiB hard part limit.+export const GFS_FILE_UPLOAD_MAX_BYTES = 200 * 1024 * 1024+export const GFS_FILE_UPLOAD_MAX_MEGABYTES = 200+export const GFS_FILE_UPLOAD_PREFERRED_PART_BYTES = 8 * 1024 * 1024+export const GFS_FILE_UPLOAD_MAX_PART_BYTES = 16 * 1024 * 1024+export const GFS_FILE_UPLOAD_DEFAULT_CONCURRENCY = 4+export const GFS_FILE_UPLOAD_FALLBACK_CONCURRENCY = 2diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsxindex f1bee87e7..227cae0c8 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx@@ -94,7 +94,7 @@ function Probe() {type="button"onClick={() =>ctrl.current- ? void ctrl.createFile(ctrl.current.resourceId, 'notes.md', 'IyBOb3Rlcw==')+ ? void ctrl.createFile(ctrl.current.resourceId, 'notes.md', 'notes.md'): undefined}>@@ -118,7 +118,7 @@ function Probe() {type="button"onClick={() =>ctrl.current- ? void ctrl.replaceFile(ctrl.current.resourceId, 'aGVsbG8=', ctrl.current.version)+ ? void ctrl.replaceFile(ctrl.current.resourceId, 'replacement.md', ctrl.current.version): undefined}>@@ -243,7 +243,7 @@ describe('useGfsBrowserController', () => {grantableBits: [],canCreateShare: false,}))- const createFile = vi.fn(async () => undefined)+ const createFileFromPath = vi.fn(async () => undefined)Object.defineProperty(window, 'clerum', {configurable: true,value: {@@ -257,7 +257,7 @@ describe('useGfsBrowserController', () => {})),listChildren,affordances,- createFile,+ createFileFromPath,},},})@@ -274,7 +274,7 @@ describe('useGfsBrowserController', () => {})await waitFor(() =>- expect(createFile).toHaveBeenCalledWith('root', 'notes.md', 'IyBOb3Rlcw==', 'main')+ expect(createFileFromPath).toHaveBeenCalledWith('root', 'notes.md', 'notes.md', 'main'))await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(2))expect(affordances).toHaveBeenCalledTimes(1)@@ -467,7 +467,7 @@ describe('useGfsBrowserController', () => {canCreateShare: false,})),renameResource: vi.fn(async () => ({ resourceId: 'file-1', version: 2 })),- replaceFile: vi.fn(async () => ({+ replaceFileFromPath: vi.fn(async () => ({...fileResource,name: 'Renamed report.md',version: 3,diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.tsindex 442fb210b..ebaff6d41 100644--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts@@ -66,6 +66,28 @@ export interface GfsBrowserControllerOptions {grantsListEnabled?: boolean}+export interface GfsUploadSnapshot {+ state:+ | 'initiated'+ | 'uploading'+ | 'paused'+ | 'finalizing'+ | 'canceling'+ | 'completed'+ | 'aborted'+ | 'failed'+ session: {+ uploadId: string+ state: string+ expectedBytes: number+ committedBytes: number+ resultResourceId?: string+ resultVersion?: number+ } | null+ uploadedBytes: number+ totalBytes: number+}+function toMessage(error: unknown): string {return error instanceof Error ? error.message : String(error)}@@ -85,6 +107,8 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {const [crumbs, setCrumbs] = useState<GfsCrumb[]>([])const [openError, setOpenError] = useState<string | null>(null)const [resolving, setResolving] = useState(false)+ const [uploadSnapshot, setUploadSnapshot] = useState<GfsUploadSnapshot | null>(null)+ const uploadIdRef = useRef<string | null>(null)const previousSessionScopeRef = useRef<string | null>(null)const current = crumbs.length ? crumbs[crumbs.length - 1] : null@@ -191,21 +215,27 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {onSuccess: refreshGfs,})const createFileMutation = useMutation({- mutationFn: (input: { parentResourceId: string; name: string; encodedData: string }) =>- window.clerum.gfs.createFile(input.parentResourceId, input.name, input.encodedData, DRIVE),+ mutationFn: (input: { parentResourceId: string; name: string; filePath: string }) =>+ window.clerum.gfs.createFileFromPath(+ input.parentResourceId,+ input.name,+ input.filePath,+ DRIVE+ ),onSuccess: refreshGfs,})const replaceFileMutation = useMutation({- mutationFn: (input: { resourceId: string; encodedData: string; ifMatch?: number }) =>- window.clerum.gfs.replaceFile(input.resourceId, input.encodedData, DRIVE, input.ifMatch),- onSuccess: async resource => {- setCrumbs(prev =>- prev.map(crumb =>- crumb.resourceId === resource.resourceId- ? { ...crumb, name: resource.name, version: resource.version }- : crumb+ mutationFn: (input: { resourceId: string; filePath: string; ifMatch?: number }) =>+ window.clerum.gfs.replaceFileFromPath(input.resourceId, input.filePath, DRIVE, input.ifMatch),+ onSuccess: async receipt => {+ const legacyResource = receipt as unknown as { resourceId?: string; version?: number }+ const resourceId = receipt.resultResourceId ?? legacyResource.resourceId+ const version = receipt.resultVersion ?? legacyResource.version+ if (resourceId && version !== undefined) {+ setCrumbs(prev =>+ prev.map(crumb => (crumb.resourceId === resourceId ? { ...crumb, version } : crumb)))- )+ }await refreshGfs()},})@@ -232,6 +262,107 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {},})+ const waitForUpload = useCallback(async (uploadId: string): Promise<GfsUploadSnapshot> => {+ const deadline = Date.now() + 24 * 60 * 60 * 1000+ for (;;) {+ if (Date.now() > deadline)+ throw new Error(+ 'GFS upload status polling timed out; the upload can be resumed from the Files page.'+ )+ const snapshot = await window.clerum.gfs.getUploadSnapshot(uploadId)+ if (!snapshot) throw new Error('GFS upload is no longer available in this desktop session')+ setUploadSnapshot(snapshot)+ if (+ snapshot.state === 'paused' ||+ snapshot.state === 'completed' ||+ snapshot.state === 'aborted' ||+ snapshot.state === 'failed'+ )+ return snapshot+ await new Promise(resolve => window.setTimeout(resolve, 500))+ }+ }, [])++ const startFileUpload = useCallback(+ async (input: {+ parentResourceId: string+ name: string+ filePath: string+ resumeUploadId?: string+ }): Promise<GfsUploadSnapshot> => {+ const session = await window.clerum.gfs.startFileUpload(+ input.parentResourceId,+ input.name,+ input.filePath,+ DRIVE,+ input.resumeUploadId+ )+ uploadIdRef.current = session.uploadId+ setUploadSnapshot({+ state: session.state === 'paused' ? 'paused' : 'uploading',+ session,+ uploadedBytes: session.committedBytes,+ totalBytes: session.expectedBytes,+ })+ const snapshot = await waitForUpload(session.uploadId)+ if (snapshot.state === 'completed') await refreshGfs()+ return snapshot+ },+ [refreshGfs, waitForUpload]+ )++ const startFileReplace = useCallback(+ async (input: {+ resourceId: string+ filePath: string+ ifMatch?: number+ resumeUploadId?: string+ }): Promise<GfsUploadSnapshot> => {+ const session = await window.clerum.gfs.startFileReplace(+ input.resourceId,+ input.filePath,+ DRIVE,+ input.ifMatch,+ input.resumeUploadId+ )+ uploadIdRef.current = session.uploadId+ setUploadSnapshot({+ state: session.state === 'paused' ? 'paused' : 'uploading',+ session,+ uploadedBytes: session.committedBytes,+ totalBytes: session.expectedBytes,+ })+ const snapshot = await waitForUpload(session.uploadId)+ if (snapshot.state === 'completed') await refreshGfs()+ return snapshot+ },+ [refreshGfs, waitForUpload]+ )++ const pauseUpload = useCallback(async (): Promise<GfsUploadSnapshot> => {+ const uploadId = uploadIdRef.current+ if (!uploadId) throw new Error('No active GFS upload')+ await window.clerum.gfs.pauseUpload(uploadId)+ return waitForUpload(uploadId)+ }, [waitForUpload])++ const resumeUpload = useCallback(async (): Promise<GfsUploadSnapshot> => {+ const uploadId = uploadIdRef.current+ if (!uploadId) throw new Error('No paused GFS upload')+ await window.clerum.gfs.resumeUpload(uploadId)+ const snapshot = await waitForUpload(uploadId)+ if (snapshot.state === 'completed') await refreshGfs()+ return snapshot+ }, [refreshGfs, waitForUpload])++ const cancelUpload = useCallback(async (): Promise<void> => {+ const uploadId = uploadIdRef.current+ if (!uploadId) return+ await window.clerum.gfs.cancelUpload(uploadId)+ setUploadSnapshot(previous => (previous ? { ...previous, state: 'aborted' } : null))+ uploadIdRef.current = null+ }, [])+const items = useMemo<GfsBrowserChild[]>(() => (childrenQuery.data?.pages ?? []).flatMap(page => page.items),[childrenQuery.data]@@ -406,10 +537,16 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {revoking: revokeGrantMutation.isPending,createShare,createFolder: (name: string) => createFolderMutation.mutateAsync(name),- createFile: (parentResourceId: string, name: string, encodedData: string) =>- createFileMutation.mutateAsync({ parentResourceId, name, encodedData }),- replaceFile: (resourceId: string, encodedData: string, ifMatch?: number) =>- replaceFileMutation.mutateAsync({ resourceId, encodedData, ifMatch }),+ createFile: (parentResourceId: string, name: string, filePath: string) =>+ createFileMutation.mutateAsync({ parentResourceId, name, filePath }),+ replaceFile: (resourceId: string, filePath: string, ifMatch?: number) =>+ replaceFileMutation.mutateAsync({ resourceId, filePath, ifMatch }),+ uploadSnapshot,+ startFileUpload,+ startFileReplace,+ pauseUpload,+ resumeUpload,+ cancelUpload,renameResource: (resourceId: string, name: string, ifMatch?: number) =>renameResourceMutation.mutateAsync({ resourceId, name, ifMatch }),deleteResource: (resourceId: string, ifMatch?: number) =>diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsxindex d21ef6b0b..4cd2e8758 100644--- a/desktop-app/ui/src/pages/FilesPage.tsx+++ b/desktop-app/ui/src/pages/FilesPage.tsx@@ -35,18 +35,6 @@ import type {MyAgentEntry,} from './FilesPage.types'-async function fileToEncodedData(file: File): Promise<string> {- assertGfsFileUploadSize(file.size)- const bytes = new Uint8Array(await file.arrayBuffer())- assertGfsFileUploadSize(bytes.byteLength)- let binary = ''- const chunkSize = 0x8000- for (let offset = 0; offset < bytes.length; offset += chunkSize) {- binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize))- }- return btoa(binary)-}-function hasBit(affordances: { held?: string[] } | null, bit: string): boolean {return Boolean(affordances?.held?.includes(bit))}@@ -55,14 +43,6 @@ function hasDraggedFiles(event: ReactDragEvent<HTMLElement>): boolean {return Array.from(event.dataTransfer.types || []).includes('Files')}-function isDroppedPreviewFile(file: File): boolean {- return (- file.type.toLowerCase().startsWith('image/') ||- gfsImagePreviewMimeType(file.name) !== null ||- isGfsMarkdownPreviewFile(file.name)- )-}-function isGfsPreviewFile(fileName: string): boolean {return gfsImagePreviewMimeType(fileName) !== null || isGfsMarkdownPreviewFile(fileName)}@@ -134,6 +114,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:const [filePreview, setFilePreview] = useState<GfsPreviewResource | null>(null)const [dragActive, setDragActive] = useState(false)const [droppedUploadCount, setDroppedUploadCount] = useState(0)+ const [uploadFileName, setUploadFileName] = useState<string | null>(null)const uploadInputRef = useRef<HTMLInputElement | null>(null)const replaceInputRef = useRef<HTMLInputElement | null>(null)const ctrl = useGfsBrowserController({ grantsListEnabled: manageOpen })@@ -153,6 +134,12 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:openError,resolving,refreshAffordances,+ uploadSnapshot,+ startFileUpload,+ startFileReplace,+ pauseUpload,+ resumeUpload,+ cancelUpload,} = ctrlconst teamDirectoryQuery = useQuery({@@ -359,10 +346,29 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:) => {if (!file || !parentResourceId) returntry {+ assertGfsFileUploadSize(file.size)const name = await normalizeGfsResourceName(file.name)- await ctrl.createFile(parentResourceId, name, await fileToEncodedData(file))- pushToast?.(`Uploaded ${name}`, 'success')+ setUploadFileName(name)+ const filePath = window.clerum.gfs.getPathForFile(file)+ if (!filePath) throw new Error('Could not resolve the selected local file')+ // Keep the renderer usable while an older main/preload pair is being+ // replaced. The resumable IPC path is always preferred; this bounded+ // compatibility branch uses the existing one-shot API and therefore+ // retains that API's own size/feature ceiling.+ if (typeof startFileUpload === 'function') {+ const result = await startFileUpload({ parentResourceId, name, filePath })+ if (result.state === 'completed') {+ pushToast?.(`Uploaded ${name}`, 'success')+ setUploadFileName(null)+ } else if (result.state === 'paused')+ pushToast?.(`Upload paused. Resume ${name} from this page.`, 'info')+ } else {+ await ctrl.createFile(parentResourceId, name, filePath)+ pushToast?.(`Uploaded ${name}`, 'success')+ setUploadFileName(null)+ }} catch (uploadError) {+ setUploadFileName(null)pushToast?.(uploadError instanceof Error ? uploadError.message : String(uploadError), 'error')}}@@ -401,24 +407,16 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:}const droppedFiles = Array.from(event.dataTransfer.files || [])- const previewFiles = droppedFiles.filter(isDroppedPreviewFile)- if (!previewFiles.length) {- pushToast?.('Only image and Markdown files can be dropped here.', 'error')+ if (!droppedFiles.length) {+ pushToast?.('No files were dropped.', 'error')return}- setDroppedUploadCount(previewFiles.length)+ setDroppedUploadCount(droppedFiles.length)try {- for (const file of previewFiles) {+ for (const file of droppedFiles) {await handleUploadFile(file, destinationResourceId)}- const skippedCount = droppedFiles.length - previewFiles.length- if (skippedCount > 0) {- pushToast?.(- `${skippedCount} unsupported ${skippedCount === 1 ? 'file was' : 'files were'} skipped.`,- 'error'- )- }} finally {setDroppedUploadCount(0)}@@ -427,9 +425,28 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:const handleReplaceCurrentFile = async (file: File | null | undefined) => {if (!file || !current) returntry {- await ctrl.replaceFile(current.resourceId, await fileToEncodedData(file), current.version)- pushToast?.(`Replaced ${current.name}`, 'success')+ assertGfsFileUploadSize(file.size)+ setUploadFileName(current.name)+ const filePath = window.clerum.gfs.getPathForFile(file)+ if (!filePath) throw new Error('Could not resolve the selected local file')+ if (typeof startFileReplace === 'function') {+ const result = await startFileReplace({+ resourceId: current.resourceId,+ filePath,+ ifMatch: current.version,+ })+ if (result.state === 'completed') {+ pushToast?.(`Replaced ${current.name}`, 'success')+ setUploadFileName(null)+ } else if (result.state === 'paused')+ pushToast?.(`Replace paused. Resume ${current.name} from this page.`, 'info')+ } else {+ await ctrl.replaceFile(current.resourceId, filePath, current.version)+ pushToast?.(`Replaced ${current.name}`, 'success')+ setUploadFileName(null)+ }} catch (replaceError) {+ setUploadFileName(null)pushToast?.(replaceError instanceof Error ? replaceError.message : String(replaceError),'error'@@ -574,13 +591,80 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:{droppedUploadCount > 0? `Uploading ${droppedUploadCount} ${droppedUploadCount === 1 ? 'file' : 'files'}…`: droppedUploadRestriction ||- `Drop images or Markdown files to upload to ${current?.name || 'this folder'}`}+ `Drop files to upload to ${current?.name || 'this folder'}`}</div>) : null}{accessibleNotice ? <StatusBanner tone="info" text={accessibleNotice} /> : null}{visibleError ? <StatusBanner tone="error" text={visibleError} /> : null}+ {uploadSnapshot &&+ ['initiated', 'uploading', 'paused', 'finalizing', 'canceling', 'failed'].includes(+ uploadSnapshot.state+ ) ? (+ <section+ className="da-gfs-upload-status"+ data-testid="gfs-upload-row"+ data-upload-file-name={uploadFileName || undefined}+ aria-label={+ uploadFileName ? `GFS upload progress for ${uploadFileName}` : 'GFS upload progress'+ }+ aria-live="polite"+ >+ <div className="da-gfs-upload-status__head">+ <strong>+ {uploadSnapshot.state === 'paused'+ ? 'Upload paused'+ : uploadSnapshot.state === 'failed'+ ? 'Upload needs attention'+ : uploadSnapshot.state === 'finalizing'+ ? 'Finalizing upload'+ : uploadSnapshot.state === 'canceling'+ ? 'Canceling upload'+ : 'Uploading file'}+ </strong>+ <span>+ {formatSharedFileSize(uploadSnapshot.uploadedBytes)} /{' '}+ {formatSharedFileSize(uploadSnapshot.totalBytes)}+ </span>+ </div>+ <progress+ aria-label={+ uploadFileName+ ? `GFS upload progress for ${uploadFileName}`+ : 'GFS upload progress'+ }+ aria-valuemin={0}+ aria-valuemax={Math.max(uploadSnapshot.totalBytes, 1)}+ aria-valuenow={Math.min(+ uploadSnapshot.uploadedBytes,+ Math.max(uploadSnapshot.totalBytes, 1)+ )}+ max={Math.max(uploadSnapshot.totalBytes, 1)}+ value={Math.min(+ uploadSnapshot.uploadedBytes,+ Math.max(uploadSnapshot.totalBytes, 1)+ )}+ />+ <div className="da-gfs-upload-status__actions">+ {uploadSnapshot.state === 'paused' ? (+ <Button size="sm" variant="outline" onClick={() => void resumeUpload()}>+ Resume+ </Button>+ ) : uploadSnapshot.state === 'uploading' || uploadSnapshot.state === 'initiated' ? (+ <Button size="sm" variant="outline" onClick={() => void pauseUpload()}>+ Pause+ </Button>+ ) : null}+ {uploadSnapshot.state !== 'canceling' && uploadSnapshot.state !== 'finalizing' ? (+ <Button size="sm" variant="text" onClick={() => void cancelUpload()}>+ Cancel upload+ </Button>+ ) : null}+ </div>+ </section>+ ) : null}+{visibleLoading ? (<divclassName="da-gfs-loading"diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsxindex 1df6c4947..3f72a2405 100644--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdomimport { useState } from 'react'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'import { GFS_FILE_UPLOAD_MAX_BYTES } from '@constants/gfsFileUpload'@@ -90,6 +90,17 @@ async function chooseManageAction(resourceName: string, actionName: string) {}describe('FilesPage', () => {+ beforeEach(() => {+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ getPathForFile: vi.fn((file: File) => file.name),+ },+ },+ })+ })+afterEach(() => {cleanup()vi.useRealTimers()@@ -244,7 +255,7 @@ describe('FilesPage', () => {it('shortens oversized file names before uploading through Desktop GFS', async () => {const createFile = vi.fn(- async (_parentResourceId: string, _name: string, _encodedData: string) => undefined+ async (_parentResourceId: string, _name: string, _filePath: string) => undefined)const pushToast = vi.fn()hookMock.useGfsBrowserController.mockReturnValue({@@ -281,18 +292,18 @@ describe('FilesPage', () => {await waitFor(() => expect(createFile).toHaveBeenCalled())const uploadCall = createFile.mock.calls[0]expect(uploadCall).toBeTruthy()- const [parentResourceId, uploadedName, encodedData] = uploadCall!+ const [parentResourceId, uploadedName, filePath] = uploadCall!expect(parentResourceId).toBe('folder-1')expect(uploadedName).not.toBe(rawName)expect(uploadedName).toHaveLength(255)expect(uploadedName).toMatch(/-[0-9a-f]{12}\.txt$/)- expect(encodedData).toBe('ZGVza3RvcCB1cGxvYWQ=')+ expect(filePath).toBe(rawName)expect(pushToast).toHaveBeenCalledWith(`Uploaded ${uploadedName}`, 'success')})it('uploads dropped images and Markdown files into the open writable folder', async () => {const createFile = vi.fn(- async (_parentResourceId: string, _name: string, _encodedData: string) => undefined+ async (_parentResourceId: string, _name: string, _filePath: string) => undefined)const pushToast = vi.fn()hookMock.useGfsBrowserController.mockReturnValue({@@ -321,9 +332,7 @@ describe('FilesPage', () => {fireEvent.dragEnter(browser, { dataTransfer })const dropStatus = screen.getByRole('status')- expect(dropStatus.textContent).toContain(- 'Drop images or Markdown files to upload to Team folder'- )+ expect(dropStatus.textContent).toContain('Drop files to upload to Team folder')expect(dropStatus.className).toContain('composer-drop-overlay')await act(async () => {@@ -332,9 +341,9 @@ describe('FilesPage', () => {})await waitFor(() =>- expect(createFile).toHaveBeenCalledWith('folder-1', 'diagram.png', 'ZGVza3RvcCBpbWFnZQ==')+ expect(createFile).toHaveBeenCalledWith('folder-1', 'diagram.png', 'diagram.png'))- expect(createFile).toHaveBeenCalledWith('folder-1', 'notes.markdown', 'IyBEZXNrdG9wIG5vdGVz')+ expect(createFile).toHaveBeenCalledWith('folder-1', 'notes.markdown', 'notes.markdown')expect(pushToast).toHaveBeenCalledWith('Uploaded diagram.png', 'success')expect(pushToast).toHaveBeenCalledWith('Uploaded notes.markdown', 'success')})@@ -388,7 +397,7 @@ describe('FilesPage', () => {})await waitFor(() => expect(createFile).toHaveBeenCalledTimes(2))- expect(createFile).toHaveBeenLastCalledWith('folder-1', 'retry.md', 'IyBSZXRyeQ==')+ expect(createFile).toHaveBeenLastCalledWith('folder-1', 'retry.md', 'retry.md')expect(pushToast).toHaveBeenCalledWith('Uploaded retry.md', 'success')})@@ -414,7 +423,7 @@ describe('FilesPage', () => {path: '/shared',}let releaseFirstUpload: (() => void) | undefined- const createFile = vi.fn((_parentResourceId: string, _name: string, _encodedData: string) =>+ const createFile = vi.fn((_parentResourceId: string, _name: string, _filePath: string) =>createFile.mock.calls.length === 1? new Promise<void>(resolve => {releaseFirstUpload = resolve@@ -490,7 +499,7 @@ describe('FilesPage', () => {})await waitFor(() =>- expect(pushToast).toHaveBeenCalledWith('GFS uploads are limited to 16 MB per file.', 'error')+ expect(pushToast).toHaveBeenCalledWith('GFS uploads are limited to 200 MB per file.', 'error'))expect(arrayBuffer).not.toHaveBeenCalled()expect(createFile).not.toHaveBeenCalled()@@ -526,13 +535,46 @@ describe('FilesPage', () => {}fireEvent.dragEnter(browser, { dataTransfer })- expect(screen.getByRole('status').textContent).toContain(- 'Drop images or Markdown files to upload to Team folder'- )+ expect(screen.getByRole('status').textContent).toContain('Drop files to upload to Team folder')fireEvent.drop(browser, { dataTransfer })- await waitFor(() =>- expect(createFile).toHaveBeenCalledWith('folder-1', 'notes.md', 'IyBOb3Rlcw==')- )+ await waitFor(() => expect(createFile).toHaveBeenCalledWith('folder-1', 'notes.md', 'notes.md'))+ })++ it('renders byte progress and wires visible pause/resume/cancel actions', async () => {+ const pauseUpload = vi.fn()+ const cancelUpload = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ current: {+ resourceId: 'folder-1',+ gfsUri: 'gfs://main/folder-1',+ name: 'Team folder',+ kind: 'directory',+ version: 7,+ },+ affordances: {+ held: ['read', 'write'],+ canDelegate: false,+ grantableBits: [],+ canCreateShare: false,+ },+ uploadSnapshot: {+ state: 'uploading',+ session: { uploadId: 'upload-1', state: 'uploading', expectedBytes: 4, committedBytes: 2 },+ uploadedBytes: 2,+ totalBytes: 4,+ },+ pauseUpload,+ cancelUpload,+ })++ renderFilesPage()+ const progress = screen.getByRole('progressbar', { name: 'GFS upload progress' })+ expect(progress.getAttribute('value')).toBe('2')+ fireEvent.click(screen.getByRole('button', { name: 'Pause' }))+ fireEvent.click(screen.getByRole('button', { name: 'Cancel upload' }))+ expect(pauseUpload).toHaveBeenCalledTimes(1)+ expect(cancelUpload).toHaveBeenCalledTimes(1)})it('explains why dropped preview files cannot be uploaded without folder write permission', () => {@@ -657,7 +699,7 @@ describe('FilesPage', () => {await Promise.resolve()})- expect(replaceFile).toHaveBeenCalledWith('file-1', 'cmVwbGFjZW1lbnQ=', 7)+ expect(replaceFile).toHaveBeenCalledWith('file-1', 'report.txt', 7)expect(renameResource).toHaveBeenCalledWith('file-1', 'report-renamed.txt', 7)expect(pushToast).toHaveBeenCalledWith('precondition_failed: stale file version', 'error')expect(pushToast).toHaveBeenCalledWith('precondition_failed: stale resource version', 'error')diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.cssindex 064f530d9..b5b8c7b19 100644--- a/desktop-app/ui/src/styles.css+++ b/desktop-app/ui/src/styles.css@@ -13827,6 +13827,44 @@ pre {flex: 0 0 auto;}+.da-gfs-upload-status {+ display: grid;+ gap: var(--space-2);+ margin: var(--space-3) var(--space-4) 0;+ padding: var(--space-3);+ border: 1px solid rgba(var(--accent-rgb), 0.28);+ border-radius: var(--radius-md);+ background: rgba(var(--accent-rgb), 0.06);+}++.da-gfs-upload-status__head,+.da-gfs-upload-status__actions {+ display: flex;+ align-items: center;+ justify-content: space-between;+ flex-wrap: wrap;+ gap: var(--space-2);+}++.da-gfs-upload-status__head {+ color: var(--text-muted);+ font-size: var(--font-size-sm);+}++.da-gfs-upload-status__head strong {+ color: var(--text);+}++.da-gfs-upload-status progress {+ width: 100%;+ height: 0.5rem;+ accent-color: var(--accent-strong);+}++.da-gfs-upload-status__actions {+ justify-content: flex-end;+}+.da-gfs-drive > .status-banner,.da-gfs-drive > .empty-state {margin: var(--space-3) var(--space-4);diff --git a/docs/architecture/gfs-upload-v2.md b/docs/architecture/gfs-upload-v2.mdnew file mode 100644index 000000000..28d0f64b0--- /dev/null+++ b/docs/architecture/gfs-upload-v2.md@@ -0,0 +1,137 @@+# GFS Upload v2 architecture++Status: contract for the additive 200 MiB rollout. v2 remains disabled until+the T0–T3 gates in [the testing contract](../testing/gfs-upload-v2.md) pass.++## Decision++The packaged Desktop app and Control UI use a custom indexed resumable upload+protocol. A small metadata request creates a server-owned session; each binary+part is sent in its own authenticated request; the GFS writer stages parts on+the existing PVC and streams them in order into the immutable blob writer at+finalization.++This is deliberately not a one-request 200 MiB upload and is not a claim of+tus 1.0 compatibility. It does not raise the legacy JSON/base64 body limit.++| Contract | Frozen value |+| --- | ---: |+| Product maximum | `209715200` bytes (200 MiB binary) |+| Oversize boundary | `209715201` is rejected before session/payload allocation |+| Preferred part | `8388608` bytes (8 MiB) |+| Hard part/request maximum | `16777216` bytes (16 MiB) |+| Default session concurrency | 4 parts |+| Instability fallback | 2 parts after 3 consecutive retryable failures/timeouts |+| Legacy raw-file limit | `16777216` bytes (16 MiB), unchanged during rollout |+| Legacy GFSC body cap | `25165824` bytes (24 MiB), unchanged during rollout |+| Protocol arithmetic ceiling | `1073741824` bytes (1 GiB); not an enabled product value |++Cloudflare evaluates the body of each HTTP request. The aggregate file limit+is therefore independent of the request limit: every v2 data-bearing request+is at most 16 MiB, and the verified zone setting can force a lower negotiated+`maxChunkBytes`. No client may send a single 100 MB or 200 MiB body.++## End-to-end shape++```text+Control UI / Desktop+ -> authenticated capabilities + small JSON session create+ -> indexed binary PUT parts (4 in flight, then 2 on instability)+ -> UI/HTTP relays with backpressure and no whole-file buffering+ -> gfsc writer+ -> staged part files on <GFS root>/.uploads/<server-upload-uuid>/parts+ -> ordered stream into immutable blob writer+ -> resource + manifest + audit + completed receipt transaction+```++The browser renderer never receives a GFSC bearer token. Desktop main reads+one bounded part per request; file paths and metadata cross the preload bridge,+not a whole-file IPC value. Legacy agent/host JSON callers remain separate.++## Protocol surface++The public relays expose the same contract to the authenticated user:++- `GET /v1/capabilities` (`Cache-Control: no-store`);+- `POST /v1/uploads` with at most 64 KiB JSON metadata;+- `HEAD /v1/uploads/:uploadId` for the contiguous prefix;+- `GET /v1/uploads/:uploadId/status` for a bounded committed-part map,+ including part number, offset, length, and SHA-256;+- `PUT /v1/uploads/:uploadId/parts/:partNumber` with raw+ `application/offset+octet-stream` bytes;+- `POST /v1/uploads/:uploadId/pause` and `/resume`;+- `POST /v1/uploads/:uploadId/complete` with an empty or at most 16 KiB body;+- `DELETE /v1/uploads/:uploadId` as terminal cancel.++The writer selects one deterministic `partBytes` for a session. Part number,+offset, and length are derived from that geometry; parallel PUTs are+independently idempotent. A committed repeat with the same length and checksum+is successful without rewriting; a conflicting repeat is a stable conflict.+The database has unique `(upload_id, part_number)` and `(upload_id,+offset_bytes)` keys, so a scalar append offset can never masquerade as a+parallel protocol.++### Session state++`initiated → uploading ↔ paused → finalizing → completed` is the successful+path. `aborted`, `expired`, and `failed` are terminal. Pause drains reserved+parts before becoming `paused`; cancel advances `session_epoch`, aborts in-flight+streams, releases the reservation, and removes staging. Cancel is not resume.++`complete` first locks the session row and changes it to `finalizing`. DELETE+observing that state returns `409 upload_finalizing`; it does not report a+false cancellation. The publication transaction re-checks state and epoch+before writing the resource, so a canceled response can never accompany a+published resource.++## Persistence and safety++`gfs_upload_sessions` stores owner, operation/target, an immutable request+fingerprint, expected bytes, selected geometry, checksum, counters, state,+epochs, expiry, and the completion receipt. `gfs_upload_parts` stores only+part metadata, checksum, lease state, and a server-generated staging path; it+never stores the chunk bytes in Postgres. The writer role alone may mutate both+tables. Readers cannot mutate sessions, and even `HEAD` is routed to the+writer.++Before accepting a part the writer re-authorizes the current principal,+reserves the indexed part and a global/session stream slot, and validates the+declared and observed lengths. The stream is checksumed incrementally into a+server-generated path, fsynced, atomically renamed, then committed with the+matching `session_epoch` and `lease_epoch`. Disconnect, timeout, checksum, or+process failure removes only the uncommitted file and releases its lease.++Create idempotency compares owner, drive, operation, normalized target/name,+size, `ifMatch`, whole-file digest, and geometry. Reusing a key with any+different fingerprint returns `409 idempotency_conflict` without exposing the+old session. Finalization verifies complete ordered coverage, current auth and+replace preconditions, streams the staged parts, verifies byte count/digest,+and commits resource, manifest, audit, and receipt atomically.++Disk admission reserves remaining staging plus the full immutable destination;+active sessions, per-session parts, global streams, and finalizers are bounded.+Metrics and logs are low-cardinality and never contain file contents, names,+tokens, full paths, or upload IDs as labels.++## Rollout boundary++The public base owns the protocol, schema, relays, and generated-workload+inputs. Private infrastructure owns only explicit overlays and image pins.+`GFS_UPLOAD_V2_ENABLED=false` is the default and is the rollback switch. No+production enablement follows from this document. Any change to the protocol,+limits, state machine, ownership, or gates is an architecture/plan change and+requires a fresh GPT-5.6 Sol design review plus explicit user approval.++## Issue mapping++- **#282** — route-scoped metadata parsing and raw binary relay; do not raise+ the global JSON parser cap.+- **#285** — resumable upload behavior, retry/resume, response-loss and+ failure coverage; the indexed protocol replaces one-request streaming.+- **#286** — update the issue contract to describe resumable indexed parts, not+ a single streaming request.+- **#300** — Desktop IPC/memory boundary: v2 uses disk-backed, bounded parts+ and runtime capabilities instead of whole-file encoded content.++The live issue state and ownership are rechecked at PR0; this mapping is not a+substitute for current GitHub issue truth.diff --git a/docs/testing/gfs-upload-v2.md b/docs/testing/gfs-upload-v2.mdnew file mode 100644index 000000000..e7a50a709--- /dev/null+++ b/docs/testing/gfs-upload-v2.md@@ -0,0 +1,137 @@+# GFS Upload v2 testing contract++This document is the executable test contract for the 200 MiB GFS Upload v2+rollout. It is intentionally separate from the legacy small-file GFS suites.+The feature flag remains false until T0, T1, T2, and T3 are green.++## Test fixtures++Generate deterministic files in a run-unique temporary directory, not in the+repository and not in memory:++| Fixture | Exact size |+| --- | ---: |+| below boundary | `209715199` bytes |+| exact boundary | `209715200` bytes |+| oversize | `209715201` bytes |+| legacy regression | `16777216` bytes and one byte above |++Record SHA-256 for every fixture and verify the downloaded result matches the+source. A fixture may be sparse only when the target filesystem and the+checksum step prove the bytes; the default fixture is deterministic, ordinary+file data. No test uses `Buffer`, `arrayBuffer()`, base64, browser storage, or+an API shortcut for a whole file.++## T0 — static and unit++T0 must execute real tests and fail loudly if zero tests run. It covers:++- exact binary boundary and oversize rejection before session allocation;+- strict part geometry, min/max part sizes, zero-byte geometry, gap/overlap+ rejection, checksums, indexed idempotent replay and fingerprint conflicts;+- owner isolation, current authorization, leases, expiry, pause/resume,+ terminal cancel, finalization fencing, storage admission and bounded quotas;+- route recognition and writer selection for capabilities, `HEAD`, status,+ part PUT, pause/resume, complete, and DELETE;+- no v2 whole-file `Buffer`/`ArrayBuffer`/base64/JSON/IPC value;+- retry classification, response-loss reconciliation, contiguous-vs-committed+ progress, four-to-two fallback, and Desktop IPC byte isolation;+- proxy invariants: exact v2 prefix bypasses the broad JSON parser, declared+ and observed 16 MiB caps are enforced, `Expect` is stripped, upload headers+ survive, and disconnect aborts upstream.++The T0 red fixtures are contract tests: before the implementation seam exists,+they must be marked as planned/disabled in the test harness rather than hidden+behind a passing assertion. Once PR1/PR2 land, each fixture is enabled and a+zero-executed-test result is a failure.++## T1 — integration and real Postgres++T1 uses real Postgres for migration and role checks. It proves:++- additive migration order, writer-only mutation privileges, and reader-role+ mutation denial;+- session/part uniqueness, offset geometry, idempotency, status map and+ response-loss replay;+- restart recovery, orphan reconciliation, lease release, disk reservation,+ bounded per-subject/global concurrency and finalization limits;+- external-rest-api → profile funnel → control-api → GFSC streaming with+ backpressure, auth re-check, header/status preservation and no broad-parser+ buffering;+- atomic resource/manifest/audit/session completion with no duplicate on crash+ or replay, create-name race, replace `ifMatch` conflict, or checksum error;+- cancel-versus-part-commit and cancel-versus-finalize hold-before-commit+ races. The latter must deterministically return `409 upload_finalizing` and+ yield either one committed publication or a cleaned failure, never a+ canceled response with a published resource;+- same name/size/mtime with different bytes cannot adopt a committed part or+ complete a resumed session.++The 512 MiB/1 GiB arithmetic ceiling is tested only under an explicit protocol+test configuration. It must not become an enabled 200 MiB product capability.++## Control UI and Desktop E2E Guardian gate++New large-upload projects must enter through real visible user actions (file+picker or drag/drop from the product surface), observe a visible intermediate+progress state at least twice before completion, and verify the final visible+state plus a business signal: resource identity/version and SHA-256. The tests+must use stable accessible labels or `data-testid` selectors, wait on critical+responses/state transitions, retain traces on failure, and clean up by+run-unique owner/session identifiers.++Required journeys:++1. create and replace at `209715199` and `209715200` bytes;+2. connection drop/timeout, writer restart, response loss, resume after app+ restart, and exact committed-part adoption;+3. visible pause then resume, and separate terminal cancel with no resource;+4. retryable failures that show four parts in flight before the threshold and+ no more than two afterward, with one correct progress bar;+5. oversize `209715201` rejection before any session/part/complete request;+6. permission revocation while paused, with visible denial and no publication;+7. v2-disabled legacy fallback at 16 MiB and rejection above the legacy cap;+8. foreign/missing session and direct terminal/deep-link guards never show+ `Completed` without the server receipt.++The E2E Guardian adversarial gate must fail if an intermediate page disappears,+submit does nothing, the API succeeds but the UI does not transition, or a+direct terminal URL makes the happy path look complete. Do not use fixed+sleeps, direct terminal navigation in a happy path, storage/session mutation,+global core-route mocks, or `{ force: true }` to bypass the product journey.++## T2 — owned Minikube and Cloudflare-backed dev host++Before cluster work record worktree, branch, exact HEAD, `origin/dev`, profile,+explicit Kubernetes context, pre-gate marker, random profile-owned ports, and+active processes. Every `kubectl` invocation carries that context. Use four+subjects or a documented test-only quota override for concurrent maximum-size+uploads. Prove no OOMKill/restart/corruption, peak RSS below 80% of limits,+bounded finalization, expected disk growth, unrelated small-request latency+within baseline, and no more than four per-session/sixteen global part streams+unless capability negotiation advertises lower.++The browser and packaged Desktop journeys run through the Cloudflare-backed+dev hostname. A local green suite is not T2 evidence.++## T3 — packaged Desktop++Use the packaged Electron artifact, not only renderer tests. Select and+drag/drop exact-boundary arbitrary binary files (including `.parquet`), verify+responsive progress, pause/resume, terminal cancel, persisted resume after+restart, source-file mutation failure, no giant IPC message, bounded large+download-to-disk, and legacy fallback against a v2-disabled server.++## Static E2E audit and evidence++Before accepting new E2E files add `tools/e2e_static_audit.py` and run it on+changed specs. It rejects fixed sleeps, storage/session mutation, core-route+success mocks, fragile selectors, direct terminal happy paths, and missing+critical-response waits. Configure large-upload projects with+`trace: 'retain-on-failure'`; retries may not hide a failed journey.++Every gate records command, exact commit SHA, fixture size/hash, route and+hostname, pass/fail, executed/skipped counts, peak RSS, restarts, PVC free+space, and unresolved blockers. T0/T1 evidence must pass before commit/push/PR;+the exact-head `review-pr` audit must pass before T2. The review is read-only+and cannot be replaced by a green unit suite or a documentation screenshot.diff --git a/external-rest-api/src/app.ts b/external-rest-api/src/app.tsindex 65a8ae08a..edf9c38a6 100644--- a/external-rest-api/src/app.ts+++ b/external-rest-api/src/app.ts@@ -19,6 +19,10 @@ import { createUserApprovalDecisionsRouter } from './routes/userApprovalDecisionimport { createWorkflowApprovalMediumsRouter } from './routes/workflowApprovalMediums.js'import { createExternalWorkflowsRouter } from './routes/workflows.js'+// Upload v2 part bodies are streamed octets and must not pass through the+// global JSON parser (which would buffer/reject the binary payload).+const GFS_UPLOAD_PART_PATH = /^\/api\/v1\/me\/gfs\/uploads\/[0-9a-f-]{36}\/parts\/[0-9]+$/i+export function createApp() {const app = express()app.set('trust proxy', 1)@@ -28,7 +32,14 @@ export function createApp() {credentials: true,}))- app.use(express.json({ limit: config.jsonBodyLimit }))+ const jsonBodyParser = express.json({ limit: config.jsonBodyLimit })+ app.use((req, res, next) => {+ if (req.method === 'PUT' && GFS_UPLOAD_PART_PATH.test(req.path)) {+ next()+ return+ }+ jsonBodyParser(req, res, next)+ })app.use(createHealthRouter())diff --git a/external-rest-api/src/controlApiClient.ts b/external-rest-api/src/controlApiClient.tsindex eb7a087a0..b3bb8c5c8 100644--- a/external-rest-api/src/controlApiClient.ts+++ b/external-rest-api/src/controlApiClient.ts@@ -1,6 +1,6 @@import { config } from './config.js'-type RequestMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'+type RequestMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'export class ControlApiError extends Error {status: number@@ -175,13 +175,14 @@ export async function controlApiBinaryRequestWithStatus(}export async function controlApiStreamRequest(- method: 'GET',+ method: RequestMethod,path: string,options?: {query?: Record<string, string | undefined>userSessionToken?: stringextraHeaders?: Record<string, string>signal?: AbortSignal+ body?: unknown}): Promise<Response> {const headers: Record<string, string> = {@@ -195,11 +196,16 @@ export async function controlApiStreamRequest(Object.assign(headers, options.extraHeaders)}- const response = await fetch(buildUrl(path, options?.query), {+ const fetchInit: RequestInit & { duplex?: 'half' } = {method,headers,signal: options?.signal,- })+ body: options?.body as BodyInit | null | undefined,+ }+ if (options?.body && typeof options.body === 'object' && Symbol.asyncIterator in options.body) {+ fetchInit.duplex = 'half'+ }+ const response = await fetch(buildUrl(path, options?.query), fetchInit)if (!response.ok) {let parsed: unknown = nullconst raw = await readResponseText(response)diff --git a/external-rest-api/src/routes/gfs.ts b/external-rest-api/src/routes/gfs.tsindex ee7c0a245..98bdb6cb6 100644--- a/external-rest-api/src/routes/gfs.ts+++ b/external-rest-api/src/routes/gfs.ts@@ -20,7 +20,23 @@ import { type AuthedRequest, extractAuthToken, requireAuth } from '../middleware// every 5xx to a generic 500 and the documented codes become unobservable at the// client (a wedged gfsc looks identical to an internal bug).const PROPAGATED = new Set([400, 401, 403, 404, 409, 410, 412, 422, 429, 500, 502, 503, 504])-const STREAM_HEADERS = ['content-type', 'content-length', 'content-disposition']+const STREAM_HEADERS = [+ 'content-type',+ 'content-length',+ 'content-disposition',+ 'cache-control',+ 'upload-offset',+ 'upload-length',+ 'upload-part-bytes',+ 'upload-part-count',+ 'upload-active-parts',+ 'upload-state',+ 'upload-expires',+ 'upload-part-number',+ 'upload-part-offset',+ 'upload-part-length',+ 'upload-checksum',+]function forwardControlApiError(error: unknown, res: Response, next: NextFunction): void {if (error instanceof ControlApiError && PROPAGATED.has(error.status)) {@@ -37,6 +53,63 @@ export function createGfsRouter(): Router {router.use('/me/gfs', requireAuth)+ // Resumable v2 relay. JSON lifecycle calls remain bounded metadata requests;+ // a part PUT passes the IncomingMessage directly to control-api so neither+ // external-rest-api nor control-api materializes the part in memory.+ router.get('/me/gfs/capabilities', (req: AuthedRequest, res, next) => {+ void proxyUploadStream(req, res, next, 'GET', '/external/gfs/capabilities')+ })+ router.post('/me/gfs/uploads', (req: AuthedRequest, res, next) => {+ void proxyUploadStream(req, res, next, 'POST', '/external/gfs/uploads')+ })+ router.head('/me/gfs/uploads/:id', (req: AuthedRequest, res, next) => {+ void proxyUploadStream(+ req,+ res,+ next,+ 'HEAD',+ `/external/gfs/uploads/${encodeURIComponent(req.params.id)}`+ )+ })+ router.get('/me/gfs/uploads/:id/status', (req: AuthedRequest, res, next) => {+ void proxyUploadStream(+ req,+ res,+ next,+ 'GET',+ `/external/gfs/uploads/${encodeURIComponent(req.params.id)}/status`+ )+ })+ router.put('/me/gfs/uploads/:id/parts/:part', (req: AuthedRequest, res, next) => {+ void proxyUploadStream(+ req,+ res,+ next,+ 'PUT',+ `/external/gfs/uploads/${encodeURIComponent(req.params.id)}/parts/${encodeURIComponent(req.params.part)}`+ )+ })+ for (const action of ['pause', 'resume', 'complete'] as const) {+ router.post(`/me/gfs/uploads/:id/${action}`, (req: AuthedRequest, res, next) => {+ void proxyUploadStream(+ req,+ res,+ next,+ 'POST',+ `/external/gfs/uploads/${encodeURIComponent(req.params.id)}/${action}`+ )+ })+ }+ router.delete('/me/gfs/uploads/:id', (req: AuthedRequest, res, next) => {+ void proxyUploadStream(+ req,+ res,+ next,+ 'DELETE',+ `/external/gfs/uploads/${encodeURIComponent(req.params.id)}`+ )+ })+router.post('/me/gfs/token', async (req: AuthedRequest, res, next) => {try {const data = await controlApiRequest('POST', '/external/gfs/token', {@@ -283,3 +356,62 @@ export function createGfsRouter(): Router {return router}++async function proxyUploadStream(+ req: AuthedRequest,+ res: Response,+ next: NextFunction,+ method: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE',+ path: string+): Promise<void> {+ try {+ const extraHeaders: Record<string, string> = {}+ for (const name of [+ 'content-type',+ 'upload-part-number',+ 'upload-offset',+ 'upload-chunk-length',+ 'upload-checksum',+ ]) {+ const value = req.headers[name]+ if (typeof value === 'string') extraHeaders[name] = value+ }+ const isPart = method === 'PUT' && /\/parts\/[0-9]+$/.test(path)+ const body =+ method === 'GET' || method === 'HEAD'+ ? undefined+ : isPart+ ? req+ : JSON.stringify(req.body ?? {})+ const upstream = await controlApiStreamRequest(method, path, {+ userSessionToken: extractAuthToken(req),+ // Preserve the bounded status cursor contract across the relay. Dropping+ // these query parameters makes every resume request fetch page one and+ // can silently truncate a session with more than 256 parts.+ query: {+ drive: typeof req.query.drive === 'string' ? req.query.drive : undefined,+ limit: typeof req.query.limit === 'string' ? req.query.limit : undefined,+ cursor: typeof req.query.cursor === 'string' ? req.query.cursor : undefined,+ },+ extraHeaders,+ body,+ })+ res.status(upstream.status)+ for (const header of STREAM_HEADERS) {+ const value = upstream.headers.get(header)+ if (value) res.setHeader(header, value)+ }+ if (!upstream.body) {+ res.end()+ return+ }+ await pipeline(+ Readable.fromWeb(+ upstream.body as unknown as import('node:stream/web').ReadableStream<Uint8Array>+ ),+ res+ )+ } catch (error) {+ forwardControlApiError(error, res, next)+ }+}diff --git a/gfs-controller/src/api/errors.ts b/gfs-controller/src/api/errors.tsindex 5e8ca4c46..2da687ae6 100644--- a/gfs-controller/src/api/errors.ts+++ b/gfs-controller/src/api/errors.ts@@ -17,6 +17,15 @@ export type GfsErrorCode =| "precondition_failed"| "payload_too_large"| "quota_exceeded"+ | "conflict"+ | "idempotency_conflict"+ | "upload_incomplete"+ | "upload_finalizing"+ | "upload_completed"+ | "upload_aborted"+ | "upload_expired"+ | "checksum_mismatch"+ | "insufficient_storage"| "cross_boundary"| "forbidden"| "unauthorized"@@ -34,6 +43,15 @@ export const HTTP_STATUS: Record<GfsErrorCode, number> = {precondition_failed: 412, // spec-pinnedpayload_too_large: 413, // spec-pinnedquota_exceeded: 429,+ conflict: 409,+ idempotency_conflict: 409,+ upload_incomplete: 409,+ upload_finalizing: 409,+ upload_completed: 409,+ upload_aborted: 410,+ upload_expired: 410,+ checksum_mismatch: 422,+ insufficient_storage: 507,cross_boundary: 409,forbidden: 403,unauthorized: 401,diff --git a/gfs-controller/src/api/serve.test.ts b/gfs-controller/src/api/serve.test.tsindex 9835db416..3b5f06e1a 100644--- a/gfs-controller/src/api/serve.test.ts+++ b/gfs-controller/src/api/serve.test.ts@@ -7,6 +7,7 @@ import type { GfsPermission } from "../authz/resolve";import { GfsError } from "./errors";import { GfsResource } from "./read";import { GfsServingHandler, ServingDeps } from "./serve";+import type { UploadPartStatus, UploadSessionReceipt } from "../upload/uploadSession";/** A minimal ServerResponse stand-in: a Writable that also records status/headers. */class FakeRes extends Writable {@@ -51,6 +52,18 @@ function reqBody(return stream;}+function reqPart(+ url: string,+ headers: Record<string, string>,+ body = Buffer.from("part")+): IncomingMessage {+ const stream = Readable.from([body]) as unknown as IncomingMessage;+ stream.url = url;+ stream.method = "PUT";+ stream.headers = { authorization: "Bearer t", ...headers };+ return stream;+}+const CLAIMS: GfsVerifiedClaims = {sub: "user-1",drive: "main",@@ -129,6 +142,134 @@ describe("GfsReadServer.tryHandle — routing", () => {});});+describe("GFS Upload v2 capability route", () => {+ it("requires auth and returns an honest disabled capability", async () => {+ const unauthenticated = new FakeRes();+ await run(deps(), req("/v1/capabilities"), unauthenticated);+ expect(unauthenticated.statusCode).toBe(401);++ const authenticated = new FakeRes();+ await run(deps(), req("/v1/capabilities", { auth: "Bearer t" }), authenticated);+ expect(authenticated.statusCode).toBe(200);+ expect(authenticated.headers["Cache-Control"]).toBe("no-store");+ expect(authenticated.body).toContain('"resumableV2":{"enabled":false');+ expect(authenticated.body).toContain('"legacyBase64":{"enabled":true');+ });++ it("does not treat an unsupported verb as a capability request", async () => {+ const res = new FakeRes();+ await run(deps(), req("/v1/capabilities", { method: "POST", auth: "Bearer t" }), res);+ expect(res.statusCode).toBe(404);+ });+});++const UPLOAD_ID = "11111111-1111-4111-8111-111111111111";+const UPLOAD_SESSION: UploadSessionReceipt = {+ uploadId: UPLOAD_ID,+ drive: "main",+ operation: "create",+ expectedBytes: 4,+ partBytes: 4,+ partCount: 1,+ state: "uploading",+ contiguousBytes: 0,+ committedBytes: 0,+ committedPartCount: 0,+ activePartCount: 0,+ expiresAt: new Date(Date.now() + 60_000).toISOString(),+};+const UPLOAD_PART: UploadPartStatus = {+ partNumber: 0,+ offsetBytes: 0,+ lengthBytes: 4,+ sha256: "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",+};++function uploadDeps(over: Partial<ServingDeps> = {}): ServingDeps {+ const service = {+ create: async () => ({ created: true, session: UPLOAD_SESSION }),+ target: async () => ({ operation: "create" as const, targetRid: RID }),+ get: async () => UPLOAD_SESSION,+ status: async () => ({ session: UPLOAD_SESSION, parts: [UPLOAD_PART] }),+ putPart: async () => ({ part: UPLOAD_PART, session: UPLOAD_SESSION }),+ pause: async () => ({ ...UPLOAD_SESSION, state: "paused" }),+ resume: async () => UPLOAD_SESSION,+ complete: async () => ({ ...UPLOAD_SESSION, state: "completed" }),+ cancel: async () => undefined,+ };+ return deps({+ verifyToken: () => USER_WRITE_CLAIMS,+ uploadService: service as unknown as ServingDeps["uploadService"],+ ...over,+ });+}++describe("GFS Upload v2 route contract", () => {+ it("creates a session with a Location and writer authorization", async () => {+ const res = new FakeRes();+ const authorize = async () => ({ allowed: true });+ await run(+ uploadDeps({ authorize }),+ reqBody("/v1/uploads", {+ method: "POST",+ auth: "Bearer t",+ body: {+ operation: "create",+ parentRid: RID,+ name: "payload.bin",+ sizeBytes: 4,+ idempotencyKey: UPLOAD_ID,+ },+ }),+ res,+ );+ expect(res.statusCode).toBe(201);+ expect(res.headers.Location).toBe(`/v1/uploads/${UPLOAD_ID}`);+ expect(res.headers["Upload-Length"]).toBe("4");+ expect(res.json).toMatchObject({ ok: true, data: { uploadId: UPLOAD_ID } });+ });++ it("rejects a binary part when the path/header part number differs", async () => {+ const res = new FakeRes();+ const putPart = async () => {+ throw new Error("putPart must not be reached");+ };+ await run(+ uploadDeps({ uploadService: { ...uploadDeps().uploadService, putPart } as ServingDeps["uploadService"] }),+ reqPart(`/v1/uploads/${UPLOAD_ID}/parts/0`, {+ "upload-part-number": "1",+ "upload-offset": "0",+ "upload-chunk-length": "4",+ "upload-checksum": "sha256 n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg=",+ "content-type": "application/offset+octet-stream",+ "content-length": "4",+ }),+ res,+ );+ expect(res.statusCode).toBe(400);+ expect((res.json as { error: { code: string } }).error.code).toBe("path_invalid");+ });++ it("returns the indexed part receipt and base64 checksum headers", async () => {+ const res = new FakeRes();+ await run(+ uploadDeps(),+ reqPart(`/v1/uploads/${UPLOAD_ID}/parts/0`, {+ "upload-part-number": "0",+ "upload-offset": "0",+ "upload-chunk-length": "4",+ "upload-checksum": "sha256 n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg=",+ "content-type": "application/offset+octet-stream",+ "content-length": "4",+ }),+ res,+ );+ expect(res.statusCode).toBe(204);+ expect(res.headers["Upload-Part-Number"]).toBe("0");+ expect(res.headers["Upload-Checksum"]).toMatch(/^sha256 [A-Za-z0-9+/]{43}={1}$/);+ });+});+describe("GfsReadServer.tryHandle — auth chain (fail-closed)", () => {it("401 when the Authorization header is missing", async () => {const res = new FakeRes();diff --git a/gfs-controller/src/api/serve.ts b/gfs-controller/src/api/serve.tsindex c440f3e65..8884ca6c1 100644--- a/gfs-controller/src/api/serve.ts+++ b/gfs-controller/src/api/serve.ts@@ -8,6 +8,13 @@ import type { GfsPermission } from "../authz/resolve";import { checkTokenCeiling } from "../authz/tokenCeiling";import type { GfsVerifiedClaims } from "../auth/verify";import type { GfsWriteService } from "../db/writeStore";+import type {+ GfsUploadPartGeometry,+ GfsUploadSessionService,+ UploadPartStatus,+ UploadPrincipal,+ UploadSessionReceipt,+} from "../upload/uploadSession";import { normalizeResourceId, PathError } from "../storage/paths";import {BlobReader,@@ -23,6 +30,7 @@ import { executeRenameRoute } from "./renameRoute";import { GfsError } from "./errors";import { normalizeResourceName, ResourceNameError } from "./resourceName";import { planWrite, WriteError } from "./write";+import { disabledGfsUploadV2Capability } from "../upload/protocol";/*** Strip control characters (CR/LF/tab, C0 controls, DEL) and bound the length of@@ -87,6 +95,16 @@ export interface ServingDeps {metrics?: GfsMetrics;/** Injectable clock for deterministic latency tests; defaults to Date.now. */now?: () => number;+ /** Capability response is injected so PR1 can remain disabled and testable. */+ uploadCapabilities?: () => GfsUploadCapabilities;+ uploadService?: GfsUploadSessionService;+}++export interface GfsUploadCapabilities {+ upload: {+ legacyBase64: { enabled: true; maxFileBytes: number };+ resumableV2: { enabled: boolean; [key: string]: unknown };+ };}/**@@ -158,6 +176,9 @@ const RESOURCE_RE = /^\/v1\/resources\/([^/]+)(?:\/(children|content))?$/;const RESOLVE_RE = /^\/v1\/resolve$/;const ACCESSIBLE_RE = /^\/v1\/accessible$/;const COPY_RE = /^\/v1\/copy$/;+const CAPABILITIES_RE = /^\/v1\/capabilities$/;+const UPLOAD_COLLECTION_RE = /^\/v1\/uploads$/;+const UPLOAD_ITEM_RE = /^\/v1\/uploads\/([0-9a-f-]{36})(?:\/(status|parts\/([0-9]+)|pause|resume|complete))?$/i;const GFS_URI_RE = /^gfs:\/\/([^/]+)\/([^/?#]+)$/;function bearerToken(req: IncomingMessage): string {@@ -226,7 +247,10 @@ export class GfsServingHandler {const resolveMatch = RESOLVE_RE.exec(url.pathname);const accessibleMatch = ACCESSIBLE_RE.exec(url.pathname);const copyMatch = COPY_RE.exec(url.pathname);- if (!resourceMatch && !resolveMatch && !accessibleMatch && !copyMatch) return false;+ const capabilitiesMatch = CAPABILITIES_RE.exec(url.pathname);+ const uploadCollectionMatch = UPLOAD_COLLECTION_RE.exec(url.pathname);+ const uploadItemMatch = UPLOAD_ITEM_RE.exec(url.pathname);+ if (!resourceMatch && !resolveMatch && !accessibleMatch && !copyMatch && !capabilitiesMatch && !uploadCollectionMatch && !uploadItemMatch) return false;const method = req.method ?? "GET";const isWrite = method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE";@@ -235,7 +259,8 @@ export class GfsServingHandler {&& this.deps.writeService && this.deps.audit && this.deps.rename;const resourceWrite = isWrite && this.deps.writeService && resourceMatch&& (method === "DELETE" || Boolean(this.deps.audit));- if ((copyMatch && !copyWrite) || (method === "PATCH" && !renameWrite) || (method !== "GET" && !resourceWrite && !copyWrite)) {+ const uploadRoute = Boolean(uploadCollectionMatch || uploadItemMatch);+ if ((capabilitiesMatch && method !== "GET") || (copyMatch && !copyWrite) || (method === "PATCH" && !renameWrite) || (method !== "GET" && !resourceWrite && !copyWrite && !capabilitiesMatch && !uploadRoute)) {// This 404 can be written before a request body was consumed (e.g. a// POST with a body to an unsupported verb/route) — same socket-poisoning// risk as the catch path below, so it carries the same close semantics.@@ -256,7 +281,11 @@ export class GfsServingHandler {const ctx = await this.authContext(claims, req, requestId);copyAbort?.signal.throwIfAborted();- if (method === "GET") {+ if (capabilitiesMatch) {+ await this.serveCapabilities(res);+ } else if (uploadRoute) {+ await this.serveUpload(req, res, claims, ctx, method, url, uploadCollectionMatch, uploadItemMatch);+ } else if (method === "GET") {await this.handleRead(res, claims, ctx, url, resourceMatch, resolveMatch, accessibleMatch);this.deps.metrics?.recordRead(this.clock() - started);} else if (copyMatch) {@@ -289,6 +318,135 @@ export class GfsServingHandler {return true;}+ private async serveCapabilities(res: ServerResponse): Promise<void> {+ const capabilities = this.deps.uploadCapabilities?.() ?? {+ upload: {+ legacyBase64: { enabled: true as const, maxFileBytes: 16 * 1024 * 1024 },+ resumableV2: disabledGfsUploadV2Capability(),+ },+ };+ sendJson(res, 200, capabilities, { "Cache-Control": "no-store" });+ }++ private async serveUpload(+ req: IncomingMessage,+ res: ServerResponse,+ claims: GfsVerifiedClaims,+ ctx: AuthzContext,+ method: string,+ url: URL,+ collectionMatch: RegExpExecArray | null,+ itemMatch: RegExpExecArray | null+ ): Promise<void> {+ const service = this.deps.uploadService;+ if (!service) throw new GfsError("not_mounted", "upload session service is unavailable");+ const principal: UploadPrincipal = { drive: claims.drive, ownerSubject: claims.sub, primarySubject: ctx.primarySubject };+ // Session DELETE is a cancel action, not deletion of the GFS resource; the+ // session's original write authority governs it just like pause/resume.+ const sessionPermission: GfsPermission = "write";+ const sessionCeiling = checkTokenCeiling({ scopes: claims.scopes, pathBindings: claims.pathBindings, op: sessionPermission, resourcePath: null });+ if (!sessionCeiling.allowed && (claims.pathBindings.length === 0 || sessionCeiling.reason === "scope_not_in_token")) {+ throw new GfsError("forbidden", `token does not authorize ${sessionPermission}`, sessionCeiling.reason);+ }+ if (collectionMatch) {+ if (method !== "POST") throw new GfsError("not_found", `no ${method} route for upload collection`);+ const body = await readJsonBody(req, { maxBytes: 64 * 1024 });+ const operation = body.operation;+ if (operation !== "create" && operation !== "replace") throw new GfsError("path_invalid", "operation must be create or replace");+ const targetRid = operation === "create" ? optionalString(body, "parentRid") : optionalString(body, "resourceRid");+ if (!targetRid) throw new GfsError("path_invalid", `${operation} requires its target`);+ const ifMatch = optionalNumber(body, "ifMatch");+ const plan = mapWritePlan(() => planWrite({+ op: operation,+ ...(operation === "create" ? { parentId: targetRid } : { resourceId: targetRid }),+ ifMatch,+ isAgent: isAgentSub(claims.sub),+ }));+ await this.authorizeChecks(claims, ctx, plan.checks);+ const sizeBytes = requireInteger(body, "sizeBytes");+ const idempotencyKey = requireString(body, "idempotencyKey");+ const session = await service.create({+ ...principal,+ idempotencyKey,+ operation,+ sizeBytes,+ parentRid: optionalString(body, "parentRid"),+ resourceRid: optionalString(body, "resourceRid"),+ name: optionalString(body, "name"),+ ifMatch,+ wholeSha256: optionalString(body, "wholeSha256") ?? null,+ });+ sendJson(res, session.created ? 201 : 200, ok(session.session), {+ ...uploadSessionHeaders(session.session),+ Location: `/v1/uploads/${session.session.uploadId}`,+ });+ return;+ }+ const uploadId = itemMatch![1]!;+ const action = itemMatch![2];+ const target = await service.target(uploadId, principal);+ if (!target.targetRid) throw new GfsError("path_invalid", "upload session target is missing");+ await this.authorizeOp(claims, ctx, target.targetRid, sessionPermission);+ if (method === "HEAD" && action === undefined) {+ const session = await service.get(uploadId, principal);+ res.writeHead(204, uploadSessionHeaders(session));+ res.end();+ return;+ }+ if (method === "GET" && action === "status") {+ const rawLimit = url.searchParams.get("limit");+ const parsedLimit = rawLimit === null ? null : Number(rawLimit);+ if (parsedLimit !== null && (!Number.isSafeInteger(parsedLimit) || parsedLimit < 1 || parsedLimit > 256)) {+ throw new GfsError("path_invalid", "status limit is invalid");+ }+ const cursor = url.searchParams.get("cursor") ?? undefined;+ const status = await service.status(uploadId, principal, {+ cursor,+ ...(parsedLimit === null ? {} : { limit: parsedLimit }),+ });+ sendJson(res, 200, ok(status), uploadSessionHeaders(status.session));+ return;+ }+ if (method === "PUT" && action?.startsWith("parts/")) {+ const partNumber = Number(itemMatch![3]);+ const declaredPartNumber = requireHeaderInteger(req, "upload-part-number");+ if (declaredPartNumber !== partNumber) throw new GfsError("path_invalid", "Upload-Part-Number must match the part path");+ const offsetBytes = requireHeaderInteger(req, "upload-offset");+ const lengthBytes = requireHeaderInteger(req, "upload-chunk-length");+ const contentType = headerValue(req, "content-type")?.split(";", 1)[0]?.trim().toLowerCase();+ if (contentType !== "application/offset+octet-stream") {+ throw new GfsError("path_invalid", "content-type must be application/offset+octet-stream");+ }+ const contentLength = headerValue(req, "content-length");+ if (contentLength !== undefined) {+ const declaredContentLength = requireHeaderInteger(req, "content-length");+ if (declaredContentLength !== lengthBytes) throw new GfsError("path_invalid", "Content-Length must match Upload-Chunk-Length");+ }+ const result = await service.putPart(uploadId, { partNumber, offsetBytes, lengthBytes }, parseUploadChecksum(headerValue(req, "upload-checksum")), req, principal);+ res.writeHead(204, uploadPartHeaders(result.session, result.part));+ res.end();+ return;+ }+ if (method === "POST" && (action === "pause" || action === "resume")) {+ const session = action === "pause" ? await service.pause(uploadId, principal) : await service.resume(uploadId, principal);+ sendJson(res, 200, ok(session), uploadSessionHeaders(session));+ return;+ }+ if (method === "POST" && action === "complete") {+ const body = await readJsonBody(req, { allowEmpty: true, maxBytes: 16 * 1024 });+ const session = await service.complete(uploadId, principal, optionalString(body, "wholeSha256"));+ sendJson(res, session.operation === "create" ? 201 : 200, ok(session), uploadSessionHeaders(session));+ return;+ }+ if (method === "DELETE" && action === undefined) {+ await service.cancel(uploadId, principal);+ res.writeHead(204, { "Cache-Control": "no-store" });+ res.end();+ return;+ }+ throw new GfsError("not_found", `no ${method} route for upload session`);+ }+private async handleRead(res: ServerResponse,claims: GfsVerifiedClaims,@@ -645,6 +803,61 @@ function requireString(body: Record<string, unknown>, key: string): string {return value;}+function optionalString(body: Record<string, unknown>, key: string): string | undefined {+ const value = body[key]+ if (value === undefined || value === null) return undefined+ if (typeof value !== "string") throw new GfsError("path_invalid", `'${key}' must be a string`)+ return value+}++function requireInteger(body: Record<string, unknown>, key: string): number {+ const value = body[key]+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {+ throw new GfsError("path_invalid", `'${key}' must be an integer`)+ }+ return value+}++function requireHeaderInteger(req: IncomingMessage, name: string): number {+ const raw = headerValue(req, name)+ if (raw === undefined || !/^[0-9]+$/.test(raw)) throw new GfsError("path_invalid", `${name} must be a non-negative integer header`)+ const value = Number(raw)+ if (!Number.isSafeInteger(value)) throw new GfsError("path_invalid", `${name} is outside the safe integer range`)+ return value+}++function uploadSessionHeaders(session: UploadSessionReceipt): Record<string, string> {+ return {+ "Cache-Control": "no-store",+ "Upload-Offset": String(session.contiguousBytes),+ "Upload-Length": String(session.expectedBytes),+ "Upload-Part-Bytes": String(session.partBytes),+ "Upload-Part-Count": String(session.partCount),+ "Upload-Active-Parts": String(session.activePartCount),+ "Upload-State": session.state,+ "Upload-Expires": session.expiresAt,+ }+}++function uploadPartHeaders(session: UploadSessionReceipt, part: UploadPartStatus): Record<string, string> {+ return {+ ...uploadSessionHeaders(session),+ "Upload-Part-Number": String(part.partNumber),+ "Upload-Part-Offset": String(part.offsetBytes),+ "Upload-Part-Length": String(part.lengthBytes),+ "Upload-Checksum": `sha256 ${Buffer.from(part.sha256, "hex").toString("base64")}`,+ }+}++function parseUploadChecksum(value: string | undefined): string {+ if (value === undefined) throw new GfsError("path_invalid", "Upload-Checksum must be sha256 <base64 digest>");+ const match = /^sha256\s+([A-Za-z0-9+/]{43}={1})$/.exec(value.trim());+ if (!match) throw new GfsError("path_invalid", "Upload-Checksum must be sha256 <base64 digest>");+ const decoded = Buffer.from(match[1], "base64");+ if (decoded.length !== 32) throw new GfsError("path_invalid", "Upload-Checksum must contain a SHA-256 digest");+ return decoded.toString("hex");+}+function optionalResourceKind(body: Record<string, unknown>): "file" | "directory" {const value = body.kind;if (value === undefined || value === null) return "file";@@ -687,7 +900,7 @@ function requireName(body: Record<string, unknown>, key: string): string {function optionalNumber(body: Record<string, unknown>, key: string): number | undefined {const value = body[key];if (value === undefined || value === null) return undefined;- if (typeof value !== "number" || !Number.isInteger(value)) {+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {throw new GfsError("path_invalid", `'${key}' must be an integer`);}return value;@@ -700,7 +913,7 @@ function optionalNumber(body: Record<string, unknown>, key: string): number | un*/async function readJsonBody(req: IncomingMessage,- opts: { allowEmpty?: boolean; signal?: AbortSignal } = {}+ opts: { allowEmpty?: boolean; signal?: AbortSignal; maxBytes?: number } = {}): Promise<Record<string, unknown>> {const chunks: Buffer[] = [];let total = 0;@@ -716,8 +929,9 @@ async function readJsonBody(opts.signal?.throwIfAborted();const buf = chunk as Buffer;total += buf.length;- if (total > MAX_WRITE_BODY_BYTES) {- throw new GfsError("payload_too_large", `request body exceeds ${MAX_WRITE_BODY_BYTES} bytes`);+ const maxBytes = opts.maxBytes ?? MAX_WRITE_BODY_BYTES;+ if (total > maxBytes) {+ throw new GfsError("payload_too_large", `request body exceeds ${maxBytes} bytes`);}chunks.push(buf);}diff --git a/gfs-controller/src/config.test.ts b/gfs-controller/src/config.test.tsindex 9b4d8f1dc..b2d503918 100644--- a/gfs-controller/src/config.test.ts+++ b/gfs-controller/src/config.test.ts@@ -96,3 +96,73 @@ describe('GFS_SYNC_COPY_*', () => {).toBe(Number.MAX_SAFE_INTEGER)})})++describe('GFS_UPLOAD_V2 strict disabled contract', () => {+ beforeEach(() => vi.stubEnv('GFS_STORAGE_ROLE', 'writer'))+ afterEach(() => vi.unstubAllEnvs())++ it('uses the 200 MiB product policy, 1 GiB protocol ceiling, and disabled capability defaults', () => {+ vi.stubEnv('GFS_DEV_MODE', 'true')+ expect(loadConfig().uploadV2).toMatchObject({+ productMaxFileBytes: 209715200,+ protocolMaxFileBytes: 1073741824,+ preferredPartBytes: 8388608,+ maxPartBytes: 16777216,+ maxConcurrentPartsPerSession: 4,+ maxConcurrentPartStreamsGlobal: 16,+ instabilityFailureThreshold: 3,+ enabled: false,+ })+ })++ it('accepts an explicit enable only as a configuration value; runtime readiness owns activation', () => {+ vi.stubEnv('GFS_DEV_MODE', 'true')+ vi.stubEnv('GFS_UPLOAD_V2_ENABLED', 'true')+ expect(loadConfig().uploadV2.enabled).toBe(true)+ })++ it('requires the product boundary and deprecated max-file alias to agree', () => {+ vi.stubEnv('GFS_DEV_MODE', 'true')+ vi.stubEnv('GFS_UPLOAD_PRODUCT_MAX_FILE_BYTES', '209715200')+ vi.stubEnv('GFS_UPLOAD_MAX_FILE_BYTES', '209715199')+ expect(() => loadConfig()).toThrow(/must match/)+ })++ it('accepts the plan-owned chunk and millisecond TTL names', () => {+ vi.stubEnv('GFS_DEV_MODE', 'true')+ vi.stubEnv('GFS_UPLOAD_PREFERRED_CHUNK_BYTES', '8388608')+ vi.stubEnv('GFS_UPLOAD_MAX_CHUNK_BYTES', '16777216')+ vi.stubEnv('GFS_UPLOAD_MIN_PART_BYTES', '1048576')+ vi.stubEnv('GFS_UPLOAD_SESSION_TTL_MS', '86400000')+ vi.stubEnv('GFS_UPLOAD_COMPLETED_RECEIPT_TTL_MS', '86400000')+ expect(loadConfig().uploadV2).toMatchObject({+ productMaxFileBytes: 209715200,+ preferredPartBytes: 8388608,+ maxPartBytes: 16777216,+ sessionTtlSeconds: 86400,+ receiptRetentionSeconds: 86400,+ })+ })++ it.each(['', '1', 'yes', 'TRUE'])('rejects non-canonical flag %s', raw => {+ vi.stubEnv('GFS_DEV_MODE', 'true')+ vi.stubEnv('GFS_UPLOAD_V2_ENABLED', raw)+ expect(() => loadConfig()).toThrow(/must be exactly 'true' or 'false'/)+ })++ it('rejects a protocol ceiling below the product boundary or above 1 GiB', () => {+ for (const raw of ['209715199', '1073741825']) {+ vi.stubEnv('GFS_DEV_MODE', 'true')+ vi.stubEnv('GFS_UPLOAD_PROTOCOL_MAX_FILE_BYTES', raw)+ expect(() => loadConfig()).toThrow(/GFS_UPLOAD_PROTOCOL_MAX_FILE_BYTES/)+ vi.unstubAllEnvs()+ vi.stubEnv('GFS_STORAGE_ROLE', 'writer')+ }+ })++ it('rejects a fallback concurrency that cannot reduce the four-part window', () => {+ vi.stubEnv('GFS_DEV_MODE', 'true')+ vi.stubEnv('GFS_UPLOAD_FALLBACK_CONCURRENCY', '4')+ expect(() => loadConfig()).toThrow(/FALLBACK_CONCURRENCY must be lower/)+ })+})diff --git a/gfs-controller/src/config.ts b/gfs-controller/src/config.tsindex efffd9f5b..eb54d4ab7 100644--- a/gfs-controller/src/config.ts+++ b/gfs-controller/src/config.ts@@ -10,6 +10,45 @@* mounting the volume. The Postgres connection points at the permission store,* which is the source of truth for authorization (re-checked on every op).*/+import {+ GFS_UPLOAD_V2_DEFAULT_CONCURRENCY,+ GFS_UPLOAD_V2_FALLBACK_CONCURRENCY,+ GFS_UPLOAD_V2_INSTABILITY_FAILURE_THRESHOLD,+ GFS_UPLOAD_V2_MAX_PART_BYTES,+ GFS_UPLOAD_V2_MIN_PART_BYTES,+ GFS_UPLOAD_V2_PART_TIMEOUT_MS,+ GFS_UPLOAD_V2_FINALIZE_TIMEOUT_MS,+ GFS_UPLOAD_V2_STALE_PART_LEASE_MS,+ GFS_UPLOAD_V2_PREFERRED_PART_BYTES,+ GFS_UPLOAD_V2_PRODUCT_MAX_BYTES,+ GFS_UPLOAD_V2_PROTOCOL_MAX_BYTES,+ GFS_UPLOAD_V2_SESSION_TTL_SECONDS,+} from './upload/protocol'++export interface GfsUploadConfig {+ /** Product policy; never raised by changing the protocol ceiling alone. */+ productMaxFileBytes: number+ /** Arithmetic/test ceiling; not a public capability. */+ protocolMaxFileBytes: number+ preferredPartBytes: number+ maxPartBytes: number+ maxPartCount: number+ maxConcurrentPartsPerSession: number+ maxConcurrentPartStreamsGlobal: number+ maxActivePerSubject: number+ maxActiveGlobal: number+ maxConcurrentFinalizations: number+ minFreeBytes: number+ instabilityFailureThreshold: number+ fallbackConcurrency: number+ sessionTtlSeconds: number+ partTimeoutMs: number+ finalizeTimeoutMs: number+ stalePartLeaseMs: number+ receiptRetentionSeconds: number+ enabled: boolean+}+export interface GfsConfig {port: number/** Path where the drive PVC is mounted (writer RW, readers RO). */@@ -52,6 +91,7 @@ export interface GfsConfig {syncRenameMaxObjects: number/** End-to-end deadline for one synchronous rename request. */syncRenameTimeoutMs: number+ uploadV2: GfsUploadConfigdevMode: boolean}@@ -106,6 +146,210 @@ function storageRole(): GfsConfig['storageRole'] {throw new Error(`[gfsc] GFS_STORAGE_ROLE must be explicitly set to 'reader' or 'writer', got: ${JSON.stringify(value)}`)}+function strictBoolean(name: string, defaultValue: boolean): boolean {+ const raw = process.env[name]+ if (raw === undefined) return defaultValue+ if (raw === 'true') return true+ if (raw === 'false') return false+ throw new Error(`[gfsc] ${name} must be exactly 'true' or 'false', got: ${JSON.stringify(raw)}`)+}++function uploadInteger(name: string, defaultValue: number, min: number, max: number): number {+ const raw = process.env[name]+ if (raw === undefined) return defaultValue+ if (!/^[0-9]+$/.test(raw)) {+ throw new Error(`[gfsc] ${name} must be an integer from ${min} through ${max}, got: ${JSON.stringify(raw)}`)+ }+ const value = Number(raw)+ if (!Number.isSafeInteger(value) || value < min || value > max) {+ throw new Error(`[gfsc] ${name} must be an integer from ${min} through ${max}, got: ${raw}`)+ }+ return value+}++function uploadDurationMs(name: string, defaultValue: number, max: number): number {+ const raw = process.env[name]+ if (raw === undefined) return defaultValue+ if (!/^[0-9]+$/.test(raw)) throw new Error(`[gfsc] ${name} must be a positive integer number of milliseconds`)+ const value = Number(raw)+ if (!Number.isSafeInteger(value) || value <= 0 || value > max) {+ throw new Error(`[gfsc] ${name} must be a positive integer number of milliseconds`)+ }+ return value+}++function uploadDurationMsWithAlias(+ canonicalName: string,+ aliasName: string,+ defaultValue: number,+ max: number,+ aliasMultiplier: number,+): number {+ const canonicalRaw = process.env[canonicalName]+ const aliasRaw = process.env[aliasName]+ const canonical = canonicalRaw === undefined+ ? undefined+ : uploadDurationMs(canonicalName, defaultValue, max)+ const alias = aliasRaw === undefined+ ? undefined+ : uploadInteger(aliasName, Math.round(defaultValue / aliasMultiplier), 1, Math.floor(max / aliasMultiplier)) * aliasMultiplier+ if (canonical !== undefined && alias !== undefined && canonical !== alias) {+ throw new Error(`[gfsc] ${canonicalName} and deprecated ${aliasName} must match`)+ }+ return canonical ?? alias ?? defaultValue+}++function uploadIntegerWithAlias(+ canonicalName: string,+ aliasName: string,+ defaultValue: number,+ min: number,+ max: number,+): number {+ const canonicalRaw = process.env[canonicalName]+ const aliasRaw = process.env[aliasName]+ // Report a conflicting pair before validating the individual range. This+ // keeps the deprecated alias contract explicit even when one side is just+ // outside the canonical range (for example, an old 199 MiB value).+ if (canonicalRaw !== undefined && aliasRaw !== undefined) {+ const canonicalNumber = Number(canonicalRaw)+ const aliasNumber = Number(aliasRaw)+ if (Number.isFinite(canonicalNumber) && Number.isFinite(aliasNumber) && canonicalNumber !== aliasNumber) {+ throw new Error(`[gfsc] ${canonicalName} and deprecated ${aliasName} must match`)+ }+ }+ const canonical = process.env[canonicalName] === undefined+ ? undefined+ : uploadInteger(canonicalName, defaultValue, min, max)+ const alias = process.env[aliasName] === undefined+ ? undefined+ : uploadInteger(aliasName, defaultValue, min, max)+ if (canonical !== undefined && alias !== undefined && canonical !== alias) {+ throw new Error(`[gfsc] ${canonicalName} and deprecated ${aliasName} must match`)+ }+ return canonical ?? alias ?? defaultValue+}++function uploadConfig(): GfsUploadConfig {+ const enabled = strictBoolean('GFS_UPLOAD_V2_ENABLED', false)+ const protocolMaxFileBytes = uploadInteger(+ 'GFS_UPLOAD_PROTOCOL_MAX_FILE_BYTES',+ GFS_UPLOAD_V2_PROTOCOL_MAX_BYTES,+ GFS_UPLOAD_V2_PRODUCT_MAX_BYTES,+ GFS_UPLOAD_V2_PROTOCOL_MAX_BYTES+ )+ const productMaxFileBytes = uploadIntegerWithAlias(+ 'GFS_UPLOAD_PRODUCT_MAX_FILE_BYTES',+ 'GFS_UPLOAD_MAX_FILE_BYTES',+ GFS_UPLOAD_V2_PRODUCT_MAX_BYTES,+ GFS_UPLOAD_V2_PRODUCT_MAX_BYTES,+ GFS_UPLOAD_V2_PRODUCT_MAX_BYTES+ )+ const preferredPartBytes = uploadIntegerWithAlias(+ 'GFS_UPLOAD_PREFERRED_CHUNK_BYTES',+ 'GFS_UPLOAD_PREFERRED_PART_BYTES',+ GFS_UPLOAD_V2_PREFERRED_PART_BYTES,+ GFS_UPLOAD_V2_MIN_PART_BYTES,+ GFS_UPLOAD_V2_MAX_PART_BYTES+ )+ const maxPartBytes = uploadIntegerWithAlias(+ 'GFS_UPLOAD_MAX_CHUNK_BYTES',+ 'GFS_UPLOAD_MAX_PART_BYTES',+ GFS_UPLOAD_V2_MAX_PART_BYTES,+ GFS_UPLOAD_V2_MIN_PART_BYTES,+ GFS_UPLOAD_V2_MAX_PART_BYTES+ )+ if (preferredPartBytes > maxPartBytes) {+ throw new Error(+ `[gfsc] GFS_UPLOAD_PREFERRED_CHUNK_BYTES cannot exceed GFS_UPLOAD_MAX_CHUNK_BYTES (${preferredPartBytes} > ${maxPartBytes})`+ )+ }+ const minPartBytes = uploadInteger(+ 'GFS_UPLOAD_MIN_PART_BYTES',+ GFS_UPLOAD_V2_MIN_PART_BYTES,+ GFS_UPLOAD_V2_MIN_PART_BYTES,+ maxPartBytes,+ )+ if (minPartBytes > maxPartBytes) {+ throw new Error(`[gfsc] GFS_UPLOAD_MIN_PART_BYTES cannot exceed GFS_UPLOAD_MAX_CHUNK_BYTES`)+ }+ if (preferredPartBytes < minPartBytes) {+ throw new Error(`[gfsc] GFS_UPLOAD_PREFERRED_CHUNK_BYTES cannot be below GFS_UPLOAD_MIN_PART_BYTES`)+ }+ const maxPartCount = uploadInteger('GFS_UPLOAD_MAX_PART_COUNT', 1024, 1, 1024)+ const maxConcurrentPartsPerSession = uploadInteger(+ 'GFS_UPLOAD_MAX_CONCURRENT_PARTS_PER_SESSION',+ GFS_UPLOAD_V2_DEFAULT_CONCURRENCY,+ 1,+ GFS_UPLOAD_V2_DEFAULT_CONCURRENCY+ )+ const fallbackConcurrency = uploadInteger(+ 'GFS_UPLOAD_FALLBACK_CONCURRENCY',+ GFS_UPLOAD_V2_FALLBACK_CONCURRENCY,+ 1,+ GFS_UPLOAD_V2_DEFAULT_CONCURRENCY+ )+ if (fallbackConcurrency >= maxConcurrentPartsPerSession) {+ throw new Error(+ `[gfsc] GFS_UPLOAD_FALLBACK_CONCURRENCY must be lower than GFS_UPLOAD_MAX_CONCURRENT_PARTS_PER_SESSION`+ )+ }+ const maxConcurrentPartStreamsGlobal = uploadInteger(+ 'GFS_UPLOAD_MAX_CONCURRENT_PART_STREAMS_GLOBAL',+ 16,+ 1,+ 1024+ )+ const maxActivePerSubject = uploadInteger('GFS_UPLOAD_MAX_ACTIVE_PER_SUBJECT', 2, 1, 100)+ const maxActiveGlobal = uploadInteger('GFS_UPLOAD_MAX_ACTIVE_GLOBAL', 8, 1, 1000)+ const maxConcurrentFinalizations = uploadInteger('GFS_UPLOAD_MAX_CONCURRENT_FINALIZATIONS', 1, 1, 100)+ const minFreeBytes = uploadInteger('GFS_UPLOAD_MIN_FREE_BYTES', 10 * 1024 * 1024 * 1024, 0, Number.MAX_SAFE_INTEGER)+ const instabilityFailureThreshold = uploadInteger(+ 'GFS_UPLOAD_INSTABILITY_FAILURE_THRESHOLD',+ GFS_UPLOAD_V2_INSTABILITY_FAILURE_THRESHOLD,+ 1,+ 100+ )+ const sessionTtlMs = uploadDurationMsWithAlias(+ 'GFS_UPLOAD_SESSION_TTL_MS',+ 'GFS_UPLOAD_SESSION_TTL_SECONDS',+ GFS_UPLOAD_V2_SESSION_TTL_SECONDS * 1000,+ 7 * 24 * 60 * 60 * 1000,+ 1000,+ )+ const partTimeoutMs = uploadDurationMs('GFS_UPLOAD_PART_TIMEOUT_MS', GFS_UPLOAD_V2_PART_TIMEOUT_MS, 24 * 60 * 60 * 1000)+ const finalizeTimeoutMs = uploadDurationMs('GFS_UPLOAD_FINALIZE_TIMEOUT_MS', GFS_UPLOAD_V2_FINALIZE_TIMEOUT_MS, 24 * 60 * 60 * 1000)+ const stalePartLeaseMs = uploadDurationMs('GFS_UPLOAD_STALE_PART_LEASE_MS', GFS_UPLOAD_V2_STALE_PART_LEASE_MS, 24 * 60 * 60 * 1000)+ const receiptRetentionMs = uploadDurationMsWithAlias(+ 'GFS_UPLOAD_COMPLETED_RECEIPT_TTL_MS',+ 'GFS_UPLOAD_RECEIPT_RETENTION_SECONDS',+ 24 * 60 * 60 * 1000,+ 7 * 24 * 60 * 60 * 1000,+ 1000,+ )+ return {+ productMaxFileBytes,+ protocolMaxFileBytes,+ preferredPartBytes,+ maxPartBytes,+ maxPartCount,+ maxConcurrentPartsPerSession,+ maxConcurrentPartStreamsGlobal,+ maxActivePerSubject,+ maxActiveGlobal,+ maxConcurrentFinalizations,+ minFreeBytes,+ instabilityFailureThreshold,+ fallbackConcurrency,+ sessionTtlSeconds: Math.floor(sessionTtlMs / 1000),+ partTimeoutMs,+ finalizeTimeoutMs,+ stalePartLeaseMs,+ receiptRetentionSeconds: Math.floor(receiptRetentionMs / 1000),+ enabled,+ }+}+export function loadConfig(): GfsConfig {const devMode = process.env.GFS_DEV_MODE === 'true'return {@@ -134,6 +378,7 @@ export function loadConfig(): GfsConfig {syncCopyTimeoutMs: syncCopyPositiveInteger('GFS_SYNC_COPY_TIMEOUT_MS', 30000),syncRenameMaxObjects: syncCopyPositiveInteger('GFS_SYNC_RENAME_MAX_OBJECTS', 1000),syncRenameTimeoutMs: syncCopyPositiveInteger('GFS_SYNC_RENAME_TIMEOUT_MS', 30000),+ uploadV2: uploadConfig(),devMode,}}diff --git a/gfs-controller/src/db/blobStaging.ts b/gfs-controller/src/db/blobStaging.tsindex f8dfa2e5b..54216730b 100644--- a/gfs-controller/src/db/blobStaging.ts+++ b/gfs-controller/src/db/blobStaging.ts@@ -1,5 +1,6 @@import { createHash } from "node:crypto";import type { Readable } from "node:stream";+import { GfsError } from "../api/errors";import type { ImmutableWriteOptions } from "../storage/blobStore";import { generationBlobKey } from "../storage/paths";import { withDeadlineTransaction, type DeadlineBudget, type DeadlineClient } from "./deadlineQuery";@@ -10,6 +11,14 @@ export type { PublishedTreeRef } from "./publishedTree";export type BlobManifestState = "staged" | "committed" | "deleting";+/** A bounded stream source for large mutations; callers retain Buffer support. */+export interface GfsContentSource {+ stream: Readable;+ expectedBytes: number;+ expectedSha256?: string;+}+export type GfsContent = Buffer | GfsContentSource;+export interface ManifestRow {blobKey: string;requestId: string;@@ -320,31 +329,37 @@ export async function stageVerifiedBlob(blobs: StagingBlobStore,ids: { generation: () => string; requestId: () => string },resourceId: string,- content: Buffer+ content: GfsContent,+ options?: ImmutableWriteOptions): Promise<{ blobKey: string; bytes: number; contentSha256: string }> {const generation = ids.generation();const blobKey = generationBlobKey(resourceId, generation);- const contentSha256 = createHash("sha256").update(content).digest("hex");+ const expectedBytes = Buffer.isBuffer(content) ? content.length : content.expectedBytes;+ if (!Number.isSafeInteger(expectedBytes) || expectedBytes < 0) {+ throw new Error("content source expectedBytes must be a non-negative safe integer");+ }+ const contentSha256 = Buffer.isBuffer(content) ? createHash("sha256").update(content).digest("hex") : content.expectedSha256 ?? null;await manifests.recordStaged({blobKey,requestId: ids.requestId(),resourceId,candidateKind: "generation",contentSha256,- bytes: content.length,+ bytes: expectedBytes,});let physicalCandidateOwned = false;try {- const written = await blobs.writeImmutable(resourceId, generation, content);+ options?.signal?.throwIfAborted();+ const written = await blobs.writeImmutable(resourceId, generation, Buffer.isBuffer(content) ? content : content.stream, options);physicalCandidateOwned = true;if (written.blobKey !== blobKey ||- written.bytes !== content.length ||- written.contentSha256 !== contentSha256+ written.bytes !== expectedBytes ||+ (contentSha256 !== null && written.contentSha256 !== contentSha256)) {- throw new Error("staged blob verification mismatch");+ throw new GfsError("checksum_mismatch", "staged blob verification mismatch");}- await blobs.verify(blobKey, content.length, contentSha256);+ await blobs.verify(blobKey, expectedBytes, written.contentSha256, options);return written;} catch (err) {// A failure before writeImmutable returns does not prove that this requestdiff --git a/gfs-controller/src/db/writeStore.ts b/gfs-controller/src/db/writeStore.tsindex c12af53f9..ed191049d 100644--- a/gfs-controller/src/db/writeStore.ts+++ b/gfs-controller/src/db/writeStore.ts@@ -7,7 +7,8 @@ import { assertIfMatch } from "../api/write";import type { AuditSink } from "../authz/audit";import type { PermissionEpoch } from "../authz/cache";import { normalizeResourceId } from "../storage/paths";-import { discardCandidate, PgBlobStagingStore, stageVerifiedBlob } from "./blobStaging";+import { discardCandidate, PgBlobStagingStore, stageVerifiedBlob, type GfsContent } from "./blobStaging";+export type { GfsContent, GfsContentSource } from "./blobStaging";import { publishCopy, type CopyPublicationResult } from "./copyPublication";import { acquireBeforeDeadline } from "./deadlineQuery";import {@@ -192,15 +193,25 @@ export interface CreateInput {parentId: string;name: string;kind?: "file" | "directory";- content?: Buffer;+ /** Reserved by an idempotent caller such as an upload session. */+ resourceId?: string;+ content?: GfsContent;mutation?: ManagedMutationContext;+ /** Optional hook executed in the same transaction as resource publication. */+ onPublished?: (client: TxClient, resource: GfsResource, signal?: AbortSignal) => Promise<void>;+ signal?: AbortSignal;+ deadlineAtMs?: number;}export interface ReplaceInput {drive: string;resourceId: string;ifMatch?: number;- content: Buffer;+ content: GfsContent;mutation?: ManagedMutationContext;+ /** Optional hook executed in the same transaction as resource publication. */+ onPublished?: (client: TxClient, resource: GfsResource, signal?: AbortSignal) => Promise<void>;+ signal?: AbortSignal;+ deadlineAtMs?: number;}export interface DeleteInput {drive: string;@@ -257,7 +268,7 @@ export class GfsWriteService {throw new GfsError("path_invalid", `unsupported resource kind: ${String(kind)}`);}const content = input.content ?? Buffer.alloc(0);- const resourceId = this.ids.resourceId();+ const resourceId = input.resourceId ?? this.ids.resourceId();const dbResourceId = toDbResourceId(resourceId);const parentId = toDbResourceId(input.parentId);let staged: Awaited<ReturnType<typeof stageVerifiedBlob>> | null = null;@@ -265,9 +276,15 @@ export class GfsWriteService {try {staged = kind === "file"- ? await stageVerifiedBlob(this.manifests, this.blobs, this.ids, resourceId, content)+ ? await stageVerifiedBlob(this.manifests, this.blobs, this.ids, resourceId, content, {+ signal: input.signal,+ ...(input.deadlineAtMs ? { checkDeadline: () => {+ if (Date.now() >= input.deadlineAtMs!) throw new GfsError("precondition_failed", "upload finalization timed out");+ } } : {}),+ }): null;const created = await this.tx.transaction(async client => {+ input.signal?.throwIfAborted();await this.lockStructure(client, input.drive);const observedAncestors = await this.loadAncestorChain(client, parentId);if (observedAncestors.length === 0) {@@ -301,7 +318,7 @@ export class GfsWriteService {input.name,kind,pathCache,- kind === "file" ? content.length : 0,+ kind === "file" ? staged?.bytes ?? 0 : 0,staged?.blobKey ?? null,staged?.contentSha256 ?? null,]@@ -315,9 +332,12 @@ export class GfsWriteService {}if (staged) await this.manifests.markCommitted(client, staged.blobKey);expected = rowToResource(row);+ await input.onPublished?.(client, expected, input.signal);+ input.signal?.throwIfAborted();await recordManagedMutation(input.mutation, { op: "create", resourceId: dbResourceId, drive: input.drive }, "succeeded", undefined, client);+ input.signal?.throwIfAborted();return expected;- });+ }, input.deadlineAtMs ? { deadlineAtMs: input.deadlineAtMs, signal: input.signal } : undefined);if (staged) await this.manifests.removeCommitted(staged.blobKey).catch(() => undefined);return created;} catch (err) {@@ -344,9 +364,15 @@ export class GfsWriteService {let staged: Awaited<ReturnType<typeof stageVerifiedBlob>> | null = null;let previous: GfsResource | undefined;try {- const candidate = await stageVerifiedBlob(this.manifests, this.blobs, this.ids, resourceId, input.content);+ const candidate = await stageVerifiedBlob(this.manifests, this.blobs, this.ids, resourceId, input.content, {+ signal: input.signal,+ ...(input.deadlineAtMs ? { checkDeadline: () => {+ if (Date.now() >= input.deadlineAtMs!) throw new GfsError("precondition_failed", "upload finalization timed out");+ } } : {}),+ });staged = candidate;const updated = await this.tx.transaction(async client => {+ input.signal?.throwIfAborted();const current = await this.lockResource(client, input.drive, resourceId);if (!current) throw new GfsError("not_found", `resource not found: ${input.resourceId}`);if (current.deletedAt) {@@ -363,7 +389,7 @@ export class GfsWriteService {content_sha256 = $5, updated_at = now()WHERE drive = $1 AND resource_id = $2 AND deleted_at IS NULLRETURNING ${RETURNING}`,- [input.drive, resourceId, input.content.length, candidate.blobKey, candidate.contentSha256]+ [input.drive, resourceId, candidate.bytes, candidate.blobKey, candidate.contentSha256]);await this.manifests.markCommitted(client, candidate.blobKey);if (current.blobKey && current.contentSha256) {@@ -377,9 +403,12 @@ export class GfsWriteService {await this.manifests.markLegacySuperseded(client, resourceId, current.bytes);}const published = rowToResource(res.rows[0]);+ await input.onPublished?.(client, published, input.signal);+ input.signal?.throwIfAborted();await recordManagedMutation(input.mutation, { op: "replace", resourceId, drive: input.drive }, "succeeded", undefined, client);+ input.signal?.throwIfAborted();return published;- });+ }, input.deadlineAtMs ? { deadlineAtMs: input.deadlineAtMs, signal: input.signal } : undefined);await this.manifests.removeCommitted(staged.blobKey).catch(() => undefined);return updated;} catch (err) {diff --git a/gfs-controller/src/index.ts b/gfs-controller/src/index.tsindex 02e0aaf94..72a3c2b9a 100644--- a/gfs-controller/src/index.ts+++ b/gfs-controller/src/index.ts@@ -1,4 +1,8 @@-import { stat } from "node:fs/promises";+import { createHash, randomUUID } from "node:crypto";+import { constants } from "node:fs";+import { lstat, mkdir, open, rm, stat } from "node:fs/promises";+import { resolve } from "node:path";+import { Readable } from "node:stream";import { Client, Pool } from "pg";import { verifyGfsToken } from "./auth/verify";import { KeyConfigError, loadVerificationKey } from "./auth/keys";@@ -16,11 +20,81 @@ import { PgBlobStagingStore, reconcileExpiredBlobs } from "./db/blobStaging";import { GfsMetrics } from "./metrics";import { GfsServer, ReadinessDeps } from "./server";import { BlobStore } from "./storage/blobStore";+import { GfsUploadSessionService, uploadCapabilities, type UploadPartRow, type UploadSessionRow } from "./upload/uploadSession";+import { GfsError } from "./api/errors";function errMsg(err: unknown): string {return err instanceof Error ? err.message : String(err);}+function orderedUploadStream(storageMountPath: string, parts: readonly UploadPartRow[], signal?: AbortSignal): Readable {+ return Readable.from((async function* () {+ for (const part of [...parts].sort((a, b) => a.partNumber - b.partNumber)) {+ signal?.throwIfAborted();+ const root = resolve(storageMountPath);+ const expectedPath = resolve(root, ".uploads", part.uploadId, "parts", `${part.partNumber}.part`);+ if (part.stagingPath !== expectedPath || !part.stagingPath.startsWith(`${root}/.uploads/${part.uploadId}/parts/`)) {+ throw new GfsError("path_invalid", "staged upload part path is invalid");+ }+ const handle = await open(part.stagingPath, constants.O_RDONLY | constants.O_NOFOLLOW);+ const buffer = Buffer.allocUnsafe(64 * 1024);+ const digest = createHash("sha256");+ let bytes = 0;+ try {+ for (;;) {+ signal?.throwIfAborted();+ const result = await handle.read(buffer, 0, buffer.length, null);+ if (result.bytesRead === 0) break;+ const chunk = Buffer.from(buffer.subarray(0, result.bytesRead));+ bytes += result.bytesRead;+ digest.update(chunk);+ yield chunk;+ }+ } finally {+ await handle.close().catch(() => undefined);+ }+ if (bytes !== part.lengthBytes || digest.digest("hex") !== part.sha256) {+ throw new GfsError("checksum_mismatch", `staged upload part ${part.partNumber} failed verification`);+ }+ }+ })());+}++async function assertUploadV2Ready(+ pool: Pool,+ storageMountPath: string,+ storageRole: "writer" | "reader"+): Promise<void> {+ const tables = await pool.query(+ `SELECT to_regclass('public.gfs_upload_sessions')::text AS sessions,+ to_regclass('public.gfs_upload_parts')::text AS parts`+ );+ const row = tables.rows[0] as { sessions?: string | null; parts?: string | null } | undefined;+ if (!row?.sessions || !row.parts) throw new Error("[gfsc] GFS_UPLOAD_V2_ENABLED requires migration 0091 upload tables");+ if (storageRole === "writer") {+ const info = await stat(storageMountPath);+ if (!info.isDirectory()) throw new Error("[gfsc] GFS_UPLOAD_V2_ENABLED requires a writable GFS storage directory");+ const uploadRoot = resolve(storageMountPath, ".uploads");+ await mkdir(uploadRoot, { recursive: true, mode: 0o700 });+ for (const ancestor of [resolve(storageMountPath), uploadRoot]) {+ const ancestorInfo = await lstat(ancestor);+ if (!ancestorInfo.isDirectory()) throw new Error("[gfsc] GFS upload storage ancestors must be real directories");+ }+ const probePath = resolve(uploadRoot, `.ready-${randomUUID()}`);+ const probe = await open(+ probePath,+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,+ 0o600,+ );+ try {+ await probe.sync();+ } finally {+ await probe.close().catch(() => undefined);+ await rm(probePath, { force: true }).catch(() => undefined);+ }+ }+}+/*** Adapt a pg Client to the narrow ListenClient surface. The only real* impedance is `connect()`: @types/pg resolves it to the client, while the@@ -84,6 +158,9 @@ async function main(): Promise<void> {const config = loadConfig();const pool = new Pool({ connectionString: config.pgConnectionString });+ if (config.uploadV2.enabled) {+ await assertUploadV2Ready(pool, config.storageMountPath, config.storageRole);+ }const readiness: ReadinessDeps = {isStorageMounted: async () => {const info = await stat(config.storageMountPath);@@ -106,10 +183,11 @@ async function main(): Promise<void> {// gfsc cannot verify a token without the platform public key, so it must not// serve authorized reads without one. In production an absent key is fatal// (fail-loud crash); dev mode may run probes-only with a loud warning.- const metrics = new GfsMetrics();- let serving: GfsServingHandler | undefined;- let invalidation: { stop: () => Promise<void> } | undefined;- let cleanupTimer: NodeJS.Timeout | undefined;+ const metrics = new GfsMetrics();+ let serving: GfsServingHandler | undefined;+ let invalidation: { stop: () => Promise<void> } | undefined;+ let cleanupTimer: NodeJS.Timeout | undefined;+ let runCleanup: (() => Promise<void>) | undefined;if (config.publicKey.trim() !== "") {const verificationKey = loadVerificationKey(config.publicKey);@@ -126,6 +204,7 @@ async function main(): Promise<void> {const store = new PgResourceStore(pool);const blobs = new BlobStore(config.storageMountPath, config.storageRole);const blobManifests = config.storageRole === "writer" ? new PgBlobStagingStore(pool) : undefined;+ let uploadServiceForCleanup: GfsUploadSessionService | undefined;const writeService =config.storageRole === "writer"? new GfsWriteService(new PgTransactor(pool), blobs, blobManifests!)@@ -137,17 +216,27 @@ async function main(): Promise<void> {if (cleanupRunning) return;cleanupRunning = true;try {- await reconcileExpiredBlobs(blobManifests!, blobs, metrics, {- olderThanMs: config.blobCleanupSafetyWindowMs,- limit: config.blobCleanupBatchSize,- });- } catch (err) {- metrics.recordBlobCleanupFailure();- console.error(`[gfsc] blob reconciliation failed: ${errMsg(err)}`);+ if (uploadServiceForCleanup) {+ try {+ await uploadServiceForCleanup.reconcile();+ } catch (err) {+ console.error(`[gfsc] upload reconciliation failed: ${errMsg(err)}`);+ }+ }+ try {+ await reconcileExpiredBlobs(blobManifests!, blobs, metrics, {+ olderThanMs: config.blobCleanupSafetyWindowMs,+ limit: config.blobCleanupBatchSize,+ });+ } catch (err) {+ metrics.recordBlobCleanupFailure();+ console.error(`[gfsc] blob reconciliation failed: ${errMsg(err)}`);+ }} finally {cleanupRunning = false;}};+ runCleanup = cleanup;cleanupTimer = setInterval(() => void cleanup(), config.blobCleanupIntervalMs);cleanupTimer.unref();void cleanup();@@ -179,7 +268,105 @@ async function main(): Promise<void> {},} : {}),metrics,+ // Upload mutation and capability advertisement are writer-only. Reader+ // replicas deliberately do not expose a v2 capability even if an+ // operator accidentally carries the same tuning env into both pods.+ uploadCapabilities: () => ({+ upload: uploadCapabilities(+ config.storageRole === "writer" && config.uploadV2.enabled && Boolean(writeService),+ config.uploadV2,+ ),+ }),+ ...(writeService ? {+ uploadService: (uploadServiceForCleanup = new GfsUploadSessionService({+ db: pool,+ tx: new PgTransactor(pool),+ blobs,+ storageMountPath: config.storageMountPath,+ config: config.uploadV2,+ authorize: async (principal, operation, targetRid) => {+ if (!targetRid) throw new GfsError("path_invalid", "upload target is required");+ const targetContext = await resolveAuthzContext(pool, {+ sub: principal.ownerSubject,+ drive: principal.drive,+ });+ const decision = await permissions.authorize(targetContext, targetRid, "write");+ if (!decision.allowed) throw new GfsError("forbidden", `not authorized to ${operation} upload`);+ },+ finalize: async (session: UploadSessionRow, parts: UploadPartRow[], signal?: AbortSignal, deadlineAtMs?: number) => {+ const capturedPermissionEpoch = permissions.permissionEpoch();+ const source = {+ stream: orderedUploadStream(config.storageMountPath, parts, signal),+ expectedBytes: session.expectedBytes,+ ...(session.wholeSha256 ? { expectedSha256: session.wholeSha256 } : {}),+ };+ const mutation = { subject: session.primarySubject, requestId: session.uploadId, audit };+ const onPublished = async (client: import("./db/writeStore").TxClient, published: import("./api/read").GfsResource, publicationSignal?: AbortSignal): Promise<void> => {+ publicationSignal?.throwIfAborted();+ if (deadlineAtMs !== undefined && Date.now() >= deadlineAtMs) {+ throw new GfsError("precondition_failed", "upload finalization timed out");+ }+ const currentPermissionEpoch = permissions.permissionEpoch();+ if (+ capturedPermissionEpoch.bypassed+ || currentPermissionEpoch.bypassed+ || currentPermissionEpoch.generation !== capturedPermissionEpoch.generation+ ) {+ throw new GfsError("precondition_failed", "authorization changed during upload finalization");+ }+ const targetRid = session.operation === "create" ? session.parentRid : session.resourceRid;+ if (!targetRid) throw new GfsError("path_invalid", "upload target is required");+ const targetContext = await resolveAuthzContext(pool, {+ sub: session.ownerSubject,+ drive: session.drive,+ });+ const decision = await permissions.authorize(targetContext, targetRid, "write");+ publicationSignal?.throwIfAborted();+ if (deadlineAtMs !== undefined && Date.now() >= deadlineAtMs) {+ throw new GfsError("precondition_failed", "upload finalization timed out");+ }+ if (!decision.allowed) throw new GfsError("forbidden", "upload authorization was revoked before publication");+ const completed = await client.query(+ `UPDATE gfs_upload_sessions+ SET state = 'completed', result_resource_id = $2, result_version = $3,+ result_sha256 = $4, completed_at = now(), updated_at = now()+ WHERE upload_id = $1 AND state = 'finalizing' AND session_epoch = $5+ RETURNING upload_id`,+ [session.uploadId, published.resourceId, published.version, published.contentSha256, session.sessionEpoch]+ );+ publicationSignal?.throwIfAborted();+ if (completed.rows.length !== 1) throw new GfsError("upload_aborted", "upload session changed before publication");+ };+ const resource = session.operation === "create"+ ? await writeService.create({+ drive: session.drive,+ parentId: session.parentRid!,+ name: session.resourceName!,+ kind: "file",+ resourceId: session.uploadId,+ content: source,+ mutation,+ onPublished,+ signal,+ deadlineAtMs,+ })+ : await writeService.replace({+ drive: session.drive,+ resourceId: session.resourceRid!,+ ifMatch: session.ifMatch ?? undefined,+ content: source,+ mutation,+ onPublished,+ signal,+ deadlineAtMs,+ });+ if (!resource.contentSha256) throw new GfsError("internal", "published upload has no checksum");+ return { resourceId: resource.resourceId, version: resource.version, sha256: resource.contentSha256 };+ },+ })),+ } : {}),});+ void runCleanup?.();} else if (!config.devMode) {throw new KeyConfigError("GFS_JWT_PUBLIC_KEY is required to serve authorized reads");} else {diff --git a/gfs-controller/src/upload/protocol.test.ts b/gfs-controller/src/upload/protocol.test.tsnew file mode 100644index 000000000..2a0b47352--- /dev/null+++ b/gfs-controller/src/upload/protocol.test.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from 'vitest'+import {+ disabledGfsUploadV2Capability,+ GFS_UPLOAD_V2_DEFAULT_CONCURRENCY,+ GFS_UPLOAD_V2_FALLBACK_CONCURRENCY,+ GFS_UPLOAD_V2_MAX_PART_BYTES,+ GFS_UPLOAD_V2_PRODUCT_MAX_BYTES,+ GFS_UPLOAD_V2_PROTOCOL_MAX_BYTES,+ GFS_UPLOAD_V2_PREFERRED_PART_BYTES,+ GFS_UPLOAD_V2_INSTABILITY_FAILURE_THRESHOLD,+ isGfsUploadV2Route,+ partCountFor,+ partGeometry,+ validatePartGeometry,+} from './protocol'++describe('GFS Upload v2 frozen contract', () => {+ it('uses binary product/request boundaries without advertising v2', () => {+ expect(GFS_UPLOAD_V2_PRODUCT_MAX_BYTES).toBe(209_715_200)+ expect(GFS_UPLOAD_V2_PROTOCOL_MAX_BYTES).toBe(1_073_741_824)+ expect(GFS_UPLOAD_V2_PREFERRED_PART_BYTES).toBe(8_388_608)+ expect(GFS_UPLOAD_V2_MAX_PART_BYTES).toBe(16_777_216)+ expect(GFS_UPLOAD_V2_DEFAULT_CONCURRENCY).toBe(4)+ expect(GFS_UPLOAD_V2_FALLBACK_CONCURRENCY).toBe(2)+ expect(GFS_UPLOAD_V2_INSTABILITY_FAILURE_THRESHOLD).toBe(3)+ expect(disabledGfsUploadV2Capability()).toEqual({+ enabled: false,+ maxFileBytes: 0,+ preferredChunkBytes: 0,+ maxChunkBytes: 0,+ })+ })++ it('calculates exact 8 MiB geometry at the product boundary', () => {+ const geometry = { expectedBytes: GFS_UPLOAD_V2_PRODUCT_MAX_BYTES, partBytes: GFS_UPLOAD_V2_PREFERRED_PART_BYTES }+ expect(partCountFor(geometry)).toBe(25)+ expect(partGeometry(geometry, 0)).toEqual({ partNumber: 0, offsetBytes: 0, lengthBytes: 8_388_608 })+ expect(partGeometry(geometry, 24)).toEqual({+ partNumber: 24,+ offsetBytes: 201_326_592,+ lengthBytes: 8_388_608,+ })+ expect(() => partGeometry(geometry, 25)).toThrow('invalid part number')+ })++ it('accepts a short final part and rejects mismatched offset or length', () => {+ const geometry = { expectedBytes: 8_388_609, partBytes: 8_388_608 }+ const finalPart = partGeometry(geometry, 1)+ expect(finalPart).toEqual({ partNumber: 1, offsetBytes: 8_388_608, lengthBytes: 1 })+ expect(() => validatePartGeometry(geometry, { ...finalPart, offsetBytes: 0 })).toThrow(+ 'offset must be 8388608'+ )+ expect(() => validatePartGeometry(geometry, { ...finalPart, lengthBytes: 8_388_608 })).toThrow(+ 'length must be 1'+ )+ })++ it('recognizes only the exact v2 routes', () => {+ expect(isGfsUploadV2Route('/v1/capabilities')).toBe(true)+ expect(isGfsUploadV2Route('/v1/uploads')).toBe(true)+ expect(isGfsUploadV2Route('/v1/uploads/01234567-89ab-cdef-0123-456789abcdef/parts/0')).toBe(true)+ expect(isGfsUploadV2Route('/v1/resources/0123456789abcdef0123456789abcdef')).toBe(false)+ expect(isGfsUploadV2Route('/v1/uploads/not-an-id/parts/0')).toBe(false)+ })+})diff --git a/gfs-controller/src/upload/protocol.ts b/gfs-controller/src/upload/protocol.tsnew file mode 100644index 000000000..06cbc95d3--- /dev/null+++ b/gfs-controller/src/upload/protocol.ts@@ -0,0 +1,156 @@+/**+ * Shared, side-effect-free constants and geometry helpers for GFS Upload v2.+ *+ * The writer and both clients import this module so the capability response,+ * session admission, part routes, and UI geometry share one arithmetic+ * definition. The route remains capability-gated: disabled deployments still+ * advertise the legacy surface and reject v2 mutations.+ */++export const GFS_UPLOAD_V2_PRODUCT_MAX_BYTES = 209_715_200+export const GFS_UPLOAD_V2_PROTOCOL_MAX_BYTES = 1_073_741_824+export const GFS_UPLOAD_V2_PREFERRED_PART_BYTES = 8 * 1024 * 1024+export const GFS_UPLOAD_V2_MAX_PART_BYTES = 16 * 1024 * 1024+export const GFS_UPLOAD_V2_MIN_PART_BYTES = 1 * 1024 * 1024+export const GFS_UPLOAD_V2_DEFAULT_CONCURRENCY = 4+export const GFS_UPLOAD_V2_FALLBACK_CONCURRENCY = 2+export const GFS_UPLOAD_V2_INSTABILITY_FAILURE_THRESHOLD = 3+export const GFS_UPLOAD_V2_MAX_PART_COUNT = 1024+export const GFS_UPLOAD_V2_METADATA_BODY_MAX_BYTES = 64 * 1024+export const GFS_UPLOAD_V2_COMPLETE_BODY_MAX_BYTES = 16 * 1024+export const GFS_UPLOAD_V2_SESSION_TTL_SECONDS = 24 * 60 * 60+export const GFS_UPLOAD_V2_PART_TIMEOUT_MS = 300_000+export const GFS_UPLOAD_V2_FINALIZE_TIMEOUT_MS = 600_000+export const GFS_UPLOAD_V2_STALE_PART_LEASE_MS = 600_000++export type GfsUploadOperation = 'create' | 'replace'++export interface GfsUploadGeometry {+ expectedBytes: number+ partBytes: number+}++export interface GfsUploadPartGeometry {+ partNumber: number+ offsetBytes: number+ lengthBytes: number+}++export type GfsUploadGeometryErrorCode =+ | 'invalid_expected_bytes'+ | 'invalid_part_bytes'+ | 'part_count_exceeded'+ | 'invalid_part_number'+ | 'invalid_part_offset'+ | 'invalid_part_length'+ | 'part_offset_mismatch'+ | 'part_length_mismatch'++export class GfsUploadGeometryError extends Error {+ readonly code: GfsUploadGeometryErrorCode++ constructor(code: GfsUploadGeometryErrorCode, message: string) {+ super(message)+ this.name = 'GfsUploadGeometryError'+ this.code = code+ }+}++export function partCountFor({ expectedBytes, partBytes }: GfsUploadGeometry): number {+ validateGeometry({ expectedBytes, partBytes })+ if (expectedBytes === 0) return 0+ return Math.ceil(expectedBytes / partBytes)+}++export function validateGeometry({ expectedBytes, partBytes }: GfsUploadGeometry): void {+ if (!Number.isSafeInteger(expectedBytes) || expectedBytes < 0 || expectedBytes > GFS_UPLOAD_V2_PROTOCOL_MAX_BYTES) {+ throw new GfsUploadGeometryError(+ 'invalid_expected_bytes',+ `expectedBytes must be an integer from 0 through ${GFS_UPLOAD_V2_PROTOCOL_MAX_BYTES}`+ )+ }+ if (+ !Number.isSafeInteger(partBytes) ||+ partBytes < GFS_UPLOAD_V2_MIN_PART_BYTES ||+ partBytes > GFS_UPLOAD_V2_MAX_PART_BYTES+ ) {+ throw new GfsUploadGeometryError(+ 'invalid_part_bytes',+ `partBytes must be an integer from ${GFS_UPLOAD_V2_MIN_PART_BYTES} through ${GFS_UPLOAD_V2_MAX_PART_BYTES}`+ )+ }+ const count = expectedBytes === 0 ? 0 : Math.ceil(expectedBytes / partBytes)+ if (count > GFS_UPLOAD_V2_MAX_PART_COUNT) {+ throw new GfsUploadGeometryError(+ 'part_count_exceeded',+ `part count ${count} exceeds ${GFS_UPLOAD_V2_MAX_PART_COUNT}`+ )+ }+}++export function partGeometry(+ geometry: GfsUploadGeometry,+ partNumber: number+): GfsUploadPartGeometry {+ validateGeometry(geometry)+ const count = partCountFor(geometry)+ if (!Number.isSafeInteger(partNumber) || partNumber < 0 || partNumber >= count) {+ throw new GfsUploadGeometryError('invalid_part_number', `invalid part number ${partNumber}`)+ }+ const offsetBytes = partNumber * geometry.partBytes+ if (offsetBytes >= geometry.expectedBytes) {+ throw new GfsUploadGeometryError('invalid_part_offset', `invalid part offset ${offsetBytes}`)+ }+ const lengthBytes = Math.min(geometry.partBytes, geometry.expectedBytes - offsetBytes)+ if (lengthBytes <= 0 || lengthBytes > GFS_UPLOAD_V2_MAX_PART_BYTES) {+ throw new GfsUploadGeometryError('invalid_part_length', `invalid part length ${lengthBytes}`)+ }+ return { partNumber, offsetBytes, lengthBytes }+}++export function validatePartGeometry(+ geometry: GfsUploadGeometry,+ part: GfsUploadPartGeometry+): void {+ if (!Number.isSafeInteger(part.partNumber) || part.partNumber < 0) {+ throw new GfsUploadGeometryError('invalid_part_number', 'partNumber must be a non-negative integer')+ }+ if (!Number.isSafeInteger(part.offsetBytes) || part.offsetBytes < 0) {+ throw new GfsUploadGeometryError('invalid_part_offset', 'offsetBytes must be a non-negative integer')+ }+ if (!Number.isSafeInteger(part.lengthBytes) || part.lengthBytes <= 0) {+ throw new GfsUploadGeometryError('invalid_part_length', 'lengthBytes must be a positive integer')+ }+ const expected = partGeometry(geometry, part.partNumber)+ if (part.offsetBytes !== expected.offsetBytes) {+ throw new GfsUploadGeometryError(+ 'part_offset_mismatch',+ `part ${part.partNumber} offset must be ${expected.offsetBytes}`+ )+ }+ if (part.lengthBytes !== expected.lengthBytes) {+ throw new GfsUploadGeometryError(+ 'part_length_mismatch',+ `part ${part.partNumber} length must be ${expected.lengthBytes}`+ )+ }+}++/** Route recognition is exact so the broad legacy JSON parser cannot capture v2 binary parts. */+export function isGfsUploadV2Route(pathname: string): boolean {+ return (+ pathname === '/v1/capabilities' ||+ pathname === '/v1/uploads' ||+ /^\/v1\/uploads\/[0-9a-f-]{36}(?:\/status|\/parts\/[0-9]+|\/pause|\/resume|\/complete)?$/.test(pathname)+ )+}++/** Capability payload used while the writer feature flag is disabled. */+export function disabledGfsUploadV2Capability(): {+ enabled: false+ maxFileBytes: 0+ preferredChunkBytes: 0+ maxChunkBytes: 0+} {+ return { enabled: false, maxFileBytes: 0, preferredChunkBytes: 0, maxChunkBytes: 0 }+}diff --git a/gfs-controller/src/upload/uploadSession.test.ts b/gfs-controller/src/upload/uploadSession.test.tsnew file mode 100644index 000000000..cfb752e1b--- /dev/null+++ b/gfs-controller/src/upload/uploadSession.test.ts@@ -0,0 +1,410 @@+import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'+import { createHash } from 'node:crypto'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { Readable } from 'node:stream'+import { afterEach, describe, expect, it } from 'vitest'+import { GfsUploadSessionService, type UploadSessionServiceDeps } from './uploadSession'+import { partGeometry } from './protocol'+import type { GfsUploadConfig } from '../config'++type Row = Record<string, unknown>++class MemoryDb {+ sessions: Row[] = []+ parts: Row[] = []++ async query(text: string, values: unknown[] = []): Promise<{ rows: Row[] }> {+ const sql = text.replace(/\s+/g, ' ').trim()+ if (sql.startsWith('SELECT pg_advisory_xact_lock')) return { rows: [] }+ if (sql.startsWith('SELECT * FROM gfs_upload_sessions WHERE owner_subject')) {+ const [owner, drive, key] = values.map(String)+ return { rows: this.sessions.filter(row => row.owner_subject === owner && row.drive === drive && row.idempotency_key === key) }+ }+ if (sql.startsWith('SELECT * FROM gfs_upload_sessions WHERE upload_id')) {+ const [id, drive, owner] = values.map(String)+ return { rows: this.sessions.filter(row => row.upload_id === id && row.drive === drive && row.owner_subject === owner) }+ }+ if (sql.startsWith('SELECT session_epoch, state FROM gfs_upload_sessions WHERE upload_id')) {+ const [id, drive, owner] = values.map(String)+ return {+ rows: this.sessions+ .filter(row => row.upload_id === id && row.drive === drive && row.owner_subject === owner)+ .map(row => ({ session_epoch: row.session_epoch, state: row.state })),+ }+ }+ if (sql.startsWith('SELECT p.upload_id, p.part_number, p.staging_path FROM gfs_upload_parts p')) {+ return { rows: [] }+ }+ if (sql.startsWith("SELECT upload_id FROM gfs_upload_sessions WHERE state IN ('initiated','uploading','paused','finalizing') AND expires_at <= now()")) {+ return { rows: [] }+ }+ if (sql.startsWith('SELECT p.upload_id, p.part_number, p.offset_bytes, p.length_bytes')) {+ return { rows: [] }+ }+ if (sql.startsWith("SELECT upload_id, state FROM gfs_upload_sessions WHERE state IN ('aborted', 'expired', 'failed', 'completed') AND cleanup_at IS NULL")) {+ return {+ rows: this.sessions+ .filter(row => ['aborted', 'expired', 'failed', 'completed'].includes(String(row.state)) && row.cleanup_at == null)+ .map(row => ({ upload_id: row.upload_id, state: row.state })),+ }+ }+ if (sql.startsWith("SELECT upload_id FROM gfs_upload_sessions WHERE state = 'completed' AND cleanup_at <= now()")) {+ return { rows: [] }+ }+ if (sql.startsWith('SELECT COALESCE(SUM((expected_bytes - committed_bytes) + expected_bytes)')) {+ const drive = String(values[0])+ const reserved = this.sessions+ .filter(row => row.drive === drive && ['initiated', 'uploading', 'paused', 'finalizing'].includes(String(row.state)))+ .reduce((sum, row) => sum + (Number(row.expected_bytes) - Number(row.committed_bytes ?? 0)) + Number(row.expected_bytes), 0)+ return { rows: [{ reserved: String(reserved) }] }+ }+ if (sql === "SELECT COUNT(*)::bigint AS count FROM gfs_upload_sessions WHERE state = 'finalizing'") {+ return { rows: [{ count: String(this.sessions.filter(row => row.state === 'finalizing').length) }] }+ }+ if (sql.startsWith('SELECT COUNT(*)::bigint AS count FROM gfs_upload_sessions')) {+ const [drive, owner] = values.map(value => value === undefined ? undefined : String(value))+ const active = this.sessions.filter(row =>+ ['initiated', 'uploading', 'paused', 'finalizing'].includes(String(row.state))+ && (drive === undefined || row.drive === drive)+ && (owner === undefined || row.owner_subject === owner)+ ).length+ return { rows: [{ count: String(active) }] }+ }+ if (sql.startsWith('SELECT COUNT(*)::bigint')) {+ const drive = String(values[0])+ return { rows: [{ count: String(this.parts.filter(part => part.state === 'reserved' && this.sessions.some(session => session.upload_id === part.upload_id && session.drive === drive)).length) }] }+ }+ if (sql.startsWith('INSERT INTO gfs_upload_sessions')) {+ const [uploadId, key, drive, owner, primary, operation, fingerprint, parent, resource, name, ifMatch, expected, partBytes, partCount, sha, expiresAt] = values+ const row: Row = {+ upload_id: String(uploadId), idempotency_key: String(key), drive: String(drive), owner_subject: String(owner), primary_subject: String(primary),+ operation: String(operation), request_fingerprint: String(fingerprint), parent_rid: parent, resource_rid: resource,+ resource_name: name, if_match: ifMatch, expected_bytes: expected, part_bytes: partBytes, part_count: partCount,+ whole_sha256: sha, committed_bytes: 0, contiguous_bytes: 0, committed_part_count: 0, active_part_count: 0,+ session_epoch: 0, state: 'initiated', result_resource_id: null, result_version: null, result_sha256: null,+ failure_code: null, expires_at: expiresAt, completed_at: null,+ cleanup_at: null,+ }+ this.sessions.push(row)+ return { rows: [row] }+ }+ if (sql.startsWith('SELECT upload_id, part_number')) {+ const [uploadId, partNumber] = values+ const rows = this.parts.filter(part => part.upload_id === String(uploadId) && (partNumber === undefined || Number(part.part_number) === Number(partNumber)) && (!sql.includes("state = 'committed'") || part.state === 'committed'))+ return { rows }+ }+ if (sql.startsWith('INSERT INTO gfs_upload_parts')) {+ const [uploadId, partNumber, offset, length, sha, staging, epoch] = values+ const row: Row = { upload_id: String(uploadId), part_number: partNumber, offset_bytes: offset, length_bytes: length, sha256: sha, state: 'reserved', staging_path: staging, lease_epoch: epoch, committed_at: null }+ this.parts.push(row)+ return { rows: [] }+ }+ if (sql.startsWith('UPDATE gfs_upload_parts SET offset_bytes')) {+ const [uploadId, partNumber, offset, length, sha, staging, epoch] = values+ const row = this.parts.find(part => part.upload_id === String(uploadId) && Number(part.part_number) === Number(partNumber))!+ Object.assign(row, { offset_bytes: offset, length_bytes: length, sha256: sha, state: 'reserved', staging_path: staging, lease_epoch: epoch, committed_at: null })+ return { rows: [] }+ }+ if (sql.startsWith("UPDATE gfs_upload_sessions SET state = 'uploading'")) {+ const row = this.sessions.find(session => session.upload_id === String(values[0]))!+ row.state = 'uploading'; row.active_part_count = Number(row.active_part_count) + 1+ return { rows: [] }+ }+ if (sql.startsWith('UPDATE gfs_upload_parts SET state = \'committed\'')) {+ const [uploadId, partNumber, path] = values+ const row = this.parts.find(part => part.upload_id === String(uploadId) && Number(part.part_number) === Number(partNumber))!+ Object.assign(row, { state: 'committed', staging_path: path })+ return { rows: [] }+ }+ if (sql.startsWith('UPDATE gfs_upload_sessions SET committed_bytes')) {+ const [uploadId, length] = values+ const row = this.sessions.find(session => session.upload_id === String(uploadId))!+ row.committed_bytes = Number(row.committed_bytes) + Number(length)+ row.committed_part_count = Number(row.committed_part_count) + 1+ row.active_part_count = Math.max(0, Number(row.active_part_count) - 1)+ let contiguous = 0+ for (let number = 0; number < Number(row.part_count); number += 1) {+ const part = this.parts.find(candidate => candidate.upload_id === row.upload_id && Number(candidate.part_number) === number && candidate.state === 'committed')+ if (!part) break+ contiguous += Number(part.length_bytes)+ }+ row.contiguous_bytes = contiguous+ return { rows: [] }+ }+ if (sql.startsWith("UPDATE gfs_upload_parts SET state = 'failed'")) {+ const uploadId = String(values[0])+ for (const row of this.parts.filter(part => part.upload_id === uploadId && part.state === 'reserved')) row.state = 'failed'+ return { rows: [] }+ }+ if (sql.startsWith('UPDATE gfs_upload_sessions SET active_part_count')) {+ const row = this.sessions.find(session => session.upload_id === String(values[0]))!+ row.active_part_count = Math.max(0, Number(row.active_part_count) - 1)+ return { rows: [] }+ }+ if (sql.startsWith("UPDATE gfs_upload_sessions SET state = 'paused'")) {+ const row = this.sessions.find(session => session.upload_id === String(values[0]))!+ row.state = 'paused'+ return { rows: [] }+ }+ if (sql.startsWith("UPDATE gfs_upload_sessions SET state = 'uploading'")) {+ const row = this.sessions.find(session => session.upload_id === String(values[0]))!+ row.state = 'uploading'+ return { rows: [] }+ }+ if (sql.startsWith("UPDATE gfs_upload_sessions SET state = 'aborted'")) {+ const row = this.sessions.find(session => session.upload_id === String(values[0]))!+ row.state = 'aborted'; row.session_epoch = Number(row.session_epoch) + 1+ return { rows: [] }+ }+ if (sql.startsWith("UPDATE gfs_upload_sessions SET state = 'finalizing'")) {+ const row = this.sessions.find(session => session.upload_id === String(values[0]))!+ row.state = 'finalizing'+ return { rows: [] }+ }+ if (sql.startsWith("UPDATE gfs_upload_sessions SET state = 'failed'")) {+ const row = this.sessions.find(session => session.upload_id === String(values[0]))!+ row.state = 'failed'+ row.failure_code = values[1]+ row.active_part_count = 0+ return { rows: [] }+ }+ if (sql.startsWith('UPDATE gfs_upload_sessions SET cleanup_at')) {+ const row = this.sessions.find(session => session.upload_id === String(values[0]))+ if (row) row.cleanup_at = new Date().toISOString()+ return { rows: [] }+ }+ if (sql.startsWith('DELETE FROM gfs_upload_parts')) {+ const uploadId = String(values[0])+ this.parts = this.parts.filter(part => part.upload_id !== uploadId)+ return { rows: [] }+ }+ throw new Error(`unhandled fake SQL: ${sql}`)+ }+}++const CONFIG: GfsUploadConfig = {+ productMaxFileBytes: 209715200,+ protocolMaxFileBytes: 1073741824,+ preferredPartBytes: 8388608,+ maxPartBytes: 16777216,+ maxPartCount: 1024,+ maxConcurrentPartsPerSession: 4,+ maxConcurrentPartStreamsGlobal: 16,+ maxActivePerSubject: 2,+ maxActiveGlobal: 8,+ maxConcurrentFinalizations: 1,+ minFreeBytes: 10 * 1024 * 1024 * 1024,+ instabilityFailureThreshold: 3,+ fallbackConcurrency: 2,+ sessionTtlSeconds: 86400,+ partTimeoutMs: 300000,+ finalizeTimeoutMs: 600000,+ stalePartLeaseMs: 600000,+ receiptRetentionSeconds: 86400,+ enabled: true,+}++const TEST_CONFIG: GfsUploadConfig = {+ ...CONFIG,+ preferredPartBytes: 1048576,+ maxPartBytes: 1048576,+}++const principal = { drive: 'main', ownerSubject: 'user-1', primarySubject: 'user-1' }+const key = '11111111-1111-4111-8111-111111111111'++let tempRoot: string+afterEach(async () => {+ if (tempRoot) await rm(tempRoot, { recursive: true, force: true })+})++function service(+ db: MemoryDb,+ config: GfsUploadConfig = TEST_CONFIG,+ overrides: Partial<Pick<UploadSessionServiceDeps, 'now' | 'finalize'>> = {},+): GfsUploadSessionService {+ return new GfsUploadSessionService({+ db,+ tx: { transaction: async fn => fn(db) },+ blobs: { availableBytes: async () => 10n ** 12n } as never,+ storageMountPath: tempRoot,+ config,+ ...overrides,+ })+}++async function settleWithin<T>(promise: Promise<T>, timeoutMs = 500): Promise<+ | { kind: 'completed'; value: T }+ | { kind: 'rejected'; error: unknown }+ | { kind: 'timeout' }+> {+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ return await Promise.race([+ promise.then(+ value => ({ kind: 'completed' as const, value }),+ error => ({ kind: 'rejected' as const, error }),+ ),+ new Promise<{ kind: 'timeout' }>(resolve => {+ timer = setTimeout(() => resolve({ kind: 'timeout' }), timeoutMs)+ }),+ ])+ } finally {+ if (timer) clearTimeout(timer)+ }+}++describe('GfsUploadSessionService', () => {+ it('creates idempotent sessions and keeps indexed commits separate from contiguous progress', async () => {+ tempRoot = await mkdtemp(join(tmpdir(), 'gfsc-upload-'))+ const db = new MemoryDb()+ const uploads = service(db)+ const created = await uploads.create({ ...principal, operation: 'create', parentRid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', name: 'data.bin', sizeBytes: 2097152, idempotencyKey: key })+ expect(created.created).toBe(true)+ const replay = await uploads.create({ ...principal, operation: 'create', parentRid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', name: 'data.bin', sizeBytes: 2097152, idempotencyKey: key })+ expect(replay.created).toBe(false)+ expect(replay.session.uploadId).toBe(created.session.uploadId)++ const first = Buffer.alloc(1048576, 0x11)+ const second = Buffer.alloc(1048576, 0x22)+ const firstGeometry = partGeometry({ expectedBytes: 2097152, partBytes: 1048576 }, 0)+ const secondGeometry = partGeometry({ expectedBytes: 2097152, partBytes: 1048576 }, 1)+ const checksum = (value: Buffer) => createSha(value)+ const outOfOrder = await uploads.putPart(created.session.uploadId, secondGeometry, checksum(second), Readable.from([second]) as never, principal)+ expect(outOfOrder.session.contiguousBytes).toBe(0)+ const ordered = await uploads.putPart(created.session.uploadId, firstGeometry, checksum(first), Readable.from([first]) as never, principal)+ expect(ordered.session.contiguousBytes).toBe(2097152)+ expect(ordered.session.committedPartCount).toBe(2)+ expect(await readFile(ordered.part.stagingPath)).toEqual(first)+ const duplicate = await uploads.putPart(created.session.uploadId, firstGeometry, checksum(first), Readable.from([first]) as never, principal)+ expect(duplicate.part.sha256).toBe(checksum(first))+ })++ it('cancels terminally and rejects a conflicting idempotency fingerprint', async () => {+ tempRoot = await mkdtemp(join(tmpdir(), 'gfsc-upload-'))+ const db = new MemoryDb()+ const uploads = service(db)+ await uploads.create({ ...principal, operation: 'create', parentRid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', name: 'data.bin', sizeBytes: 0, idempotencyKey: key })+ await expect(uploads.create({ ...principal, operation: 'create', parentRid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', name: 'other.bin', sizeBytes: 0, idempotencyKey: key })).rejects.toMatchObject({ code: 'idempotency_conflict' })+ const session = await uploads.create({ ...principal, operation: 'create', parentRid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', name: 'cancel.bin', sizeBytes: 0, idempotencyKey: '22222222-2222-4222-8222-222222222222' })+ await uploads.cancel(session.session.uploadId, principal)+ await expect(uploads.get(session.session.uploadId, principal)).rejects.toMatchObject({ code: 'upload_aborted' })+ })++ it('releases a rejected finalizer before quiescence and cleans the failed upload immediately', async () => {+ tempRoot = await mkdtemp(join(tmpdir(), 'gfsc-upload-'))+ const db = new MemoryDb()+ let now = 0+ const uploads = service(db, TEST_CONFIG, {+ // Advance beyond the drain deadline on its first condition check. This+ // makes the regression deterministic without waiting for the production+ // five-minute part timeout: the old code still skipped cleanup because+ // the failed finalizer remained registered while it drained itself.+ now: () => (now += TEST_CONFIG.partTimeoutMs + 1),+ finalize: async () => { throw new Error('synthetic finalizer rejection') },+ })+ const created = await uploads.create({+ ...principal,+ operation: 'create',+ parentRid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ name: 'finalizer-rejection.bin',+ sizeBytes: 0,+ idempotencyKey: '33333333-3333-4333-8333-333333333333',+ })+ const uploadDirectory = join(tempRoot, '.uploads', created.session.uploadId)+ await mkdir(uploadDirectory, { recursive: true })+ await writeFile(join(uploadDirectory, 'finalizer-marker'), 'pending')++ const outcome = await settleWithin(uploads.complete(created.session.uploadId, principal))++ expect(outcome.kind).toBe('rejected')+ if (outcome.kind !== 'rejected') throw new Error(`unexpected completion outcome: ${outcome.kind}`)+ expect(outcome.error).toMatchObject({ message: 'synthetic finalizer rejection' })+ expect(db.sessions[0]).toMatchObject({+ state: 'failed',+ failure_code: 'finalization_failed',+ cleanup_at: expect.any(String),+ })+ expect((uploads as unknown as { inFlightFinalizers: Map<string, unknown> }).inFlightFinalizers.size).toBe(0)+ expect(db.parts).toHaveLength(0)+ await expect(stat(uploadDirectory)).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('releases a timed-out finalizer and preserves the timeout failure code during cleanup', async () => {+ tempRoot = await mkdtemp(join(tmpdir(), 'gfsc-upload-'))+ const db = new MemoryDb()+ let now = 0+ const config = { ...TEST_CONFIG, finalizeTimeoutMs: 5 }+ const uploads = service(db, config, {+ now: () => (now += config.partTimeoutMs + 1),+ finalize: async (_session, _parts, signal) => new Promise((_resolve, reject) => {+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true })+ }),+ })+ const created = await uploads.create({+ ...principal,+ operation: 'create',+ parentRid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ name: 'finalizer-timeout.bin',+ sizeBytes: 0,+ idempotencyKey: '44444444-4444-4444-8444-444444444444',+ })+ const uploadDirectory = join(tempRoot, '.uploads', created.session.uploadId)+ await mkdir(uploadDirectory, { recursive: true })+ await writeFile(join(uploadDirectory, 'finalizer-marker'), 'pending')++ const outcome = await settleWithin(uploads.complete(created.session.uploadId, principal))++ expect(outcome.kind).toBe('rejected')+ if (outcome.kind !== 'rejected') throw new Error(`unexpected completion outcome: ${outcome.kind}`)+ expect(outcome.error).toMatchObject({ code: 'precondition_failed' })+ expect(db.sessions[0]).toMatchObject({+ state: 'failed',+ failure_code: 'precondition_failed',+ cleanup_at: expect.any(String),+ })+ expect((uploads as unknown as { inFlightFinalizers: Map<string, unknown> }).inFlightFinalizers.size).toBe(0)+ expect(db.parts).toHaveLength(0)+ await expect(stat(uploadDirectory)).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('leaves a failed finalizer cleanup eligible for the reconciler after the registry is released', async () => {+ tempRoot = await mkdtemp(join(tmpdir(), 'gfsc-upload-'))+ const db = new MemoryDb()+ let now = 0+ const uploads = service(db, TEST_CONFIG, {+ now: () => (now += TEST_CONFIG.partTimeoutMs + 1),+ finalize: async () => { throw new Error('synthetic cleanup retry') },+ })+ const created = await uploads.create({+ ...principal,+ operation: 'create',+ parentRid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ name: 'finalizer-cleanup-retry.bin',+ sizeBytes: 0,+ idempotencyKey: '55555555-5555-4555-8555-555555555555',+ })+ const uploadDirectory = join(tempRoot, '.uploads', created.session.uploadId)+ await mkdir(join(tempRoot, '.uploads'), { recursive: true })+ // A non-directory at the private session path makes the strict direct+ // cleanup fail closed. The terminal row must remain retryable.+ await writeFile(uploadDirectory, 'not-a-directory')++ const outcome = await settleWithin(uploads.complete(created.session.uploadId, principal))+ expect(outcome.kind).toBe('rejected')+ expect(db.sessions[0]).toMatchObject({ state: 'failed', cleanup_at: null })+ expect((uploads as unknown as { inFlightFinalizers: Map<string, unknown> }).inFlightFinalizers.size).toBe(0)++ await rm(uploadDirectory, { force: true })+ await mkdir(uploadDirectory, { recursive: true })+ await writeFile(join(uploadDirectory, 'finalizer-marker'), 'pending')+ await expect(uploads.reconcile()).resolves.toEqual({ staleParts: 0, expiredSessions: 0 })+ expect(db.sessions[0]).toMatchObject({ state: 'failed', cleanup_at: expect.any(String) })+ await expect(stat(uploadDirectory)).rejects.toMatchObject({ code: 'ENOENT' })+ })+})++function createSha(value: Buffer): string {+ return createHash('sha256').update(value).digest('hex')+}diff --git a/gfs-controller/src/upload/uploadSession.ts b/gfs-controller/src/upload/uploadSession.tsnew file mode 100644index 000000000..388ccbc1c--- /dev/null+++ b/gfs-controller/src/upload/uploadSession.ts@@ -0,0 +1,1354 @@+import { createHash, randomUUID } from 'node:crypto'+import { constants } from 'node:fs'+import { lstat, mkdir, open, rename, rm, stat } from 'node:fs/promises'+import { dirname, resolve } from 'node:path'+import type { IncomingMessage } from 'node:http'+import { Readable, Transform } from 'node:stream'+import { pipeline } from 'node:stream/promises'+import { GfsError } from '../api/errors'+import { normalizeResourceName, ResourceNameError } from '../api/resourceName'+import { normalizeResourceId, PathError } from '../storage/paths'+import { CommitOutcomeUnknownError, RollbackOutcomeUnknownError } from '../db/writeStore'+import type { BlobWriter, Transactor, TxClient } from '../db/writeStore'+import type { GfsUploadConfig } from '../config'+import {+ GFS_UPLOAD_V2_COMPLETE_BODY_MAX_BYTES,+ GFS_UPLOAD_V2_METADATA_BODY_MAX_BYTES,+ GFS_UPLOAD_V2_PRODUCT_MAX_BYTES,+ disabledGfsUploadV2Capability,+ partCountFor,+ partGeometry,+ validatePartGeometry,+ GfsUploadGeometryError,+ type GfsUploadPartGeometry,+} from './protocol'++export type { GfsUploadPartGeometry } from './protocol'++export interface UploadSessionQuery {+ query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>+}++export interface UploadPrincipal {+ drive: string+ ownerSubject: string+ primarySubject: string+}++export interface CreateUploadSessionInput extends UploadPrincipal {+ uploadId?: string+ idempotencyKey: string+ operation: 'create' | 'replace'+ parentRid?: string+ resourceRid?: string+ name?: string+ ifMatch?: number+ sizeBytes: number+ wholeSha256?: string | null+}++export interface UploadSessionReceipt {+ uploadId: string+ drive: string+ operation: 'create' | 'replace'+ expectedBytes: number+ partBytes: number+ partCount: number+ state: string+ contiguousBytes: number+ committedBytes: number+ committedPartCount: number+ activePartCount: number+ expiresAt: string+ resultResourceId?: string+ resultVersion?: number+ resultSha256?: string+}++export interface UploadPartStatus {+ partNumber: number+ offsetBytes: number+ lengthBytes: number+ sha256: string+}++export interface UploadStatusPage {+ session: UploadSessionReceipt+ parts: UploadPartStatus[]+ nextCursor: string | null+}++export interface UploadSessionServiceDeps {+ db: UploadSessionQuery+ tx: Transactor+ blobs: BlobWriter+ storageMountPath: string+ config: GfsUploadConfig+ now?: () => number+ authorize?: (principal: UploadPrincipal, operation: 'create' | 'replace', resourceRid?: string) => Promise<void>+ /** PR3 supplies this; PR2 intentionally cannot publish a resource. */+ finalize?: (session: UploadSessionRow, parts: UploadPartRow[], signal?: AbortSignal, deadlineAtMs?: number) => Promise<{ resourceId: string; version: number; sha256: string }>+}++export interface UploadSessionRow {+ uploadId: string+ idempotencyKey: string+ drive: string+ ownerSubject: string+ primarySubject: string+ operation: 'create' | 'replace'+ requestFingerprint: string+ parentRid: string | null+ resourceRid: string | null+ resourceName: string | null+ ifMatch: number | null+ expectedBytes: number+ partBytes: number+ partCount: number+ wholeSha256: string | null+ committedBytes: number+ contiguousBytes: number+ committedPartCount: number+ activePartCount: number+ sessionEpoch: number+ state: string+ resultResourceId: string | null+ resultVersion: number | null+ resultSha256: string | null+ failureCode: string | null+ expiresAt: string+}++export interface UploadPartRow extends UploadPartStatus {+ uploadId: string+ state: 'reserved' | 'committed' | 'failed'+ stagingPath: string+ leaseEpoch: number+}++export interface UploadSessionTarget {+ operation: 'create' | 'replace'+ targetRid: string | null+}++export interface UploadReconcileResult {+ staleParts: number+ expiredSessions: number+}++interface InFlightPart {+ controller: AbortController+ sessionEpoch: number+}++interface InFlightFinalizer {+ controller: AbortController+ sessionEpoch: number+}++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i+const SHA256_RE = /^[0-9a-f]{64}$/i+const TEMP_PART_RE = /^(\d+)\.part\.tmp-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i++function rowToSession(row: Record<string, unknown>): UploadSessionRow {+ return {+ uploadId: String(row.upload_id),+ idempotencyKey: String(row.idempotency_key),+ drive: String(row.drive),+ ownerSubject: String(row.owner_subject),+ primarySubject: String(row.primary_subject),+ operation: row.operation === 'replace' ? 'replace' : 'create',+ requestFingerprint: String(row.request_fingerprint),+ parentRid: row.parent_rid == null ? null : String(row.parent_rid),+ resourceRid: row.resource_rid == null ? null : String(row.resource_rid),+ resourceName: row.resource_name == null ? null : String(row.resource_name),+ ifMatch: row.if_match == null ? null : Number(row.if_match),+ expectedBytes: Number(row.expected_bytes),+ partBytes: Number(row.part_bytes),+ partCount: Number(row.part_count),+ wholeSha256: row.whole_sha256 == null ? null : String(row.whole_sha256),+ committedBytes: Number(row.committed_bytes),+ contiguousBytes: Number(row.contiguous_bytes),+ committedPartCount: Number(row.committed_part_count),+ activePartCount: Number(row.active_part_count),+ sessionEpoch: Number(row.session_epoch),+ state: String(row.state),+ resultResourceId: row.result_resource_id == null ? null : String(row.result_resource_id),+ resultVersion: row.result_version == null ? null : Number(row.result_version),+ resultSha256: row.result_sha256 == null ? null : String(row.result_sha256),+ failureCode: row.failure_code == null ? null : String(row.failure_code),+ expiresAt: new Date(String(row.expires_at)).toISOString(),+ }+}++function rowToPart(row: Record<string, unknown>): UploadPartRow {+ return {+ uploadId: String(row.upload_id),+ partNumber: Number(row.part_number),+ offsetBytes: Number(row.offset_bytes),+ lengthBytes: Number(row.length_bytes),+ sha256: String(row.sha256),+ state: String(row.state) as UploadPartRow['state'],+ stagingPath: String(row.staging_path),+ leaseEpoch: Number(row.lease_epoch),+ }+}++function canonicalFingerprint(input: CreateUploadSessionInput, partBytes: number, partCount: number): string {+ return JSON.stringify({+ owner: input.ownerSubject,+ drive: input.drive,+ operation: input.operation,+ parentRid: input.parentRid ?? null,+ resourceRid: input.resourceRid ?? null,+ name: input.name ?? null,+ sizeBytes: input.sizeBytes,+ ifMatch: input.ifMatch ?? null,+ wholeSha256: input.wholeSha256 ?? null,+ partBytes,+ partCount,+ })+}++function normalizedName(value: string | undefined): string | undefined {+ if (value === undefined) return undefined+ try {+ return normalizeResourceName(value)+ } catch (error) {+ if (error instanceof ResourceNameError) throw new GfsError('path_invalid', error.message)+ throw error+ }+}++function normalizedRid(value: string | undefined, field: string): string | undefined {+ if (value === undefined) return undefined+ try {+ return normalizeResourceId(value)+ } catch (error) {+ if (error instanceof PathError) throw new GfsError('path_invalid', `${field} is invalid`)+ throw error+ }+}++function requireUuid(value: string, field: string): string {+ if (!UUID_RE.test(value)) throw new GfsError('path_invalid', `${field} must be a UUID`)+ return value.toLowerCase()+}++function requireChecksum(value: string | undefined, field: string): string {+ if (value === undefined || !SHA256_RE.test(value)) throw new GfsError('path_invalid', `${field} must be a SHA-256 hex digest`)+ return value.toLowerCase()+}++function requireEnabled(config: GfsUploadConfig): void {+ if (!config.enabled) throw new GfsError('forbidden', 'resumable GFS uploads are disabled')+}++function toReceipt(session: UploadSessionRow): UploadSessionReceipt {+ return {+ uploadId: session.uploadId,+ drive: session.drive,+ operation: session.operation,+ expectedBytes: session.expectedBytes,+ partBytes: session.partBytes,+ partCount: session.partCount,+ state: session.state,+ contiguousBytes: session.contiguousBytes,+ committedBytes: session.committedBytes,+ committedPartCount: session.committedPartCount,+ activePartCount: session.activePartCount,+ expiresAt: session.expiresAt,+ ...(session.resultResourceId ? { resultResourceId: session.resultResourceId } : {}),+ ...(session.resultVersion === null ? {} : { resultVersion: session.resultVersion }),+ ...(session.resultSha256 ? { resultSha256: session.resultSha256 } : {}),+ }+}++function assertNotExpired(session: UploadSessionRow, now: number): void {+ if (Date.parse(session.expiresAt) <= now && !['completed', 'aborted', 'expired'].includes(session.state)) {+ throw new GfsError('upload_expired', 'upload session has expired')+ }+}++function sessionPath(root: string, uploadId: string, partNumber: number, suffix: string): string {+ requireUuid(uploadId, 'uploadId')+ if (!Number.isSafeInteger(partNumber) || partNumber < 0 || partNumber > 1024) {+ throw new GfsError('path_invalid', 'part number is invalid')+ }+ const base = resolve(root)+ const dir = resolve(base, '.uploads', uploadId, 'parts')+ const path = resolve(dir, `${partNumber}.part${suffix}`)+ if (!path.startsWith(`${base}/.uploads/${uploadId}/parts/`)) {+ throw new GfsError('path_invalid', 'staging path escapes upload root')+ }+ return path+}++/**+ * A database path is metadata, never an authorization to delete an arbitrary+ * writer file. Reconciliation may unlink only the exact temporary filename+ * generated for this upload/part. The common committed `<n>.part` path is+ * intentionally rejected because a new lease may own it after the row lock is+ * released.+ */+async function validatedTempPath(root: string, uploadId: string, partNumber: number, candidate: string): Promise<string | null> {+ const canonicalUploadId = requireUuid(uploadId, 'uploadId')+ const expectedDir = resolve(root, '.uploads', canonicalUploadId, 'parts')+ const resolved = resolve(candidate)+ const prefix = `${expectedDir}/`+ if (!resolved.startsWith(prefix)) return null+ const match = TEMP_PART_RE.exec(resolved.slice(prefix.length))+ if (!match || Number(match[1]) !== partNumber) return null+ for (const directory of [resolve(root), resolve(root, '.uploads'), resolve(root, '.uploads', canonicalUploadId), expectedDir]) {+ try {+ if (!(await lstat(directory)).isDirectory()) return null+ } catch (error) {+ if ((error as { code?: string }).code === 'ENOENT') return resolved+ return null+ }+ }+ return resolved+}++async function ensureStagingDir(path: string): Promise<void> {+ const partsDir = dirname(path)+ const uploadDir = dirname(partsDir)+ const uploadsDir = dirname(uploadDir)+ const root = dirname(uploadsDir)+ await mkdir(partsDir, { recursive: true, mode: 0o700 })+ for (const directory of [root, uploadsDir, uploadDir, partsDir]) {+ const info = await lstat(directory)+ if (!info.isDirectory()) throw new GfsError('path_invalid', 'upload staging ancestors must be real directories')+ }+}++async function removeIfPresent(path: string): Promise<void> {+ await rm(path, { force: true }).catch(() => undefined)+}++async function removeStrict(path: string, recursive = false): Promise<boolean> {+ try {+ await rm(path, { force: true, ...(recursive ? { recursive: true } : {}) })+ return true+ } catch {+ return false+ }+}++async function removeUploadDirectory(root: string, uploadId: string): Promise<boolean> {+ const directory = resolve(root, '.uploads', requireUuid(uploadId, 'uploadId'))+ try {+ const info = await lstat(directory)+ if (!info.isDirectory()) return false+ } catch (error) {+ return (error as { code?: string }).code === 'ENOENT'+ }+ return removeStrict(directory, true)+}++async function committedPartFilePresent(root: string, part: UploadPartRow): Promise<boolean> {+ const expected = sessionPath(root, part.uploadId, part.partNumber, '')+ if (part.stagingPath !== expected) return false+ const safe = await validatedTempPath(root, part.uploadId, part.partNumber, `${expected}.tmp-${randomUUID()}`)+ // validatedTempPath also validates all private ancestors. The synthetic+ // candidate is never unlinked and only serves as the containment check.+ if (!safe) return false+ try {+ const handle = await open(expected, constants.O_RDONLY | constants.O_NOFOLLOW)+ try {+ return (await handle.stat()).isFile()+ } finally {+ await handle.close().catch(() => undefined)+ }+ } catch (error) {+ if ((error as { code?: string }).code === 'ENOENT') return false+ throw error+ }+}++async function readPartBody(+ req: IncomingMessage,+ expectedLength: number,+ maxLength: number,+ destination?: string,+ signal?: AbortSignal+): Promise<{ bytes: number; sha256: string }> {+ if (!Number.isSafeInteger(expectedLength) || expectedLength <= 0 || expectedLength > maxLength) {+ throw new GfsError('payload_too_large', `part length must be between 1 and ${maxLength} bytes`)+ }+ const digest = createHash('sha256')+ let handle: Awaited<ReturnType<typeof open>> | undefined+ let stream: import('node:fs').WriteStream | undefined+ try {+ if (destination) {+ await ensureStagingDir(destination)+ handle = await open(destination, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600)+ stream = handle.createWriteStream()+ }+ let bytes = 0+ if (stream) {+ const verifier = new Transform({+ transform(raw: Buffer | string, _encoding, callback) {+ try {+ signal?.throwIfAborted()+ const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw)+ bytes += chunk.length+ if (bytes > expectedLength || bytes > maxLength) {+ callback(new GfsError('payload_too_large', 'part body exceeds its declared length'))+ return+ }+ digest.update(chunk)+ callback(null, chunk)+ } catch (error) {+ callback(error as Error)+ }+ },+ })+ await pipeline(req as unknown as Readable, verifier, stream, { signal })+ // createWriteStream owns and closes this descriptor when the pipeline+ // finishes; keeping the FileHandle around would double-close it.+ handle = undefined+ } else {+ for await (const raw of req as unknown as AsyncIterable<Buffer | string>) {+ signal?.throwIfAborted()+ const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw)+ bytes += chunk.length+ if (bytes > expectedLength || bytes > maxLength) throw new GfsError('payload_too_large', 'part body exceeds its declared length')+ digest.update(chunk)+ }+ }+ if (bytes !== expectedLength) throw new GfsError('path_invalid', `part body has ${bytes} bytes; expected ${expectedLength}`)+ if (destination) {+ const syncHandle = await open(destination, constants.O_RDONLY | constants.O_NOFOLLOW)+ try {+ await syncHandle.sync()+ } finally {+ await syncHandle.close().catch(() => undefined)+ }+ }+ const sha256 = digest.digest('hex')+ return { bytes, sha256 }+ } catch (error) {+ stream?.destroy()+ if (!stream) await handle?.close().catch(() => undefined)+ if (destination) await removeIfPresent(destination)+ const reason = signal?.reason+ if (reason instanceof GfsError) throw reason+ const cause = (error as { cause?: unknown } | undefined)?.cause+ if (cause instanceof GfsError) throw cause+ throw error+ } finally {+ if (!stream) await handle?.close().catch(() => undefined)+ }+}++/**+ * Stateful writer-side engine. It owns part geometry/leases and never hands a+ * whole file to a caller. Publication is injected by PR3 so PR2 can be tested+ * independently without silently inventing a second blob/resource writer.+ */+export class GfsUploadSessionService {+ private readonly inFlight = new Map<string, InFlightPart>()+ private readonly inFlightFinalizers = new Map<string, InFlightFinalizer>()+ private readonly canceledUploads = new Set<string>()+ /**+ * The writer is a singleton. This keyed gate closes the reservation race+ * while pause drains existing leases; committed in-flight parts are still+ * allowed to finish, then the durable state transitions to `paused`.+ */+ private readonly pauseRequested = new Set<string>()++ constructor(private readonly deps: UploadSessionServiceDeps) {}++ private now(): number {+ return (this.deps.now ?? Date.now)()+ }++ private hasInFlight(uploadId: string): boolean {+ return [...this.inFlight.keys()].some(key => key.startsWith(`${uploadId}:`))+ || this.inFlightFinalizers.has(uploadId)+ }++ async create(input: CreateUploadSessionInput): Promise<{ created: boolean; session: UploadSessionReceipt }> {+ requireEnabled(this.deps.config)+ const idempotencyKey = requireUuid(input.idempotencyKey, 'idempotencyKey')+ if (!Number.isSafeInteger(input.sizeBytes) || input.sizeBytes < 0 || input.sizeBytes > GFS_UPLOAD_V2_PRODUCT_MAX_BYTES) {+ throw new GfsError('payload_too_large', `sizeBytes must be between 0 and ${GFS_UPLOAD_V2_PRODUCT_MAX_BYTES}`)+ }+ const name = normalizedName(input.name)+ const parentRid = normalizedRid(input.parentRid, 'parentRid')+ const resourceRid = normalizedRid(input.resourceRid, 'resourceRid')+ if (input.operation === 'create' && (!parentRid || !name)) throw new GfsError('path_invalid', 'create requires parentRid and name')+ if (input.operation === 'replace' && !resourceRid) throw new GfsError('path_invalid', 'replace requires resourceRid')+ const wholeSha256 = input.wholeSha256 === null || input.wholeSha256 === undefined+ ? null+ : requireChecksum(input.wholeSha256, 'wholeSha256')+ await this.deps.authorize?.(input, input.operation, input.operation === 'create' ? parentRid : resourceRid)+ const partBytes = this.deps.config.preferredPartBytes+ const partCount = partCountFor({ expectedBytes: input.sizeBytes, partBytes })+ if (partCount > this.deps.config.maxPartCount) throw new GfsError('payload_too_large', 'upload part count exceeds the configured maximum')+ const canonicalInput = { ...input, name, parentRid, resourceRid, wholeSha256 }+ const requestFingerprint = canonicalFingerprint(canonicalInput, partBytes, partCount)+ const existing = await this.deps.db.query(+ `SELECT * FROM gfs_upload_sessions WHERE owner_subject = $1 AND drive = $2 AND idempotency_key = $3`,+ [input.ownerSubject, input.drive, idempotencyKey]+ )+ if (existing.rows[0]) {+ const row = rowToSession(existing.rows[0])+ if (row.requestFingerprint !== requestFingerprint) throw new GfsError('idempotency_conflict', 'idempotency key is bound to a different request')+ return { created: false, session: toReceipt(row) }+ }+ const uploadId = requireUuid(input.uploadId ?? randomUUID(), 'uploadId')+ const expiresAt = new Date(this.now() + this.deps.config.sessionTtlSeconds * 1000)+ const available = this.deps.blobs.availableBytes ? await this.deps.blobs.availableBytes() : null+ try {+ const result = await this.deps.tx.transaction(async client => {+ await client.query(`SELECT pg_advisory_xact_lock(hashtext('gfs:upload:admission:' || $1)::bigint)`, [input.drive])+ const subjectActive = await client.query(+ `SELECT COUNT(*)::bigint AS count FROM gfs_upload_sessions+ WHERE drive = $1 AND owner_subject = $2 AND state IN ('initiated','uploading','paused','finalizing') AND expires_at > now()`,+ [input.drive, input.ownerSubject]+ )+ if (Number(subjectActive.rows[0]?.count ?? 0) >= this.deps.config.maxActivePerSubject) {+ throw new GfsError('quota_exceeded', 'active upload session subject quota reached')+ }+ const globalActive = await client.query(+ `SELECT COUNT(*)::bigint AS count FROM gfs_upload_sessions+ WHERE state IN ('initiated','uploading','paused','finalizing') AND expires_at > now()`,+ []+ )+ if (Number(globalActive.rows[0]?.count ?? 0) >= this.deps.config.maxActiveGlobal) {+ throw new GfsError('quota_exceeded', 'active upload session global quota reached')+ }+ if (available !== null) {+ const reserved = await client.query(+ `SELECT COALESCE(SUM((expected_bytes - committed_bytes) + expected_bytes), 0)::bigint AS reserved+ FROM gfs_upload_sessions+ WHERE drive = $1 AND state IN ('initiated','uploading','paused','finalizing') AND expires_at > now()`,+ [input.drive]+ )+ const reservedBytes = BigInt(String(reserved.rows[0]?.reserved ?? 0))+ if (reservedBytes + BigInt(input.sizeBytes) * 2n + BigInt(this.deps.config.minFreeBytes) > available) {+ throw new GfsError('insufficient_storage', 'insufficient storage for upload reservation')+ }+ }+ const inserted = await client.query(+ `INSERT INTO gfs_upload_sessions+ (upload_id, idempotency_key, drive, owner_subject, primary_subject,+ operation, request_fingerprint, parent_rid, resource_rid,+ resource_name, if_match, expected_bytes, part_bytes, part_count,+ whole_sha256, state, expires_at)+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,'initiated',$16)+ RETURNING *`,+ [uploadId, idempotencyKey, input.drive, input.ownerSubject, input.primarySubject,+ input.operation, requestFingerprint, parentRid ?? null, resourceRid ?? null,+ name ?? null, input.ifMatch ?? null, input.sizeBytes, partBytes, partCount,+ wholeSha256, expiresAt]+ )+ return rowToSession(inserted.rows[0]!)+ })+ return { created: true, session: toReceipt(result) }+ } catch (error) {+ if ((error as { code?: string }).code !== '23505') throw error+ const replay = await this.deps.db.query(+ `SELECT * FROM gfs_upload_sessions WHERE owner_subject = $1 AND drive = $2 AND idempotency_key = $3`,+ [input.ownerSubject, input.drive, idempotencyKey]+ )+ const row = replay.rows[0] ? rowToSession(replay.rows[0]) : null+ if (!row) throw error+ if (row.requestFingerprint !== requestFingerprint) throw new GfsError('idempotency_conflict', 'idempotency key is bound to a different request')+ return { created: false, session: toReceipt(row) }+ }+ }++ async get(uploadId: string, principal: UploadPrincipal): Promise<UploadSessionReceipt> {+ requireEnabled(this.deps.config)+ requireUuid(uploadId, 'uploadId')+ const result = await this.deps.db.query(+ `SELECT * FROM gfs_upload_sessions WHERE upload_id = $1 AND drive = $2 AND owner_subject = $3`,+ [uploadId, principal.drive, principal.ownerSubject]+ )+ const row = result.rows[0] ? rowToSession(result.rows[0]) : null+ if (!row) throw new GfsError('not_found', 'upload session not found')+ if (row.state === 'expired') throw new GfsError('upload_expired', 'upload session has expired')+ if (row.state === 'aborted') throw new GfsError('upload_aborted', 'upload session was canceled')+ return toReceipt(row)+ }++ async target(uploadId: string, principal: UploadPrincipal): Promise<UploadSessionTarget> {+ requireEnabled(this.deps.config)+ const session = await this.loadOwned(uploadId, principal)+ return {+ operation: session.operation,+ targetRid: session.operation === 'create' ? session.parentRid : session.resourceRid,+ }+ }++ async status(uploadId: string, principal: UploadPrincipal, options?: { cursor?: string; limit?: number }): Promise<UploadStatusPage> {+ requireEnabled(this.deps.config)+ const session = await this.loadOwned(uploadId, principal)+ const rawCursor = options?.cursor ?? ''+ if (rawCursor && !/^\d+$/.test(rawCursor)) throw new GfsError('path_invalid', 'status cursor is invalid')+ const cursor = rawCursor ? Number(rawCursor) : -1+ const requestedLimit = options?.limit ?? 256+ if (!Number.isSafeInteger(requestedLimit) || requestedLimit < 1 || requestedLimit > 256) throw new GfsError('path_invalid', 'status limit is invalid')+ const result = await this.deps.db.query(+ `SELECT upload_id, part_number, offset_bytes, length_bytes, sha256, state, staging_path, lease_epoch+ FROM gfs_upload_parts WHERE upload_id = $1 AND state = 'committed' AND part_number > $2 ORDER BY part_number ASC LIMIT $3`,+ [uploadId, cursor, requestedLimit + 1]+ )+ const hasMore = result.rows.length > requestedLimit+ const rows = hasMore ? result.rows.slice(0, requestedLimit) : result.rows+ const lastPart = rows.at(-1)+ return {+ session: toReceipt(session),+ parts: rows.map(row => {+ const part = rowToPart(row)+ return {+ partNumber: part.partNumber,+ offsetBytes: part.offsetBytes,+ lengthBytes: part.lengthBytes,+ sha256: part.sha256,+ }+ }),+ nextCursor: hasMore && lastPart ? String(Number(lastPart.part_number)) : null,+ }+ }++ async putPart(+ uploadId: string,+ part: GfsUploadPartGeometry,+ checksum: string | undefined,+ req: IncomingMessage,+ principal: UploadPrincipal+ ): Promise<{ part: UploadPartStatus; session: UploadSessionReceipt }> {+ requireEnabled(this.deps.config)+ const expectedChecksum = requireChecksum(checksum, 'Upload-Checksum')+ const session = await this.loadOwned(uploadId, principal)+ await this.deps.authorize?.(principal, session.operation, session.operation === 'create' ? session.parentRid ?? undefined : session.resourceRid ?? undefined)+ if (this.pauseRequested.has(uploadId)) throw new GfsError('conflict', 'upload session is pausing')+ assertNotExpired(session, this.now())+ if (session.state === 'paused') throw new GfsError('conflict', 'upload session is paused')+ if (['finalizing', 'completed'].includes(session.state)) throw new GfsError('upload_completed', 'upload session is no longer writable')+ if (['aborted', 'expired', 'failed'].includes(session.state)) throw new GfsError('upload_aborted', 'upload session is not writable')+ try {+ validatePartGeometry({ expectedBytes: session.expectedBytes, partBytes: session.partBytes }, part)+ } catch (error) {+ if (error instanceof GfsUploadGeometryError) throw new GfsError('path_invalid', error.message)+ throw error+ }++ const key = `${uploadId}:${part.partNumber}`+ if (this.inFlight.has(key)) throw new GfsError('conflict', 'upload part is already in flight')+ // Register the abort controller before the reservation transaction. DELETE+ // can therefore fence and abort this request even in the small interval+ // between the DB reservation commit and the first body read.+ const controller = new AbortController()+ this.inFlight.set(key, { controller, sessionEpoch: session.sessionEpoch })+ let reserved: {+ session: UploadSessionRow+ existing: UploadPartRow | null+ stagingPath?: string+ leaseEpoch?: number+ }+ try {+ reserved = await this.deps.tx.transaction(async client => {+ const locked = await this.lockSession(client, uploadId, principal)+ if (this.pauseRequested.has(uploadId)) throw new GfsError('conflict', 'upload session is pausing')+ if (locked.state === 'paused') throw new GfsError('conflict', 'upload session is paused')+ if (locked.state !== 'initiated' && locked.state !== 'uploading') throw new GfsError('upload_aborted', 'upload session is not writable')+ await client.query(`SELECT pg_advisory_xact_lock(hashtext('gfs:upload:streams:' || $1)::bigint)`, [locked.drive])+ const existing = await client.query(+ `SELECT upload_id, part_number, offset_bytes, length_bytes, sha256, state, staging_path, lease_epoch+ FROM gfs_upload_parts WHERE upload_id = $1 AND part_number = $2 FOR UPDATE`,+ [uploadId, part.partNumber]+ )+ if (existing.rows[0] && String(existing.rows[0].state) === 'committed') return { session: locked, existing: rowToPart(existing.rows[0]) }+ if (existing.rows[0] && String(existing.rows[0].state) === 'reserved') {+ throw new GfsError('conflict', 'upload part is already in flight')+ }+ const activeGlobal = await client.query(+ `SELECT COUNT(*)::bigint AS count+ FROM gfs_upload_parts p+ JOIN gfs_upload_sessions s ON s.upload_id = p.upload_id+ WHERE s.drive = $1 AND p.state = 'reserved'`,+ [locked.drive]+ )+ if (Number(activeGlobal.rows[0]?.count ?? 0) >= this.deps.config.maxConcurrentPartStreamsGlobal) {+ throw new GfsError('quota_exceeded', 'global upload stream concurrency limit reached')+ }+ if (locked.activePartCount >= this.deps.config.maxConcurrentPartsPerSession) throw new GfsError('quota_exceeded', 'per-session part concurrency limit reached')+ const stagingPath = sessionPath(this.deps.storageMountPath, uploadId, part.partNumber, `.tmp-${randomUUID()}`)+ const previousLeaseEpoch = existing.rows[0] ? Number(existing.rows[0].lease_epoch) : locked.sessionEpoch+ const leaseEpoch = Math.max(locked.sessionEpoch + 1, previousLeaseEpoch + 1)+ if (existing.rows[0]) {+ await client.query(+ `UPDATE gfs_upload_parts+ SET offset_bytes = $3, length_bytes = $4, sha256 = $5, state = 'reserved',+ staging_path = $6, lease_epoch = $7, lease_started_at = now(), committed_at = NULL+ WHERE upload_id = $1 AND part_number = $2`,+ [uploadId, part.partNumber, part.offsetBytes, part.lengthBytes, expectedChecksum, stagingPath, leaseEpoch]+ )+ } else {+ await client.query(+ `INSERT INTO gfs_upload_parts+ (upload_id, part_number, offset_bytes, length_bytes, sha256, state, staging_path, lease_epoch, lease_started_at)+ VALUES ($1,$2,$3,$4,$5,'reserved',$6,$7,now())`,+ [uploadId, part.partNumber, part.offsetBytes, part.lengthBytes, expectedChecksum, stagingPath, leaseEpoch]+ )+ }+ await client.query(+ `UPDATE gfs_upload_sessions SET state = 'uploading', active_part_count = active_part_count + 1, updated_at = now()+ WHERE upload_id = $1`,+ [uploadId]+ )+ return { session: { ...locked, state: 'uploading', activePartCount: locked.activePartCount + 1 }, existing: null as UploadPartRow | null, stagingPath, leaseEpoch }+ })+ } catch (error) {+ this.inFlight.delete(key)+ throw error+ }++ if (reserved.existing) {+ this.inFlight.set(key, { controller, sessionEpoch: reserved.session.sessionEpoch })+ const replayTimer = setTimeout(+ () => controller.abort(new GfsError('precondition_failed', 'upload part replay timed out')),+ this.deps.config.partTimeoutMs+ )+ replayTimer.unref?.()+ try {+ const postReplay = await this.deps.db.query(+ `SELECT session_epoch, state FROM gfs_upload_sessions WHERE upload_id = $1 AND drive = $2 AND owner_subject = $3`,+ [uploadId, principal.drive, principal.ownerSubject]+ )+ const postReplayRow = postReplay.rows[0]+ if (+ this.canceledUploads.has(uploadId)+ || !postReplayRow+ || String(postReplayRow.state) === 'aborted'+ || Number(postReplayRow.session_epoch) !== reserved.session.sessionEpoch+ ) {+ controller.abort(new GfsError('upload_aborted', 'upload session changed while replay was starting'))+ }+ const observed = await readPartBody(req, reserved.existing.lengthBytes, this.deps.config.maxPartBytes, undefined, controller.signal)+ if (observed.sha256 !== reserved.existing.sha256 || observed.bytes !== reserved.existing.lengthBytes || expectedChecksum !== reserved.existing.sha256) {+ throw new GfsError('conflict', 'committed part checksum or length differs')+ }+ if (this.canceledUploads.has(uploadId)) throw new GfsError('upload_aborted', 'upload session was canceled')+ return { part: reserved.existing, session: toReceipt(reserved.session) }+ } finally {+ clearTimeout(replayTimer)+ this.inFlight.delete(key)+ }+ }+ const stagingPath = reserved.stagingPath!+ this.inFlight.set(key, { controller, sessionEpoch: reserved.session.sessionEpoch })+ const partTimer = setTimeout(+ () => controller.abort(new GfsError('precondition_failed', 'upload part timed out')),+ this.deps.config.partTimeoutMs+ )+ partTimer.unref?.()+ let finalPath: string | undefined+ try {+ const postReservation = await this.deps.db.query(+ `SELECT session_epoch, state FROM gfs_upload_sessions WHERE upload_id = $1 AND drive = $2 AND owner_subject = $3`,+ [uploadId, principal.drive, principal.ownerSubject]+ )+ const postReservationRow = postReservation.rows[0]+ if (+ this.canceledUploads.has(uploadId)+ || !postReservationRow+ || String(postReservationRow.state) === 'aborted'+ || Number(postReservationRow.session_epoch) !== reserved.session.sessionEpoch+ ) {+ controller.abort(new GfsError('upload_aborted', 'upload session changed while part was reserving'))+ }+ const observed = await readPartBody(req, part.lengthBytes, this.deps.config.maxPartBytes, stagingPath, controller.signal)+ if (observed.sha256 !== expectedChecksum) throw new GfsError('checksum_mismatch', 'part checksum does not match Upload-Checksum')+ finalPath = sessionPath(this.deps.storageMountPath, uploadId, part.partNumber, '')+ try {+ await stat(finalPath)+ throw new GfsError('conflict', 'committed part file already exists')+ } catch (error) {+ if (error instanceof GfsError) throw error+ if ((error as { code?: string }).code !== 'ENOENT') throw error+ }+ await rename(stagingPath, finalPath)+ const committed = await this.deps.tx.transaction(async client => {+ const locked = await this.lockSession(client, uploadId, principal)+ const rowResult = await client.query(+ `SELECT upload_id, part_number, offset_bytes, length_bytes, sha256, state, staging_path, lease_epoch+ FROM gfs_upload_parts WHERE upload_id = $1 AND part_number = $2 FOR UPDATE`,+ [uploadId, part.partNumber]+ )+ const row = rowResult.rows[0] ? rowToPart(rowResult.rows[0]) : null+ if (!row || row.state !== 'reserved' || row.leaseEpoch !== reserved.leaseEpoch || locked.sessionEpoch !== reserved.session.sessionEpoch || locked.state !== 'uploading') {+ throw new GfsError('upload_aborted', 'upload session changed while part was in flight')+ }+ await client.query(+ `UPDATE gfs_upload_parts SET state = 'committed', staging_path = $3, committed_at = now()+ WHERE upload_id = $1 AND part_number = $2`,+ [uploadId, part.partNumber, finalPath]+ )+ await client.query(+ `UPDATE gfs_upload_sessions+ SET committed_bytes = committed_bytes + $2,+ committed_part_count = committed_part_count + 1,+ active_part_count = GREATEST(active_part_count - 1, 0),+ contiguous_bytes = COALESCE((+ SELECT SUM(p.length_bytes) FROM gfs_upload_parts p+ WHERE p.upload_id = $1 AND p.state = 'committed'+ AND p.part_number < COALESCE((+ SELECT MIN(missing.part_number)+ FROM generate_series(0, $3 - 1) AS missing(part_number)+ WHERE NOT EXISTS (+ SELECT 1 FROM gfs_upload_parts present+ WHERE present.upload_id = $1 AND present.part_number = missing.part_number+ AND present.state = 'committed'+ )+ ), $3)+ ), 0),+ updated_at = now()+ WHERE upload_id = $1`,+ [uploadId, part.lengthBytes, reserved.session.partCount]+ )+ const refreshed = await this.lockSession(client, uploadId, principal)+ return { row: { ...row, state: 'committed', stagingPath: finalPath }, session: refreshed }+ })+ return { part: committed.row, session: toReceipt(committed.session) }+ } catch (error) {+ let reconciliation: { part: UploadPartRow; session: UploadSessionRow } | null | undefined+ if (finalPath) {+ try {+ reconciliation = await this.reconcileCommittedPart(+ uploadId,+ part,+ expectedChecksum,+ reserved.leaseEpoch!,+ finalPath,+ principal+ )+ } catch {+ // A failed read cannot prove whether COMMIT reached Postgres. Keep+ // the renamed file; the writer reconciler can remove it after a+ // definitive row/lease check. Deleting here could destroy a part+ // whose transaction actually committed.+ reconciliation = undefined+ }+ }+ if (reconciliation) return { part: reconciliation.part, session: toReceipt(reconciliation.session) }+ await removeIfPresent(stagingPath)+ if (finalPath && reconciliation !== undefined) await removeIfPresent(finalPath)+ await this.deps.tx.transaction(async client => {+ await client.query(+ `UPDATE gfs_upload_parts SET state = 'failed', committed_at = NULL+ WHERE upload_id = $1 AND part_number = $2 AND state = 'reserved'`,+ [uploadId, part.partNumber]+ )+ await client.query(+ `UPDATE gfs_upload_sessions SET active_part_count = GREATEST(active_part_count - 1, 0), updated_at = now()+ WHERE upload_id = $1`,+ [uploadId]+ )+ }).catch(() => undefined)+ throw error+ } finally {+ clearTimeout(partTimer)+ this.inFlight.delete(key)+ }+ }++ async pause(uploadId: string, principal: UploadPrincipal): Promise<UploadSessionReceipt> {+ requireEnabled(this.deps.config)+ const session = await this.loadOwned(uploadId, principal)+ await this.deps.authorize?.(principal, session.operation, session.operation === 'create' ? session.parentRid ?? undefined : session.resourceRid ?? undefined)+ if (session.state === 'paused') return toReceipt(session)+ if (session.state !== 'initiated' && session.state !== 'uploading') throw new GfsError('conflict', `cannot pause upload in ${session.state}`)+ if (this.pauseRequested.has(uploadId)) throw new GfsError('conflict', 'upload session is already pausing')+ this.pauseRequested.add(uploadId)+ try {+ const deadline = this.now() + this.deps.config.partTimeoutMs+ for (;;) {+ const latest = await this.loadOwned(uploadId, principal)+ if (!['initiated', 'uploading'].includes(latest.state)) {+ if (latest.state === 'paused') return toReceipt(latest)+ throw new GfsError('conflict', `upload pause was interrupted by ${latest.state}`)+ }+ const localInFlight = [...this.inFlight.keys()].some(key => key.startsWith(`${uploadId}:`))+ if (latest.activePartCount === 0 && !localInFlight) {+ const paused = await this.deps.tx.transaction(async client => {+ const locked = await this.lockSession(client, uploadId, principal)+ if (locked.state === 'paused') return locked+ if (!['initiated', 'uploading'].includes(locked.state)) {+ throw new GfsError('conflict', `cannot pause upload in ${locked.state}`)+ }+ if (locked.activePartCount !== 0) return locked+ await client.query(`UPDATE gfs_upload_sessions SET state = 'paused', updated_at = now() WHERE upload_id = $1 AND state IN ('initiated','uploading') AND active_part_count = 0`, [uploadId])+ return { ...locked, state: 'paused' }+ })+ if (paused.state === 'paused') return toReceipt(paused)+ }+ if (this.now() >= deadline) throw new GfsError('precondition_failed', 'upload pause timed out while draining in-flight parts')+ await new Promise<void>(resolve => setTimeout(resolve, Math.min(25, Math.max(1, deadline - this.now()))))+ }+ } finally {+ this.pauseRequested.delete(uploadId)+ }+ }++ async resume(uploadId: string, principal: UploadPrincipal): Promise<UploadSessionReceipt> {+ requireEnabled(this.deps.config)+ const session = await this.loadOwned(uploadId, principal)+ assertNotExpired(session, this.now())+ await this.deps.authorize?.(principal, session.operation, session.operation === 'create' ? session.parentRid ?? undefined : session.resourceRid ?? undefined)+ if (this.pauseRequested.has(uploadId)) throw new GfsError('conflict', 'upload session is pausing')+ if (session.state === 'uploading' || session.state === 'initiated') return toReceipt(session)+ if (session.state !== 'paused') throw new GfsError('conflict', `cannot resume upload in ${session.state}`)+ const resumed = await this.deps.tx.transaction(async client => {+ const locked = await this.lockSession(client, uploadId, principal)+ await client.query(`UPDATE gfs_upload_sessions SET state = 'uploading', updated_at = now() WHERE upload_id = $1 AND state = 'paused'`, [uploadId])+ return { ...locked, state: 'uploading' }+ })+ return toReceipt(resumed)+ }++ async cancel(uploadId: string, principal: UploadPrincipal): Promise<void> {+ requireEnabled(this.deps.config)+ const session = await this.loadOwned(uploadId, principal)+ await this.deps.authorize?.(principal, session.operation, session.operation === 'create' ? session.parentRid ?? undefined : session.resourceRid ?? undefined)+ if (session.state === 'completed') throw new GfsError('upload_completed', 'completed upload cannot be canceled')+ if (session.state === 'finalizing') throw new GfsError('upload_finalizing', 'upload finalization is in progress')+ if (session.state === 'aborted') return+ this.canceledUploads.add(uploadId)+ try {+ await this.deps.tx.transaction(async client => {+ const locked = await this.lockSession(client, uploadId, principal)+ if (locked.state === 'finalizing') throw new GfsError('upload_finalizing', 'upload finalization is in progress')+ if (locked.state === 'completed') throw new GfsError('upload_completed', 'completed upload cannot be canceled')+ // Once the row is fenced as aborted no new reservation can enter. Any+ // reserved rows are now owned by the cancel drain (or the startup+ // reconciler), so the durable counter must not keep DELETE waiting for+ // a process that may have crashed before registering an in-flight+ // controller.+ await client.query(`UPDATE gfs_upload_sessions SET state = 'aborted', session_epoch = session_epoch + 1, active_part_count = 0, updated_at = now() WHERE upload_id = $1`, [uploadId])+ await client.query(`UPDATE gfs_upload_parts SET state = 'failed' WHERE upload_id = $1 AND state = 'reserved'`, [uploadId])+ })+ } catch (error) {+ this.canceledUploads.delete(uploadId)+ throw error+ }+ for (const [key, flight] of this.inFlight) {+ if (key.startsWith(`${uploadId}:`)) flight.controller.abort(new GfsError('upload_aborted', 'upload canceled'))+ }+ await this.waitForActivePartsZero(uploadId, principal)+ await this.deps.tx.transaction(async client => {+ await client.query(`DELETE FROM gfs_upload_parts WHERE upload_id = $1`, [uploadId])+ })+ const cleaned = await removeUploadDirectory(this.deps.storageMountPath, uploadId)+ if (cleaned) {+ await this.deps.tx.transaction(async client => {+ await client.query(`DELETE FROM gfs_upload_parts WHERE upload_id = $1`, [uploadId])+ await client.query(`UPDATE gfs_upload_sessions SET cleanup_at = now(), updated_at = now() WHERE upload_id = $1 AND state = 'aborted'`, [uploadId])+ })+ }+ this.canceledUploads.delete(uploadId)+ }++ /**+ * Crash/expiry repair hook. It is deliberately writer-only: callers should+ * run it from the writer's periodic maintenance loop, never from a reader.+ */+ async reconcile(): Promise<UploadReconcileResult> {+ const uploadDirs = new Map<string, { purgeReceipt: boolean }>()+ let staleParts = 0+ let expiredSessions = 0+ await this.deps.tx.transaction(async client => {+ const stale = await client.query(+ `SELECT p.upload_id, p.part_number, p.staging_path+ FROM gfs_upload_parts p+ JOIN gfs_upload_sessions s ON s.upload_id = p.upload_id+ WHERE p.state = 'reserved' AND p.lease_started_at < now() - ($1::bigint * interval '1 millisecond')+ LIMIT 100+ FOR UPDATE SKIP LOCKED`,+ [this.deps.config.stalePartLeaseMs]+ )+ for (const row of stale.rows) {+ const uploadId = String(row.upload_id)+ const partNumber = Number(row.part_number)+ const safePath = await validatedTempPath(this.deps.storageMountPath, uploadId, partNumber, String(row.staging_path))+ if (!safePath) continue+ // The row lock fences a new lease for this part. Remove both the+ // recorded temporary file and a possible rename-before-commit orphan+ // while the lock is still held; deleting the common final path after+ // releasing the row would race a fresh reservation.+ if (!(await removeStrict(safePath) && await removeStrict(sessionPath(this.deps.storageMountPath, uploadId, partNumber, '')))) continue+ const failed = await client.query(+ `UPDATE gfs_upload_parts SET state = 'failed', committed_at = NULL+ WHERE upload_id = $1 AND part_number = $2 AND state = 'reserved'+ RETURNING staging_path`,+ [row.upload_id, row.part_number]+ )+ if (failed.rows.length === 1) {+ await client.query(+ `UPDATE gfs_upload_sessions SET active_part_count = GREATEST(active_part_count - 1, 0), updated_at = now()+ WHERE upload_id = $1`,+ [row.upload_id]+ )+ }+ if (failed.rows.length === 1) staleParts += 1+ }+ const expired = await client.query(+ `SELECT upload_id FROM gfs_upload_sessions+ WHERE state IN ('initiated','uploading','paused','finalizing') AND expires_at <= now()+ LIMIT 100+ FOR UPDATE SKIP LOCKED`,+ []+ )+ for (const row of expired.rows) {+ const uploadId = String(row.upload_id)+ uploadDirs.set(uploadId, { purgeReceipt: false })+ this.canceledUploads.add(uploadId)+ await client.query(+ `UPDATE gfs_upload_sessions SET state = 'expired', session_epoch = session_epoch + 1, active_part_count = 0, updated_at = now()+ WHERE upload_id = $1`,+ [uploadId]+ )+ await client.query(`DELETE FROM gfs_upload_parts WHERE upload_id = $1`, [uploadId])+ expiredSessions += 1+ }+ const committed = await client.query(+ `SELECT p.upload_id, p.part_number, p.offset_bytes, p.length_bytes, p.sha256, p.state, p.staging_path, p.lease_epoch+ FROM gfs_upload_parts p+ JOIN gfs_upload_sessions s ON s.upload_id = p.upload_id+ WHERE p.state = 'committed' AND s.state IN ('uploading','paused','finalizing')+ ORDER BY p.committed_at ASC NULLS FIRST+ LIMIT 100+ FOR UPDATE OF p SKIP LOCKED`,+ []+ )+ for (const row of committed.rows) {+ const part = rowToPart(row)+ if (await committedPartFilePresent(this.deps.storageMountPath, part)) continue+ await client.query(+ `UPDATE gfs_upload_sessions+ SET state = 'failed', failure_code = 'corrupt_part_missing', session_epoch = session_epoch + 1,+ active_part_count = 0, updated_at = now()+ WHERE upload_id = $1 AND state IN ('uploading','paused','finalizing')`,+ [part.uploadId]+ )+ uploadDirs.set(part.uploadId, { purgeReceipt: false })+ this.canceledUploads.add(part.uploadId)+ }+ const terminal = await client.query(+ `SELECT upload_id, state FROM gfs_upload_sessions+ WHERE state IN ('aborted', 'expired', 'failed', 'completed') AND cleanup_at IS NULL+ ORDER BY updated_at ASC+ LIMIT 100`,+ []+ )+ for (const row of terminal.rows) {+ const uploadId = String(row.upload_id)+ uploadDirs.set(uploadId, { purgeReceipt: false })+ this.canceledUploads.add(uploadId)+ }+ const purge = await client.query(+ `SELECT upload_id FROM gfs_upload_sessions+ WHERE state = 'completed' AND cleanup_at <= now() - ($1::bigint * interval '1 second')+ ORDER BY cleanup_at ASC+ LIMIT 100`,+ [this.deps.config.receiptRetentionSeconds]+ )+ for (const row of purge.rows) {+ const uploadId = String(row.upload_id)+ uploadDirs.set(uploadId, { purgeReceipt: true })+ }+ })+ for (const [uploadId, cleanup] of uploadDirs) {+ for (const [key, flight] of this.inFlight) {+ if (key.startsWith(`${uploadId}:`)) flight.controller.abort(new GfsError('upload_aborted', 'upload session expired or was canceled'))+ }+ this.inFlightFinalizers.get(uploadId)?.controller.abort(+ new GfsError('upload_aborted', 'upload session expired or was canceled')+ )+ const deadline = this.now() + this.deps.config.partTimeoutMs+ while (this.hasInFlight(uploadId) && this.now() < deadline) {+ await new Promise<void>(resolve => setTimeout(resolve, 25))+ }+ if (!this.hasInFlight(uploadId) && await removeUploadDirectory(this.deps.storageMountPath, uploadId)) {+ await this.deps.tx.transaction(async client => {+ await client.query(`DELETE FROM gfs_upload_parts WHERE upload_id = $1`, [uploadId])+ if (cleanup.purgeReceipt) {+ await client.query(`DELETE FROM gfs_upload_sessions WHERE upload_id = $1 AND state = 'completed'`, [uploadId])+ } else {+ await client.query(`UPDATE gfs_upload_sessions SET cleanup_at = now(), updated_at = now() WHERE upload_id = $1 AND state IN ('aborted','expired','failed','completed')`, [uploadId])+ }+ }).catch(() => undefined)+ this.canceledUploads.delete(uploadId)+ } else {+ // Rotate failed cleanup attempts so a permanently broken oldest batch+ // cannot starve newer terminal sessions. The terminal row remains+ // eligible (`cleanup_at IS NULL`) and will be retried next cycle.+ await this.deps.tx.transaction(async client => {+ await client.query(+ `UPDATE gfs_upload_sessions SET updated_at = now()+ WHERE upload_id = $1 AND state IN ('aborted','expired','failed','completed') AND cleanup_at IS NULL`,+ [uploadId]+ )+ }).catch(() => undefined)+ }+ }+ return { staleParts, expiredSessions }+ }++ async complete(uploadId: string, principal: UploadPrincipal, wholeSha256?: string | null): Promise<UploadSessionReceipt> {+ requireEnabled(this.deps.config)+ const session = await this.loadOwned(uploadId, principal)+ assertNotExpired(session, this.now())+ await this.deps.authorize?.(principal, session.operation, session.operation === 'create' ? session.parentRid ?? undefined : session.resourceRid ?? undefined)+ if (this.pauseRequested.has(uploadId)) throw new GfsError('conflict', 'upload session is pausing')+ if (session.state === 'completed') return toReceipt(session)+ if (session.state === 'finalizing') throw new GfsError('upload_finalizing', 'upload finalization is already in progress')+ if (!this.deps.finalize) throw new GfsError('not_mounted', 'upload finalization is not available yet')+ const expectedWhole = wholeSha256 === null || wholeSha256 === undefined+ ? session.wholeSha256+ : requireChecksum(wholeSha256, 'wholeSha256')+ const started: UploadSessionRow & { parts?: UploadPartRow[] } = await this.deps.tx.transaction(async client => {+ const locked = await this.lockSession(client, uploadId, principal)+ if (this.pauseRequested.has(uploadId)) throw new GfsError('conflict', 'upload session is pausing')+ if (locked.state === 'completed') return locked+ if (locked.state === 'finalizing') throw new GfsError('upload_finalizing', 'upload finalization is already in progress')+ if (!['initiated', 'uploading', 'paused'].includes(locked.state)) {+ if (locked.state === 'aborted') throw new GfsError('upload_aborted', 'upload session was canceled')+ if (locked.state === 'expired') throw new GfsError('upload_expired', 'upload session has expired')+ throw new GfsError('conflict', `cannot complete upload in ${locked.state}`)+ }+ if (locked.wholeSha256 && expectedWhole && locked.wholeSha256 !== expectedWhole) {+ throw new GfsError('conflict', 'whole-file checksum differs from the session checksum')+ }+ const parts = await client.query(`SELECT upload_id, part_number, offset_bytes, length_bytes, sha256, state, staging_path, lease_epoch FROM gfs_upload_parts WHERE upload_id = $1 AND state = 'committed' ORDER BY part_number`, [uploadId])+ const committedParts = parts.rows.map(rowToPart)+ if (committedParts.length !== locked.partCount) throw new GfsError('upload_incomplete', 'not all upload parts are committed')+ for (let index = 0; index < locked.partCount; index += 1) {+ const actual = committedParts[index]+ const expected = partGeometry({ expectedBytes: locked.expectedBytes, partBytes: locked.partBytes }, index)+ if (!actual || actual.partNumber !== expected.partNumber || actual.offsetBytes !== expected.offsetBytes || actual.lengthBytes !== expected.lengthBytes) {+ throw new GfsError('upload_incomplete', `upload part ${index} does not match the session geometry`)+ }+ }+ if (locked.activePartCount !== 0 || locked.committedPartCount !== locked.partCount || locked.committedBytes !== locked.expectedBytes) throw new GfsError('upload_incomplete', 'not all upload parts are committed')+ await client.query(`SELECT pg_advisory_xact_lock(hashtext('gfs:upload:finalizers')::bigint)`, [])+ const finalizing = await client.query(+ `SELECT COUNT(*)::bigint AS count FROM gfs_upload_sessions WHERE state = 'finalizing'`,+ []+ )+ if (Number(finalizing.rows[0]?.count ?? 0) >= this.deps.config.maxConcurrentFinalizations) {+ throw new GfsError('quota_exceeded', 'upload finalization concurrency limit reached')+ }+ if (!locked.wholeSha256 && expectedWhole) {+ await client.query(`UPDATE gfs_upload_sessions SET whole_sha256 = $2, updated_at = now() WHERE upload_id = $1`, [uploadId, expectedWhole])+ }+ await client.query(`UPDATE gfs_upload_sessions SET state = 'finalizing', updated_at = now() WHERE upload_id = $1 AND session_epoch = $2`, [uploadId, locked.sessionEpoch])+ return { ...locked, wholeSha256: expectedWhole ?? locked.wholeSha256, state: 'finalizing' as const, parts: committedParts }+ })+ if (started.state === 'completed') return toReceipt(started)+ if (!started.parts) throw new GfsError('internal', 'finalization parts were not loaded')+ let receipt: { resourceId: string; version: number; sha256: string }+ const finalizationAbort = new AbortController()+ const finalizationDeadlineAtMs = this.now() + this.deps.config.finalizeTimeoutMs+ const finalizationTimer = setTimeout(+ () => finalizationAbort.abort(new GfsError('precondition_failed', 'upload finalization timed out')),+ Math.max(1, this.deps.config.finalizeTimeoutMs)+ )+ finalizationTimer.unref?.()+ if (this.inFlightFinalizers.has(uploadId)) {+ clearTimeout(finalizationTimer)+ throw new GfsError('upload_finalizing', 'upload finalization is already in progress')+ }+ this.inFlightFinalizers.set(uploadId, { controller: finalizationAbort, sessionEpoch: started.sessionEpoch })+ try {+ receipt = await this.deps.finalize(started, started.parts, finalizationAbort.signal, finalizationDeadlineAtMs)+ } catch (error) {+ const failureCode = error instanceof GfsError ? error.code : 'finalization_failed'+ await this.deps.tx.transaction(async client => {+ const locked = await this.lockSession(client, uploadId, principal)+ if (locked.state === 'finalizing' && locked.sessionEpoch === started.sessionEpoch) {+ await client.query(+ `UPDATE gfs_upload_sessions+ SET state = 'failed', failure_code = $2, active_part_count = 0, updated_at = now()+ WHERE upload_id = $1`,+ [uploadId, failureCode]+ )+ }+ })+ // `deps.finalize` has already settled, so this controller no longer+ // represents active work. Release it before draining; otherwise+ // waitForQuiescence observes the current finalizer and waits on itself+ // until the part timeout, preventing the direct failure cleanup below.+ const current = this.inFlightFinalizers.get(uploadId)+ if (current?.controller === finalizationAbort) this.inFlightFinalizers.delete(uploadId)+ await this.waitForQuiescence(uploadId)+ if (!this.hasInFlight(uploadId) && await removeUploadDirectory(this.deps.storageMountPath, uploadId)) {+ await this.deps.tx.transaction(async client => {+ await client.query(`DELETE FROM gfs_upload_parts WHERE upload_id = $1`, [uploadId])+ await client.query(`UPDATE gfs_upload_sessions SET cleanup_at = now(), updated_at = now() WHERE upload_id = $1 AND state = 'failed'`, [uploadId])+ }).catch(() => undefined)+ }+ throw error+ } finally {+ clearTimeout(finalizationTimer)+ const current = this.inFlightFinalizers.get(uploadId)+ if (current?.controller === finalizationAbort) this.inFlightFinalizers.delete(uploadId)+ }+ let completed: UploadSessionRow+ try {+ completed = await this.deps.tx.transaction(async client => {+ const locked = await this.lockSession(client, uploadId, principal)+ if (locked.state === 'completed') return locked+ if (locked.state !== 'finalizing' || locked.sessionEpoch !== started.sessionEpoch) throw new GfsError('upload_aborted', 'upload session changed during finalization')+ await client.query(+ `UPDATE gfs_upload_sessions SET state = 'completed', result_resource_id = $2, result_version = $3, result_sha256 = $4, completed_at = now(), updated_at = now() WHERE upload_id = $1`,+ [uploadId, receipt.resourceId, receipt.version, receipt.sha256]+ )+ return { ...locked, state: 'completed', resultResourceId: receipt.resourceId, resultVersion: receipt.version, resultSha256: receipt.sha256 }+ })+ } catch (error) {+ if (error instanceof CommitOutcomeUnknownError || error instanceof RollbackOutcomeUnknownError) {+ const observed = await this.deps.db.query(+ `SELECT * FROM gfs_upload_sessions WHERE upload_id = $1 AND drive = $2 AND owner_subject = $3`,+ [uploadId, principal.drive, principal.ownerSubject]+ )+ const row = observed.rows[0] ? rowToSession(observed.rows[0]) : null+ if (+ row?.state === 'completed'+ && row.resultResourceId === receipt.resourceId+ && row.resultVersion === receipt.version+ && row.resultSha256 === receipt.sha256+ ) {+ completed = row+ } else {+ throw error+ }+ } else {+ throw error+ }+ }+ if (await removeUploadDirectory(this.deps.storageMountPath, uploadId)) {+ await this.deps.tx.transaction(async client => {+ await client.query(`DELETE FROM gfs_upload_parts WHERE upload_id = $1`, [uploadId])+ await client.query(`UPDATE gfs_upload_sessions SET cleanup_at = now(), updated_at = now() WHERE upload_id = $1 AND state = 'completed'`, [uploadId])+ }).catch(() => undefined)+ }+ return toReceipt(completed)+ }++ private async loadOwned(uploadId: string, principal: UploadPrincipal): Promise<UploadSessionRow> {+ requireUuid(uploadId, 'uploadId')+ const result = await this.deps.db.query(`SELECT * FROM gfs_upload_sessions WHERE upload_id = $1 AND drive = $2 AND owner_subject = $3`, [uploadId, principal.drive, principal.ownerSubject])+ if (!result.rows[0]) throw new GfsError('not_found', 'upload session not found')+ const session = rowToSession(result.rows[0])+ assertNotExpired(session, this.now())+ return session+ }++ private async waitForActivePartsZero(uploadId: string, principal: UploadPrincipal): Promise<void> {+ const deadline = this.now() + this.deps.config.partTimeoutMs+ for (;;) {+ const result = await this.deps.db.query(+ `SELECT * FROM gfs_upload_sessions WHERE upload_id = $1 AND drive = $2 AND owner_subject = $3`,+ [uploadId, principal.drive, principal.ownerSubject]+ )+ const row = result.rows[0] ? rowToSession(result.rows[0]) : null+ if (!row) throw new GfsError('not_found', 'upload session not found')+ const localInFlight = this.hasInFlight(uploadId)+ if (row.activePartCount === 0 && !localInFlight) return+ if (this.now() >= deadline) throw new GfsError('precondition_failed', 'upload cancellation timed out while draining in-flight parts')+ await new Promise<void>(resolve => setTimeout(resolve, Math.min(25, Math.max(1, deadline - this.now()))))+ }+ }++ private async waitForQuiescence(uploadId: string): Promise<void> {+ const deadline = this.now() + this.deps.config.partTimeoutMs+ while (this.hasInFlight(uploadId) && this.now() < deadline) {+ await new Promise<void>(resolve => setTimeout(resolve, 25))+ }+ }++ private async reconcileCommittedPart(+ uploadId: string,+ part: GfsUploadPartGeometry,+ checksum: string,+ leaseEpoch: number,+ finalPath: string,+ principal: UploadPrincipal+ ): Promise<{ part: UploadPartRow; session: UploadSessionRow } | null> {+ const result = await this.deps.db.query(+ `SELECT upload_id, part_number, offset_bytes, length_bytes, sha256, state, staging_path, lease_epoch+ FROM gfs_upload_parts WHERE upload_id = $1 AND part_number = $2`,+ [uploadId, part.partNumber]+ )+ if (!result.rows[0]) return null+ const committedPart = rowToPart(result.rows[0])+ if (+ committedPart.state !== 'committed'+ || committedPart.sha256 !== checksum+ || committedPart.offsetBytes !== part.offsetBytes+ || committedPart.lengthBytes !== part.lengthBytes+ || committedPart.leaseEpoch !== leaseEpoch+ || committedPart.stagingPath !== finalPath+ ) return null+ const sessionResult = await this.deps.db.query(+ `SELECT * FROM gfs_upload_sessions WHERE upload_id = $1 AND drive = $2 AND owner_subject = $3`,+ [uploadId, principal.drive, principal.ownerSubject]+ )+ if (!sessionResult.rows[0]) return null+ const session = rowToSession(sessionResult.rows[0])+ if (['aborted', 'expired', 'failed'].includes(session.state)) return null+ return { part: committedPart, session }+ }++ private async lockSession(client: TxClient, uploadId: string, principal: UploadPrincipal): Promise<UploadSessionRow> {+ const result = await client.query(`SELECT * FROM gfs_upload_sessions WHERE upload_id = $1 AND drive = $2 AND owner_subject = $3 FOR UPDATE`, [uploadId, principal.drive, principal.ownerSubject])+ if (!result.rows[0]) throw new GfsError('not_found', 'upload session not found')+ return rowToSession(result.rows[0])+ }+}++export const GFS_UPLOAD_REQUEST_BODY_LIMITS = {+ metadataBytes: GFS_UPLOAD_V2_METADATA_BODY_MAX_BYTES,+ completeBytes: GFS_UPLOAD_V2_COMPLETE_BODY_MAX_BYTES,+}++export function uploadCapabilities(enabled: boolean, config: GfsUploadConfig): {+ legacyBase64: { enabled: true; maxFileBytes: number }+ resumableV2: ReturnType<typeof disabledGfsUploadV2Capability> | {+ enabled: true+ maxFileBytes: number+ preferredChunkBytes: number+ maxChunkBytes: number+ maxConcurrentPartsPerSession: number+ fallbackConcurrency: number+ maxConcurrentPartStreamsGlobal: number+ instabilityFailureThreshold: number+ sessionTtlSeconds: number+ checksumAlgorithms: ['sha256']+ wholeFileChecksumRequired: boolean+ }+} {+ if (!enabled) return { legacyBase64: { enabled: true, maxFileBytes: 16 * 1024 * 1024 }, resumableV2: disabledGfsUploadV2Capability() }+ return {+ legacyBase64: { enabled: true, maxFileBytes: 16 * 1024 * 1024 },+ resumableV2: {+ enabled: true,+ maxFileBytes: config.productMaxFileBytes,+ preferredChunkBytes: config.preferredPartBytes,+ maxChunkBytes: config.maxPartBytes,+ maxConcurrentPartsPerSession: config.maxConcurrentPartsPerSession,+ fallbackConcurrency: config.fallbackConcurrency,+ maxConcurrentPartStreamsGlobal: config.maxConcurrentPartStreamsGlobal,+ instabilityFailureThreshold: config.instabilityFailureThreshold,+ sessionTtlSeconds: config.sessionTtlSeconds,+ checksumAlgorithms: ['sha256'],+ wholeFileChecksumRequired: false,+ },+ }+}diff --git a/host-context-controller/src/gfsConfig.test.ts b/host-context-controller/src/gfsConfig.test.tsindex eece76ca0..62ea23510 100644--- a/host-context-controller/src/gfsConfig.test.ts+++ b/host-context-controller/src/gfsConfig.test.ts@@ -9,6 +9,11 @@ afterEach(() => {delete process.env.GFS_SYNC_COPY_MAX_BYTESdelete process.env.GFS_SYNC_COPY_TIMEOUT_MSdelete process.env.GFS_MAX_WRITE_BODY_BYTES+ for (const key of Object.keys(process.env).filter(k =>+ k.startsWith('CONTEXT_MAPPER_GFSC_UPLOAD_')+ )) {+ delete process.env[key]+ }delete process.env.CONTEXT_MAPPER_GFSC_IMAGE_PULL_POLICYdelete process.env.CONTEXT_MAPPER_NODELOCAL_DNS_CIDR})@@ -30,6 +35,7 @@ describe('gfsDefaultFactoryConfig', () => {expect(c.syncCopyMaxBytes).toBeUndefined()expect(c.syncCopyTimeoutMs).toBeUndefined()expect(c.maxWriteBodyBytes).toBeUndefined()+ expect(c.uploadV2Enabled).toBeUndefined()})it('passes synchronous copy limits through verbatim, including explicit empty values', () => {@@ -45,6 +51,16 @@ describe('gfsDefaultFactoryConfig', () => {expect(c.maxWriteBodyBytes).toBe('25165824')})+ it('maps the private-infra upload prefix to writer-owned gfsc settings', () => {+ process.env.CONTEXT_MAPPER_GFSC_UPLOAD_V2_ENABLED = 'true'+ process.env.CONTEXT_MAPPER_GFSC_UPLOAD_PRODUCT_MAX_FILE_BYTES = '209715200'+ process.env.CONTEXT_MAPPER_GFSC_UPLOAD_PREFERRED_CHUNK_BYTES = '8388608'+ const c = gfsDefaultFactoryConfig()+ expect(c.uploadV2Enabled).toBe('true')+ expect(c.uploadProductMaxFileBytes).toBe('209715200')+ expect(c.uploadPreferredChunkBytes).toBe('8388608')+ })+it('fails loud on an invalid image pull policy (no silent default)', () => {process.env.CONTEXT_MAPPER_GFSC_IMAGE_PULL_POLICY = 'bogus'expect(() => gfsDefaultFactoryConfig()).toThrow(/Always\|IfNotPresent\|Never/)diff --git a/host-context-controller/src/gfsConfig.ts b/host-context-controller/src/gfsConfig.tsindex 8dbc9ca7a..f2e751cb8 100644--- a/host-context-controller/src/gfsConfig.ts+++ b/host-context-controller/src/gfsConfig.ts@@ -67,11 +67,33 @@ export function gfsDefaultFactoryConfig(): GfsFactoryConfig {syncCopyMaxObjects: process.env.GFS_SYNC_COPY_MAX_OBJECTS,syncCopyMaxBytes: process.env.GFS_SYNC_COPY_MAX_BYTES,syncCopyTimeoutMs: process.env.GFS_SYNC_COPY_TIMEOUT_MS,- // Largest mutation body gfsc accepts (bytes). Passed through to the gfsc pod so- // ops can raise the upload ceiling above gfsc's 16MiB default (base64 inflates a- // raw file ×1.34, so a 16MB file needs ~22.4MB here). Raise the client cap and- // gfsc memory (CONTEXT_MAPPER_GFSC_LIMIT_MEMORY) together.+ // Legacy JSON body cap. Upload v2 parts are raw streamed requests and remain+ // independently bounded by the strict CONTEXT_MAPPER_GFSC_UPLOAD_* settings.maxWriteBodyBytes: process.env.GFS_MAX_WRITE_BODY_BYTES,+ uploadV2Enabled: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_V2_ENABLED,+ uploadProtocolMaxFileBytes: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_PROTOCOL_MAX_FILE_BYTES,+ uploadProductMaxFileBytes: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_PRODUCT_MAX_FILE_BYTES,+ uploadMaxFileBytes: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_MAX_FILE_BYTES,+ uploadPreferredChunkBytes: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_PREFERRED_CHUNK_BYTES,+ uploadMaxChunkBytes: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_MAX_CHUNK_BYTES,+ uploadMinPartBytes: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_MIN_PART_BYTES,+ uploadMaxPartCount: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_MAX_PART_COUNT,+ uploadSessionTtlMs: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_SESSION_TTL_MS,+ uploadCompletedReceiptTtlMs: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_COMPLETED_RECEIPT_TTL_MS,+ uploadStalePartLeaseMs: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_STALE_PART_LEASE_MS,+ uploadMaxActivePerSubject: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_MAX_ACTIVE_PER_SUBJECT,+ uploadMaxActiveGlobal: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_MAX_ACTIVE_GLOBAL,+ uploadMaxConcurrentPartsPerSession:+ process.env.CONTEXT_MAPPER_GFSC_UPLOAD_MAX_CONCURRENT_PARTS_PER_SESSION,+ uploadMaxConcurrentPartStreamsGlobal:+ process.env.CONTEXT_MAPPER_GFSC_UPLOAD_MAX_CONCURRENT_PART_STREAMS_GLOBAL,+ uploadInstabilityFailureThreshold:+ process.env.CONTEXT_MAPPER_GFSC_UPLOAD_INSTABILITY_FAILURE_THRESHOLD,+ uploadMaxConcurrentFinalizations:+ process.env.CONTEXT_MAPPER_GFSC_UPLOAD_MAX_CONCURRENT_FINALIZATIONS,+ uploadMinFreeBytes: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_MIN_FREE_BYTES,+ uploadPartTimeoutMs: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_PART_TIMEOUT_MS,+ uploadFinalizeTimeoutMs: process.env.CONTEXT_MAPPER_GFSC_UPLOAD_FINALIZE_TIMEOUT_MS,nodeLocalDnsCidr: parseNodeLocalDnsCidr(env('CONTEXT_MAPPER_NODELOCAL_DNS_CIDR', '')),}}diff --git a/host-context-controller/src/k8s/gfsFactory.test.ts b/host-context-controller/src/k8s/gfsFactory.test.tsindex f9d3306dd..8068a7675 100644--- a/host-context-controller/src/k8s/gfsFactory.test.ts+++ b/host-context-controller/src/k8s/gfsFactory.test.ts@@ -151,6 +151,7 @@ describe('gfsFactory writer Deployment', () => {expect(byName('GFS_SYNC_COPY_MAX_BYTES')).toBeUndefined()expect(byName('GFS_SYNC_COPY_TIMEOUT_MS')).toBeUndefined()expect(byName('GFS_MAX_WRITE_BODY_BYTES')).toBeUndefined()+ expect(byName('GFS_UPLOAD_V2_ENABLED')).toBeUndefined()})it('passes configured synchronous copy limits verbatim to writer and reader', () => {@@ -160,6 +161,10 @@ describe('gfsFactory writer Deployment', () => {syncCopyMaxBytes: '',syncCopyTimeoutMs: '45000',maxWriteBodyBytes: '25165824',+ uploadV2Enabled: 'true',+ uploadProductMaxFileBytes: '209715200',+ uploadPreferredChunkBytes: '8388608',+ uploadMaxChunkBytes: '16777216',}for (const role of ['writer', 'reader'] as const) {@@ -172,6 +177,11 @@ describe('gfsFactory writer Deployment', () => {// The 16MB upload cap depends on this reaching gfsc; a dropped passthrough// leaves gfsc on its 16MiB default and 413s a 16MB file.expect(byName('GFS_MAX_WRITE_BODY_BYTES')?.value).toBe('25165824')+ expect(byName('GFS_UPLOAD_PRODUCT_MAX_FILE_BYTES')?.value).toBe('209715200')+ expect(byName('GFS_UPLOAD_PREFERRED_CHUNK_BYTES')?.value).toBe('8388608')+ expect(byName('GFS_UPLOAD_MAX_CHUNK_BYTES')?.value).toBe('16777216')+ if (role === 'writer') expect(byName('GFS_UPLOAD_V2_ENABLED')?.value).toBe('true')+ else expect(byName('GFS_UPLOAD_V2_ENABLED')).toBeUndefined()}})diff --git a/host-context-controller/src/k8s/gfsFactory.ts b/host-context-controller/src/k8s/gfsFactory.tsindex 431f90594..be06825cf 100644--- a/host-context-controller/src/k8s/gfsFactory.ts+++ b/host-context-controller/src/k8s/gfsFactory.ts@@ -97,6 +97,27 @@ export interface GfsFactoryConfig {syncCopyTimeoutMs?: string/** Optional largest mutation body gfsc accepts (bytes), passed through to gfsc. */maxWriteBodyBytes?: string+ /** Strict upload-v2 settings are operator-owned and passed only to gfsc. */+ uploadV2Enabled?: string+ uploadProtocolMaxFileBytes?: string+ uploadProductMaxFileBytes?: string+ uploadMaxFileBytes?: string+ uploadPreferredChunkBytes?: string+ uploadMaxChunkBytes?: string+ uploadMinPartBytes?: string+ uploadMaxPartCount?: string+ uploadSessionTtlMs?: string+ uploadCompletedReceiptTtlMs?: string+ uploadStalePartLeaseMs?: string+ uploadMaxActivePerSubject?: string+ uploadMaxActiveGlobal?: string+ uploadMaxConcurrentPartsPerSession?: string+ uploadMaxConcurrentPartStreamsGlobal?: string+ uploadInstabilityFailureThreshold?: string+ uploadMaxConcurrentFinalizations?: string+ uploadMinFreeBytes?: string+ uploadPartTimeoutMs?: string+ uploadFinalizeTimeoutMs?: string/** Optional kube-dns Service ClusterIP /32 for GKE NodeLocal DNS + Calico. */nodeLocalDnsCidr?: string}@@ -265,6 +286,25 @@ function gfscEnv(config: GfsFactoryConfig, role: GfscRole): k8s.V1EnvVar[] {['GFS_SYNC_COPY_MAX_BYTES', config.syncCopyMaxBytes],['GFS_SYNC_COPY_TIMEOUT_MS', config.syncCopyTimeoutMs],['GFS_MAX_WRITE_BODY_BYTES', config.maxWriteBodyBytes],+ ['GFS_UPLOAD_PROTOCOL_MAX_FILE_BYTES', config.uploadProtocolMaxFileBytes],+ ['GFS_UPLOAD_PRODUCT_MAX_FILE_BYTES', config.uploadProductMaxFileBytes],+ ['GFS_UPLOAD_MAX_FILE_BYTES', config.uploadMaxFileBytes],+ ['GFS_UPLOAD_PREFERRED_CHUNK_BYTES', config.uploadPreferredChunkBytes],+ ['GFS_UPLOAD_MAX_CHUNK_BYTES', config.uploadMaxChunkBytes],+ ['GFS_UPLOAD_MIN_PART_BYTES', config.uploadMinPartBytes],+ ['GFS_UPLOAD_MAX_PART_COUNT', config.uploadMaxPartCount],+ ['GFS_UPLOAD_SESSION_TTL_MS', config.uploadSessionTtlMs],+ ['GFS_UPLOAD_COMPLETED_RECEIPT_TTL_MS', config.uploadCompletedReceiptTtlMs],+ ['GFS_UPLOAD_STALE_PART_LEASE_MS', config.uploadStalePartLeaseMs],+ ['GFS_UPLOAD_MAX_ACTIVE_PER_SUBJECT', config.uploadMaxActivePerSubject],+ ['GFS_UPLOAD_MAX_ACTIVE_GLOBAL', config.uploadMaxActiveGlobal],+ ['GFS_UPLOAD_MAX_CONCURRENT_PARTS_PER_SESSION', config.uploadMaxConcurrentPartsPerSession],+ ['GFS_UPLOAD_MAX_CONCURRENT_PART_STREAMS_GLOBAL', config.uploadMaxConcurrentPartStreamsGlobal],+ ['GFS_UPLOAD_INSTABILITY_FAILURE_THRESHOLD', config.uploadInstabilityFailureThreshold],+ ['GFS_UPLOAD_MAX_CONCURRENT_FINALIZATIONS', config.uploadMaxConcurrentFinalizations],+ ['GFS_UPLOAD_MIN_FREE_BYTES', config.uploadMinFreeBytes],+ ['GFS_UPLOAD_PART_TIMEOUT_MS', config.uploadPartTimeoutMs],+ ['GFS_UPLOAD_FINALIZE_TIMEOUT_MS', config.uploadFinalizeTimeoutMs],]const passthroughEnv = passthroughEnvEntries.flatMap(([name, value]): k8s.V1EnvVar[] =>value === undefined ? [] : [{ name, value }]@@ -276,6 +316,9 @@ function gfscEnv(config: GfsFactoryConfig, role: GfscRole): k8s.V1EnvVar[] {{ name: 'GFS_STORAGE_ROLE', value: role },{ name: 'GFS_DRIVE_NAME', value: config.driveName },{ name: 'GFS_TOKEN_AUDIENCE', value: config.tokenAudience },+ ...(role === 'writer' && config.uploadV2Enabled !== undefined+ ? [{ name: 'GFS_UPLOAD_V2_ENABLED', value: config.uploadV2Enabled }]+ : []),{name: 'GFS_JWT_PUBLIC_KEY',valueFrom: {diff --git a/scripts/e2e/gfs-upload-v2-gate.sh b/scripts/e2e/gfs-upload-v2-gate.shnew file mode 100755index 000000000..7665f9ac4--- /dev/null+++ b/scripts/e2e/gfs-upload-v2-gate.sh@@ -0,0 +1,55 @@+#!/usr/bin/env bash+set -euo pipefail++# GFS Upload v2 gate. This wrapper is intentionally opt-in: the large-upload+# journeys must run only against a branch-owned, non-production dev host with+# profile-scoped random URLs. It never treats a shell/API run as UI evidence.++repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+cd "$repo_root"++: "${E2E_K8S_CONTEXT:?Set E2E_K8S_CONTEXT to the owned non-production context}"+: "${CONTROL_UI_BASE_URL:?Set CONTROL_UI_BASE_URL to the profile-owned random URL}"+: "${EXTERNAL_REST_API_BASE_URL:?Set EXTERNAL_REST_API_BASE_URL to the profile-owned random URL}"++case "$E2E_K8S_CONTEXT" in+ *prod*|*production*)+ echo "Refusing GFS Upload v2 E2E against production context: $E2E_K8S_CONTEXT" >&2+ exit 2+ ;;+esac++python3 tools/e2e_static_audit.py \+ control-ui/e2e/gfs-upload-v2.spec.ts \+ desktop-app/test/e2e-playwright/gfs-upload-v2.test.ts++run_ui="${GFS_UPLOAD_V2_RUN_UI:-0}"+run_desktop="${GFS_UPLOAD_V2_RUN_DESKTOP:-0}"+run_integration="${GFS_UPLOAD_V2_RUN_INTEGRATION:-0}"++if [[ "$run_ui" == "1" ]]; then+ GFS_UPLOAD_V2_E2E=1 npm --prefix control-ui exec playwright test \+ --config=playwright.config.ts --project=large-upload e2e/gfs-upload-v2.spec.ts+fi++if [[ "$run_desktop" == "1" ]]; then+ GFS_UPLOAD_V2_E2E=1 npm --prefix desktop-app exec playwright test \+ --config=test/e2e-playwright/playwright.config.ts \+ --project=packaged-gfs-upload-v2 test/e2e-playwright/gfs-upload-v2.test.ts+fi++if [[ "$run_integration" == "1" ]]; then+ : "${CONTROL_API_REAL_PG_ADMIN_URL:?Set CONTROL_API_REAL_PG_ADMIN_URL for the real-Postgres integration lane}"+ npm --prefix control-api test -- --run \+ test/gfsUploadSession.realPostgres.integration.test.ts+ # Runtime restart/chaos/load is caller-owned because it must be bound to the+ # exact branch profile and Cloudflare-backed dev hostname. Do not silently+ # substitute an older RED gate or report integration-only evidence as T2.+ : "${GFS_UPLOAD_V2_RUNTIME_GATE_COMMAND:?Set GFS_UPLOAD_V2_RUNTIME_GATE_COMMAND to the exact-head restart/chaos/load command}"+ bash -lc "$GFS_UPLOAD_V2_RUNTIME_GATE_COMMAND"+fi++if [[ "$run_ui$run_desktop$run_integration" == "000" ]]; then+ echo "No runtime lane selected. Static audit passed; set one or more GFS_UPLOAD_V2_RUN_* flags." >&2+ exit 2+fidiff --git a/tests/e2e/gfsUploadV2Fixtures.ts b/tests/e2e/gfsUploadV2Fixtures.tsnew file mode 100644index 000000000..170cd6f99--- /dev/null+++ b/tests/e2e/gfsUploadV2Fixtures.ts@@ -0,0 +1,55 @@+import { createHash } from 'node:crypto'+import { createReadStream } from 'node:fs'+import { mkdtemp, rm, truncate, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'++export const GFS_UPLOAD_V2_MAX_BYTES = 209_715_200+export const GFS_UPLOAD_V2_BOUNDARIES = [+ GFS_UPLOAD_V2_MAX_BYTES - 1,+ GFS_UPLOAD_V2_MAX_BYTES,+] as const++export interface DiskUploadFixture {+ directory: string+ filePath: string+ fileName: string+ byteLength: number+ sha256: string+}++/**+ * Creates a deterministic sparse, zero-filled fixture on disk. Playwright+ * receives only the path, never a 200 MiB Buffer or ArrayBuffer.+ */+export async function createDiskUploadFixture(+ byteLength: number,+ extension = '.parquet',+ label = 'gfs-v2'+): Promise<DiskUploadFixture> {+ if (!Number.isSafeInteger(byteLength) || byteLength < 0 || byteLength > GFS_UPLOAD_V2_MAX_BYTES) {+ throw new Error(`invalid GFS v2 fixture size: ${byteLength}`)+ }+ const directory = await mkdtemp(path.join(os.tmpdir(), 'evenfire-gfs-upload-v2-'))+ const fileName = `${label}-${byteLength}${extension}`+ const filePath = path.join(directory, fileName)+ await writeFile(filePath, Buffer.alloc(0))+ await truncate(filePath, byteLength)+ return {+ directory,+ filePath,+ fileName,+ byteLength,+ sha256: await sha256File(filePath),+ }+}++export async function sha256File(filePath: string): Promise<string> {+ const hash = createHash('sha256')+ for await (const chunk of createReadStream(filePath)) hash.update(chunk as Buffer)+ return hash.digest('hex')+}++export async function removeDiskUploadFixture(fixture: DiskUploadFixture): Promise<void> {+ await rm(fixture.directory, { recursive: true, force: true })+}diff --git a/tools/e2e_static_audit.py b/tools/e2e_static_audit.pynew file mode 100755index 000000000..74210a54f--- /dev/null+++ b/tools/e2e_static_audit.py@@ -0,0 +1,66 @@+#!/usr/bin/env python3+"""Small, dependency-free E2E Guardian gate for changed Playwright specs.++This is intentionally a conservative source audit. It does not replace a real+browser run; it prevents common shortcuts from entering the large-upload+project where a green test must represent a user journey.+"""++from __future__ import annotations++import argparse+import re+import sys+from pathlib import Path+++RULES: tuple[tuple[str, re.Pattern[str]], ...] = (+ ("fixed sleep", re.compile(r"\b(?:waitForTimeout|sleep\s*\()")),+ ("browser storage/session mutation", re.compile(r"\b(?:localStorage|sessionStorage|storageState)\b")),+ ("fragile positional selector", re.compile(r"\.(?:nth|first|last)\s*\(")),+ ("fragile text/class CSS selector", re.compile(r"locator\(\s*['\"](?:[^'\"]*has-text|[^'\"]*class=)")),+ ("core-route success mock", re.compile(r"(?:route|fulfill)\s*\([^\n]*(?:uploads|gfs|complete|parts)[^\n]*(?:status\s*:\s*2|status\s*:\s*20)")),+)+++def audit_file(path: Path) -> list[str]:+ text = path.read_text(encoding="utf-8")+ findings: list[str] = []+ for label, pattern in RULES:+ for match in pattern.finditer(text):+ line = text.count("\n", 0, match.start()) + 1+ findings.append(f"{path}:{line}: {label}")++ if "waitForResponse" not in text and "waitForRequest" not in text:+ findings.append(f"{path}: missing critical network-response/request wait")++ # Direct navigation is allowed only in an explicitly negative terminal+ # guard. Happy-path large-upload journeys must enter through UI actions.+ for match in re.finditer(r"\bpage\.goto\s*\(", text):+ before = text[max(0, match.start() - 240) : match.start()]+ if not re.search(r"terminal|deep.?link|foreign|missing|guard", before, re.IGNORECASE):+ line = text.count("\n", 0, match.start()) + 1+ findings.append(f"{path}:{line}: direct page.goto outside an explicit negative guard")+ return findings+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("paths", nargs="+", type=Path)+ args = parser.parse_args()+ findings: list[str] = []+ for path in args.paths:+ if not path.is_file():+ findings.append(f"{path}: file does not exist")+ continue+ findings.extend(audit_file(path))+ if findings:+ print("E2E Guardian static audit: FAIL", file=sys.stderr)+ print("\n".join(findings), file=sys.stderr)+ return 1+ print(f"E2E Guardian static audit: PASS ({len(args.paths)} files)")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())