diff --git a/src/storage/protocols/tus/s3-locker.ts b/src/storage/protocols/tus/s3-locker.ts index 89965dac0..797d0254f 100644 --- a/src/storage/protocols/tus/s3-locker.ts +++ b/src/storage/protocols/tus/s3-locker.ts @@ -399,6 +399,14 @@ export class S3Lock implements Lock { if (!acquired || stopSignal.aborted) { this.cleanup() + + // The request aborted while the lock was being created, so nobody will unlock it + if (acquired) { + await this.locker.releaseLock(this.id).catch((error) => { + this.locker.getLogger().error('Failed to release S3 lock:', error) + }) + } + throw ERRORS.LockTimeout() } diff --git a/src/test/s3-locker.test.ts b/src/test/s3-locker.test.ts index 4e07dc03b..88c685213 100644 --- a/src/test/s3-locker.test.ts +++ b/src/test/s3-locker.test.ts @@ -6,6 +6,7 @@ import { PutObjectCommand, S3Client, } from '@aws-sdk/client-s3' +import { ErrorCode } from '@internal/errors' import type { PubSubAdapter } from '@internal/pubsub' import type { Mock } from 'vitest' import { getConfig } from '../config' @@ -697,6 +698,32 @@ describe('S3Locker', () => { trackLock(newLock) await newLock.unlock() }, 15000) + + test('should not keep the lock when the request aborts as the acquiring PUT completes', async () => { + const lockId = 'abort-during-acquire-lock' + const abortController = new AbortController() + + // S3 creates the lock object, then the request aborts before lock() sees the result + const originalSend = s3Client.send.bind(s3Client) + vi.spyOn(s3Client, 'send').mockImplementation(async (command) => { + const result = await originalSend(command) + if (command instanceof PutObjectCommand && command.input.IfNoneMatch === '*') { + abortController.abort() + } + return result + }) + + await expect( + locker.newLock(lockId).lock(abortController.signal, vi.fn()) + ).rejects.toMatchObject({ code: ErrorCode.LockTimeout }) + + // Nobody owns the lock now, so it must not be left in S3 for the next request to wait on + await expect( + s3Client.send( + new GetObjectCommand({ Bucket: testBucket, Key: `test-locks/${lockId}.lock` }) + ) + ).rejects.toMatchObject({ name: 'NoSuchKey' }) + }) }) describe('Instance Isolation', () => {