Count a timed-out upload waiter while shared transport continues

This commit is contained in:
creatixchu committed 2026-11-11 21:17:45 +08:00
1 parent 92994f4d32
commit 9fd05ac4f4
2 files changed
+39 -11

No files matched your search

+9 -7
View File
@@ -1,6 +1,5 @@
/** DeepSeek Files API upload reuse, invalidation, and quota recovery. @module dsh-llm-deepseek/file-store */
import { addAbortListener } from 'node:events'
import { timeoutOf } from '@deepseek-ai/dsh-timeout'
import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment'
import { LlmError } from '@deepseek-ai/dsh-llm'
@@ -57,6 +56,7 @@ interface SharedUpload {
promise: Promise<DeepSeekFileReference>
settled: boolean
waiters: number
onUploadTimeout?: () => void
}
/** The Files resource's parent URL identifies the upload namespace. */
@@ -100,6 +100,7 @@ function waitForUpload(operation: SharedUpload, signal: AbortSignal | undefined)
return new Promise<DeepSeekFileReference>((resolve, reject) => {
const abort = (): void => {
const reason = abortReason(signal)
if (timeoutOf(signal, FILES_API_TIMEOUT)) operation.onUploadTimeout?.()
release(reason)
reject(reason)
}
@@ -211,7 +212,7 @@ export class DeepSeekFileStore {
waiters: 0,
promise: undefined as never,
}
shared.promise = this.ensureUploadedOnce(version, connection, policy, scope, controller.signal).then((value) => {
shared.promise = this.ensureUploadedOnce(version, connection, policy, scope, shared).then((value) => {
shared.settled = true
return value
}, (error: unknown) => {
@@ -230,8 +231,9 @@ export class DeepSeekFileStore {
connection: DeepSeekFileConnection,
policy: DeepSeekFilePolicy,
scope: DeepSeekUploadRecord['scope'],
signal: AbortSignal,
shared: SharedUpload,
): Promise<DeepSeekFileReference> {
const signal = shared.controller.signal
const now = this.now()
const marginMs = policy.refreshMarginSeconds * 1_000
const cached = await this.index.get(scope, version.variantId, now, marginMs)
@@ -242,18 +244,18 @@ export class DeepSeekFileStore {
signal.throwIfAborted()
const previous = this.backoffs.get(scope)
// Count overlapping uploads from one failure interval once, even if an aborted transport never settles.
using _listener = addAbortListener(signal, () => {
if (!timeoutOf(signal, FILES_API_TIMEOUT) || this.backoffs.get(scope) !== previous) return
shared.onUploadTimeout = () => {
if (this.backoffs.get(scope) !== previous) return
const interval = previous ? previous.interval * 2n : 1n
this.backoffs.set(scope, { interval, remaining: interval })
})
}
const remote = await client.upload({
data: version.data,
mediaType: version.mediaType,
filename: filename(version),
expiresAfterSeconds: policy.expiresAfterSeconds,
signal,
})
}).finally(() => { delete shared.onUploadTimeout })
if (remote.bytes !== version.data.byteLength) {
throw new LlmError('DeepSeek Files API upload response does not match the submitted image.', 'INVALID_RESPONSE')
}
@@ -108,8 +108,32 @@ describe('DeepSeekFileStore', () => {
await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true })
const fresh = { ...VERSION, variantId: brandString<ImageVariantId>(`sha256:${'d'.repeat(64)}`) }
await expire(fresh)
await expect(store.ensureUploaded(fresh, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'TIMEOUT' })
await expect(store.ensureUploaded(fresh, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true })
// Two independent requests race for the last skip. The other must upload.
const competing = await Promise.allSettled([
store.ensureUploaded(fresh, CONNECTION, POLICY), store.ensureUploaded(fresh, CONNECTION, POLICY),
])
expect(competing).toEqual(expect.arrayContaining([
expect.objectContaining({ status: 'rejected', reason: expect.objectContaining({ code: 'TIMEOUT' }) }),
expect.objectContaining({ status: 'fulfilled', value: expect.objectContaining({ uploaded: true }) }),
]))
})
it('does not count a Files deadline reached before the upload starts', async () => {
const dir = await mkdtemp(join(tmpdir(), 'dsh-files-index-timeout-'))
roots.push(dir)
const index = new DeepSeekUploadIndex(join(dir, 'index.json'))
const lookup = Promise.withResolvers<undefined>()
vi.spyOn(index, 'get').mockReturnValueOnce(lookup.promise)
const remote = uploadFetch()
const store = new DeepSeekFileStore({ index, fetch: remote.fetchImpl, now: () => NOW })
const controller = new AbortController()
const pending = store.ensureUploaded(VERSION, CONNECTION, POLICY, controller.signal)
const reason = new TimeoutReason(FILES_API_TIMEOUT, 20_000)
controller.abort(reason)
lookup.resolve(undefined)
await expect(pending).rejects.toBe(reason)
await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true })
expect(remote.uploads()).toBe(1)
})
it('counts overlapping timeouts once and keeps an abandoned response from clearing backoff', async () => {
@@ -252,7 +276,7 @@ describe('DeepSeekFileStore', () => {
expect(remote.uploads()).toBe(1)
})
it('keeps a shared upload alive while another waiter remains', async () => {
it.each([new Error('cancel one upload waiter'), new TimeoutReason(FILES_API_TIMEOUT, 20_000)])('keeps a shared upload alive after one waiter exits with %s', async (reason) => {
const dir = await mkdtemp(join(tmpdir(), 'dsh-file-store-'))
roots.push(dir)
const index = new DeepSeekUploadIndex(join(dir, 'index.json'))
@@ -275,11 +299,13 @@ describe('DeepSeekFileStore', () => {
await vi.waitFor(() => {
expect(fetchImpl).toHaveBeenCalledTimes(1)
})
const reason = new Error('cancel one upload waiter')
controller.abort(reason)
await expect(cancelled).rejects.toBe(reason)
expect(uploadSignal?.aborted).toBe(false)
if (reason instanceof TimeoutReason) {
await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'TIMEOUT' })
}
complete?.(new Response(JSON.stringify({
id: 'file-api-shared',
type: 'file',