diff --git a/.changeset/31607-s3-chunked-upload-session-key.md b/.changeset/31607-s3-chunked-upload-session-key.md new file mode 100644 index 00000000000..74b11173efc --- /dev/null +++ b/.changeset/31607-s3-chunked-upload-session-key.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-storage': patch +--- + +fix(storage): S3 chunked uploads find their object key in the upload session row, on any replica + +Clause-②: no +Metadata-protocol: none + +Chunked uploads to S3 work again. Who is affected: any deployment whose storage adapter is S3 (or S3-compatible) and whose clients upload in chunks (`POST /storage/upload/chunked`, the SDK's chunked and resumable uploads). Before this fix the first chunk answered `500` ("S3StorageAdapter: key not found for uploadId") even on a single server, and a chunk or completion served by another replica could never have found the key. + +S3 addresses a multipart upload by object key and upload id, but the storage contract's chunk and completion calls carry the upload id alone, so the S3 adapter kept the key in an in-memory map filled at the start of the upload. The kernel's `storage` service is the swappable proxy, which did not forward that call, so the map was never filled; and a map in one process cannot serve another. The chunk and completion doors now read the key from `sys_upload_session.key` (the durable record the init door already writes) and hand it to the adapter before every backend call, and the proxy forwards `setUploadKey` to the active adapter. + +Nothing changes for the local adapter or any adapter without `setUploadKey`, nor in the chunked-upload HTTP requests and answers. No migration: upload sessions already store their key. diff --git a/packages/services/service-storage/src/attachment-lifecycle.ts b/packages/services/service-storage/src/attachment-lifecycle.ts index 9392fabf457..906bcb20421 100644 --- a/packages/services/service-storage/src/attachment-lifecycle.ts +++ b/packages/services/service-storage/src/attachment-lifecycle.ts @@ -763,8 +763,9 @@ export function createUploadSessionReapGuard( // A cold sweep runs long after the live session, so the S3 adapter's // in-process `uploadId → key` map (populated by `setUploadKey` during // upload) is empty — re-seed it from the row so the abort can resolve - // the S3 key. `setUploadKey` is S3-specific and not forwarded by the - // swappable proxy, so reach the inner adapter; a no-op for `local`. + // the S3 key. `setUploadKey` is S3-specific and off the IStorageService + // contract; the inner adapter is reached directly (the swappable proxy + // forwards it too); a no-op for `local`. const inner: any = typeof (storage as any).getInner === 'function' ? (storage as any).getInner() : storage; if (typeof row.key === 'string' && row.key && typeof inner?.setUploadKey === 'function') { inner.setUploadKey(backendId, row.key); diff --git a/packages/services/service-storage/src/s3-chunked-upload-session-key.test.ts b/packages/services/service-storage/src/s3-chunked-upload-session-key.test.ts new file mode 100644 index 00000000000..428eed7bbc0 --- /dev/null +++ b/packages/services/service-storage/src/s3-chunked-upload-session-key.test.ts @@ -0,0 +1,298 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A chunked upload to S3 finds its object key in the upload session row, on + * any process. + * + * S3 addresses a multipart upload by `(Key, UploadId)`, but the + * `IStorageService` chunk and completion methods carry the `uploadId` alone. + * The S3 adapter answers the key from its own `uploadId → key` map, which + * `setUploadKey` fills. Two ways that map came up empty: + * + * 1. The plugin registers the SWAPPABLE proxy as the kernel's `storage` + * service, and the proxy did not forward `setUploadKey`, so the init + * door's call never reached the adapter. Chunk 0 answered 500 on a single + * replica. + * 2. The map lives in one process. A chunk or completion served by another + * replica (or by the same replica after a restart or an adapter swap) + * had no entry, whatever the init door did. + * + * The durable record of the key is `sys_upload_session.key`, written by the + * init door. The chunk and completion doors read that row before they reach + * the backend, so they hand its key to the adapter on every call. These cases + * drive the doors against an S3-compatible stand-in that, like S3, refuses a + * part or a completion addressed to the wrong key. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; + +const fakeS3 = vi.hoisted(() => { + const objects = new Map(); + const multipart = new Map }>(); + let uploadSeq = 0; + + function noSuchUpload(): Error { + const err = new Error('NoSuchUpload') as Error & { name: string; $metadata: { httpStatusCode: number } }; + err.name = 'NoSuchUpload'; + err.$metadata = { httpStatusCode: 404 }; + return err; + } + + /** S3 matches BOTH halves of the address: an UploadId under another Key is no upload at all. */ + function upload(input: { Key?: string; UploadId?: string }) { + const found = input.UploadId ? multipart.get(input.UploadId) : undefined; + if (!found || found.key !== input.Key) throw noSuchUpload(); + return found; + } + + function reset(): void { + objects.clear(); + multipart.clear(); + uploadSeq = 0; + } + + return { objects, multipart, upload, reset, nextUploadId: () => `s3-upload-${++uploadSeq}` }; +}); + +vi.mock('@aws-sdk/client-s3', () => { + class Command { + constructor(public readonly input: Record) {} + } + class CreateMultipartUploadCommand extends Command {} + class UploadPartCommand extends Command {} + class CompleteMultipartUploadCommand extends Command {} + class AbortMultipartUploadCommand extends Command {} + + class S3Client { + constructor(_config: unknown) {} + async send(command: any): Promise { + const input = command.input; + if (command instanceof CreateMultipartUploadCommand) { + const uploadId = fakeS3.nextUploadId(); + fakeS3.multipart.set(uploadId, { key: input.Key, parts: new Map() }); + return { UploadId: uploadId }; + } + if (command instanceof UploadPartCommand) { + fakeS3.upload(input).parts.set(input.PartNumber, input.Body); + return { ETag: `"etag-${input.PartNumber}"` }; + } + if (command instanceof CompleteMultipartUploadCommand) { + const found = fakeS3.upload(input); + const listed: Array<{ PartNumber: number }> = input.MultipartUpload.Parts; + fakeS3.objects.set(input.Key, Buffer.concat(listed.map((p) => found.parts.get(p.PartNumber)!))); + fakeS3.multipart.delete(input.UploadId); + return {}; + } + if (command instanceof AbortMultipartUploadCommand) { + fakeS3.upload(input); + fakeS3.multipart.delete(input.UploadId); + return {}; + } + throw new Error(`S3 stand-in: unhandled command ${command.constructor.name}`); + } + } + + return { + S3Client, + CreateMultipartUploadCommand, + UploadPartCommand, + CompleteMultipartUploadCommand, + AbortMultipartUploadCommand, + }; +}); + +import type { IHttpRequest, IHttpResponse, IStorageService, RouteHandler } from '@objectstack/spec/contracts'; +import { promises as fs } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { S3StorageAdapter } from './s3-storage-adapter.js'; +import { LocalStorageAdapter } from './local-storage-adapter.js'; +import { SwappableStorageService } from './swappable-storage-service.js'; +import { StorageMetadataStore } from './metadata-store.js'; +import { registerStorageRoutes } from './storage-routes.js'; + +const BASE = '/api/v1/storage'; +const INIT = `${BASE}/upload/chunked`; +const CHUNK = `${BASE}/upload/chunked/:uploadId/chunk/:chunkIndex`; +const COMPLETE = `${BASE}/upload/chunked/:uploadId/complete`; + +/** The smallest chunk the init door accepts (5 MiB), so two chunks are one full and one short. */ +const CHUNK_SIZE = 5 * 1024 * 1024; +const FIRST = Buffer.alloc(CHUNK_SIZE, 0x61); +const SECOND = Buffer.from('tail'); + +/** + * The stored object is the whole file, byte for byte. Compared with + * `Buffer.equals` rather than `toEqual`, which walks 5 MiB one element at a time. + */ +function expectWhole(stored: Buffer | undefined): void { + expect(stored?.length).toBe(FIRST.length + SECOND.length); + expect(stored?.equals(Buffer.concat([FIRST, SECOND]))).toBe(true); +} + +type Res = IHttpResponse & { _status: number; _json: any }; + +function createMockRes(): Res { + const res: any = { + _status: 200, + _json: null, + json(data: any) { res._json = data; }, + send(data: any) { res._sent = data; }, + status(code: number) { res._status = code; return res; }, + header() { return res; }, + }; + return res; +} + +function createMockReq(overrides: Record): IHttpRequest { + return { params: {}, query: {}, body: undefined, headers: {}, method: 'GET', path: '/', ...overrides } as IHttpRequest; +} + +/** + * One server process: its own adapter instance (so its own in-process state) + * mounted behind its own swappable proxy, the way `StorageServicePlugin` + * composes it. Replicas share the metadata store (the database) and the bucket. + */ +function replica(store: StorageMetadataStore, inner: IStorageService) { + const routes = new Map(); + const server = { + get: (path: string, h: RouteHandler) => { routes.set(`GET:${path}`, h); }, + post: (path: string, h: RouteHandler) => { routes.set(`POST:${path}`, h); }, + put: (path: string, h: RouteHandler) => { routes.set(`PUT:${path}`, h); }, + delete: () => {}, + patch: () => {}, + use: () => {}, + }; + registerStorageRoutes(server as any, new SwappableStorageService(inner), store, { basePath: BASE }); + const call = async (method: string, path: string, req: Record): Promise => { + const res = createMockRes(); + await routes.get(`${method}:${path}`)!(createMockReq(req), res); + return res; + }; + return { + init: () => + call('POST', INIT, { + body: { filename: 'big.bin', mimeType: 'application/octet-stream', totalSize: FIRST.length + SECOND.length, chunkSize: CHUNK_SIZE }, + }), + chunk: (uploadId: string, resumeToken: string, chunkIndex: number, bytes: Buffer) => + call('PUT', CHUNK, { + params: { uploadId, chunkIndex: String(chunkIndex) }, + headers: { 'x-resume-token': resumeToken }, + rawBody: async () => bytes, + }), + complete: (uploadId: string, parts: Array<{ chunkIndex: number; eTag: string }>) => + call('POST', COMPLETE, { params: { uploadId }, body: { uploadId, parts } }), + }; +} + +const s3 = () => new S3StorageAdapter({ bucket: 'uploads', region: 'us-east-1', keyPrefix: null }); + +/** Drive one upload: init on `a`, chunk 0 on `b`, chunk 1 and completion on `c`. */ +async function drive(a: ReturnType, b: ReturnType, c: ReturnType) { + const init = await a.init(); + expect(init._status, JSON.stringify(init._json)).toBe(200); + const { uploadId, resumeToken } = init._json.data; + + const first = await b.chunk(uploadId, resumeToken, 0, FIRST); + expect(first._status, JSON.stringify(first._json)).toBe(200); + const second = await c.chunk(uploadId, resumeToken, 1, SECOND); + expect(second._status, JSON.stringify(second._json)).toBe(200); + + const done = await c.complete(uploadId, [ + { chunkIndex: 0, eTag: first._json.data.eTag }, + { chunkIndex: 1, eTag: second._json.data.eTag }, + ]); + expect(done._status, JSON.stringify(done._json)).toBe(200); + return done._json.data as { fileId: string; key: string; size: number }; +} + +beforeEach(() => { + fakeS3.reset(); +}); + +describe('a chunked upload through the swappable proxy reaches the S3 object it started', () => { + it('completes on a single replica', async () => { + const one = replica(new StorageMetadataStore(null), s3()); + + const done = await drive(one, one, one); + + expect(done.size).toBe(FIRST.length + SECOND.length); + expectWhole(fakeS3.objects.get(done.key)); + expect(fakeS3.multipart.size).toBe(0); + }); + + it('resumes on a fresh adapter instance: another process finds the key in the session row', async () => { + // One database and one bucket; three processes, none sharing memory. The + // replica that serves a chunk or the completion has never seen the init. + const store = new StorageMetadataStore(null); + const a = replica(store, s3()); + const b = replica(store, s3()); + const c = replica(store, s3()); + + const done = await drive(a, b, c); + + expectWhole(fakeS3.objects.get(done.key)); + expect(fakeS3.multipart.size).toBe(0); + // The key the object landed under is the one the session row recorded. + const file = await store.getFile(done.fileId); + expect(file?.key).toBe(done.key); + expect(file?.status).toBe('committed'); + }); +}); + +describe('adapters that do not track upload keys are untouched', () => { + let rootDir: string; + + afterEach(async () => { + if (rootDir) await fs.rm(rootDir, { recursive: true, force: true }); + }); + + it('local: the assembled file holds the bytes sent, across two adapter instances on one root', async () => { + rootDir = join(tmpdir(), `os-chunk-session-key-${Date.now()}-${Math.random().toString(36).slice(2)}`); + await fs.mkdir(rootDir, { recursive: true }); + const store = new StorageMetadataStore(null); + const local = () => new LocalStorageAdapter({ rootDir, signingSecret: 'test-secret' }); + const reader = local(); + + const done = await drive(replica(store, local()), replica(store, local()), replica(store, local())); + + expectWhole(await reader.download(done.key)); + }); + + it('an adapter with no setUploadKey receives exactly the contract calls, with the arguments it did before', async () => { + const calls: unknown[][] = []; + const parts = new Map(); + const memory: IStorageService = { + upload: async () => {}, + download: async () => Buffer.alloc(0), + delete: async () => {}, + exists: async () => false, + getInfo: async (key) => ({ key, size: 0, lastModified: new Date(0) }), + initiateChunkedUpload: async (key) => { + calls.push(['initiateChunkedUpload', key]); + parts.set('mem-1', []); + return 'mem-1'; + }, + uploadChunk: async (uploadId, partNumber, data) => { + calls.push(['uploadChunk', uploadId, partNumber, data.length]); + parts.get(uploadId)!.push(data); + return `m${partNumber}`; + }, + completeChunkedUpload: async (uploadId, listed) => { + calls.push(['completeChunkedUpload', uploadId, listed]); + return 'assembled-key'; + }, + }; + + const one = replica(new StorageMetadataStore(null), memory); + const done = await drive(one, one, one); + + expect(done.key).toBe('assembled-key'); + expect(calls).toEqual([ + ['initiateChunkedUpload', expect.stringMatching(/^user\/.+\.bin$/)], + ['uploadChunk', 'mem-1', 1, FIRST.length], + ['uploadChunk', 'mem-1', 2, SECOND.length], + ['completeChunkedUpload', 'mem-1', [{ partNumber: 1, eTag: 'm1' }, { partNumber: 2, eTag: 'm2' }]], + ]); + }); +}); diff --git a/packages/services/service-storage/src/s3-storage-adapter.ts b/packages/services/service-storage/src/s3-storage-adapter.ts index dc496ed4750..16d0a5f8256 100644 --- a/packages/services/service-storage/src/s3-storage-adapter.ts +++ b/packages/services/service-storage/src/s3-storage-adapter.ts @@ -607,13 +607,11 @@ export class S3StorageAdapter implements IStorageService { async uploadChunk(uploadId: string, partNumber: number, data: Buffer): Promise { const client = await this.getClient(); const s3 = await this.s3Mod(); - // We need the key — store the relationship elsewhere or pass via metadata. - // For the S3 adapter, `uploadId` is the S3-native UploadId. The key is - // tracked in the StorageMetadataStore (sys_upload_session.key). - // Here we retrieve it from session state; the plugin ensures the correct - // key is passed. However, the IStorageService contract doesn't include key - // in uploadChunk — so we work around by storing the mapping in a WeakMap - // keyed by uploadId. For a robust implementation we'll add a lookup: + // S3 addresses a part by key AND UploadId, but the IStorageService + // contract carries the UploadId alone. The durable record of the key is + // `sys_upload_session.key`; the storage routes hand it down through + // `setUploadKey` before every chunk and completion call, on whichever + // process serves the request. const key = this._uploadKeys?.get(uploadId); if (!key) { throw new Error('S3StorageAdapter: key not found for uploadId. Call setUploadKey() before uploadChunk().'); @@ -672,10 +670,16 @@ export class S3StorageAdapter implements IStorageService { private _uploadKeys: Map = new Map(); /** - * Register the storage key for a multipart upload session. Must be called - * by the StorageServicePlugin after `initiateChunkedUpload()` returns so - * that subsequent `uploadChunk` / `completeChunkedUpload` calls can resolve - * the S3 key without it being part of the IStorageService contract signature. + * Register the storage key (the CALLER key, unprefixed) for a multipart + * upload, so `uploadChunk` / `completeChunkedUpload` / `abortChunkedUpload` + * can address it without the key being part of the IStorageService contract + * signature. + * + * This map is a per-process hand-off, never the record: the storage routes + * call this (through the swappable proxy, which forwards it) with + * `sys_upload_session.key` before every chunk and completion call, and the + * upload-session reap guard does the same before an abort, so a request + * served by a process that never saw the upload start still finds its key. */ setUploadKey(uploadId: string, key: string): void { this._uploadKeys.set(uploadId, key); diff --git a/packages/services/service-storage/src/storage-routes.ts b/packages/services/service-storage/src/storage-routes.ts index cf3f2cb0a95..8e21af92d37 100644 --- a/packages/services/service-storage/src/storage-routes.ts +++ b/packages/services/service-storage/src/storage-routes.ts @@ -225,6 +225,28 @@ function chunkIndexRefusalMessage(totalChunks: number): string { ); } +/** + * Hand the backend the object key of chunked upload `uploadId`, read from the + * upload session row, before every backend call that names the upload. + * + * S3 addresses a multipart upload by key AND upload id, but the + * `IStorageService` chunk and completion methods carry the upload id alone, so + * the S3 adapter answers the key from what `setUploadKey` gave it. That record + * lives in one process: a chunk or a completion served by another replica, or + * after a restart or an adapter swap, finds nothing there. The durable record + * is `sys_upload_session.key`, which the init door writes and every later door + * already reads, so each door hands it down again rather than trusting + * whichever process happened to start the upload. + * + * Off the `IStorageService` contract: reached by name, on the swappable proxy + * (which forwards it) or on a bare adapter. A no-op for a backend without it — + * the local adapter records the key beside the parts itself. + */ +function handUploadKeyToBackend(storage: IStorageService, uploadId: string, key: string): void { + const keyed = storage as IStorageService & { setUploadKey?: (uploadId: string, key: string) => void }; + if (typeof keyed.setUploadKey === 'function') keyed.setUploadKey(uploadId, key); +} + /** * [#22332] How many times the chunk door tries to record a stored chunk in the * upload's progress before it refuses. @@ -1274,10 +1296,6 @@ export function registerStorageFamily( let backendUploadId: string | undefined; if (storage.initiateChunkedUpload) { backendUploadId = await storage.initiateChunkedUpload(key, { contentType: mimeType, metadata }); - // S3 adapter needs to know the key for subsequent chunk/complete calls - if ('setUploadKey' in storage && typeof (storage as any).setUploadKey === 'function') { - (storage as any).setUploadKey(backendUploadId, key); - } } const uploadId = backendUploadId ?? randomUUID().replace(/-/g, ''); @@ -1420,6 +1438,7 @@ export function registerStorageFamily( // Upload the chunk (S3 uses 1-based part numbers) let eTag = ''; if (storage.uploadChunk) { + handUploadKeyToBackend(storage, uploadId, session.key); eTag = await storage.uploadChunk(uploadId, chunkIndex + 1, data); } @@ -1565,6 +1584,7 @@ export function registerStorageFamily( let finalKey = session.key; try { if (storage.completeChunkedUpload) { + handUploadKeyToBackend(storage, uploadId, session.key); finalKey = await storage.completeChunkedUpload(uploadId, partsForBackend); } diff --git a/packages/services/service-storage/src/swappable-storage-service.ts b/packages/services/service-storage/src/swappable-storage-service.ts index 15f70a95da8..a5b6010fb8e 100644 --- a/packages/services/service-storage/src/swappable-storage-service.ts +++ b/packages/services/service-storage/src/swappable-storage-service.ts @@ -188,6 +188,26 @@ export class SwappableStorageService implements IStorageService { return this.inner.abortChunkedUpload(uploadId); } + /** + * Hand the active adapter the object key of a chunked upload + * (S3StorageAdapter-specific). + * + * S3 addresses a multipart upload by key AND upload id, while the + * `IStorageService` chunk, completion and abort methods carry the upload id + * alone; the S3 adapter answers the key from what this call gave it. Not on + * `IStorageService`, so without this passthrough a caller holding the proxy + * (the kernel's `storage` service) never reached the adapter's + * `setUploadKey`, and chunk 0 of every S3 chunked upload failed. + * + * A no-op for an adapter that keeps the key itself (the local adapter + * records it beside the parts when the upload starts). + */ + setUploadKey(uploadId: string, key: string): void { + const inner = this.inner as unknown as { setUploadKey?: (uploadId: string, key: string) => void }; + if (typeof inner.setUploadKey !== 'function') return; + inner.setUploadKey(uploadId, key); + } + /** * Verify a presigned HMAC token (LocalStorageAdapter-specific). *