diff --git a/src/gateways/fetch-http-stack.ts b/src/gateways/fetch-http-stack.ts new file mode 100644 index 0000000..928b85c --- /dev/null +++ b/src/gateways/fetch-http-stack.ts @@ -0,0 +1,130 @@ +import { Readable } from 'node:stream'; + +import type { HttpRequest, HttpResponse, HttpStack } from 'tus-js-client'; + +/** + * A tus `HttpStack` that sends each request with `fetch` and a fully-read body. + * + * tus-js-client's default Node stack pipes the chunk into a `node:http` + * request. Under Bun (the standalone `dcd` binary is `bun build --compile`d), + * that fails on the upload-creating POST with "The socket connection was + * closed unexpectedly", so every Storage upload from the binary failed while + * the npm package, on Node, worked. Bun's own `fetch` sends the same request + * fine, so the binary uses this stack instead (see `tusHttpStack`). + * + * Each body is read into memory before it is sent. tus sends at most one + * chunk per request (6 MB for Supabase), so that is one chunk at a time. + * `fetch` can't report upload progress, so progress moves once per chunk. + */ +export class FetchHttpStack implements HttpStack { + createRequest(method: string, url: string): HttpRequest { + return new FetchHttpRequest(method, url); + } + + getName(): string { + return 'FetchHttpStack'; + } +} + +class FetchHttpRequest implements HttpRequest { + private readonly controller = new AbortController(); + private readonly headers: Record = {}; + private progress: (bytesSent: number) => void = () => {}; + + constructor( + private readonly method: string, + private readonly url: string, + ) {} + + getMethod(): string { + return this.method; + } + + getURL(): string { + return this.url; + } + + setHeader(header: string, value: string): void { + this.headers[header] = value; + } + + getHeader(header: string): string | undefined { + return this.headers[header]; + } + + setProgressHandler(handler: (bytesSent: number) => void): void { + this.progress = handler; + } + + async send(body?: unknown): Promise { + const data = await readBody(body); + const res = await fetch(this.url, { + method: this.method, + headers: this.headers, + body: data, + signal: this.controller.signal, + }); + if (data) this.progress(data.byteLength); + const text = await res.text(); + return new FetchHttpResponse(res, text); + } + + abort(): Promise { + this.controller.abort(); + return Promise.resolve(); + } + + getUnderlyingObject(): unknown { + return this.controller; + } +} + +class FetchHttpResponse implements HttpResponse { + constructor( + private readonly res: Response, + private readonly body: string, + ) {} + + getStatus(): number { + return this.res.status; + } + + getHeader(header: string): string | undefined { + return this.res.headers.get(header) ?? undefined; + } + + getBody(): string { + return this.body; + } + + getUnderlyingObject(): unknown { + return this.res; + } +} + +/** The slice tus hands to `send`: nothing, a Buffer, or a file ReadStream. */ +async function readBody(body: unknown): Promise | undefined> { + if (body === null || body === undefined) return undefined; + // A Node Buffer slice, always backed by an ArrayBuffer (not a shared one). + if (body instanceof Uint8Array) return body as Uint8Array; + if (body instanceof Readable) { + const parts: Buffer[] = []; + for await (const part of body) { + parts.push(typeof part === 'string' ? Buffer.from(part) : (part as Buffer)); + } + return Buffer.concat(parts); + } + throw new TypeError(`FetchHttpStack can't send a body of type ${typeof body}`); +} + +/** + * tus options that pick the HTTP stack: `FetchHttpStack` under Bun, and no + * key at all under Node, so tus keeps its default stack (what the npm package + * has always used). It must be no key, not `httpStack: undefined`: tus spreads + * the options over its defaults, so an `undefined` would replace the default. + */ +export function tusHttpStackOptions( + isBun = 'bun' in process.versions, +): { httpStack?: HttpStack } { + return isBun ? { httpStack: new FetchHttpStack() } : {}; +} diff --git a/src/gateways/supabase-gateway.ts b/src/gateways/supabase-gateway.ts index 084148c..fff9211 100644 --- a/src/gateways/supabase-gateway.ts +++ b/src/gateways/supabase-gateway.ts @@ -4,6 +4,7 @@ import * as tus from 'tus-js-client'; import { ENVIRONMENTS, type DcdEnvName } from '../config/environments.js'; import { getSupabaseKey, supabaseKeyHeaders } from '../config/supabase-key.js'; +import { tusHttpStackOptions } from './fetch-http-stack.js'; /** Disk-backed upload descriptor — see UploadSource in src/methods.ts. */ export interface ResumableUploadSource { @@ -52,6 +53,9 @@ export class SupabaseGateway { const upload = new tus.Upload(createReadStream(source.diskPath), { uploadSize: source.size, + // Bun's node:http can't send tus's create request; see FetchHttpStack. + ...tusHttpStackOptions(), + // TUS endpoint for Supabase Storage endpoint: `${storageUrl}/storage/v1/upload/resumable`, diff --git a/test/unit/fetch-http-stack.test.ts b/test/unit/fetch-http-stack.test.ts new file mode 100644 index 0000000..bd36e90 --- /dev/null +++ b/test/unit/fetch-http-stack.test.ts @@ -0,0 +1,109 @@ +import { expect } from 'chai'; +import { createReadStream, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type IncomingMessage, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import * as tus from 'tus-js-client'; + +import { FetchHttpStack, tusHttpStackOptions } from '../../src/gateways/fetch-http-stack.js'; + +/** + * The standalone binary runs on Bun, whose node:http can't send tus's + * upload-creating POST, so it uploads through FetchHttpStack instead. + */ +describe('FetchHttpStack', () => { + let server: Server; + let endpoint: string; + let dir: string; + let received: Buffer; + let requests: string[]; + + const readAll = async (req: IncomingMessage): Promise => { + const parts: Buffer[] = []; + for await (const part of req) parts.push(part as Buffer); + return Buffer.concat(parts); + }; + + // A minimal tus server: POST creates (with data), PATCH appends. + beforeEach(async () => { + received = Buffer.alloc(0); + requests = []; + dir = mkdtempSync(join(tmpdir(), 'dcd-tus-')); + server = createServer(async (req, res) => { + const body = await readAll(req); + requests.push(`${req.method} ${body.length} ${req.headers['x-upsert'] ?? ''}`); + received = Buffer.concat([received, body]); + const headers = { 'Tus-Resumable': '1.0.0', 'Upload-Offset': String(received.length) }; + if (req.method === 'POST') { + res.writeHead(201, { ...headers, Location: `${endpoint}/upload-1` }); + } else { + res.writeHead(204, headers); + } + res.end(); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}/files`; + }); + + afterEach(async () => { + rmSync(dir, { recursive: true, force: true }); + // fetch keeps its connections alive, which would hold close() open. + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }); + + it('uploads a file stream in chunks, data on create', async () => { + const file = join(dir, 'app.bin'); + const content = Buffer.from(Array.from({ length: 2500 }, (_, i) => i % 251)); + writeFileSync(file, content); + const progress: number[] = []; + + await new Promise((resolve, reject) => { + new tus.Upload(createReadStream(file), { + endpoint, + uploadSize: content.length, + chunkSize: 1000, + uploadDataDuringCreation: true, + retryDelays: [], + headers: { 'x-upsert': 'true' }, + httpStack: new FetchHttpStack(), + onProgress: (sent) => progress.push(sent), + onError: reject, + onSuccess: () => resolve(), + }).start(); + }); + + expect(received.equals(content)).to.equal(true); + expect(requests).to.deep.equal(['POST 1000 true', 'PATCH 1000 true', 'PATCH 500 true']); + expect(progress.at(-1)).to.equal(content.length); + }); + + it('turns a server error into a tus error', async () => { + server.removeAllListeners('request'); + server.on('request', (_req, res) => { + res.writeHead(403, { 'Tus-Resumable': '1.0.0' }); + res.end('denied'); + }); + + const error = await new Promise((resolve, reject) => { + new tus.Upload(Buffer.from('abc'), { + endpoint, + retryDelays: [], + httpStack: new FetchHttpStack(), + onError: resolve, + onSuccess: () => reject(new Error('expected the upload to fail')), + }).start(); + }); + + expect(error.message).to.contain('response code: 403'); + expect(error.message).to.contain('denied'); + }); + + it('is used under Bun only, and leaves no httpStack key under Node', () => { + expect(tusHttpStackOptions(true).httpStack).to.be.instanceOf(FetchHttpStack); + // An explicit `httpStack: undefined` would replace tus's default stack. + expect(tusHttpStackOptions(false)).to.deep.equal({}); + }); +});