Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/cache-declared-upload-length.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@tus/s3-store": patch
---

Update cached metadata after declaring a deferred upload length so uploads can finish with caches that return copies such as RedisKvStore, IoRedisKvStore and FileKvStore.
`remove` now awaits cache eviction so a failing cache rejects the termination instead of causing an unhandled rejection.
Expiration cleanup also evicts cached metadata. When a multipart upload is missing, verify that the final object exists and matches the declared size before reporting completion, so aborted uploads are not mistaken for completed uploads.
Missing cache entries are tolerated during S3 expiration cleanup.
55 changes: 44 additions & 11 deletions packages/s3-store/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,19 @@ export class S3Store extends DataStore {
*/
protected async clearCache(id: string) {
log(`[${id}] removing cached data`)
await this.cache.delete(id)
try {
await this.cache.delete(id)
} catch (error) {
if (
typeof error === 'object' &&
error !== null &&
'code' in error &&
error.code === 'ENOENT'
) {
return
}
throw error
}
}

protected calcOptimalPartSize(size?: number): number {
Expand Down Expand Up @@ -685,16 +697,30 @@ export class S3Store extends DataStore {
const parts = await this.retrieveParts(id)
offset = calcOffsetFromParts(parts)
} catch (error) {
// Check if the error is caused by the upload not being found. This happens
// when the multipart upload has already been completed or aborted. Since
// we already found the info object, we know that the upload has been
// completed and therefore can ensure the the offset is the size.
// A missing multipart upload can mean completion or abortion.
// AWS S3 returns NoSuchUpload, but other implementations, such as DigitalOcean
// Spaces, can also return NoSuchKey.
if (isS3NotFoundError(error, S3_MISSING_UPLOAD_ERROR_CODES)) {
let object: AWS.HeadObjectCommandOutput
try {
object = await this.client.headObject({Bucket: this.bucket, Key: id})
} catch (headError) {
if (isS3NotFoundError(headError)) {
throw ERRORS.FILE_NOT_FOUND
}
throw headError
}

if (
metadata.file.size === undefined ||
object.ContentLength !== metadata.file.size
) {
throw ERRORS.FILE_NOT_FOUND
}

return new Upload({
...metadata.file,
offset: metadata.file.size as number,
offset: metadata.file.size,
size: metadata.file.size,
metadata: metadata.file.metadata,
storage: metadata.file.storage,
Expand All @@ -716,14 +742,15 @@ export class S3Store extends DataStore {
}

public async declareUploadLength(file_id: string, upload_length: number) {
const {file, 'upload-id': uploadId} = await this.getMetadata(file_id)
if (!file) {
const metadata = await this.getMetadata(file_id)
if (!metadata.file) {
throw ERRORS.FILE_NOT_FOUND
}

file.size = upload_length
metadata.file.size = upload_length

await this.saveMetadata(file, uploadId)
await this.saveMetadata(metadata.file, metadata['upload-id'])
await this.cache.set(file_id, metadata)
}

public async remove(id: string): Promise<void> {
Expand Down Expand Up @@ -751,7 +778,7 @@ export class S3Store extends DataStore {
},
})

this.clearCache(id)
await this.clearCache(id)
}

protected getExpirationDate(created_at: string) {
Expand Down Expand Up @@ -834,6 +861,12 @@ export class S3Store extends DataStore {
}),
])

await Promise.all(
expiredUploads.map((expiredUpload) =>
this.clearCache(expiredUpload.Key as string)
)
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
)

deleted += objectsDeleted.reduce((all, acc) => all + (acc.Deleted?.length ?? 0), 0)

isTruncated = Boolean(listResponse.IsTruncated)
Expand Down
198 changes: 196 additions & 2 deletions packages/s3-store/src/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {once} from 'node:events'
import fs from 'node:fs'
import {createServer, type Server} from 'node:http'
import type {AddressInfo} from 'node:net'
import {tmpdir} from 'node:os'
import {Readable} from 'node:stream'
import {buffer} from 'node:stream/consumers'
import stream from 'node:stream/promises'
Expand All @@ -13,10 +14,10 @@ import {gzipSync} from 'node:zlib'
import {NoSuchKey, NoSuchUpload, NotFound} from '@aws-sdk/client-s3'
import sinon from 'sinon'

import {S3Store} from '@tus/s3-store'
import {S3Store, type MetadataValue} from '@tus/s3-store'
import {Server as TusServer} from '@tus/server'
import * as shared from '../../../utils/dist/test/stores.js'
import {StreamLimiter, Upload} from '@tus/utils'
import {FileKvStore, StreamLimiter, Upload} from '@tus/utils'

const fixturesPath = path.resolve('../', '../', 'test', 'fixtures')
const storePath = path.resolve('../', '../', 'test', 'output', 's3-store')
Expand Down Expand Up @@ -291,6 +292,34 @@ describe('S3DataStore', () => {
}
})

for (const size of [0, 10]) {
it(`should finalize a ${size}-byte deferred upload with FileKvStore`, async () => {
const directory = await fs.promises.mkdtemp(
path.join(tmpdir(), 'tus-declared-length-')
)
const store = new S3Store({
cache: new FileKvStore<MetadataValue>(directory),
s3ClientConfig,
})
const upload = new Upload({
id: shared.testId('declared-length-file-cache'),
offset: 0,
})

try {
await store.create(upload)
assert.equal((await store.getUpload(upload.id)).size, undefined)

await store.declareUploadLength(upload.id, size)
const data = Buffer.alloc(size, 0x61)
assert.equal(await store.write(Readable.from([data]), upload.id, 0), size)
assert.deepEqual(await buffer(await store.read(upload.id)), data)
} finally {
await fs.promises.rm(directory, {recursive: true, force: true})
}
})
}

for (const creationWithUpload of [false, true]) {
const scenario = creationWithUpload ? 'creation-with-upload' : 'ordinary POST'

Expand Down Expand Up @@ -354,6 +383,27 @@ describe('S3DataStore', () => {
await assert.rejects(store.remove(id), {status_code: 404})
})

it('should reject when clearing the cache fails after removing an upload', async function () {
const store = this.datastore as S3Store
const id = shared.testId('remove-cache-failure')
const error = new Error('cache unavailable')

// @ts-expect-error protected method
sinon.stub(store, 'getMetadata').resolves({
file: new Upload({id, size: 1, offset: 0}),
'upload-id': 'upload-id',
'tus-version': '1.0.0',
})
// @ts-expect-error protected property
sinon.stub(store.client, 'abortMultipartUpload').resolves({})
// @ts-expect-error protected property
sinon.stub(store.client, 'deleteObjects').resolves({})
// @ts-expect-error protected method
sinon.stub(store, 'clearCache').rejects(error)

await assert.rejects(store.remove(id), (thrown) => thrown === error)
})

it('should delete the incomplete part when removing an upload', async function () {
const store = this.datastore as S3Store
const incompleteSize = 1024
Expand Down Expand Up @@ -426,17 +476,161 @@ describe('S3DataStore', () => {

// @ts-expect-error protected property
sinon.stub(store.client, 'listParts').rejects(error)
// @ts-expect-error protected property
const head = sinon.stub(store.client, 'headObject').resolves({ContentLength: 10})

if (completed) {
const upload = await store.getUpload(id)
assert.equal(upload.offset, 10)
assert.deepEqual(head.args, [[{Bucket: s3ClientConfig.bucket, Key: id}]])
} else {
await assert.rejects(store.getUpload(id), (thrown) => thrown === error)
assert.equal(head.called, false)
}
})
}
}

describe('missing multipart upload verification', () => {
for (const scenario of [
{
name: 'missing object',
error: new NotFound({$metadata: {}, message: 'missing'}),
missing: true,
},
{name: 'missing key', error: {Code: 'NoSuchKey'}, missing: true},
{
name: 'access denied',
error: Object.assign(new Error('denied'), {name: 'AccessDenied'}),
missing: false,
},
{name: 'network failure', error: new Error('connection reset'), missing: false},
{name: 'size mismatch', size: 10, length: 9, missing: true},
{name: 'undeclared size', size: undefined, length: 0, missing: true},
]) {
it(`should reject a ${scenario.name} instead of reporting completion`, async function () {
const store = this.datastore as S3Store
const id = shared.testId('verify-completion')
// @ts-expect-error protected method
sinon.stub(store, 'getMetadata').resolves({
file: new Upload({
id,
size: 'size' in scenario ? scenario.size : 10,
offset: 0,
}),
'upload-id': 'upload-id',
'tus-version': '1.0.0',
})
// @ts-expect-error protected property
sinon.stub(store.client, 'listParts').rejects({Code: 'NoSuchUpload'})
// @ts-expect-error protected property
const head = sinon.stub(store.client, 'headObject')
if ('error' in scenario) {
head.rejects(scenario.error)
} else {
head.resolves({ContentLength: scenario.length})
}

await assert.rejects(
store.getUpload(id),
scenario.missing ? {status_code: 404} : (error) => error === scenario.error
)
})
}
})

for (const cleanup of [false, true]) {
it(`should report a cached upload missing after ${cleanup ? 'expiration cleanup' : 'a lifecycle-style abort'}`, async () => {
const store = new S3Store({s3ClientConfig, expirationPeriodInMilliseconds: 1})
const upload = new Upload({
id: shared.testId('aborted-upload'),
size: 10,
offset: 0,
})
await store.create(upload)
assert.equal((await store.getUpload(upload.id)).offset, 0)
// @ts-expect-error protected property
const client = store.client
// @ts-expect-error protected property
const cache = store.cache
const metadata = await cache.get(upload.id)
assert.ok(metadata)

try {
if (cleanup) {
sinon.stub(client, 'listMultipartUploads').resolves({
Uploads: [
{Key: upload.id, UploadId: metadata['upload-id'], Initiated: new Date(0)},
],
})
await store.deleteExpired()
assert.equal(await cache.get(upload.id), undefined)
} else {
await client.abortMultipartUpload({
Bucket: s3ClientConfig.bucket,
Key: upload.id,
UploadId: metadata['upload-id'],
})
assert.ok(await cache.get(upload.id))
}

await assert.rejects(store.getUpload(upload.id), {status_code: 404})
// Also verify the lifecycle case with metadata loaded from S3, not the cache.
await cache.delete(upload.id)
await assert.rejects(store.getUpload(upload.id), {status_code: 404})
} finally {
await client.deleteObject({
Bucket: s3ClientConfig.bucket,
Key: `${upload.id}.info`,
})
}
})
}

it('should tolerate missing file cache entries during expiration cleanup', async () => {
const directory = await fs.promises.mkdtemp(path.join(tmpdir(), 'tus-expired-cache-'))
const cache = new FileKvStore<MetadataValue>(directory)
const store = new S3Store({
cache,
s3ClientConfig,
expirationPeriodInMilliseconds: 1,
})
// @ts-expect-error protected property
const client = store.client
const get = sinon.spy(cache, 'get')
const set = sinon.spy(cache, 'set')
sinon.stub(client, 'listMultipartUploads').resolves({
Uploads: [{Key: 'expired', UploadId: 'upload-id', Initiated: new Date(0)}],
})
sinon.stub(client, 'deleteObjects').resolves({Deleted: [{Key: 'expired.info'}]})
sinon.stub(client, 'abortMultipartUpload').resolves({})

try {
assert.equal(await store.deleteExpired(), 1)
assert.equal(get.called, false)
assert.equal(set.called, false)
} finally {
await fs.promises.rm(directory, {recursive: true, force: true})
}
})

it('should reject when cache eviction fails during expiration cleanup', async () => {
const store = new S3Store({s3ClientConfig, expirationPeriodInMilliseconds: 1})
const error = new Error('cache unavailable')
// @ts-expect-error protected property
const client = store.client
// @ts-expect-error protected property
const cache = store.cache
sinon.stub(client, 'listMultipartUploads').resolves({
Uploads: [{Key: 'expired', UploadId: 'upload-id', Initiated: new Date(0)}],
})
sinon.stub(client, 'deleteObjects').resolves({})
sinon.stub(client, 'abortMultipartUpload').resolves({})
sinon.stub(cache, 'delete').rejects(error)

await assert.rejects(store.deleteExpired(), (thrown) => thrown === error)
})

it('should use default maxMultipartParts when not specified', () => {
const store = new S3Store({
s3ClientConfig,
Expand Down
Loading