diff --git a/server/src/nest/storage/drivers/s3.driver.ts b/server/src/nest/storage/drivers/s3.driver.ts index caff9963a..5be8fa525 100644 --- a/server/src/nest/storage/drivers/s3.driver.ts +++ b/server/src/nest/storage/drivers/s3.driver.ts @@ -1,7 +1,7 @@ /// import awsLite from '@aws-lite/client'; import type { Readable } from 'node:stream'; -import { assertValidKey, assertValidPrefix } from '../storage-keys'; +import { assertValidKey, assertValidPrefix, isValidKey } from '../storage-keys'; import { StorageBackendError, StorageNotFoundError, @@ -133,8 +133,29 @@ export class S3Driver implements StorageDriver { throw new StorageBackendError('not implemented'); } - async getStream(_key: string, _range?: ByteRange): Promise<{ stream: Readable; stat: ObjectStat }> { - throw new StorageBackendError('not implemented'); + async getStream(key: string, range?: ByteRange): Promise<{ stream: Readable; stat: ObjectStat }> { + assertValidKey(key); + const s3 = await this.client(); + const params: Record = { + Bucket: this.bucket, + Key: this.keyPrefix + key, + // Mandatory: a bare GetObject content-sniffs and parses JSON/XML bodies. + streamResponsePayload: true, + }; + if (range) params.Range = `bytes=${range.start}-${range.end ?? ''}`; + let res; + try { + // Deadline covers time-to-headers; body streaming is never deadlined. + res = await this.deadlined(s3.GetObject(params), `get '${key}'`); + } catch (err) { + if (isNotFound(err)) throw new StorageNotFoundError(key); + throw this.wrap(err, `get failed for '${key}'`); + } + if (!res.Body) throw new StorageBackendError(`get returned no body for '${key}' on '${this.id}'`); + // LocalDriver parity: on a ranged read the stat is the FULL object's — + // total from the 206 Content-Range, never the ranged ContentLength. + const size = range ? totalFromContentRange(res.ContentRange, key, this.id) : (res.ContentLength ?? 0); + return { stream: res.Body, stat: { key, size, mtimeMs: res.LastModified?.getTime() ?? 0 } }; } async stat(key: string): Promise { @@ -160,8 +181,38 @@ export class S3Driver implements StorageDriver { } } - list(_prefix: string): AsyncIterable { - throw new StorageBackendError('not implemented'); + async *list(prefix: string): AsyncIterable { + assertValidPrefix(prefix); + const s3 = await this.client(); + let pages: AsyncIterable<{ Contents?: Array<{ Key?: string; Size?: number; LastModified?: Date }> }>; + try { + pages = await this.deadlined( + s3.ListObjectsV2({ Bucket: this.bucket, Prefix: this.keyPrefix + prefix, paginate: 'iterator' }), + `list '${prefix}'`, + ); + } catch (err) { + throw this.wrap(err, `list failed under '${prefix}'`); + } + const it = pages[Symbol.asyncIterator](); + for (;;) { + let next: IteratorResult<{ Contents?: Array<{ Key?: string; Size?: number; LastModified?: Date }> }>; + try { + // Per-page deadline (each iteration is one ListObjectsV2 request). + next = await this.deadlined(it.next(), `list '${prefix}'`); + } catch (err) { + throw this.wrap(err, `list failed under '${prefix}'`); + } + if (next.done) return; + for (const obj of next.value.Contents ?? []) { + const objectKey = obj.Key ?? ''; + if (!objectKey.startsWith(this.keyPrefix)) continue; // out-of-band write outside our namespace + const key = objectKey.slice(this.keyPrefix.length); + // Defensive parity with LocalDriver's dotfile skip: such keys can only + // exist from out-of-band writes; serving/sweeps must never see them. + if (!isValidKey(key)) continue; + yield { key, size: obj.Size ?? 0, mtimeMs: obj.LastModified?.getTime() ?? 0 }; + } + } } private client(): Promise { @@ -205,3 +256,12 @@ function normalizeKeyPrefix(raw: string): string { assertValidPrefix(`${trimmed}/`); return `${trimmed}/`; } + +/** 'bytes 2-5/10' → 10. A 206 without a parseable total is a backend defect. */ +function totalFromContentRange(contentRange: string | undefined, key: string, id: string): number { + const total = contentRange?.match(/\/(\d+)$/)?.[1]; + if (total === undefined) { + throw new StorageBackendError(`ranged get for '${key}' on '${id}' returned no Content-Range total`); + } + return Number(total); +} diff --git a/server/tests/unit/nest/storage/s3.driver.test.ts b/server/tests/unit/nest/storage/s3.driver.test.ts index 9a26e4ce9..54aa57f4a 100644 --- a/server/tests/unit/nest/storage/s3.driver.test.ts +++ b/server/tests/unit/nest/storage/s3.driver.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi } from 'vitest'; +import { Readable } from 'node:stream'; import { S3Driver, MULTIPART_THRESHOLD, @@ -122,6 +123,105 @@ describe('S3Driver stat/delete', () => { }); }); +async function drain(stream: Readable): Promise { + const chunks: Buffer[] = []; + for await (const c of stream) chunks.push(Buffer.from(c as Buffer)); + return Buffer.concat(chunks); +} + +describe('S3Driver getStream', () => { + it('streams the body with streamResponsePayload and returns the stat', async () => { + const api = makeMockApi({ + GetObject: vi.fn().mockResolvedValue({ + Body: Readable.from('hello'), + ContentLength: 5, + LastModified: new Date(7000), + }), + }); + const { stream, stat } = await makeDriver(api).getStream('a/x.bin'); + expect((await drain(stream)).toString()).toBe('hello'); + expect(stat).toEqual({ key: 'a/x.bin', size: 5, mtimeMs: 7000 }); + expect(api.GetObject).toHaveBeenCalledWith( + expect.objectContaining({ Key: 'a/x.bin', streamResponsePayload: true }), + ); + expect((api.GetObject as ReturnType).mock.calls[0][0]).not.toHaveProperty('Range'); + }); + it('formats closed and open-ended ranges and returns the FULL-object stat from Content-Range', async () => { + const api = makeMockApi({ + GetObject: vi.fn().mockResolvedValue({ + Body: Readable.from('2345'), + ContentLength: 4, // the RANGE length — must not become stat.size + ContentRange: 'bytes 2-5/10', + LastModified: new Date(7000), + }), + }); + const { stat } = await makeDriver(api).getStream('a/x.bin', { start: 2, end: 5 }); + expect(stat.size).toBe(10); + expect(api.GetObject).toHaveBeenCalledWith(expect.objectContaining({ Range: 'bytes=2-5' })); + + await makeDriver(api).getStream('a/x.bin', { start: 7 }); + expect(api.GetObject).toHaveBeenLastCalledWith(expect.objectContaining({ Range: 'bytes=7-' })); + }); + it('maps 404/NoSuchKey to StorageNotFoundError', async () => { + const api = makeMockApi({ GetObject: vi.fn().mockRejectedValue(awsError(404, 'NoSuchKey')) }); + await expect(makeDriver(api).getStream('a/x.bin')).rejects.toBeInstanceOf(StorageNotFoundError); + }); + it('rejects a missing Body as StorageBackendError (never a bare undefined stream)', async () => { + const api = makeMockApi({ GetObject: vi.fn().mockResolvedValue({ ContentLength: 5 }) }); + await expect(makeDriver(api).getStream('a/x.bin')).rejects.toBeInstanceOf(StorageBackendError); + }); +}); + +describe('S3Driver list', () => { + function pages(...pageContents: Array>) { + return vi.fn().mockResolvedValue( + (async function* () { + for (const Contents of pageContents) yield { Contents }; + })(), + ); + } + it('paginates with the iterator, strips the keyPrefix, and requests the combined prefix', async () => { + const api = makeMockApi({ + ListObjectsV2: pages( + [{ Key: 'trek/prod/a/one.bin', Size: 2, LastModified: new Date(1000) }], + [{ Key: 'trek/prod/a/sub/two.bin', Size: 3, LastModified: new Date(2000) }], + ), + }); + const out = []; + for await (const stat of makeDriver(api, { keyPrefix: 'trek/prod' }).list('a/')) out.push(stat); + expect(out).toEqual([ + { key: 'a/one.bin', size: 2, mtimeMs: 1000 }, + { key: 'a/sub/two.bin', size: 3, mtimeMs: 2000 }, + ]); + expect(api.ListObjectsV2).toHaveBeenCalledWith( + expect.objectContaining({ Prefix: 'trek/prod/a/', paginate: 'iterator' }), + ); + }); + it('skips keys with dot-segments and keys outside the keyPrefix (out-of-band writes)', async () => { + const api = makeMockApi({ + ListObjectsV2: pages([ + { Key: 'trek/prod/a/ok.bin', Size: 1, LastModified: new Date(0) }, + { Key: 'trek/prod/.tmp/junk', Size: 1, LastModified: new Date(0) }, + { Key: 'trek/prod/a/.hidden', Size: 1, LastModified: new Date(0) }, + { Key: 'elsewhere/x.bin', Size: 1, LastModified: new Date(0) }, + ]), + }); + const out = []; + for await (const stat of makeDriver(api, { keyPrefix: 'trek/prod' }).list('')) out.push(stat); + expect(out.map((s) => s.key)).toEqual(['a/ok.bin']); + }); + it('yields nothing for an empty result and validates the prefix first', async () => { + const api = makeMockApi({ ListObjectsV2: pages([]) }); + const driver = makeDriver(api); + const out = []; + for await (const stat of driver.list('a/')) out.push(stat); + expect(out).toEqual([]); + await expect(async () => { + for await (const s of driver.list('../x')) void s; + }).rejects.toBeInstanceOf(StorageInvalidKeyError); + }); +}); + describe('defaultClientFactory', () => { it('builds a real aws-lite client exposing the S3 surface (no network at init)', async () => { const s3 = await defaultClientFactory({