diff --git a/src/runtime/webcore/s3/multipart.rs b/src/runtime/webcore/s3/multipart.rs index 46f7e67acb4c..c082b25080c3 100644 --- a/src/runtime/webcore/s3/multipart.rs +++ b/src/runtime/webcore/s3/multipart.rs @@ -113,8 +113,8 @@ use bun_s3_signing::storage_class::StorageClass; // re-export hub instead. use crate::webcore::s3::multipart_options::MultiPartUploadOptions; use crate::webcore::s3::simple_request::{ - self as s3_simple_request, S3CommitResult, S3DownloadResult, S3PartResult, S3UploadResult, - execute_simple_s3_request, + self as s3_simple_request, S3CommitResult, S3DeleteResult, S3DownloadResult, S3PartResult, + S3UploadResult, execute_simple_s3_request, }; use crate::webcore::s3::xml_response; use bun_collections::index_sort; @@ -758,7 +758,7 @@ impl MultiPartUpload { /// We do a best effort to rollback the multipart upload, if it fails we will retry, if it still we just deinit the upload pub(crate) fn on_rollback_multi_part_request( - result: S3UploadResult, + result: S3DeleteResult, this: *mut c_void, ) -> bun_jsc::JsResult<()> { let this = this.cast::(); @@ -771,7 +771,17 @@ impl MultiPartUpload { BStr::new(self_.upload_id.get()) ); match result { - S3UploadResult::Failure(_err) => { + // NoSuchUpload: the upload id is already gone, a retry cannot change that. + S3DeleteResult::Success + | S3DeleteResult::NotFound(S3Error { + code: b"NoSuchUpload", + .. + }) => { + MultiPartUpload::deref_(this); + Ok(()) + } + // Any other 404 can come from a proxy in front of the store. + S3DeleteResult::NotFound(_err) | S3DeleteResult::Failure(_err) => { let mut options = self_.options.get(); if options.retry > 0 { options.retry -= 1; @@ -783,10 +793,6 @@ impl MultiPartUpload { MultiPartUpload::deref_(this); Ok(()) } - S3UploadResult::Success => { - MultiPartUpload::deref_(this); - Ok(()) - } } } @@ -845,7 +851,7 @@ impl MultiPartUpload { request_payer: self.request_payer, ..Default::default() }, - s3_simple_request::S3Callback::Upload(Self::on_rollback_multi_part_request), + s3_simple_request::S3Callback::Delete(Self::on_rollback_multi_part_request), self.as_ctx_ptr(), ) } diff --git a/test/js/bun/s3/s3.test.ts b/test/js/bun/s3/s3.test.ts index ff6001c67df8..fa6d4e888c61 100644 --- a/test/js/bun/s3/s3.test.ts +++ b/test/js/bun/s3/s3.test.ts @@ -1802,6 +1802,108 @@ describe("s3 multipart upload id validation", () => { }, 60_000); }); +describe.concurrent("s3 multipart upload rollback", () => { + // A multipart upload that fails is rolled back with AbortMultipartUpload + // (DELETE ?uploadId=). S3 answers that request with 204 No Content. + // + // The stub fails every part, so the writer gives up and rolls back. It + // records each request it gets. The rollback request keeps the event loop + // alive, so the list the child prints at exit is final. + function fixture(abort: { status: number; body: string | null }) { + return ` + const abort = ${JSON.stringify(abort)}; + const requests = []; + const server = Bun.serve({ + port: 0, + async fetch(req) { + const url = new URL(req.url); + await req.arrayBuffer(); + if (req.method === "POST" && url.searchParams.has("uploads")) { + requests.push("initiate"); + return new Response( + "my_bucketobjupload-1", + { headers: { "Content-Type": "application/xml" } }, + ); + } + if (req.method === "PUT" && url.searchParams.has("partNumber")) { + requests.push("part"); + return new Response( + "InternalErrorWe encountered an internal error. Please try again.", + { status: 500, headers: { "Content-Type": "application/xml" } }, + ); + } + if (req.method === "DELETE" && url.searchParams.get("uploadId") === "upload-1") { + requests.push("abort"); + return new Response(abort.body, { status: abort.status }); + } + requests.push(req.method + " " + url.pathname + url.search); + return new Response(null, { status: 400 }); + }, + }); + // Only the upload may keep the child alive. + server.unref(); + + const client = new Bun.S3Client({ + accessKeyId: "test", + secretAccessKey: "test", + region: "eu-west-3", + bucket: "my_bucket", + endpoint: \`http://127.0.0.1:\${server.port}\`, + }); + // Exactly one part, so the order of the requests is fixed. + const writer = client.file("obj").writer({ partSize: 5 * 1024 * 1024, retry: 3 }); + writer.write(new Uint8Array(5 * 1024 * 1024)); + const outcome = await writer.end().then( + () => "resolved", + e => "rejected " + e.code, + ); + process.on("exit", () => console.log(JSON.stringify({ outcome, requests }))); + `; + } + + it.each([ + // The abort worked. + ["204 No Content", 1, { status: 204, body: null }], + // The upload id is already gone. A retry cannot change that. + [ + "404 NoSuchUpload", + 1, + { + status: 404, + body: "NoSuchUploadThe specified upload does not exist.", + }, + ], + // A 404 without that code can come from a proxy in front of the store. It + // says nothing about the upload, so the rollback retries. + ["404 from a proxy", 4, { status: 404, body: "404 page not found" }], + // A real failure: the best-effort rollback still retries, 1 + retry times. + [ + "500 InternalError", + 4, + { + status: 500, + body: "InternalErrorWe encountered an internal error. Please try again.", + }, + ], + ])("AbortMultipartUpload answered with %s is sent %d time(s)", async (_, aborts, abort) => { + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", fixture(abort)], + // The S3 client honors the proxy environment; the stub is on loopback. + env: { ...bunEnv, HTTP_PROXY: undefined, HTTPS_PROXY: undefined, http_proxy: undefined, https_proxy: undefined }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(JSON.parse(stdout.trim())).toEqual({ + outcome: "rejected InternalError", + // retry: 3 gives the part 4 attempts before the writer rolls back. + requests: ["initiate", "part", "part", "part", "part", ...Array(aborts).fill("abort")], + }); + expect(exitCode).toBe(0); + }); +}); + describe("s3 upload stream body error", () => { // The readStreamIntoSink abrupt path dispatches a single-file PUT before // the pump promise rejects; the PUT's response callback must not read a