From c905282eaeb1a73dab1dd868795b4b235a2e228e Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Mon, 23 Nov 2026 15:21:29 +0000 Subject: [PATCH 1/8] Reapply "fix(storage): sign uploads for server-allocated object keys (#2014)" (#2064) This reverts commit f2e1ca9b1eea00678242974d2a9e991ce6ec1f64. --- .../graphile-presigned-url-plugin/README.md | 22 ++- .../__tests__/custom-key-upload.test.ts | 41 +++-- .../__tests__/custom-key.test.ts | 4 +- .../__tests__/dedup-liveness.test.ts | 20 ++- .../__tests__/storage-file-recorder.test.ts | 24 ++- .../src/custom-key.ts | 3 +- .../src/file-ref-urls.ts | 8 +- .../src/plugin.ts | 151 ++++-------------- .../src/storage-file-recorder.ts | 23 ++- .../src/types.ts | 4 +- .../seed/db-scope-storage/schema.sql | 9 +- .../seed/shared-db-scope-storage/schema.sql | 9 +- .../seed/simple-seed-storage/schema.sql | 10 +- .../db-scope-upload.integration.test.ts | 2 +- .../download-url-status.integration.test.ts | 8 +- .../file-ref-urls.integration.test.ts | 40 ++--- .../__tests__/upload.integration.test.ts | 43 ++++- 17 files changed, 223 insertions(+), 198 deletions(-) diff --git a/graphile/graphile-presigned-url-plugin/README.md b/graphile/graphile-presigned-url-plugin/README.md index ce45fabfeb..bba8ebc5ba 100644 --- a/graphile/graphile-presigned-url-plugin/README.md +++ b/graphile/graphile-presigned-url-plugin/README.md @@ -19,7 +19,7 @@ Presigned URL upload plugin for PostGraphile v5. - Per-files-table `upload` mutations — generate presigned PUT URLs for direct client-to-S3 upload; use `createStorageClient` from `@constructive-io/graphql-query` with `storageTransport` from `@constructive-io/upload-client` for client orchestration - `downloadUrl` computed field — presigned GET URLs for private files, public URLs for public files - `maxBulkFiles` field on bucket types — the most files one bulk-upload call accepts (`storage_module.max_bulk_files`, default 100) -- Content-hash based S3 keys (SHA-256) with automatic deduplication — only against rows whose bytes are in S3, so a retry of a never-completed upload gets a fresh URL +- Independent server-allocated object keys (`originals/`), with SHA-256 integrity and deduplication of confirmed content in the same logical slot - Per-bucket MIME type and file size validation ## Usage @@ -44,3 +44,23 @@ const preset = { ], }; ``` + +## Upload identity and retries + +The optional upload input `key` names a **logical slot** (`files.logical_key`); +without it the logical slot is the SHA-256 content hash. It never chooses an S3 +location. The generated recorder allocates a fresh `originals/` for each +new request and returns it as `files.key`. The response `key`, projection `key`, +PUT signature and downloads all use that physical key. + +A confirmed (`uploaded`/`processed`) row with the same bucket, logical key and +checksum is reused, without issuing a PUT URL. Pending or rejected attempts do +not deduplicate: a new request gets a new object and confirm job, and leaves the +older attempt to its existing lifecycle. Repeating a PUT with the same URL is a +retry of that same object; checksum and upload-id must still match its signature. + +This requires the matching constructive-db storage generator with `logical_key` +and a server-allocated recorder result. Deploy the generator and pinned package +together; there is no fallback to signing the caller's logical key. Successful +logical replacement retains the existing database authorization policy; UUIDs +are object identities, not access control. diff --git a/graphile/graphile-presigned-url-plugin/__tests__/custom-key-upload.test.ts b/graphile/graphile-presigned-url-plugin/__tests__/custom-key-upload.test.ts index 1d37788372..ebc02f6b41 100644 --- a/graphile/graphile-presigned-url-plugin/__tests__/custom-key-upload.test.ts +++ b/graphile/graphile-presigned-url-plugin/__tests__/custom-key-upload.test.ts @@ -10,6 +10,7 @@ */ import { processSingleFile } from '../src/plugin'; +import { generatePresignedPutUrl } from '../src/s3-signer'; import type { BucketConfig, PresignedUrlPluginOptions, S3Config, StorageModuleConfig } from '../src/types'; jest.mock('../src/s3-signer', () => ({ @@ -21,6 +22,8 @@ const BUCKET_ID = '33333333-3333-3333-3333-333333333333'; const OLD_FILE_ID = '44444444-4444-4444-4444-444444444444'; const NEW_FILE_ID = '55555555-5555-5555-5555-555555555555'; const KEY = 'index.html'; +const OLD_KEY = `originals/${OLD_FILE_ID}`; +const NEW_KEY = `originals/${NEW_FILE_ID}`; function storageConfig(overrides: Partial = {}): StorageModuleConfig { return { @@ -60,15 +63,15 @@ function fakeTx(existingHash: string, deletable = true, existingStatus = 'upload const txClient = { async query(opts: { text: string; values: unknown[] }) { queries.push(opts); - if (/^SELECT id, status/.test(opts.text)) { + if (/^SELECT id, (?:key|status)/.test(opts.text) && !/record_file\(/.test(opts.text)) { // The probe is by (key, bucket, hash): a row carrying other bytes is not seen. const probedHash = opts.values[2]; - return { rows: probedHash === existingHash ? [{ id: OLD_FILE_ID, status: existingStatus }] : [] }; + return { rows: probedHash === existingHash && ['uploaded', 'processed'].includes(existingStatus) ? [{ id: OLD_FILE_ID, key: OLD_KEY, status: existingStatus }] : [] }; } if (/^DELETE FROM storage_public\.app_files/.test(opts.text)) { return { rows: deletable ? [{ id: OLD_FILE_ID }] : [] }; } - if (/record_file\(/.test(opts.text)) return { rows: [{ id: NEW_FILE_ID }] }; + if (/record_file\(/.test(opts.text)) return { rows: [{ id: NEW_FILE_ID, key: NEW_KEY }] }; throw new Error(`unexpected query: ${opts.text}`); }, }; @@ -96,7 +99,7 @@ describe('custom-key upload of changed bytes', () => { expect(result).toMatchObject({ fileId: NEW_FILE_ID, - key: KEY, + key: NEW_KEY, deduplicated: false, uploadUrl: 'https://s3.example.com/put', }); @@ -116,23 +119,29 @@ describe('custom-key upload of changed bytes', () => { const result = await upload(storageConfig(), txClient); expect(result).toMatchObject({ fileId: NEW_FILE_ID, deduplicated: false }); - expect(queries.map((q) => q.text.trim().split(/\s+/)[0])).toEqual(['SELECT', 'DELETE', 'SELECT']); - expect(queries[1].values).toEqual([OLD_FILE_ID]); + expect(queries.map((q) => q.text.trim().split(/\s+/)[0])).toEqual(['SELECT', 'SELECT']); + expect(result.key).toBe(NEW_KEY); + expect(queries.some((q) => /^DELETE/.test(q.text))).toBe(false); }); - it('refuses to restart a row the caller cannot delete', async () => { + it('retries independently even when the caller cannot delete an earlier attempt', async () => { const { txClient, queries } = fakeTx('b'.repeat(64), false, 'requested'); - - const refused = upload(storageConfig(), txClient); - await expect(refused).rejects.toThrow( - `FILE_NOT_REPLACEABLE: file ${OLD_FILE_ID} at key ${KEY}`, - ); - // A named error carries its code, so the server passes it through - // instead of masking it as INTERNAL_SERVER_ERROR. - await expect(refused).rejects.toMatchObject({ code: 'FILE_NOT_REPLACEABLE', errorClass: 'public' }); - expect(queries.some((q) => /record_file\(/.test(q.text))).toBe(false); + await expect(upload(storageConfig(), txClient)).resolves.toMatchObject({ key: NEW_KEY, deduplicated: false }); + expect(queries.some((q) => /^DELETE/.test(q.text))).toBe(false); }); + it.each(['a'.repeat(64), OLD_KEY, `derived/${OLD_KEY}/thumb.webp`])( + 'never signs the attacker-selected logical key %s', async (logicalKey) => { + const { txClient } = fakeTx('a'.repeat(64)); + const result = await processSingleFile(options, txClient, storageConfig(), 'db', bucket, s3, { + contentHash: 'b'.repeat(64), contentType: 'text/html', size: 16, key: logicalKey, + }); + expect(result.key).toBe(NEW_KEY); + expect(result.file.key).toBe(NEW_KEY); + expect(generatePresignedPutUrl).toHaveBeenLastCalledWith(s3, NEW_KEY, 'text/html', 16, 900, 'b'.repeat(64), NEW_FILE_ID); + }, + ); + it('deduplicates identical bytes at the key without touching the row', async () => { const { txClient, queries } = fakeTx('b'.repeat(64)); diff --git a/graphile/graphile-presigned-url-plugin/__tests__/custom-key.test.ts b/graphile/graphile-presigned-url-plugin/__tests__/custom-key.test.ts index f1bbbc56ed..3ecdebab43 100644 --- a/graphile/graphile-presigned-url-plugin/__tests__/custom-key.test.ts +++ b/graphile/graphile-presigned-url-plugin/__tests__/custom-key.test.ts @@ -70,8 +70,8 @@ describe('validateCustomKey', () => { expect(validateCustomKey(key)).toMatch(/^INVALID_KEY:/); }); - // A file's rendered versions live under `.versions/` and are served to - // whoever can read that file, so no file of its own may be stored there. + // The legacy `.versions/` suffix remains reserved in logical-key syntax; + // physical storage isolation no longer depends on this validation. it.each(['photo.png.versions/secret.webp', 'a/b.versions/c/d.txt'])('rejects %s: the versions prefix is reserved', (key) => { expect(validateCustomKey(key)).toMatch(/reserved/); }); diff --git a/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts b/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts index 619ebda899..0611f9d4be 100644 --- a/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts +++ b/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts @@ -82,14 +82,15 @@ const options: PresignedUrlPluginOptions = { credentials: { accessKeyId: 'test', * resolver probes by key (the custom key, or the hash's own key), so the row is * found only when the probed key is its own. */ -function fakeTx(rowKey: string, status: string) { +function fakeTx(rowKey: string, status: string, retired = false) { const queries: Array<{ text: string; values: unknown[] }> = []; const txClient = { async query(opts: { text: string; values: unknown[] }) { queries.push(opts); - if (/record_file\(/.test(opts.text)) return { rows: [{ id: NEW_FILE_ID }] }; + if (/record_file\(/.test(opts.text)) return { rows: [{ id: NEW_FILE_ID, key: `originals/${NEW_FILE_ID}` }] }; if (/^SELECT id/.test(opts.text)) { - return { rows: opts.values[0] === rowKey ? [{ id: OLD_FILE_ID, status }] : [] }; + if (retired && /AND NOT logical_key_retired/.test(opts.text)) return { rows: [] }; + return { rows: opts.values[0] === rowKey && ['uploaded', 'processed'].includes(status) ? [{ id: OLD_FILE_ID, key: `originals/${OLD_FILE_ID}` }] : [] }; } if (/^DELETE FROM storage_public\.app_files/.test(opts.text)) return { rows: [{ id: OLD_FILE_ID }] }; throw new Error(`unexpected query: ${opts.text}`); @@ -127,7 +128,7 @@ describe.each([ expect(result.file).not.toHaveProperty('url'); expect(heads(s3)).toEqual([]); const del = queries.find((q) => /^DELETE/.test(q.text)); - expect(del?.values).toEqual([OLD_FILE_ID]); + expect(del).toBeUndefined(); }, ); @@ -143,6 +144,13 @@ describe.each([ expect(queries).toHaveLength(1); expect(queries[0].text).toContain('status'); }); + + it('does not deduplicate against a retired but still readable row', async () => { + const { txClient } = fakeTx(rowKey, 'uploaded', true); + const result = await upload(txClient, fakeS3(), customKey); + + expect(result).toMatchObject({ fileId: NEW_FILE_ID, deduplicated: false }); + }); }); describe('content-addressed upload whose hash a custom-key row carries', () => { @@ -155,8 +163,8 @@ describe('content-addressed upload whose hash a custom-key row carries', () => { const result = await upload(txClient, s3); - expect(result).toMatchObject({ fileId: NEW_FILE_ID, deduplicated: false, key: HASH }); - expect(queries[0].values).toEqual([HASH, BUCKET_ID]); + expect(result).toMatchObject({ fileId: NEW_FILE_ID, deduplicated: false, key: `originals/${NEW_FILE_ID}` }); + expect(queries[0].values).toEqual([HASH, BUCKET_ID, HASH]); expect(queries.some((q) => /^DELETE/.test(q.text))).toBe(false); }); }); diff --git a/graphile/graphile-presigned-url-plugin/__tests__/storage-file-recorder.test.ts b/graphile/graphile-presigned-url-plugin/__tests__/storage-file-recorder.test.ts index 54206da86a..de9e43a6c2 100644 --- a/graphile/graphile-presigned-url-plugin/__tests__/storage-file-recorder.test.ts +++ b/graphile/graphile-presigned-url-plugin/__tests__/storage-file-recorder.test.ts @@ -50,16 +50,14 @@ function input() { describe('recordManagedFile', () => { it('calls the generated recorder with only base object facts', async () => { const query = jest.fn().mockResolvedValue({ - rows: [{ id: '33333333-3333-3333-3333-333333333333' }], + rows: [{ id: '33333333-3333-3333-3333-333333333333', key: 'originals/server-generated' }], }); - await expect(recordManagedFile({ query }, storageConfig(), input())).resolves.toBe( - '33333333-3333-3333-3333-333333333333', - ); + await expect(recordManagedFile({ query }, storageConfig(), input())).resolves.toEqual({ id: '33333333-3333-3333-3333-333333333333', key: 'originals/server-generated' }); expect(query).toHaveBeenCalledWith({ text: expect.stringContaining( - 'SELECT id FROM storage_private.app_files_record_file(bucket_id := $1::uuid, key := $2::text', + 'SELECT id, key FROM storage_private.app_files_record_file(bucket_id := $1::uuid, key := $2::text', ), values: [ input().bucketId, @@ -76,7 +74,7 @@ describe('recordManagedFile', () => { }); it('appends a supported path argument by name and never a version link', async () => { - const query = jest.fn().mockResolvedValue({ rows: [{ id: 'file-id' }] }); + const query = jest.fn().mockResolvedValue({ rows: [{ id: 'file-id', key: 'originals/server-generated' }] }); await recordManagedFile( { query }, @@ -103,6 +101,20 @@ describe('recordManagedFile', () => { }); }); + it.each([ + undefined, + { id: 'file-id' }, + { id: 'file-id', key: '' }, + { key: 'originals/server-generated' }, + { id: 'file-id', key: input().key }, + ])('refuses an invalid or echoed recorder identity: %p', async (row) => { + const query = jest.fn().mockResolvedValue({ rows: row ? [row] : [] }); + await expect(recordManagedFile({ query }, storageConfig(), input())).rejects.toMatchObject({ + code: 'INTERNAL_ERROR', + errorClass: 'internal', + }); + }); + it('fails loudly when a path is requested on a module without path shares', async () => { const query = jest.fn(); diff --git a/graphile/graphile-presigned-url-plugin/src/custom-key.ts b/graphile/graphile-presigned-url-plugin/src/custom-key.ts index ec3bbfe1f7..efc1c36d9a 100644 --- a/graphile/graphile-presigned-url-plugin/src/custom-key.ts +++ b/graphile/graphile-presigned-url-plugin/src/custom-key.ts @@ -38,8 +38,7 @@ export function validateCustomKey(key: string): string | null { if (key.includes('\0')) { return 'INVALID_KEY: null bytes not allowed'; } - // `.versions/` is where a file's rendered versions are stored, and they - // are served to whoever can read that file: no file of its own may live there. + // Preserve the existing logical-key syntax restriction on the legacy suffix. if (key.includes('.versions/')) { return 'INVALID_KEY: ".versions/" is reserved for a file\'s rendered versions'; } diff --git a/graphile/graphile-presigned-url-plugin/src/file-ref-urls.ts b/graphile/graphile-presigned-url-plugin/src/file-ref-urls.ts index 6b2dbd4c05..fd22c892fc 100644 --- a/graphile/graphile-presigned-url-plugin/src/file-ref-urls.ts +++ b/graphile/graphile-presigned-url-plugin/src/file-ref-urls.ts @@ -5,7 +5,7 @@ * (`FILE_REF_DOMAINS`: `image`, `upload`), or an array of one. It holds a * document that projects a files row — `id`, `key`, `bucket_id` — and, when a * lane has rendered versions beside the source, lists them under `versions` - * (`.versions/-.`). The column reaches GraphQL as JSON, + * (`derived//-.`). The column reaches GraphQL as JSON, * so without these fields a client has no URL to fetch the file with. * * For each such column `photo` on a table type this adds @@ -23,7 +23,7 @@ * 2. the source key, bucket, filename and publicness come from that row, * never from the document; * 3. a version is signed only when its key is a direct child of that row's - * own `.versions/` prefix. A key the document merely names is never + * own `derived//` prefix. A key the document merely names is never * signed. * * Files rows are read once per request, not once per document: every document @@ -88,11 +88,11 @@ type PgClientLike = { /** * Whether `variantKey` is an object a lane wrote beside the file at - * `sourceKey`: a direct child of `.versions/`. + * `sourceKey`: a direct child of `derived//`. */ export function isVersionKeyOf(sourceKey: string, variantKey: unknown): variantKey is string { if (typeof variantKey !== 'string' || !sourceKey) return false; - const prefix = `${sourceKey}.versions/`; + const prefix = `derived/${sourceKey}/`; if (!variantKey.startsWith(prefix)) return false; const name = variantKey.slice(prefix.length); return name.length > 0 && !name.includes('/') && name !== '.' && name !== '..'; diff --git a/graphile/graphile-presigned-url-plugin/src/plugin.ts b/graphile/graphile-presigned-url-plugin/src/plugin.ts index 5975488713..ee7949f4ab 100644 --- a/graphile/graphile-presigned-url-plugin/src/plugin.ts +++ b/graphile/graphile-presigned-url-plugin/src/plugin.ts @@ -27,8 +27,6 @@ import { checkTypeAgreement } from 'mime-bytes'; import { validateCustomKey } from './custom-key'; import { resolveDefaultBucket } from './default-bucket'; -import { isLiveFileRow } from './file-lifecycle'; -import { fileNotReplaceable } from './file-not-replaceable'; import { buildFileProjection, type FileProjection } from './file-projection'; import { assertBucketReconciled, resolveS3ForDatabase } from './physical-bucket'; import { generatePresignedPutUrl, presignedPutHeaders } from './s3-signer'; @@ -50,10 +48,6 @@ function isValidSha256(hash: string): boolean { return SHA256_HEX_REGEX.test(hash); } -function buildS3Key(contentHash: string): string { - return contentHash; -} - function derivePathFromKey(key: string): string | null { const lastSlash = key.lastIndexOf('/'); if (lastSlash <= 0) return null; @@ -201,7 +195,7 @@ export function createPresignedUrlPlugin( contentType: { type: new GraphQLNonNull(GraphQLString), description: 'MIME type of the file' }, size: { type: new GraphQLNonNull(GraphQLInt), description: 'File size in bytes' }, filename: { type: GraphQLString, description: 'Original filename (optional)' }, - key: { type: GraphQLString, description: 'Custom S3 key (only when bucket has allow_custom_keys=true)' }, + key: { type: GraphQLString, description: 'Custom logical key (only when bucket has allow_custom_keys=true)' }, }, }); @@ -338,7 +332,7 @@ export function createPresignedUrlPlugin( contentType: { type: new GraphQLNonNull(GraphQLString), description: 'MIME type of the file' }, size: { type: new GraphQLNonNull(GraphQLInt), description: 'File size in bytes' }, filename: { type: GraphQLString, description: 'Original filename (optional)' }, - key: { type: GraphQLString, description: 'Custom S3 key (only when bucket has allow_custom_keys=true)' }, + key: { type: GraphQLString, description: 'Custom logical key (only when bucket has allow_custom_keys=true)' }, }, }); @@ -561,135 +555,58 @@ export async function processSingleFile( const projectFile = (fileId: string, key: string): FileProjection => buildFileProjection({ id: fileId, key, bucketId: bucket.id, mime: contentType, size, filename }); - // Determine S3 key - let s3Key: string; - let isCustomKey = false; + // The user names a logical slot, never an object-store location. Only the + // recorder allocates the physical key, independently for every new request. + const logicalKey = customKey || contentHash; if (customKey) { if (!bucket.allow_custom_keys) { throw new Error('CUSTOM_KEY_NOT_ALLOWED: bucket does not allow custom keys'); } const keyError = validateCustomKey(customKey); - if (keyError) { - throw new Error(keyError); - } - s3Key = customKey; - isCustomKey = true; - } else { - s3Key = buildS3Key(contentHash); + if (keyError) throw new Error(keyError); } - // Dedup check. A key is one stored object: a row at the key with the same - // hash already describes these bytes, and a live one is a dedup hit. - // - // A row whose bytes never landed must not be reported as a dedup hit: the - // caller would store a reference to an object that is not in S3. Such a row is - // dropped instead, and the upload proceeds as a fresh one below — the insert is - // what enqueues the confirm-upload job, so restarting the lifecycle is the only - // way the retry can ever leave `requested`. Dropping it is also what keeps the - // retry insertable at all for a content-addressed key, where the key *is* the - // hash and a second row would collide on (bucket_id, key). The GC job the - // delete enqueues re-takes the reference count when it runs (≥5s later), by - // which point the replacement row exists, so it no-ops. - // - // A custom key holding different bytes is replaced in place, by the database: - // the new row is inserted as `requested` beside the current one (its BEFORE - // INSERT trigger refuses a key held by a row this caller cannot read), the PUT - // through its URL overwrites the object, and its confirm deletes the row it - // replaced. Until then the current row stays listable and downloadable, so - // nothing is deleted here and no version link is made — a custom key has no - // version chain. - let staleFileId: string | null = null; - - if (isCustomKey) { - const existingResult = await txClient.query({ - text: `SELECT id, status - FROM ${storageConfig.filesQualifiedName} - WHERE key = $1 - AND bucket_id = $2 - AND content_hash = $3 - ORDER BY created_at DESC - LIMIT 1`, - values: [s3Key, bucket.id, contentHash], - }); - - if (existingResult.rows.length > 0) { - const existing = existingResult.rows[0]; - if (isLiveFileRow(existing)) { - log.info(`Dedup hit (custom key): file ${existing.id} for key ${s3Key}`); - return { - uploadUrl: null as string | null, - uploadHeaders: null as Record | null, - fileId: existing.id as string, - key: s3Key, - deduplicated: true, - expiresAt: null as string | null, - file: projectFile(existing.id as string, s3Key), - }; - } - staleFileId = existing.id as string; - log.info(`Restarting upload of key ${s3Key}: file ${staleFileId} has no bytes behind it`); - } - } else { - // Only the row at the hash's own key names these bytes for good: a custom-key - // row carrying the hash holds them at a key whose next upload replaces them. - const dedupResult = await txClient.query({ - text: `SELECT id, status + // Dedup is a read of confirmed identical content in the same logical slot. + // It issues no PUT URL. Pending/rejected attempts are not reused or deleted: + // each retry gets its own object and lifecycle, including its expiry/GC. + const existingResult = await txClient.query({ + text: `SELECT id, key FROM ${storageConfig.filesQualifiedName} - WHERE key = $1 - AND bucket_id = $2 + WHERE logical_key = $1 AND bucket_id = $2 AND content_hash = $3 + AND NOT logical_key_retired + AND status IN ('uploaded', 'processed') LIMIT 1`, - values: [s3Key, bucket.id], - }); - - if (dedupResult.rows.length > 0) { - const existingFile = dedupResult.rows[0]; - if (isLiveFileRow(existingFile)) { - log.info(`Dedup hit: file ${existingFile.id} for hash ${contentHash}`); - - return { - uploadUrl: null as string | null, - uploadHeaders: null as Record | null, - fileId: existingFile.id as string, - key: s3Key, - deduplicated: true, - expiresAt: null as string | null, - file: projectFile(existingFile.id as string, s3Key), - }; - } - staleFileId = existingFile.id as string; - log.info(`Restarting upload of hash ${contentHash}: file ${staleFileId} has no bytes behind it`); - } - } - - if (staleFileId !== null) { - // The DELETE runs under the request role, so RLS decides whether this caller - // may drop the row. A row the caller can see but not delete stays, and the - // upload fails here rather than colliding on (bucket_id, key) below. - const deleted = await txClient.query({ - text: `DELETE FROM ${storageConfig.filesQualifiedName} WHERE id = $1 RETURNING id`, - values: [staleFileId], - }); - if (deleted.rows.length === 0) { - throw fileNotReplaceable(staleFileId, s3Key); - } + values: [logicalKey, bucket.id, contentHash], + }); + if (existingResult.rows.length > 0) { + const existing = existingResult.rows[0]; + return { + uploadUrl: null as string | null, + uploadHeaders: null as Record | null, + fileId: existing.id as string, + key: existing.key as string, + deduplicated: true, + expiresAt: null as string | null, + file: projectFile(existing.id as string, existing.key as string), + }; } - // Auto-derive ltree path from custom key directory (only when has_path_shares) - const derivedPath = isCustomKey && storageConfig.hasPathShares ? derivePathFromKey(s3Key) : null; - - const fileId = await recordManagedFile(txClient, storageConfig, { + const derivedPath = customKey && storageConfig.hasPathShares ? derivePathFromKey(logicalKey) : null; + const recorded = await recordManagedFile(txClient, storageConfig, { bucketId: bucket.id, - key: s3Key, + key: logicalKey, contentHash, mimeType: contentType, size, filename: filename || null, path: derivedPath, }); + const fileId = recorded.id; + const s3Key = recorded.key; // Generate presigned PUT URL, signed over the client's SHA-256 so the store - // only accepts bytes that hash to the content hash the row (and, for - // content-addressed buckets, the key and any later dedup hit) is named by. + // only accepts bytes that hash to the content hash on this row and any + // later dedup hit. Neither logical keys nor checksums locate the object. const uploadUrl = await generatePresignedPutUrl( s3ForDb, s3Key, diff --git a/graphile/graphile-presigned-url-plugin/src/storage-file-recorder.ts b/graphile/graphile-presigned-url-plugin/src/storage-file-recorder.ts index 86b7fe019f..44a0b4a7d3 100644 --- a/graphile/graphile-presigned-url-plugin/src/storage-file-recorder.ts +++ b/graphile/graphile-presigned-url-plugin/src/storage-file-recorder.ts @@ -1,7 +1,10 @@ +import { ConstructiveError } from '@constructive-io/errors'; + import type { StorageModuleConfig } from './types'; interface RecordManagedFileInput { bucketId: string; + /** Logical replacement/dedup slot; the recorder allocates the physical key. */ key: string; contentHash: string; mimeType: string; @@ -18,13 +21,14 @@ interface RecordManagedFileInput { * when the generated function supports them and the caller has a value. A * version's previous_version_id is not an argument: a version chain is written * only by a platform writer, and a custom key has none — a re-upload at a key - * replaces the row at it. + * replaces the row at it only after successful confirmation. The returned key + * is the server-allocated physical location, never input.key. */ export async function recordManagedFile( pgClient: { query: (opts: { text: string; values: unknown[] }) => Promise<{ rows: unknown[] }> }, storageConfig: StorageModuleConfig, input: RecordManagedFileInput, -): Promise { +): Promise<{ id: string; key: string }> { if (!storageConfig.recorderQualifiedName) { throw new Error( `STORAGE_RECORDER_MISSING: storage module ${storageConfig.id} (${storageConfig.filesTableName}) ` + @@ -63,8 +67,19 @@ export async function recordManagedFile( } const result = await pgClient.query({ - text: `SELECT id FROM ${storageConfig.recorderQualifiedName}(${args.join(', ')})`, + text: `SELECT id, key FROM ${storageConfig.recorderQualifiedName}(${args.join(', ')})`, values, }); - return (result.rows[0] as { id: string }).id; + const row = result.rows[0] as { id?: unknown; key?: unknown } | undefined; + if (!row || typeof row.id !== 'string' || !row.id || + typeof row.key !== 'string' || !row.key || row.key === input.key) { + throw new ConstructiveError({ + code: 'INTERNAL_ERROR', + message: 'Storage recorder did not allocate an independent object identity', + errorClass: 'internal', + http: 500, + context: { storageModuleId: storageConfig.id }, + }); + } + return { id: row.id, key: row.key }; } diff --git a/graphile/graphile-presigned-url-plugin/src/types.ts b/graphile/graphile-presigned-url-plugin/src/types.ts index 5d34fb321c..c93931afca 100644 --- a/graphile/graphile-presigned-url-plugin/src/types.ts +++ b/graphile/graphile-presigned-url-plugin/src/types.ts @@ -134,9 +134,9 @@ export interface RequestUploadUrlInput { /** Original filename (optional, for display/Content-Disposition) */ filename?: string; /** - * Custom S3 key for the file (only allowed when bucket has allow_custom_keys=true). + * Custom logical key for the file (only allowed when bucket has allow_custom_keys=true). * When omitted, key defaults to contentHash (content-addressed dedup). - * When provided, the file is stored at this key; dedup is bypassed. + * The server allocates an independent physical key; confirmed identical content in the logical slot is deduplicated. * Max 1024 chars. Must not contain path traversal (.. or leading /). */ key?: string; diff --git a/graphql/server-test/__fixtures__/seed/db-scope-storage/schema.sql b/graphql/server-test/__fixtures__/seed/db-scope-storage/schema.sql index aca3d4b149..78a64e85e2 100644 --- a/graphql/server-test/__fixtures__/seed/db-scope-storage/schema.sql +++ b/graphql/server-test/__fixtures__/seed/db-scope-storage/schema.sql @@ -33,7 +33,9 @@ COMMENT ON TABLE "tess-storage-public".buckets IS E'@storageBuckets\nStorage buc CREATE TABLE "tess-storage-public".files ( id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), bucket_id uuid NOT NULL REFERENCES "tess-storage-public".buckets(id), - key text NOT NULL, + key text NOT NULL DEFAULT 'originals/' || gen_random_uuid()::text, + logical_key text, + logical_key_retired boolean NOT NULL DEFAULT false, content_hash text NOT NULL, mime_type text NOT NULL, size bigint, @@ -47,6 +49,9 @@ CREATE TABLE "tess-storage-public".files ( UNIQUE (bucket_id, key) ); +CREATE INDEX ON "tess-storage-public".files (bucket_id, logical_key, content_hash) + WHERE status IN ('uploaded', 'processed'); + COMMENT ON TABLE "tess-storage-public".files IS E'@storageFiles\nStorage files table'; GRANT SELECT, INSERT, UPDATE, DELETE ON "tess-storage-public".buckets TO administrator, authenticated, anonymous; @@ -72,7 +77,7 @@ DECLARE BEGIN INSERT INTO "tess-storage-public".files ( bucket_id, - key, + logical_key, content_hash, mime_type, size, diff --git a/graphql/server-test/__fixtures__/seed/shared-db-scope-storage/schema.sql b/graphql/server-test/__fixtures__/seed/shared-db-scope-storage/schema.sql index 6f35a6116c..82dfdf71f1 100644 --- a/graphql/server-test/__fixtures__/seed/shared-db-scope-storage/schema.sql +++ b/graphql/server-test/__fixtures__/seed/shared-db-scope-storage/schema.sql @@ -41,7 +41,9 @@ CREATE TABLE "shared-storage-public".files ( id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), database_id uuid NOT NULL, bucket_id uuid NOT NULL REFERENCES "shared-storage-public".buckets(id), - key text NOT NULL, + key text NOT NULL DEFAULT 'originals/' || gen_random_uuid()::text, + logical_key text, + logical_key_retired boolean NOT NULL DEFAULT false, content_hash text NOT NULL, mime_type text NOT NULL, size bigint, @@ -55,6 +57,9 @@ CREATE TABLE "shared-storage-public".files ( UNIQUE (bucket_id, key) ); +CREATE INDEX ON "shared-storage-public".files (bucket_id, logical_key, content_hash) + WHERE status IN ('uploaded', 'processed'); + COMMENT ON TABLE "shared-storage-public".files IS E'@storageFiles\nStorage files table'; GRANT SELECT, INSERT, UPDATE, DELETE ON "shared-storage-public".buckets TO administrator, authenticated, anonymous; @@ -102,7 +107,7 @@ DECLARE v_row "shared-storage-public".files; BEGIN INSERT INTO "shared-storage-public".files ( - database_id, bucket_id, key, content_hash, mime_type, size, filename, is_public, previous_version_id + database_id, bucket_id, logical_key, content_hash, mime_type, size, filename, is_public, previous_version_id ) SELECT b.database_id, $1, $2, $3, $4, $5, $6, b.is_public, $9 FROM "shared-storage-public".buckets b diff --git a/graphql/server-test/__fixtures__/seed/simple-seed-storage/schema.sql b/graphql/server-test/__fixtures__/seed/simple-seed-storage/schema.sql index 2de058ddd6..28759b0df0 100644 --- a/graphql/server-test/__fixtures__/seed/simple-seed-storage/schema.sql +++ b/graphql/server-test/__fixtures__/seed/simple-seed-storage/schema.sql @@ -47,7 +47,9 @@ BEGIN 'CREATE TABLE IF NOT EXISTS %I.app_files ( id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), bucket_id uuid NOT NULL REFERENCES %I.app_buckets(id), - key text NOT NULL, + key text NOT NULL DEFAULT ''originals/'' || gen_random_uuid()::text, + logical_key text, + logical_key_retired boolean NOT NULL DEFAULT false, content_hash text NOT NULL, mime_type text NOT NULL, size bigint, @@ -65,6 +67,10 @@ BEGIN 'COMMENT ON TABLE %I.app_files IS E''@storageFiles\nStorage files table''', schema_name); + EXECUTE format( + 'CREATE INDEX ON %I.app_files (bucket_id, logical_key, content_hash) WHERE status IN (''uploaded'', ''processed'')', + schema_name); + -- Grant CRUD to all roles EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I.app_buckets TO administrator, authenticated, anonymous', schema_name); EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON %I.app_files TO administrator, authenticated, anonymous', schema_name); @@ -90,7 +96,7 @@ BEGIN BEGIN INSERT INTO %I.app_files ( bucket_id, - key, + logical_key, content_hash, mime_type, size, diff --git a/graphql/server-test/__tests__/db-scope-upload.integration.test.ts b/graphql/server-test/__tests__/db-scope-upload.integration.test.ts index 80996560e0..f818485fad 100644 --- a/graphql/server-test/__tests__/db-scope-upload.integration.test.ts +++ b/graphql/server-test/__tests__/db-scope-upload.integration.test.ts @@ -199,7 +199,7 @@ describe('database-scope upload surface', () => { // The tenant row names no endpoint: it inherits the platform row's, never an env default. expect(new URL(payload.uploadUrl).host).toBe('127.0.0.1:9000'); expect(payload.fileId).toBeTruthy(); - expect(payload.key).toBe(contentHash); + expect(payload.key).toMatch(/^originals\/[0-9a-f-]{36}$/); expect(payload.deduplicated).toBe(false); uploadUrl = payload.uploadUrl; diff --git a/graphql/server-test/__tests__/download-url-status.integration.test.ts b/graphql/server-test/__tests__/download-url-status.integration.test.ts index d2702a3ee1..523405c3db 100644 --- a/graphql/server-test/__tests__/download-url-status.integration.test.ts +++ b/graphql/server-test/__tests__/download-url-status.integration.test.ts @@ -56,7 +56,7 @@ const APP_FILES = ` const manifest = (key: string) => { const version = (name: string, leaf: string, width: number) => ({ - name, key: `${key}.versions/${leaf}`, width, height: width, format: 'webp', size: 100 + name, key: `derived/${key}/${leaf}`, width, height: width, format: 'webp', size: 100 }); return { source: { width: 1024, height: 1024, format: 'png' }, @@ -66,7 +66,7 @@ const manifest = (key: string) => { version('small', 'small-0123abcd.webp', 160), version('duplicate', 'first.webp', 320), version('duplicate', 'second.webp', 400), - { name: 'foreign', key: 'another-file.versions/small.webp' } + { name: 'foreign', key: 'derived/another-file/small.webp' } ] }; }; @@ -186,7 +186,7 @@ describe('storage file downloadUrl', () => { const rows = await files(bobDatabaseId, bobSchema, 'small'); for (const status of ['uploaded', 'processed']) { const url = new URL(rows.get(`status-${status}`).selected); - expect(url.pathname).toBe(`/app-a1a1a1a1-public-4db6afbff1a2/status-${status}.versions/small-0123abcd.webp`); + expect(url.pathname).toBe(`/app-a1a1a1a1-public-4db6afbff1a2/derived/status-${status}/small-0123abcd.webp`); expect(url.searchParams.get('X-Amz-Signature')).toEqual(expect.any(String)); expect(url.searchParams.get('response-content-disposition')).toBe('attachment; filename="small-0123abcd.webp"'); } @@ -198,7 +198,7 @@ describe('storage file downloadUrl', () => { it('returns the public artifact URL and respects the reader’s file visibility', async () => { const rows = await files(bobDatabaseId, bobSchema, 'large'); expect(rows.get('seeded-public-hash').selected).toBe( - `${cdn}/app-a1a1a1a1-public-4db6afbff1a2/seeded-public-hash.versions/large-abcd1234.webp` + `${cdn}/app-a1a1a1a1-public-4db6afbff1a2/derived/seeded-public-hash/large-abcd1234.webp` ); expect(rows.has('seeded-private-hash')).toBe(false); }); diff --git a/graphql/server-test/__tests__/file-ref-urls.integration.test.ts b/graphql/server-test/__tests__/file-ref-urls.integration.test.ts index 235bf8a5fe..6b41f82484 100644 --- a/graphql/server-test/__tests__/file-ref-urls.integration.test.ts +++ b/graphql/server-test/__tests__/file-ref-urls.integration.test.ts @@ -6,7 +6,7 @@ * included, so it is never the authority for a URL. The files row is read by * the document's `id` as the reader; the source key comes from that row; and a * version is signed only when its key is a direct child of that row's own - * `.versions/`. + * `derived//`. * * pnpm test -- --testPathPattern=file-ref-urls */ @@ -136,8 +136,8 @@ describe('file-reference column URLs', () => { it('gives the narrowest version covering the width, else the source', async () => { const id = await addFile('pick/photo.png'); - const small = version('pick/photo.png.versions/small-0a1b2c3d.webp', 'small', 320); - const large = version('pick/photo.png.versions/large-4e5f6a7b.webp', 'large', 1280); + const small = version('derived/pick/photo.png/small-0a1b2c3d.webp', 'small', 320); + const large = version('derived/pick/photo.png/large-4e5f6a7b.webp', 'large', 1280); const row = await addProduct({ id, key: 'pick/photo.png', versions: [large, small] }); const at300 = await product(alice, row, 300); @@ -153,13 +153,13 @@ describe('file-reference column URLs', () => { it('never signs a key the document names outside its own file', async () => { const id = await addFile('forge/mine.png'); await addFile('forge/victim.png'); - const own = version('forge/mine.png.versions/small-0a1b2c3d.webp', 'small', 320); + const own = version('derived/forge/mine.png/small-0a1b2c3d.webp', 'small', 320); const forged = [ version('forge/victim.png', 'other-file', 400), - version('forge/victim.png.versions/small-0a1b2c3d.webp', 'other-files-version', 400), - version('forge/mine.png.versions/../victim.png', 'traversal', 400), - version('forge/mine.png.versions/nested/deep.webp', 'nested', 400), - version('forge/mine.png.versions/', 'prefix-only', 400), + version('derived/forge/victim.png/small-0a1b2c3d.webp', 'other-files-version', 400), + version('derived/forge/mine.png/../victim.png', 'traversal', 400), + version('derived/forge/mine.png/nested/deep.webp', 'nested', 400), + version('derived/forge/mine.png/', 'prefix-only', 400), version('forge/mine.png', 'source-as-version', 400) ]; // The document also lies about its own key: the row's key is what is signed. @@ -174,7 +174,7 @@ describe('file-reference column URLs', () => { it('resolves nothing for a document without a files row the reader can fetch', async () => { const requested = await addFile('dead/requested.png', 'requested'); - const noId = await addProduct({ key: 'pick/photo.png', versions: [version('pick/photo.png.versions/small-0a1b2c3d.webp', 'small', 320)] }); + const noId = await addProduct({ key: 'pick/photo.png', versions: [version('derived/pick/photo.png/small-0a1b2c3d.webp', 'small', 320)] }); const notLive = await addProduct({ id: requested, key: 'dead/requested.png' }); const unknown = await addProduct({ id: '00000000-0000-4000-8000-000000000000', key: 'pick/photo.png' }); const empty = await addProduct(null); @@ -192,7 +192,7 @@ describe('file-reference column URLs', () => { const hidden = await addProduct({ id: bobPrivateFileId, key: 'seeded-private-hash', - versions: [version('seeded-private-hash.versions/small-0a1b2c3d.webp', 'small', 320)] + versions: [version('derived/seeded-private-hash/small-0a1b2c3d.webp', 'small', 320)] }); const visible = await addProduct({ id: bobPublicFileId, key: 'seeded-public-hash' }); @@ -203,8 +203,8 @@ describe('file-reference column URLs', () => { it('resolves each element of an image[] column on its own', async () => { const one = await addFile('list/one.png'); await addFile('list/two.png'); - const mine = version('list/one.png.versions/small-0a1b2c3d.webp', 'small', 320); - const theirs = version('list/two.png.versions/small-0a1b2c3d.webp', 'small', 320); + const mine = version('derived/list/one.png/small-0a1b2c3d.webp', 'small', 320); + const theirs = version('derived/list/two.png/small-0a1b2c3d.webp', 'small', 320); const { rows } = await pg.query( `INSERT INTO ${schema}.albums (shots) VALUES (ARRAY(SELECT jsonb_array_elements($1::jsonb))::public.image[]) RETURNING id`, @@ -251,7 +251,7 @@ describe('file-reference column URLs', () => { it('falls back to the source when no version states a width', async () => { const id = await addFile('docs/deck.pdf'); - const preview = { name: 'preview', key: 'docs/deck.pdf.versions/preview-0a1b2c3d.png' }; + const preview = { name: 'preview', key: 'derived/docs/deck.pdf/preview-0a1b2c3d.png' }; const row = await addProduct(null, { id, key: 'docs/deck.pdf', versions: [preview] }); const got = await manual(row, 320); @@ -264,14 +264,14 @@ describe('file-reference column URLs', () => { it('never signs a key the document names outside its own file', async () => { const id = await addFile('docs/mine.pdf'); await addFile('docs/victim.pdf'); - const own = version('docs/mine.pdf.versions/page-0a1b2c3d.png', 'page', 320); + const own = version('derived/docs/mine.pdf/page-0a1b2c3d.png', 'page', 320); const row = await addProduct(null, { id, key: 'docs/victim.pdf', versions: [ version('docs/victim.pdf', 'other-file', 400), - version('docs/victim.pdf.versions/page-0a1b2c3d.png', 'other-files-version', 400), - version('docs/mine.pdf.versions/../victim.pdf', 'traversal', 400), + version('derived/docs/victim.pdf/page-0a1b2c3d.png', 'other-files-version', 400), + version('derived/docs/mine.pdf/../victim.pdf', 'traversal', 400), own ] }); @@ -297,7 +297,7 @@ describe('file-reference column URLs', () => { it('resolves each element of an upload[] column on its own', async () => { const one = await addFile('papers/one.pdf'); await addFile('papers/two.pdf'); - const theirs = version('papers/two.pdf.versions/page-0a1b2c3d.png', 'page', 320); + const theirs = version('derived/papers/two.pdf/page-0a1b2c3d.png', 'page', 320); const { rows } = await pg.query( `INSERT INTO ${schema}.albums (papers) VALUES (ARRAY(SELECT jsonb_array_elements($1::jsonb))::public.upload[]) RETURNING id`, @@ -341,7 +341,7 @@ describe('file-reference column URLs', () => { it('serves a public file from the public URL prefix, its versions too', async () => { const id = await addFile('open/logo.png', 'uploaded', alicePublicBucketId, true); - const small = version('open/logo.png.versions/small-0a1b2c3d.webp', 'small', 320); + const small = version('derived/open/logo.png/small-0a1b2c3d.webp', 'small', 320); const got = await urls(id, await addProduct({ id, key: 'open/logo.png', versions: [small] })); expect(got.source).toBe(`${cdn}/app-80a2eaaf-public-c7156cb19fe3/open/logo.png`); @@ -376,7 +376,7 @@ describe('file-reference column URLs', () => { VALUES ($1, 'team/plan.png', 'team/plan.png', 'image/png', 'plan.png', 'uploaded') RETURNING id`, [secondBucketId] ); - const small = version('team/plan.png.versions/small-0a1b2c3d.webp', 'small', 320); + const small = version('derived/team/plan.png/small-0a1b2c3d.webp', 'small', 320); const got = await product(alice, await addProduct({ id: rows[0].id, key: 'team/plan.png', versions: [small] }), 300); expect(pathOf(got.source)).toContain('team-80a2eaaf-private-0123456789ab/team/plan.png'); @@ -402,7 +402,7 @@ describe('file-reference column URLs', () => { const id = await addFile(key); await pg.query(`INSERT INTO ${schema}.products (title, photo) VALUES ($1, $2::jsonb)`, [ title, - JSON.stringify({ id, key, versions: [version(`${key}.versions/small-0a1b2c3d.webp`, 'small', 320)] }) + JSON.stringify({ id, key, versions: [version(`derived/${key}/small-0a1b2c3d.webp`, 'small', 320)] }) ]); } diff --git a/graphql/server-test/__tests__/upload.integration.test.ts b/graphql/server-test/__tests__/upload.integration.test.ts index 78f5ad2e5a..b79a424789 100644 --- a/graphql/server-test/__tests__/upload.integration.test.ts +++ b/graphql/server-test/__tests__/upload.integration.test.ts @@ -287,10 +287,10 @@ describe('Integration tests (uploads, tenant isolation, RLS)', () => { * run: a row is written as `requested` and only becomes a dedup hit once the * confirm job has inspected the object and moved it to `uploaded`. */ - const confirmUploaded = async (contentHash: string): Promise => { + const confirmUploaded = async (fileId: string): Promise => { await pg.query( - `UPDATE "${aliceSchemas[0]}".app_files SET status = 'uploaded' WHERE content_hash = $1`, - [contentHash] + `UPDATE "${aliceSchemas[0]}".app_files SET status = 'uploaded' WHERE id = $1`, + [fileId] ); }; let teardown: () => Promise; @@ -419,7 +419,7 @@ describe('Integration tests (uploads, tenant isolation, RLS)', () => { expect(payload.uploadUrl).toBeTruthy(); expect(new URL(payload.uploadUrl).host).toBe('127.0.0.1:9000'); expect(payload.fileId).toBeTruthy(); - expect(payload.key).toBe(contentHash); + expect(payload.key).toMatch(/^originals\/[0-9a-f-]{36}$/); expect(payload.deduplicated).toBe(false); expect(payload.expiresAt).toBeTruthy(); @@ -435,7 +435,7 @@ describe('Integration tests (uploads, tenant isolation, RLS)', () => { it('should accept a PUT to the presigned URL', async () => { const putRes = await putToPresignedUrl(uploadUrl, fileContent, contentType, { headers: uploadHeaders }); expect(putRes.ok).toBe(true); - await confirmUploaded(contentHash); + await confirmUploaded(uploadHeaders['x-amz-meta-upload-id']); }); }); @@ -469,7 +469,7 @@ describe('Integration tests (uploads, tenant isolation, RLS)', () => { const payload = data.uploadAppFile; expect(payload.uploadUrl).toBeTruthy(); expect(payload.fileId).toBeTruthy(); - expect(payload.key).toBe(contentHash); + expect(payload.key).toMatch(/^originals\/[0-9a-f-]{36}$/); expect(payload.deduplicated).toBe(false); expect(payload.expiresAt).toBeTruthy(); @@ -519,6 +519,34 @@ describe('Integration tests (uploads, tenant isolation, RLS)', () => { // (stood in for here by confirmUploaded) moves it to `uploaded`, and only // an uploaded row is a dedup hit. A retry after a PUT that never ran must // get a URL again. + it('allocates separate objects for repeated caller-selected logical keys', async () => { + await pg.query(`INSERT INTO "${aliceSchemas[0]}".app_buckets + (key, type, is_public, allow_custom_keys, physical_name) + VALUES ('logical-slot', 'public', true, true, 'logical-slot-fixture')`); + try { + const key = 'derived/originals/known-object/thumb.webp'; + const request = async (text: string) => expectSuccess(await postGraphQL({ + query: UPLOAD_APP_FILE, + variables: { input: { + bucketKey: 'logical-slot', key, contentHash: await hashContent(text), + contentType: 'text/plain', size: Buffer.byteLength(text), filename: 'logical.txt' + } } + })).uploadAppFile; + const first = await request('first'); + const second = await request('second'); + expect(first.key).toMatch(/^originals\/[0-9a-f-]{36}$/); + expect(second.key).toMatch(/^originals\/[0-9a-f-]{36}$/); + expect(first.key).not.toBe(second.key); + expect(first.fileId).not.toBe(second.fileId); + expect(first.deduplicated).toBe(false); + expect(second.deduplicated).toBe(false); + } finally { + await pg.query(`DELETE FROM "${aliceSchemas[0]}".app_files WHERE bucket_id IN + (SELECT id FROM "${aliceSchemas[0]}".app_buckets WHERE key = 'logical-slot')`); + await pg.query(`DELETE FROM "${aliceSchemas[0]}".app_buckets WHERE key = 'logical-slot'`); + } + }); + it('issues a fresh upload URL when the earlier PUT never ran', async () => { const fileContent = `Never PUT: the client walked away (${crypto.randomUUID()}).`; const contentHash = await hashContent(fileContent); @@ -538,10 +566,11 @@ describe('Integration tests (uploads, tenant isolation, RLS)', () => { expect(retry.deduplicated).toBe(false); expect(retry.uploadUrl).toBeTruthy(); expect(retry.fileId).not.toBe(first.fileId); + expect(retry.key).not.toBe(first.key); const putRes = await putToPresignedUrl(retry.uploadUrl, fileContent, 'text/plain', { headers: retry.uploadHeaders }); expect(putRes.ok).toBe(true); - await confirmUploaded(contentHash); + await confirmUploaded(retry.fileId); const afterPut = expectSuccess(await postGraphQL({ query: UPLOAD_APP_FILE, variables: { input } })).uploadAppFile; expect(afterPut.deduplicated).toBe(true); From 8acc0a45ee9f8d8d68bb98eb3c27500ccb936971 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Mon, 23 Nov 2026 15:24:23 +0000 Subject: [PATCH 2/8] feat(site-deploy): request uploads by site instead of bucket --- .../site-deploy-ssg/__tests__/mock-server.ts | 6 ++--- .../__tests__/ssg-deploy.test.ts | 1 - examples/site-deploy-ssg/src/deploy.ts | 3 +-- packages/site-deploy/README.md | 2 -- packages/site-deploy/__tests__/deploy.test.ts | 27 ++++++++++--------- packages/site-deploy/__tests__/mock-api.ts | 13 +++------ packages/site-deploy/__tests__/walk.test.ts | 1 - packages/site-deploy/src/cas-upload.ts | 14 +++++----- packages/site-deploy/src/deploy.ts | 3 +-- packages/site-deploy/src/documents.ts | 4 +-- packages/site-deploy/src/index.ts | 1 - packages/site-deploy/src/types.ts | 4 +-- 12 files changed, 32 insertions(+), 47 deletions(-) diff --git a/examples/site-deploy-ssg/__tests__/mock-server.ts b/examples/site-deploy-ssg/__tests__/mock-server.ts index 3cc476ab5f..0f84fb6c96 100644 --- a/examples/site-deploy-ssg/__tests__/mock-server.ts +++ b/examples/site-deploy-ssg/__tests__/mock-server.ts @@ -56,14 +56,14 @@ export function createMockServer(): MockServer { function handle(operation: string, variables: Record) { const input = (variables.input ?? {}) as Record; switch (operation) { - case 'uploadFiles': + case 'uploadSiteFiles': return { - uploadFiles: { + uploadSiteFiles: { files: (input.files as any[]).map((file) => { const deduplicated = hashes.has(file.contentHash); return { fileId: `file-${file.contentHash.slice(0, 8)}`, - key: file.key as string, + key: `cas/sha256/${file.contentHash}`, deduplicated, uploadUrl: deduplicated ? null : `https://s3.test/put/${file.contentHash}`, uploadHeaders: deduplicated ? null : signedHeaders(file), diff --git a/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts b/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts index c01e715fcc..d80b63324d 100644 --- a/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts +++ b/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts @@ -40,7 +40,6 @@ const deployOptions = (server: ReturnType) => ({ putObject: server.putObject, siteId: 'site-1', databaseId: 'db-1', - bucketKey: 'site-example', source: dist, }); diff --git a/examples/site-deploy-ssg/src/deploy.ts b/examples/site-deploy-ssg/src/deploy.ts index 32af33d915..c6e26cdd33 100644 --- a/examples/site-deploy-ssg/src/deploy.ts +++ b/examples/site-deploy-ssg/src/deploy.ts @@ -4,7 +4,7 @@ * ```bash * CONSTRUCTIVE_API_URL=https://api.example.com/graphql \ * CONSTRUCTIVE_TOKEN=$TOKEN \ - * SITE_ID=... DATABASE_ID=... BUCKET_KEY=site-example \ + * SITE_ID=... DATABASE_ID=... \ * PREVIEW=play pnpm deploy * ``` * @@ -86,7 +86,6 @@ async function main(): Promise { : undefined, siteId: required('SITE_ID'), databaseId: process.env.DATABASE_ID, - bucketKey: required('BUCKET_KEY'), source: dist, preview: process.env.PREVIEW, previewApex: process.env.PREVIEW_APEX, diff --git a/packages/site-deploy/README.md b/packages/site-deploy/README.md index c20feb6adb..e267b33064 100644 --- a/packages/site-deploy/README.md +++ b/packages/site-deploy/README.md @@ -32,7 +32,6 @@ const result = await deploySite({ api, // GraphQL executor for the tenant API siteId, databaseId, // required on a site's first deploy - bucketKey: 'site-docs', source: './dist', // a directory, or the files themselves publish: true, // move site.activeCommitId when it lands }); @@ -46,7 +45,6 @@ Deploy a branch preview instead of going live: const { previewUrl } = await deploySite({ api, siteId, - bucketKey: 'site-docs', source: './dist', preview: 'pr-42', // → preview/pr-42 previewApex: 'preview.example.com', // provisions pr-42--.preview.example.com diff --git a/packages/site-deploy/__tests__/deploy.test.ts b/packages/site-deploy/__tests__/deploy.test.ts index 79b4874872..c7a7db4728 100644 --- a/packages/site-deploy/__tests__/deploy.test.ts +++ b/packages/site-deploy/__tests__/deploy.test.ts @@ -1,12 +1,11 @@ import { deploySite } from '../src/deploy'; import type { DeployProgress, GraphQLExecutor, PutObject } from '../src/types'; import { DeployError } from '../src/types'; -import { createMockServer, failingPut, file, hashOf, keyOf } from './mock-api'; +import { createMockServer, failingPut, file, hashOf } from './mock-api'; const base = { siteId: 'site-1', databaseId: 'db-1', - bucketKey: 'site-docs', }; const build = [file('index.html', '

home

'), file('assets/app.js', 'console.log(1)')]; @@ -45,16 +44,18 @@ describe('deploySite', () => { expect(server.countOf('updateSiteRelease')).toBe(0); }); - it('registers the bytes under content-addressed keys', async () => { + it('requests content-addressed uploads for the site without physical keys', async () => { const server = createMockServer(); await deploySite({ ...base, api: server.api, putObject: server.putObject, source: build }); - const upload = server.firstCall('uploadFiles') as any; - expect(upload.input.bucketKey).toBe('site-docs'); - expect(upload.input.files.map((f: any) => f.key)).toEqual([ - keyOf('

home

'), - keyOf('console.log(1)'), - ]); + const upload = server.firstCall('uploadSiteFiles') as any; + expect(upload.input).toEqual({ + siteId: 'site-1', + files: [ + { contentHash: hashOf('

home

'), contentType: 'text/html; charset=utf-8', size: 13, filename: 'index.html' }, + { contentHash: hashOf('console.log(1)'), contentType: 'text/javascript; charset=utf-8', size: 14, filename: 'app.js' }, + ], + }); }); it('patches the existing row on later deploys instead of creating a second one', async () => { @@ -137,7 +138,7 @@ describe('deploySite', () => { batchSize: 10, }); - expect(server.countOf('uploadFiles')).toBe(3); + expect(server.countOf('uploadSiteFiles')).toBe(3); expect(server.puts).toHaveLength(25); }); @@ -155,7 +156,7 @@ describe('deploySite', () => { expect(server.activeCommitId).toBe(result.commitId); expect(server.calls.map((c) => c.operation)).toEqual([ 'siteReleases', - 'uploadFiles', + 'uploadSiteFiles', 'createSiteRelease', 'updateSite', ]); @@ -221,7 +222,7 @@ describe('deploySite', () => { const server = createMockServer(); const unsigned: GraphQLExecutor = async (query, variables) => { const data = await server.api(query, variables); - for (const result of (data.uploadFiles as any)?.files ?? []) result.uploadHeaders = null; + for (const result of (data.uploadSiteFiles as any)?.files ?? []) result.uploadHeaders = null; return data; }; await expect( @@ -318,7 +319,7 @@ describe('deploySite', () => { skipped: 2, }); expect(server.countOf('updateSiteRelease')).toBe(0); - expect(server.countOf('uploadFiles')).toBe(1); + expect(server.countOf('uploadSiteFiles')).toBe(1); }); it('commits again when the tree changed even with skipIfUnchanged', async () => { diff --git a/packages/site-deploy/__tests__/mock-api.ts b/packages/site-deploy/__tests__/mock-api.ts index f884a5f75e..6f6406a4dc 100644 --- a/packages/site-deploy/__tests__/mock-api.ts +++ b/packages/site-deploy/__tests__/mock-api.ts @@ -81,15 +81,15 @@ export function createMockServer(options: MockServerOptions = {}): MockServer { function handle(operation: string, variables: Record) { const input = (variables.input ?? {}) as Record; switch (operation) { - case 'uploadFiles': + case 'uploadSiteFiles': return { - uploadFiles: { + uploadSiteFiles: { files: (input.files as any[]).map((file) => { const deduplicated = stored.has(file.contentHash); const key = file.filename === options.corruptKeyFor ? 'uploads/wrong-key' - : (file.key as string); + : casKey(file.contentHash); return { fileId: `file-${file.contentHash.slice(0, 8)}`, key, @@ -154,7 +154,7 @@ export function createMockServer(options: MockServerOptions = {}): MockServer { return server; } -/** The mutation/query field being selected, e.g. `uploadFiles`. */ +/** The mutation/query field being selected, e.g. `uploadSiteFiles`. */ function operationName(query: string): string { const match = query.match(/\{\s*(\w+)\(/); if (!match) throw new Error(`Could not read an operation from: ${query}`); @@ -166,11 +166,6 @@ export function file(path: string, body: string): DeployFile { return { path, bytes: new TextEncoder().encode(body) }; } -/** The CAS key a body will be stored under. */ -export function keyOf(body: string): string { - return casKey(hashBytes(new TextEncoder().encode(body))); -} - /** The hash of a body, as the bucket's dedupe set records it. */ export function hashOf(body: string): string { return hashBytes(new TextEncoder().encode(body)); diff --git a/packages/site-deploy/__tests__/walk.test.ts b/packages/site-deploy/__tests__/walk.test.ts index 0d9f2d4b37..1eb52e29e2 100644 --- a/packages/site-deploy/__tests__/walk.test.ts +++ b/packages/site-deploy/__tests__/walk.test.ts @@ -48,7 +48,6 @@ describe('deploySite from a directory', () => { putObject: server.putObject, siteId: 'site-1', databaseId: 'db-1', - bucketKey: 'site-docs', source: dir, }); diff --git a/packages/site-deploy/src/cas-upload.ts b/packages/site-deploy/src/cas-upload.ts index 7670b67205..ec80b86455 100644 --- a/packages/site-deploy/src/cas-upload.ts +++ b/packages/site-deploy/src/cas-upload.ts @@ -3,7 +3,7 @@ * * The generic pieces come from `@constructive-io/upload-client` (a presigned * PUT); what is added here is the part a static release needs: many files in - * one round trip, explicit `cas/sha256/` keys, and skipping every file + * one round trip, server-derived `cas/sha256/` keys, and skipping every file * the server already has. That skip is the whole incremental-deploy win — a * one-file change re-uploads one file however large the site is. */ @@ -28,10 +28,10 @@ interface BulkFilePayload { export interface UploadCasOptions { /** Executor for the storage target. */ storage: GraphQLExecutor; - /** Bulk upload mutation field name, e.g. `uploadFiles`. */ + /** Bulk upload mutation field name, e.g. `uploadSiteFiles`. */ mutation: string; - /** Bucket key of the site's bucket. */ - bucketKey: string; + /** Site whose backing bucket receives the files. */ + siteId: string; /** Files per mutation call. */ batchSize: number; /** Parallel PUTs. */ @@ -76,13 +76,12 @@ export async function diffCas( const batch = files.slice(offset, offset + options.batchSize); const data = await options.storage(mutation, { input: { - bucketKey: options.bucketKey, + siteId: options.siteId, files: batch.map((file) => ({ contentHash: file.hash, contentType: file.contentType, size: file.size, filename: file.path.slice(file.path.lastIndexOf('/') + 1), - key: file.key, })), }, }); @@ -98,8 +97,7 @@ export async function diffCas( results.forEach((result, index) => { const file = batch[index]; - // The server does not enforce the CAS key form yet, so a mismatch here - // would publish a manifest pointing at bytes nobody can serve. + // A mismatch would publish a manifest pointing at bytes nobody can serve. if (result.key !== file.key || !CAS_KEY_PATTERN.test(result.key)) { throw new DeployError( 'KEY_MISMATCH', diff --git a/packages/site-deploy/src/deploy.ts b/packages/site-deploy/src/deploy.ts index 0531f58a32..bc3375f04e 100644 --- a/packages/site-deploy/src/deploy.ts +++ b/packages/site-deploy/src/deploy.ts @@ -59,7 +59,6 @@ export async function deploySite(options: DeploySiteOptions): Promise (prefix ? `${prefix}${name}` : lowerFirst(name)); return { - bulkUploadMutation: `upload${Prefix}Files`, + bulkUploadMutation: `upload${Prefix}SiteFiles`, releasesQuery: `${lower('SiteReleases')}`, createRelease: `create${Prefix}SiteRelease`, releaseInputField: lower('SiteRelease'), @@ -54,7 +54,7 @@ export function buildBulkUploadMutation(mutation: string): string { `; } -/** `uploadFiles` → `UploadFileBulkInput`, `uploadPlatformFiles` → … */ +/** `uploadSiteFiles` → `UploadSiteFileBulkInput`, `uploadPlatformSiteFiles` → … */ function inputTypeName(mutation: string): string { const capitalized = mutation.charAt(0).toUpperCase() + mutation.slice(1); return `${capitalized.replace(/s$/, '')}BulkInput`; diff --git a/packages/site-deploy/src/index.ts b/packages/site-deploy/src/index.ts index aad2c3d124..6bfc2ba6cb 100644 --- a/packages/site-deploy/src/index.ts +++ b/packages/site-deploy/src/index.ts @@ -7,7 +7,6 @@ * api, * siteId, * databaseId, - * bucketKey: 'site-docs', * source: './dist', * publish: true, * }); diff --git a/packages/site-deploy/src/types.ts b/packages/site-deploy/src/types.ts index a2d89b6c9a..4aefc87f6e 100644 --- a/packages/site-deploy/src/types.ts +++ b/packages/site-deploy/src/types.ts @@ -56,7 +56,7 @@ export interface ReleaseManifest { * names when a plane's inflection differs. */ export interface SiteDeployNames { - /** Bulk presigned-upload mutation, e.g. `uploadFiles`. */ + /** Site-scoped bulk presigned-upload mutation, e.g. `uploadSiteFiles`. */ bulkUploadMutation: string; /** Site release collection query, e.g. `siteReleases`. */ releasesQuery: string; @@ -125,8 +125,6 @@ export interface DeploySiteOptions { * site at `database` scope, where the column is NOT NULL. */ databaseId?: string; - /** Bucket key of the site's bucket (`allow_custom_keys` must be on). */ - bucketKey: string; /** The build: a directory path, or the files themselves. */ source: DeploySource; /** Which generated surface to talk to. Defaults to `database`. */ From 01f79dc4008afcfa2b3371f19a141141f0c514a3 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Mon, 23 Nov 2026 16:14:30 +0000 Subject: [PATCH 3/8] feat: sign and confirm managed site uploads --- .../__tests__/s3-signer.integration.test.ts | 3 +- .../src/plugin.ts | 137 +++++++++++++++++- .../src/s3-signer.ts | 1 + packages/site-deploy/README.md | 9 +- packages/site-deploy/__tests__/deploy.test.ts | 9 +- .../site-deploy/__tests__/manifest.test.ts | 4 +- packages/site-deploy/__tests__/mock-api.ts | 9 +- packages/site-deploy/src/cas-upload.ts | 59 ++++++-- packages/site-deploy/src/deploy.ts | 14 +- packages/site-deploy/src/documents.ts | 2 + packages/site-deploy/src/manifest.ts | 8 +- packages/site-deploy/src/types.ts | 2 +- 12 files changed, 218 insertions(+), 39 deletions(-) diff --git a/graphile/graphile-presigned-url-plugin/__tests__/s3-signer.integration.test.ts b/graphile/graphile-presigned-url-plugin/__tests__/s3-signer.integration.test.ts index 15ce81b7ff..40c7cc49c1 100644 --- a/graphile/graphile-presigned-url-plugin/__tests__/s3-signer.integration.test.ts +++ b/graphile/graphile-presigned-url-plugin/__tests__/s3-signer.integration.test.ts @@ -228,9 +228,10 @@ describe('s3-signer integration (RustFS)', () => { return generatePresignedPutUrl(s3Config, key, 'text/plain', Buffer.byteLength(content), 300, hash, fileId); } - it('signs the upload id as a header, not a query parameter', async () => { + it('signs the upload id and content type as headers', async () => { const url = new URL(await boundUrl(`row-bound/${Date.now()}-q`)); expect(url.searchParams.get('X-Amz-SignedHeaders')).toContain(UPLOAD_ID_HEADER); + expect(url.searchParams.get('X-Amz-SignedHeaders')?.split(';')).toContain('content-type'); expect(url.searchParams.has(UPLOAD_ID_HEADER)).toBe(false); }); diff --git a/graphile/graphile-presigned-url-plugin/src/plugin.ts b/graphile/graphile-presigned-url-plugin/src/plugin.ts index ee7949f4ab..615ee3ca7e 100644 --- a/graphile/graphile-presigned-url-plugin/src/plugin.ts +++ b/graphile/graphile-presigned-url-plugin/src/plugin.ts @@ -19,6 +19,7 @@ import 'graphile-build'; import { Logger } from '@pgpmjs/logger'; +import { QuoteUtils } from '@pgsql/quotes'; import { access, context as grafastContext, lambda, object } from 'grafast'; import type { GraphileConfig } from 'graphile-config'; import { withRequestPgClient } from 'graphile-plugin-utils'; @@ -41,6 +42,7 @@ const log = new Logger('graphile-presigned-url:plugin'); const MAX_CONTENT_HASH_LENGTH = 128; const MAX_CONTENT_TYPE_LENGTH = 255; const SHA256_HEX_REGEX = /^[a-f0-9]{64}$/; +const RELEASE_SLOT_PREFIX = 'cas/sha256/'; // --- Helpers --- @@ -159,7 +161,8 @@ export function createPresignedUrlPlugin( // Each @storageFiles table is paired with its @storageBuckets table // through the registry's actual FK relation; a tagged table that cannot // be paired is a provisioning bug and throws at schema build. - const planes = discoverStoragePlanes((build.input as any).pgRegistry as any); + const registry = (build.input as any).pgRegistry; + const planes = discoverStoragePlanes(registry); if (planes.length === 0) return fields; @@ -472,6 +475,104 @@ export function createPresignedUrlPlugin( }, }, ); + + for (const siteCodec of Object.values(registry.pgCodecs) as any[]) { + const scope = siteCodec.extensions?.tags?.siteUploads; + if (scope !== 'platform' && scope !== 'database') continue; + const refs = Object.values(registry.pgRelations[siteCodec.name] ?? {}) as any[]; + if (!refs.some((ref) => + !ref.isReferencee && ref.localAttributes.length === 1 && + ref.localAttributes[0] === 'bucket_id' && ref.remoteResource?.codec === matchingBucketCodec, + )) continue; + const site = siteCodec.extensions.pg; + const sites = QuoteUtils.quoteQualifiedIdentifier(site.schemaName, site.name); + const stem = scope === 'platform' ? 'PlatformSiteFile' : 'SiteFile'; + const name = `upload${stem}s`; + const SiteFilePayload = new GraphQLObjectType({ + name: `${stem}UploadResult`, + fields: { + ...BulkFilePayloadType.toConfig().fields, + key: { type: GraphQLString }, + fileId: { type: GraphQLString }, + logicalKey: { type: new GraphQLNonNull(GraphQLString) }, + pending: { type: GraphQLBoolean }, + }, + }); + const SitePayload = new GraphQLObjectType({ + name: `${stem}UploadPayload`, + fields: { files: { type: new GraphQLList(new GraphQLNonNull(SiteFilePayload)) } }, + }); + const FileInput = new GraphQLInputObjectType({ + name: `Upload${stem}Input`, + fields: { + contentHash: { type: new GraphQLNonNull(GraphQLString) }, + contentType: { type: new GraphQLNonNull(GraphQLString) }, + size: { type: new GraphQLNonNull(GraphQLInt) }, + filename: { type: GraphQLString }, + route: { type: GraphQLString, description: 'Mutable route. Omit for release content.' }, + }, + }); + const Input = new GraphQLInputObjectType({ + name: `Upload${stem}BulkInput`, + fields: { + siteId: { type: new GraphQLNonNull(uuidGqlType) }, + files: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(FileInput))) }, + checkOnly: { type: GraphQLBoolean, description: 'Read upload status without issuing PUT URLs.' }, + }, + }); + newFields[name] = context.fieldWithHooks({ fieldName: name } as any, { + type: SitePayload, + args: { input: { type: new GraphQLNonNull(Input) } }, + plan(_$mutation: any, fieldArgs: any) { + const $input = fieldArgs.getRaw('input'); + return lambda(object({ + siteId: access($input, 'siteId'), + files: access($input, 'files'), + checkOnly: access($input, 'checkOnly'), + withPgClient: (grafastContext() as any).get('withPgClient'), + pgSettings: (grafastContext() as any).get('pgSettings'), + }), (vals: any) => withRequestPgClient(vals.withPgClient, vals.pgSettings, async (txClient) => { + const databaseId = await resolveDatabaseId(txClient); + if (!databaseId) throw new Error('DATABASE_NOT_FOUND'); + const configs = await loadAllStorageModules(txClient, databaseId); + const config = resolveStorageConfigFromCodec(capturedFilesCodec, configs); + if (!config) throw new Error('STORAGE_MODULE_NOT_FOUND'); + const { rows } = await txClient.query({ + text: `SELECT b.id, b.key, b.type, b.is_public, b.allowed_mime_types, + b.max_file_size, b.allow_custom_keys, b.physical_name + FROM ${sites} AS s + JOIN ${config.bucketsQualifiedName} AS b ON b.id = s.bucket_id + WHERE s.id = $1::uuid AND b.is_public + ${vals.checkOnly ? 'FOR SHARE OF s' : 'FOR UPDATE OF s'}`, + values: [vals.siteId], + }); + const bucket = rows[0] as unknown as BucketConfig | undefined; + if (!bucket) throw new Error('SITE_UPLOAD_NOT_AUTHORIZED'); + const files = vals.files as any[]; + if (files.length > config.maxBulkFiles) throw new Error('BULK_UPLOAD_FILES_EXCEEDED'); + if (files.reduce((sum, file) => sum + file.size, 0) > config.maxBulkTotalSize) { + throw new Error('BULK_UPLOAD_SIZE_EXCEEDED'); + } + if (!vals.checkOnly && files.some((file) => file.route == null)) { + await txClient.query({ + text: "SELECT pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended('site-release:' || $1::text, 0))", + values: [bucket.id], + }); + } + const s3 = resolveS3ForDatabase(options, config, assertBucketReconciled(bucket, databaseId)); + const results = []; + for (const file of files) { + results.push(await processSingleFile( + options, txClient, config, databaseId, bucket, s3, + { ...file, key: file.route }, + { release: file.route == null, checkOnly: vals.checkOnly === true }, + )); + } + return { files: results }; + })); + }, + }); + } } return build.extend( @@ -495,6 +596,7 @@ export async function processSingleFile( bucket: BucketConfig, s3ForDb: S3Config, input: any, + siteUpload?: { release: boolean; checkOnly: boolean }, ) { const { contentHash, contentType, size, filename, key: customKey } = input; @@ -557,15 +659,40 @@ export async function processSingleFile( // The user names a logical slot, never an object-store location. Only the // recorder allocates the physical key, independently for every new request. - const logicalKey = customKey || contentHash; - if (customKey) { - if (!bucket.allow_custom_keys) { + const logicalKey = siteUpload?.release ? RELEASE_SLOT_PREFIX + contentHash : customKey || contentHash; + if (customKey || (siteUpload && !siteUpload.release)) { + if (!customKey) throw new Error('INVALID_ROUTE'); + if (customKey.startsWith(RELEASE_SLOT_PREFIX)) { + throw new Error('RESERVED_RELEASE_SLOT'); + } + if (!siteUpload && !bucket.allow_custom_keys) { throw new Error('CUSTOM_KEY_NOT_ALLOWED: bucket does not allow custom keys'); } const keyError = validateCustomKey(customKey); if (keyError) throw new Error(keyError); } + if (siteUpload?.release || siteUpload?.checkOnly) { + const { rows } = await txClient.query({ + text: `SELECT id, key, status::text AS status + FROM ${storageConfig.filesQualifiedName} + WHERE logical_key = $1 AND bucket_id = $2 AND content_hash = $3 + AND NOT logical_key_retired AND status IN ('requested', 'uploaded', 'processed') + ORDER BY CASE WHEN status = 'requested' THEN 1 ELSE 0 END LIMIT 1`, + values: [logicalKey, bucket.id, contentHash], + }); + const row = rows[0]; + if (row) { + return { + uploadUrl: null as string | null, uploadHeaders: null as Record | null, + fileId: row.id, key: row.key, logicalKey, + deduplicated: row.status !== 'requested', pending: row.status === 'requested', + expiresAt: null as string | null, file: projectFile(row.id, row.key), + }; + } + if (siteUpload.checkOnly) return { logicalKey, deduplicated: false, pending: false }; + } + // Dedup is a read of confirmed identical content in the same logical slot. // It issues no PUT URL. Pending/rejected attempts are not reused or deleted: // each retry gets its own object and lifecycle, including its expiry/GC. @@ -585,6 +712,7 @@ export async function processSingleFile( uploadHeaders: null as Record | null, fileId: existing.id as string, key: existing.key as string, + logicalKey, deduplicated: true, expiresAt: null as string | null, file: projectFile(existing.id as string, existing.key as string), @@ -625,6 +753,7 @@ export async function processSingleFile( uploadHeaders, fileId, key: s3Key, + logicalKey, deduplicated: false, expiresAt, file: projectFile(fileId, s3Key), diff --git a/graphile/graphile-presigned-url-plugin/src/s3-signer.ts b/graphile/graphile-presigned-url-plugin/src/s3-signer.ts index cccc05866e..e6d925ac54 100644 --- a/graphile/graphile-presigned-url-plugin/src/s3-signer.ts +++ b/graphile/graphile-presigned-url-plugin/src/s3-signer.ts @@ -108,6 +108,7 @@ export async function generatePresignedPutUrl( try { url = await getSignedUrl(s3Config.client as any, command, { expiresIn, + signableHeaders: new Set(['content-type']), ...(unhoistableHeaders.size > 0 ? { unhoistableHeaders } : {}), }); } catch (err) { diff --git a/packages/site-deploy/README.md b/packages/site-deploy/README.md index e267b33064..99efe21c81 100644 --- a/packages/site-deploy/README.md +++ b/packages/site-deploy/README.md @@ -14,9 +14,9 @@ Deploy a static build as an immutable Constructive release. -A deploy is **bytes plus one manifest**: every file's bytes go to the site's -bucket at `cas/sha256/`, and one `siteRelease` row maps logical paths to -those hashes. Writing that row commits the manifest into the site's own merkle +A deploy is **bytes plus one manifest**: the site-scoped upload mutation +registers each hash in the site's bucket and allocates a managed object key. +One `siteRelease` row maps logical paths to those hashes. Writing that row commits the manifest into the site's own merkle store, so the returned commit id *is* the release — publishing, rolling back and previewing are pointer moves the server owns. @@ -68,7 +68,8 @@ await publishCommit(api, deployNames(), siteId, previousCommitId); 3. **Registers the bytes** in batches (`batchSize`, default 100) and PUTs only the files the server reports as *not* deduplicated, with bounded concurrency and retries — so a one-file change re-uploads one file. -4. **Verifies** every returned key is the `cas/sha256/` it asked for. +4. **Checks** that each returned logical slot matches the declared hash and + waits for new or in-flight uploads to be confirmed before writing the manifest. 5. **Writes the manifest**: creates the site's release row on the first deploy, patches it after, and asserts the trigger stamped a `commitId`/`storeId`. 6. **Optionally publishes** and/or points `preview/` at the new commit, as diff --git a/packages/site-deploy/__tests__/deploy.test.ts b/packages/site-deploy/__tests__/deploy.test.ts index c7a7db4728..bfe31d0ae5 100644 --- a/packages/site-deploy/__tests__/deploy.test.ts +++ b/packages/site-deploy/__tests__/deploy.test.ts @@ -138,7 +138,8 @@ describe('deploySite', () => { batchSize: 10, }); - expect(server.countOf('uploadSiteFiles')).toBe(3); + expect(server.calls.filter((call) => call.operation === 'uploadSiteFiles' && + !(call.variables.input as { checkOnly?: boolean }).checkOnly)).toHaveLength(3); expect(server.puts).toHaveLength(25); }); @@ -157,6 +158,7 @@ describe('deploySite', () => { expect(server.calls.map((c) => c.operation)).toEqual([ 'siteReleases', 'uploadSiteFiles', + 'uploadSiteFiles', 'createSiteRelease', 'updateSite', ]); @@ -253,7 +255,7 @@ describe('deploySite', () => { expect(result.uploaded).toBe(1); }); - it('fails before uploading when the server returns a non-CAS key', async () => { + it('fails before uploading when the server returns a fixed CAS object key', async () => { const server = createMockServer({ corruptKeyFor: 'index.html' }); await expect( deploySite({ ...base, api: server.api, putObject: server.putObject, source: build }), @@ -319,7 +321,7 @@ describe('deploySite', () => { skipped: 2, }); expect(server.countOf('updateSiteRelease')).toBe(0); - expect(server.countOf('uploadSiteFiles')).toBe(1); + expect(server.countOf('uploadSiteFiles')).toBe(2); }); it('commits again when the tree changed even with skipIfUnchanged', async () => { @@ -350,6 +352,7 @@ describe('deploySite', () => { expect(result.files).toBe(2); expect(server.puts).toHaveLength(0); expect(server.release).toBeNull(); + expect(server.firstCall('uploadSiteFiles')).toMatchObject({ input: { checkOnly: true } }); }); it('skips ignored paths', async () => { diff --git a/packages/site-deploy/__tests__/manifest.test.ts b/packages/site-deploy/__tests__/manifest.test.ts index 98b46431cd..c89f74b9f0 100644 --- a/packages/site-deploy/__tests__/manifest.test.ts +++ b/packages/site-deploy/__tests__/manifest.test.ts @@ -38,8 +38,8 @@ describe('normalizePath', () => { expect(() => normalizePath('../secrets.env')).toThrow(DeployError); }); - it('rejects logical paths that would shadow the byte namespace', () => { - expect(() => normalizePath(`cas/sha256/${HELLO_WORLD}`)).toThrow(/byte namespace/); + it('rejects logical paths reserved for release slots', () => { + expect(() => normalizePath(`cas/sha256/${HELLO_WORLD}`)).toThrow(/reserved for release slots/); }); }); diff --git a/packages/site-deploy/__tests__/mock-api.ts b/packages/site-deploy/__tests__/mock-api.ts index 6f6406a4dc..cce85d622c 100644 --- a/packages/site-deploy/__tests__/mock-api.ts +++ b/packages/site-deploy/__tests__/mock-api.ts @@ -86,13 +86,18 @@ export function createMockServer(options: MockServerOptions = {}): MockServer { uploadSiteFiles: { files: (input.files as any[]).map((file) => { const deduplicated = stored.has(file.contentHash); + const logicalKey = casKey(file.contentHash); + if (input.checkOnly && !deduplicated) { + return { logicalKey, key: null as string | null, deduplicated: false, pending: false }; + } const key = file.filename === options.corruptKeyFor - ? 'uploads/wrong-key' - : casKey(file.contentHash); + ? casKey(file.contentHash) + : `originals/${file.contentHash}`; return { fileId: `file-${file.contentHash.slice(0, 8)}`, key, + logicalKey, deduplicated, uploadUrl: deduplicated ? null : `https://s3.test/put/${file.contentHash}`, uploadHeaders: deduplicated ? null : signedHeaders(file), diff --git a/packages/site-deploy/src/cas-upload.ts b/packages/site-deploy/src/cas-upload.ts index ec80b86455..f8601402e5 100644 --- a/packages/site-deploy/src/cas-upload.ts +++ b/packages/site-deploy/src/cas-upload.ts @@ -12,7 +12,7 @@ import { putToPresignedUrl } from '@constructive-io/upload-client'; import { buildBulkUploadMutation } from './documents'; import type { HashedFile } from './manifest'; -import { CAS_KEY_PATTERN } from './manifest'; +import { CAS_PREFIX } from './manifest'; import type { GraphQLExecutor, PutObject } from './types'; import { DeployError } from './types'; @@ -21,8 +21,10 @@ interface BulkFilePayload { uploadUrl: string | null; uploadHeaders: Record | null; fileId: string; - key: string; + key: string | null; + logicalKey: string; deduplicated: boolean; + pending?: boolean | null; } export interface UploadCasOptions { @@ -40,7 +42,7 @@ export interface UploadCasOptions { retries: number; putObject?: PutObject; signal?: AbortSignal; - onUploaded?: (file: HashedFile) => void; + onUploaded?: (file: HashedFile, physicalKey: string) => void; } export interface UploadCasResult { @@ -52,9 +54,11 @@ export interface UploadCasResult { /** The bytes the server does not have yet, as told by the bulk mutation. */ export interface CasDiff { /** Files whose bytes must be PUT, paired with their presigned URL and the headers it is signed over. */ - missing: { file: HashedFile; uploadUrl: string; uploadHeaders: Record }[]; + missing: { file: HashedFile; physicalKey: string; uploadUrl: string; uploadHeaders: Record }[]; /** Files the server already had. */ deduplicated: HashedFile[]; + pending: HashedFile[]; + absent: HashedFile[]; } /** @@ -66,10 +70,13 @@ export interface CasDiff { export async function diffCas( files: HashedFile[], options: UploadCasOptions, + checkOnly = false, ): Promise { const mutation = buildBulkUploadMutation(options.mutation); const missing: CasDiff['missing'] = []; const deduplicated: HashedFile[] = []; + const pending: HashedFile[] = []; + const absent: HashedFile[] = []; for (let offset = 0; offset < files.length; offset += options.batchSize) { throwIfAborted(options.signal); @@ -77,6 +84,7 @@ export async function diffCas( const data = await options.storage(mutation, { input: { siteId: options.siteId, + ...(checkOnly ? { checkOnly } : {}), files: batch.map((file) => ({ contentHash: file.hash, contentType: file.contentType, @@ -97,13 +105,21 @@ export async function diffCas( results.forEach((result, index) => { const file = batch[index]; - // A mismatch would publish a manifest pointing at bytes nobody can serve. - if (result.key !== file.key || !CAS_KEY_PATTERN.test(result.key)) { + if (result.logicalKey !== file.key || result.key?.startsWith(CAS_PREFIX)) { throw new DeployError( 'KEY_MISMATCH', - `Expected key "${file.key}" for "${file.path}", server returned "${result.key}"`, + `Unexpected logical or object key for "${file.path}"`, ); } + if (checkOnly && !result.key && !result.deduplicated && !result.pending) { + absent.push(file); + return; + } + if (!result.key) throw new DeployError('KEY_MISMATCH', `Missing object key for "${file.path}"`); + if (result.pending) { + pending.push(file); + return; + } if (result.deduplicated) { deduplicated.push(file); return; @@ -114,11 +130,30 @@ export async function diffCas( `No upload URL or upload headers for "${file.path}" and deduplicated=false`, ); } - missing.push({ file, uploadUrl: result.uploadUrl, uploadHeaders: result.uploadHeaders }); + missing.push({ file, physicalKey: result.key, uploadUrl: result.uploadUrl, uploadHeaders: result.uploadHeaders }); }); } - return { missing, deduplicated }; + return { missing, deduplicated, pending, absent }; +} + +/** Wait for the worker to verify each new or already-in-flight upload before publishing. */ +export async function waitForConfirmation(files: HashedFile[], options: UploadCasOptions): Promise { + const deadline = Date.now() + 120_000; + let pending = files; + while (pending.length) { + const result = await diffCas(pending, options, true); + if (result.missing.length) throw new DeployError('UPLOAD_FAILED', 'Status check returned a PUT URL'); + if (result.absent.length) { + throw new DeployError('UPLOAD_FAILED', `No active upload for "${result.absent[0].path}"`); + } + pending = result.pending; + if (!pending.length) return; + if (Date.now() >= deadline) { + throw new DeployError('UPLOAD_FAILED', `Confirmation timed out for "${pending[0].path}"`); + } + await new Promise((resolve) => setTimeout(resolve, 1000)); + } } /** @@ -140,7 +175,7 @@ export async function uploadMissing( throwIfAborted(options.signal); const index = next++; if (index >= diff.missing.length) return; - const { file, uploadUrl, uploadHeaders } = diff.missing[index]; + const { file, physicalKey, uploadUrl, uploadHeaders } = diff.missing[index]; await withRetries( () => put(uploadUrl, file.bytes, file.contentType, options.signal, file.hash, uploadHeaders), options.retries, @@ -148,7 +183,7 @@ export async function uploadMissing( options.signal, ); bytesUploaded += file.size; - options.onUploaded?.(file); + options.onUploaded?.(file, physicalKey); } }; @@ -157,7 +192,7 @@ export async function uploadMissing( return { uploaded: diff.missing.length, - skipped: diff.deduplicated.length, + skipped: diff.deduplicated.length + diff.pending.length, bytesUploaded, }; } diff --git a/packages/site-deploy/src/deploy.ts b/packages/site-deploy/src/deploy.ts index bc3375f04e..3545bb54c1 100644 --- a/packages/site-deploy/src/deploy.ts +++ b/packages/site-deploy/src/deploy.ts @@ -11,7 +11,7 @@ * live site exactly as it was. */ -import { diffCas, errorMessage, throwIfAborted, uploadMissing } from './cas-upload'; +import { diffCas, errorMessage, throwIfAborted, uploadMissing, waitForConfirmation } from './cas-upload'; import { buildCreateReleaseMutation, buildProvisionPreviewMutation, @@ -136,13 +136,14 @@ export async function deploySite(options: DeploySiteOptions): Promise file); onProgress?.({ type: 'diffed', files: manifest.file_count, - toUpload: diff.missing.length, + toUpload: toUpload.length, skipped: diff.deduplicated.length, - bytesToUpload: diff.missing.reduce((sum, entry) => sum + entry.file.size, 0), + bytesToUpload: toUpload.reduce((sum, file) => sum + file.size, 0), }); if (dryRun) { @@ -166,18 +167,19 @@ export async function deploySite(options: DeploySiteOptions): Promise { + onUploaded: (file, physicalKey) => { done += 1; onProgress?.({ type: 'uploaded', path: file.path, - key: file.key, + key: physicalKey, size: file.size, done, total: diff.missing.length, }); }, }); + await waitForConfirmation([...diff.missing.map(({ file }) => file), ...diff.pending], uploadOptions); // 5. Write the manifest — this is the commit. const release = existing diff --git a/packages/site-deploy/src/documents.ts b/packages/site-deploy/src/documents.ts index f91d8f04af..64b3fa6890 100644 --- a/packages/site-deploy/src/documents.ts +++ b/packages/site-deploy/src/documents.ts @@ -47,7 +47,9 @@ export function buildBulkUploadMutation(mutation: string): string { uploadHeaders fileId key + logicalKey deduplicated + pending } } } diff --git a/packages/site-deploy/src/manifest.ts b/packages/site-deploy/src/manifest.ts index f3f3d532f5..c1590b9ccb 100644 --- a/packages/site-deploy/src/manifest.ts +++ b/packages/site-deploy/src/manifest.ts @@ -14,13 +14,13 @@ import { contentTypeFor } from './content-type'; import type { DeployFile, ManifestEntry, ReleaseManifest } from './types'; import { DeployError } from './types'; -/** Prefix every file's bytes are stored under, in the site's own bucket. */ +/** Namespace reserved for release logical slots in the site's bucket. */ export const CAS_PREFIX = 'cas/sha256/'; /** The one legal shape of a CAS key. */ export const CAS_KEY_PATTERN = /^cas\/sha256\/[0-9a-f]{64}$/; -/** The content-addressed bucket key holding the bytes with this hash. */ +/** The logical release slot for this hash, not an object-store key. */ export function casKey(hash: string): string { return `${CAS_PREFIX}${hash}`; } @@ -52,7 +52,7 @@ export function normalizePath(path: string): string { if (normalized.startsWith(CAS_PREFIX)) { throw new DeployError( 'INVALID_PATH', - `Logical path must not start with "${CAS_PREFIX}" (that is the byte namespace): "${path}"`, + `Logical path must not start with "${CAS_PREFIX}" (reserved for release slots): "${path}"`, ); } return normalized; @@ -62,7 +62,7 @@ export function normalizePath(path: string): string { export interface HashedFile { /** Normalized logical path. */ path: string; - /** Content-addressed bucket key for these bytes. */ + /** Logical release slot for these bytes. */ key: string; hash: string; contentType: string; diff --git a/packages/site-deploy/src/types.ts b/packages/site-deploy/src/types.ts index 4aefc87f6e..864c83973e 100644 --- a/packages/site-deploy/src/types.ts +++ b/packages/site-deploy/src/types.ts @@ -2,7 +2,7 @@ * Types for the site deploy pipeline. * * A deploy is bytes plus one manifest: every file's bytes live in the site's - * bucket at `cas/sha256/`, and one `siteRelease` row maps logical paths + * bucket under an independently allocated key, and one `siteRelease` row maps logical paths * to those hashes. Writing that row commits it into the site's own merkle * store, so the returned commit id *is* the release id. */ From cc23cda10982d781505ad62082f816dded97cad0 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Mon, 23 Nov 2026 17:46:53 +0000 Subject: [PATCH 4/8] fix(storage): retain confirmed dedup diagnostics --- graphile/graphile-presigned-url-plugin/src/plugin.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/graphile/graphile-presigned-url-plugin/src/plugin.ts b/graphile/graphile-presigned-url-plugin/src/plugin.ts index 615ee3ca7e..41778c5997 100644 --- a/graphile/graphile-presigned-url-plugin/src/plugin.ts +++ b/graphile/graphile-presigned-url-plugin/src/plugin.ts @@ -707,6 +707,7 @@ export async function processSingleFile( }); if (existingResult.rows.length > 0) { const existing = existingResult.rows[0]; + log.info(`Dedup hit: file ${existing.id} for hash ${contentHash}`); return { uploadUrl: null as string | null, uploadHeaders: null as Record | null, From c92567562583937b0d6df04632fab35d59ebd332 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Mon, 23 Nov 2026 19:01:25 +0000 Subject: [PATCH 5/8] fix(storage): reissue pending site release uploads --- .../__tests__/dedup-liveness.test.ts | 44 +++++++++++++++++++ .../src/plugin.ts | 39 +++++++++------- 2 files changed, 66 insertions(+), 17 deletions(-) diff --git a/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts b/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts index 0611f9d4be..0ffb80a9ae 100644 --- a/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts +++ b/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts @@ -23,6 +23,7 @@ jest.mock('../src/s3-signer', () => ({ import { HeadObjectCommand } from '@aws-sdk/client-s3'; import { processSingleFile } from '../src/plugin'; +import { generatePresignedPutUrl } from '../src/s3-signer'; import type { BucketConfig, PresignedUrlPluginOptions, S3Config, StorageModuleConfig } from '../src/types'; const BUCKET_ID = '33333333-3333-3333-3333-333333333333'; @@ -168,3 +169,46 @@ describe('content-addressed upload whose hash a custom-key row carries', () => { expect(queries.some((q) => /^DELETE/.test(q.text))).toBe(false); }); }); + +describe('site release requested before the deploy was canceled', () => { + const retry = async (checkOnly: boolean, ageSeconds = 60) => { + const key = `originals/${OLD_FILE_ID}`; + const txClient = { + query: jest.fn().mockResolvedValueOnce({ + rows: [{ id: OLD_FILE_ID, key, status: 'requested', mime_type: 'text/html', size: '16', + created_at: new Date(Date.now() - ageSeconds * 1000) }], + }), + }; + const s3 = fakeS3(); + const result = await processSingleFile(options, txClient, storageConfig(), 'db', bucket, s3, + { contentHash: HASH, contentType: 'text/html', size: 16, filename: SITE_KEY }, + { release: true, checkOnly }); + expect(txClient.query).toHaveBeenCalledTimes(1); + expect(heads(s3)).toEqual([]); + return { result, key, s3 }; + }; + + beforeEach(() => jest.mocked(generatePresignedPutUrl).mockClear()); + + it('reissues a PUT for the same managed row and only for its remaining lifetime', async () => { + const { result, key, s3 } = await retry(false); + expect(result).toMatchObject({ fileId: OLD_FILE_ID, key, deduplicated: false, uploadUrl: 'https://s3.example.com/put' }); + expect(result.pending).not.toBe(true); + expect(result.uploadHeaders).toMatchObject({ 'x-amz-meta-upload-id': OLD_FILE_ID, 'Content-Type': 'text/html' }); + const ttl = jest.mocked(generatePresignedPutUrl).mock.calls[0][4]!; + expect(ttl).toBeGreaterThanOrEqual(839); + expect(ttl).toBeLessThanOrEqual(840); + expect(generatePresignedPutUrl).toHaveBeenCalledWith(s3, key, 'text/html', 16, ttl, HASH, OLD_FILE_ID); + }); + + it('does not sign during a confirmation-only poll', async () => { + const { result } = await retry(true); + expect(result).toMatchObject({ fileId: OLD_FILE_ID, pending: true, uploadUrl: null }); + expect(generatePresignedPutUrl).not.toHaveBeenCalled(); + }); + + it('does not reissue a PUT after the original confirmation deadline', async () => { + await expect(retry(false, 900)).rejects.toThrow('SITE_RELEASE_UPLOAD_EXPIRED'); + expect(generatePresignedPutUrl).not.toHaveBeenCalled(); + }); +}); diff --git a/graphile/graphile-presigned-url-plugin/src/plugin.ts b/graphile/graphile-presigned-url-plugin/src/plugin.ts index 41778c5997..8ab77a2783 100644 --- a/graphile/graphile-presigned-url-plugin/src/plugin.ts +++ b/graphile/graphile-presigned-url-plugin/src/plugin.ts @@ -657,6 +657,12 @@ export async function processSingleFile( const projectFile = (fileId: string, key: string): FileProjection => buildFileProjection({ id: fileId, key, bucketId: bucket.id, mime: contentType, size, filename }); + const signUpload = async (fileId: string, key: string, mime: string, bytes: number, ttl: number) => ({ + uploadUrl: await generatePresignedPutUrl(s3ForDb, key, mime, bytes, ttl, contentHash, fileId), + uploadHeaders: presignedPutHeaders(mime, contentHash, fileId), + expiresAt: new Date(Date.now() + ttl * 1000).toISOString(), + }); + // The user names a logical slot, never an object-store location. Only the // recorder allocates the physical key, independently for every new request. const logicalKey = siteUpload?.release ? RELEASE_SLOT_PREFIX + contentHash : customKey || contentHash; @@ -674,7 +680,7 @@ export async function processSingleFile( if (siteUpload?.release || siteUpload?.checkOnly) { const { rows } = await txClient.query({ - text: `SELECT id, key, status::text AS status + text: `SELECT id, key, status::text AS status, mime_type, size, filename, created_at FROM ${storageConfig.filesQualifiedName} WHERE logical_key = $1 AND bucket_id = $2 AND content_hash = $3 AND NOT logical_key_retired AND status IN ('requested', 'uploaded', 'processed') @@ -683,6 +689,20 @@ export async function processSingleFile( }); const row = rows[0]; if (row) { + if (row.status === 'requested' && !siteUpload.checkOnly) { + const deadline = new Date(row.created_at).getTime() + storageConfig.uploadUrlExpirySeconds * 1000; + const remainingSeconds = Math.floor((deadline - Date.now()) / 1000); + if (remainingSeconds <= 0) throw new Error('SITE_RELEASE_UPLOAD_EXPIRED'); + return { + ...await signUpload(row.id, row.key, row.mime_type, Number(row.size), remainingSeconds), + fileId: row.id, key: row.key, logicalKey, + deduplicated: false, pending: false, + file: buildFileProjection({ + id: row.id, key: row.key, bucketId: bucket.id, + mime: row.mime_type, size: Number(row.size), filename: row.filename, + }), + }; + } return { uploadUrl: null as string | null, uploadHeaders: null as Record | null, fileId: row.id, key: row.key, logicalKey, @@ -736,27 +756,12 @@ export async function processSingleFile( // Generate presigned PUT URL, signed over the client's SHA-256 so the store // only accepts bytes that hash to the content hash on this row and any // later dedup hit. Neither logical keys nor checksums locate the object. - const uploadUrl = await generatePresignedPutUrl( - s3ForDb, - s3Key, - contentType, - size, - storageConfig.uploadUrlExpirySeconds, - contentHash, - fileId, - ); - const uploadHeaders = presignedPutHeaders(contentType, contentHash, fileId); - - const expiresAt = new Date(Date.now() + storageConfig.uploadUrlExpirySeconds * 1000).toISOString(); - return { - uploadUrl, - uploadHeaders, + ...await signUpload(fileId, s3Key, contentType, size, storageConfig.uploadUrlExpirySeconds), fileId, key: s3Key, logicalKey, deduplicated: false, - expiresAt, file: projectFile(fileId, s3Key), }; } From 737a58d059f44b31f123ff4b462faa1db762d23c Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Mon, 23 Nov 2026 19:01:25 +0000 Subject: [PATCH 6/8] fix(site-deploy): send site uploads to the site API --- examples/site-deploy-ssg/__tests__/mock-server.ts | 7 ++++--- .../site-deploy-ssg/__tests__/ssg-deploy.test.ts | 2 +- examples/site-deploy-ssg/src/deploy.ts | 3 --- packages/site-deploy/README.md | 3 +++ packages/site-deploy/__tests__/deploy.test.ts | 14 ++++++++++++++ packages/site-deploy/src/deploy.ts | 3 +-- packages/site-deploy/src/types.ts | 4 +--- 7 files changed, 24 insertions(+), 12 deletions(-) diff --git a/examples/site-deploy-ssg/__tests__/mock-server.ts b/examples/site-deploy-ssg/__tests__/mock-server.ts index 0f84fb6c96..2da5c7959c 100644 --- a/examples/site-deploy-ssg/__tests__/mock-server.ts +++ b/examples/site-deploy-ssg/__tests__/mock-server.ts @@ -20,7 +20,7 @@ interface ReleaseRow { export interface MockServer { api: GraphQLExecutor; putObject: PutObject; - /** CAS keys whose bytes the bucket holds. */ + /** Managed object keys whose bytes the bucket holds. */ storedKeys: string[]; /** Hashes the bucket holds, as dedupe sees them. */ storedHashes: Set; @@ -47,7 +47,7 @@ export function createMockServer(): MockServer { assertSignedHeaders(url, headers); const hash = url.slice(url.lastIndexOf('/') + 1); hashes.add(hash); - server.storedKeys.push(`cas/sha256/${hash}`); + server.storedKeys.push(`originals/${hash}`); void body; void contentType; }, @@ -63,7 +63,8 @@ export function createMockServer(): MockServer { const deduplicated = hashes.has(file.contentHash); return { fileId: `file-${file.contentHash.slice(0, 8)}`, - key: `cas/sha256/${file.contentHash}`, + key: `originals/${file.contentHash}`, + logicalKey: `cas/sha256/${file.contentHash}`, deduplicated, uploadUrl: deduplicated ? null : `https://s3.test/put/${file.contentHash}`, uploadHeaders: deduplicated ? null : signedHeaders(file), diff --git a/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts b/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts index d80b63324d..cfaec4b7dd 100644 --- a/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts +++ b/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts @@ -81,7 +81,7 @@ test('deploys the build to a play preview without touching production', async () // Bytes are addressed by content, and the manifest carries served types. expect(server.storedKeys).toHaveLength(5); - for (const key of server.storedKeys) expect(key).toMatch(/^cas\/sha256\/[0-9a-f]{64}$/); + for (const key of server.storedKeys) expect(key).toMatch(/^originals\/[0-9a-f]{64}$/); expect(result.manifest.files['assets/site.css'].content_type).toBe('text/css; charset=utf-8'); expect(result.manifest.files['index.html'].content_type).toBe('text/html; charset=utf-8'); }); diff --git a/examples/site-deploy-ssg/src/deploy.ts b/examples/site-deploy-ssg/src/deploy.ts index c6e26cdd33..3805b2e0c4 100644 --- a/examples/site-deploy-ssg/src/deploy.ts +++ b/examples/site-deploy-ssg/src/deploy.ts @@ -81,9 +81,6 @@ async function main(): Promise { const api = fetchExecutor(required('CONSTRUCTIVE_API_URL'), process.env.CONSTRUCTIVE_TOKEN); const result = await deploySite({ api, - storage: process.env.CONSTRUCTIVE_STORAGE_URL - ? fetchExecutor(process.env.CONSTRUCTIVE_STORAGE_URL, process.env.CONSTRUCTIVE_TOKEN) - : undefined, siteId: required('SITE_ID'), databaseId: process.env.DATABASE_ID, source: dist, diff --git a/packages/site-deploy/README.md b/packages/site-deploy/README.md index 99efe21c81..2d29e67a05 100644 --- a/packages/site-deploy/README.md +++ b/packages/site-deploy/README.md @@ -25,6 +25,9 @@ write itself: walk, hash, upload only what is missing, and commit one manifest. ## Usage +Use the site API endpoint that exposes both the site upload and release +mutations. A storage-only GraphQL endpoint does not expose those site mutations. + ```typescript import { deploySite } from '@constructive-io/site-deploy'; diff --git a/packages/site-deploy/__tests__/deploy.test.ts b/packages/site-deploy/__tests__/deploy.test.ts index bfe31d0ae5..4f119dde30 100644 --- a/packages/site-deploy/__tests__/deploy.test.ts +++ b/packages/site-deploy/__tests__/deploy.test.ts @@ -58,6 +58,20 @@ describe('deploySite', () => { }); }); + it('sends site uploads to the same endpoint as release mutations', async () => { + const server = createMockServer(); + const storageOnly = jest.fn(async () => { + throw new Error('Cannot query field "uploadSiteFiles" on type "Mutation".'); + }); + const options = { ...base, api: server.api, storage: storageOnly, putObject: server.putObject, source: build }; + + await deploySite(options); + + expect(storageOnly).not.toHaveBeenCalled(); + expect(server.countOf('uploadSiteFiles')).toBeGreaterThan(0); + expect(server.countOf('createSiteRelease')).toBe(1); + }); + it('patches the existing row on later deploys instead of creating a second one', async () => { const server = createMockServer({ release: { diff --git a/packages/site-deploy/src/deploy.ts b/packages/site-deploy/src/deploy.ts index 3545bb54c1..451ad0153c 100644 --- a/packages/site-deploy/src/deploy.ts +++ b/packages/site-deploy/src/deploy.ts @@ -56,7 +56,6 @@ interface ExistingRelease { export async function deploySite(options: DeploySiteOptions): Promise { const { api, - storage = options.api, siteId, databaseId, scope = 'database', @@ -127,7 +126,7 @@ export async function deploySite(options: DeploySiteOptions): Promise Promise; export interface DeploySiteOptions { - /** Executor for the tenant API target (releases, sites, previews). */ + /** Executor for the site API target (site uploads, releases, and previews). */ api: GraphQLExecutor; - /** Executor for the storage target. Defaults to `api`. */ - storage?: GraphQLExecutor; /** The site to deploy to. */ siteId: string; /** From d48929eb3d87d129e11456659ddc15febfc5c699 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Mon, 23 Nov 2026 19:53:11 +0000 Subject: [PATCH 7/8] fix: reissue PUTs for releases with subsecond lifetime --- .../__tests__/dedup-liveness.test.ts | 33 +++++++++++++++++++ .../src/plugin.ts | 7 ++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts b/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts index 0ffb80a9ae..8fd161c681 100644 --- a/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts +++ b/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts @@ -207,6 +207,39 @@ describe('site release requested before the deploy was canceled', () => { expect(generatePresignedPutUrl).not.toHaveBeenCalled(); }); + it('signs both copies of the same asset in a batch with a one-second lifetime', async () => { + const createdAt = new Date('2026-01-01T00:00:00.000Z'); + const clock = jest.spyOn(Date, 'now').mockReturnValue(createdAt.getTime()); + const key = `originals/${NEW_FILE_ID}`; + const txClient = { + query: jest.fn() + .mockResolvedValueOnce({ rows: [] }) + .mockResolvedValueOnce({ rows: [] }) + .mockResolvedValueOnce({ rows: [{ id: NEW_FILE_ID, key }] }) + .mockResolvedValueOnce({ + rows: [{ id: NEW_FILE_ID, key, status: 'requested', mime_type: 'text/html', size: '16', + filename: 'index.html', created_at: createdAt }], + }), + }; + const config = storageConfig({ uploadUrlExpirySeconds: 1 }); + const s3 = fakeS3(); + const request = (filename: string) => processSingleFile(options, txClient, config, 'db', bucket, s3, + { contentHash: HASH, contentType: 'text/html', size: 16, filename }, + { release: true, checkOnly: false }); + try { + const first = await request('index.html'); + clock.mockReturnValue(createdAt.getTime() + 50); + const second = await request('copy.html'); + + expect(first).toMatchObject({ fileId: NEW_FILE_ID, key, uploadUrl: 'https://s3.example.com/put' }); + expect(second).toMatchObject({ fileId: NEW_FILE_ID, key, uploadUrl: first.uploadUrl, expiresAt: first.expiresAt }); + expect(txClient.query).toHaveBeenCalledTimes(4); + expect(generatePresignedPutUrl).toHaveBeenNthCalledWith(2, s3, key, 'text/html', 16, 1, HASH, NEW_FILE_ID); + } finally { + clock.mockRestore(); + } + }); + it('does not reissue a PUT after the original confirmation deadline', async () => { await expect(retry(false, 900)).rejects.toThrow('SITE_RELEASE_UPLOAD_EXPIRED'); expect(generatePresignedPutUrl).not.toHaveBeenCalled(); diff --git a/graphile/graphile-presigned-url-plugin/src/plugin.ts b/graphile/graphile-presigned-url-plugin/src/plugin.ts index 8ab77a2783..b5a0cd7f8f 100644 --- a/graphile/graphile-presigned-url-plugin/src/plugin.ts +++ b/graphile/graphile-presigned-url-plugin/src/plugin.ts @@ -691,10 +691,11 @@ export async function processSingleFile( if (row) { if (row.status === 'requested' && !siteUpload.checkOnly) { const deadline = new Date(row.created_at).getTime() + storageConfig.uploadUrlExpirySeconds * 1000; - const remainingSeconds = Math.floor((deadline - Date.now()) / 1000); - if (remainingSeconds <= 0) throw new Error('SITE_RELEASE_UPLOAD_EXPIRED'); + const remainingMs = deadline - Date.now(); + if (remainingMs <= 0) throw new Error('SITE_RELEASE_UPLOAD_EXPIRED'); return { - ...await signUpload(row.id, row.key, row.mime_type, Number(row.size), remainingSeconds), + ...await signUpload(row.id, row.key, row.mime_type, Number(row.size), Math.ceil(remainingMs / 1000)), + expiresAt: new Date(deadline).toISOString(), fileId: row.id, key: row.key, logicalKey, deduplicated: false, pending: false, file: buildFileProjection({ From cf7be5f4a41c6951d9d49df9d11ac3874c33e3db Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Tue, 24 Nov 2026 00:10:28 +0000 Subject: [PATCH 8/8] Fix site deploy review regressions --- .../site-deploy-ssg/__tests__/mock-server.ts | 7 +++++- .../__tests__/ssg-deploy.test.ts | 12 ++++++++++ .../__tests__/custom-key-upload.test.ts | 4 +++- .../__tests__/dedup-liveness.test.ts | 23 ++++++++++++++++++- .../src/plugin.ts | 16 +++++++------ packages/site-deploy/__tests__/deploy.test.ts | 19 +++++++++++++++ packages/site-deploy/src/deploy.ts | 1 + 7 files changed, 72 insertions(+), 10 deletions(-) diff --git a/examples/site-deploy-ssg/__tests__/mock-server.ts b/examples/site-deploy-ssg/__tests__/mock-server.ts index 2da5c7959c..dbf2a0c176 100644 --- a/examples/site-deploy-ssg/__tests__/mock-server.ts +++ b/examples/site-deploy-ssg/__tests__/mock-server.ts @@ -61,11 +61,16 @@ export function createMockServer(): MockServer { uploadSiteFiles: { files: (input.files as any[]).map((file) => { const deduplicated = hashes.has(file.contentHash); + const logicalKey = `cas/sha256/${file.contentHash}`; + if (input.checkOnly && !deduplicated) { + return { logicalKey, key: null as string | null, deduplicated: false, pending: false }; + } return { fileId: `file-${file.contentHash.slice(0, 8)}`, key: `originals/${file.contentHash}`, - logicalKey: `cas/sha256/${file.contentHash}`, + logicalKey, deduplicated, + pending: false, uploadUrl: deduplicated ? null : `https://s3.test/put/${file.contentHash}`, uploadHeaders: deduplicated ? null : signedHeaders(file), }; diff --git a/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts b/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts index cfaec4b7dd..f5b08de3be 100644 --- a/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts +++ b/examples/site-deploy-ssg/__tests__/ssg-deploy.test.ts @@ -43,6 +43,18 @@ const deployOptions = (server: ReturnType) => ({ source: dist, }); +test('the mock reports an absent release asset without issuing a PUT URL', async () => { + const server = createMockServer(); + const contentHash = 'a'.repeat(64); + const result = await server.api('mutation { uploadSiteFiles(input: $input) { files { key } } }', { + input: { checkOnly: true, files: [{ contentHash }] }, + }); + + expect(result.uploadSiteFiles).toEqual({ + files: [{ logicalKey: `cas/sha256/${contentHash}`, key: null, deduplicated: false, pending: false }], + }); +}); + test('builds every page, the stylesheet and a 404', async () => { const files = await buildSite(content, dist); expect(files).toEqual([ diff --git a/graphile/graphile-presigned-url-plugin/__tests__/custom-key-upload.test.ts b/graphile/graphile-presigned-url-plugin/__tests__/custom-key-upload.test.ts index ebc02f6b41..211e7312be 100644 --- a/graphile/graphile-presigned-url-plugin/__tests__/custom-key-upload.test.ts +++ b/graphile/graphile-presigned-url-plugin/__tests__/custom-key-upload.test.ts @@ -66,7 +66,9 @@ function fakeTx(existingHash: string, deletable = true, existingStatus = 'upload if (/^SELECT id, (?:key|status)/.test(opts.text) && !/record_file\(/.test(opts.text)) { // The probe is by (key, bucket, hash): a row carrying other bytes is not seen. const probedHash = opts.values[2]; - return { rows: probedHash === existingHash && ['uploaded', 'processed'].includes(existingStatus) ? [{ id: OLD_FILE_ID, key: OLD_KEY, status: existingStatus }] : [] }; + const confirmedOnly = opts.text.includes("status IN ('uploaded', 'processed')"); + return { rows: probedHash === existingHash && (!confirmedOnly || ['uploaded', 'processed'].includes(existingStatus)) + ? [{ id: OLD_FILE_ID, key: OLD_KEY, status: existingStatus, mime_type: 'text/html', size: '16', filename: KEY }] : [] }; } if (/^DELETE FROM storage_public\.app_files/.test(opts.text)) { return { rows: deletable ? [{ id: OLD_FILE_ID }] : [] }; diff --git a/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts b/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts index 8fd161c681..b757873fcf 100644 --- a/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts +++ b/graphile/graphile-presigned-url-plugin/__tests__/dedup-liveness.test.ts @@ -91,7 +91,9 @@ function fakeTx(rowKey: string, status: string, retired = false) { if (/record_file\(/.test(opts.text)) return { rows: [{ id: NEW_FILE_ID, key: `originals/${NEW_FILE_ID}` }] }; if (/^SELECT id/.test(opts.text)) { if (retired && /AND NOT logical_key_retired/.test(opts.text)) return { rows: [] }; - return { rows: opts.values[0] === rowKey && ['uploaded', 'processed'].includes(status) ? [{ id: OLD_FILE_ID, key: `originals/${OLD_FILE_ID}` }] : [] }; + const confirmedOnly = opts.text.includes("status IN ('uploaded', 'processed')"); + return { rows: opts.values[0] === rowKey && (!confirmedOnly || ['uploaded', 'processed'].includes(status)) + ? [{ id: OLD_FILE_ID, key: `originals/${OLD_FILE_ID}`, mime_type: 'text/plain', size: '32', filename: 'original.txt' }] : [] }; } if (/^DELETE FROM storage_public\.app_files/.test(opts.text)) return { rows: [{ id: OLD_FILE_ID }] }; throw new Error(`unexpected query: ${opts.text}`); @@ -140,6 +142,7 @@ describe.each([ const result = await upload(txClient, s3, customKey); expect(result).toMatchObject({ fileId: OLD_FILE_ID, deduplicated: true, uploadUrl: null }); + expect(result.file).toMatchObject({ mime: 'text/plain', size: 32, filename: 'original.txt' }); expect(heads(s3)).toEqual([]); expect(result.file).not.toHaveProperty('url'); expect(queries).toHaveLength(1); @@ -207,6 +210,24 @@ describe('site release requested before the deploy was canceled', () => { expect(generatePresignedPutUrl).not.toHaveBeenCalled(); }); + it('uses the confirmed release row metadata when reusing a slot', async () => { + const key = `originals/${OLD_FILE_ID}`; + const txClient = { + query: jest.fn().mockResolvedValueOnce({ + rows: [{ id: OLD_FILE_ID, key, status: 'uploaded', mime_type: 'text/plain', + size: '32', filename: 'original.txt' }], + }), + }; + + const result = await processSingleFile(options, txClient, storageConfig(), 'db', bucket, fakeS3(), + { contentHash: HASH, contentType: 'text/html', size: 16, filename: SITE_KEY }, + { release: true, checkOnly: false }); + + expect(result).toMatchObject({ deduplicated: true, uploadUrl: null, + file: { id: OLD_FILE_ID, key, mime: 'text/plain', size: 32, filename: 'original.txt' } }); + expect(generatePresignedPutUrl).not.toHaveBeenCalled(); + }); + it('signs both copies of the same asset in a batch with a one-second lifetime', async () => { const createdAt = new Date('2026-01-01T00:00:00.000Z'); const clock = jest.spyOn(Date, 'now').mockReturnValue(createdAt.getTime()); diff --git a/graphile/graphile-presigned-url-plugin/src/plugin.ts b/graphile/graphile-presigned-url-plugin/src/plugin.ts index b5a0cd7f8f..f8e0bcf05b 100644 --- a/graphile/graphile-presigned-url-plugin/src/plugin.ts +++ b/graphile/graphile-presigned-url-plugin/src/plugin.ts @@ -656,6 +656,11 @@ export async function processSingleFile( // collecting an object a document still points at. const projectFile = (fileId: string, key: string): FileProjection => buildFileProjection({ id: fileId, key, bucketId: bucket.id, mime: contentType, size, filename }); + const projectStoredFile = (row: { id: string; key: string; mime_type: string; size: string | number; filename: string | null }): FileProjection => + buildFileProjection({ + id: row.id, key: row.key, bucketId: bucket.id, + mime: row.mime_type, size: Number(row.size), filename: row.filename, + }); const signUpload = async (fileId: string, key: string, mime: string, bytes: number, ttl: number) => ({ uploadUrl: await generatePresignedPutUrl(s3ForDb, key, mime, bytes, ttl, contentHash, fileId), @@ -698,17 +703,14 @@ export async function processSingleFile( expiresAt: new Date(deadline).toISOString(), fileId: row.id, key: row.key, logicalKey, deduplicated: false, pending: false, - file: buildFileProjection({ - id: row.id, key: row.key, bucketId: bucket.id, - mime: row.mime_type, size: Number(row.size), filename: row.filename, - }), + file: projectStoredFile(row), }; } return { uploadUrl: null as string | null, uploadHeaders: null as Record | null, fileId: row.id, key: row.key, logicalKey, deduplicated: row.status !== 'requested', pending: row.status === 'requested', - expiresAt: null as string | null, file: projectFile(row.id, row.key), + expiresAt: null as string | null, file: projectStoredFile(row), }; } if (siteUpload.checkOnly) return { logicalKey, deduplicated: false, pending: false }; @@ -718,7 +720,7 @@ export async function processSingleFile( // It issues no PUT URL. Pending/rejected attempts are not reused or deleted: // each retry gets its own object and lifecycle, including its expiry/GC. const existingResult = await txClient.query({ - text: `SELECT id, key + text: `SELECT id, key, mime_type, size, filename FROM ${storageConfig.filesQualifiedName} WHERE logical_key = $1 AND bucket_id = $2 AND content_hash = $3 AND NOT logical_key_retired @@ -737,7 +739,7 @@ export async function processSingleFile( logicalKey, deduplicated: true, expiresAt: null as string | null, - file: projectFile(existing.id as string, existing.key as string), + file: projectStoredFile(existing), }; } diff --git a/packages/site-deploy/__tests__/deploy.test.ts b/packages/site-deploy/__tests__/deploy.test.ts index 4f119dde30..7a06f7dab6 100644 --- a/packages/site-deploy/__tests__/deploy.test.ts +++ b/packages/site-deploy/__tests__/deploy.test.ts @@ -425,6 +425,25 @@ describe('deploySite', () => { expect(server.calls).toHaveLength(0); }); + it('does not write the manifest when aborted during the final status request', async () => { + const server = createMockServer(); + const controller = new AbortController(); + const api: GraphQLExecutor = async (query, variables) => { + const response = await server.api(query, variables); + if ((variables.input as { checkOnly?: boolean } | undefined)?.checkOnly) { + controller.abort(); + } + return response; + }; + + await expect(deploySite({ + ...base, api, putObject: server.putObject, source: build, signal: controller.signal, publish: true, + })).rejects.toMatchObject({ code: 'ABORTED' }); + expect(server.puts).toHaveLength(build.length); + expect(server.release).toBeNull(); + expect(server.activeCommitId).toBeNull(); + }); + it('talks to the platform surface when asked', async () => { const server = createMockServer(); const seen: string[] = []; diff --git a/packages/site-deploy/src/deploy.ts b/packages/site-deploy/src/deploy.ts index 451ad0153c..9e45bc603a 100644 --- a/packages/site-deploy/src/deploy.ts +++ b/packages/site-deploy/src/deploy.ts @@ -179,6 +179,7 @@ export async function deploySite(options: DeploySiteOptions): Promise file), ...diff.pending], uploadOptions); + throwIfAborted(signal); // 5. Write the manifest — this is the commit. const release = existing