Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 7 additions & 0 deletions .changeset/cache-declared-upload-length.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@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.
5 changes: 5 additions & 0 deletions .changeset/idempotent-file-kv-delete.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tus/utils": patch
---

Define `KvStore.delete` to succeed for missing keys and implement it in `FileKvStore`.
44 changes: 23 additions & 21 deletions packages/s3-store/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -685,24 +685,19 @@ 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.
// AWS S3 returns NoSuchUpload, but other implementations, such as DigitalOcean
// Spaces, can also return NoSuchKey.
if (isS3NotFoundError(error, S3_MISSING_UPLOAD_ERROR_CODES)) {
return new Upload({
...metadata.file,
offset: metadata.file.size as number,
size: metadata.file.size,
metadata: metadata.file.metadata,
storage: metadata.file.storage,
})
if (!isS3NotFoundError(error, S3_MISSING_UPLOAD_ERROR_CODES)) {
log(error)
throw error
}

log(error)
throw error
// Assume a missing multipart upload is complete for compatibility.
return new Upload({
...metadata.file,
offset: metadata.file.size as number,
size: metadata.file.size,
metadata: metadata.file.metadata,
storage: metadata.file.storage,
})
}

const incompletePartSize = await this.getIncompletePartSize(id)
Expand All @@ -716,14 +711,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 +747,7 @@ export class S3Store extends DataStore {
},
})

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

protected getExpirationDate(created_at: string) {
Expand Down Expand Up @@ -834,6 +830,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
138 changes: 135 additions & 3 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 @@ -425,18 +475,100 @@ describe('S3DataStore', () => {
: {Code: S3Error.name}

// @ts-expect-error protected property
sinon.stub(store.client, 'listParts').rejects(error)
const client = store.client
sinon.stub(client, 'listParts').rejects(error)
const head = sinon
.stub(client, 'headObject')
.rejects(new Error('headObject should not be called'))

if (completed) {
const upload = await store.getUpload(id)
assert.equal(upload.offset, 10)
} else {
await assert.rejects(store.getUpload(id), (thrown) => thrown === error)
}
assert.equal(head.called, false)
})
}
}

it('should report a cached upload missing after expiration cleanup', async () => {
const store = new S3Store({s3ClientConfig, expirationPeriodInMilliseconds: 1})
const upload = new Upload({
id: shared.testId('expired-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 {
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)
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
2 changes: 1 addition & 1 deletion packages/utils/src/kvstores/FileKvStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class FileKvStore<T = Upload> implements KvStore<T> {
}

async delete(key: string): Promise<void> {
await fs.rm(this.resolve(key))
await fs.rm(this.resolve(key), {force: true})
}

async list(): Promise<Array<string>> {
Expand Down
1 change: 1 addition & 0 deletions packages/utils/src/kvstores/Types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {Upload} from '../models/index.js'
export interface KvStore<T = Upload> {
get(key: string): Promise<T | undefined>
set(key: string, value: T): Promise<void>
/** Deletes a key, succeeding if it does not exist. */
delete(key: string): Promise<void>

list?(): Promise<Array<string>>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,27 @@ describe('FileKvStore', () => {
})
)

describe('delete', () => {
it('succeeds when the key is absent', async () => {
await store.delete('missing')
})

it('succeeds when deleting a key more than once', async () => {
await store.set('upload', {n: 1})
await store.delete('upload')
await store.delete('upload')
assert.equal(await store.get('upload'), undefined)
})

it('does not delete a directory at the key path', async () => {
const directoryPath = path.join(directory, 'key.json')
await fs.mkdir(directoryPath)

await assert.rejects(store.delete('key'))
assert.equal((await fs.stat(directoryPath)).isDirectory(), true)
})
})

describe('list', () => {
it('ignores unpaired files', async () => {
await touch('stray', 'orphan.json')
Expand Down
Loading