Form files: an upload aborted while the gates are pending no longer leaves its attempt key registered

Re-review of 1.16.0: beforeFiles could resume after the request was answered and
register the attempt key with nobody left to release it. It now stops after every
await once the request is over; the registration has no await before it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-13 17:09:14 +01:00
co-authored by Claude Fable 5.2
parent 7ecfb26eb1
commit 6f006825a4
2 changed files with 53 additions and 4 deletions
+19 -4
View File
@@ -195,7 +195,13 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
conclude(outcome ?? { reason: 'error', success: false })
}
/** 5–8: everything that must hold before the first file byte is accepted. */
/**
* 5–8: everything that must hold before the first file byte is accepted.
*
* The request can be aborted (and answered, and its `finally` run) while one of the awaits below is
* still pending. So after EVERY await: if the request is over, stop — above all before the attempt key
* is registered, or the key would be left behind with nobody to release it.
*/
const beforeFiles = async () => {
locale = localeOf(payload, fields._locale) ?? locale
const formId = fields._form
@@ -215,25 +221,34 @@ export async function handleFormSubmit(req: PayloadRequest): Promise<Response> {
const token = fields._token?.trim() || undefined
const blocked = await passTurnstile({ ip, payload, turnstileHostnames: submit.turnstileHostnames, turnstileOnConfigError: submit.turnstileOnConfigError, turnstileToken: token })
if (settled) {return}
if (blocked) {return stop(blocked)}
const checked = await validateSubmitFields({ data: answers, formId, locale, payload })
if (settled) {return}
if ('failure' in checked) {return stop(checked.failure)}
// A repeated request (same attempt key) gets the first answer; nothing is sent twice.
const attemptKey = cleanAttemptKey(fields._attempt)
if (attemptKey) {
const running = inflight.get(attemptKey)
if (running) {return stop(await running)}
// Registered before the next await, so a twin request arriving now waits for this one.
if (running) {
const first = await running
return settled ? undefined : stop(first)
}
// No await between the check above and this registration: a request that is already over never
// gets here, and a twin request arriving now finds the key and waits for this one.
registered = attemptKey
inflight.set(attemptKey, new Promise<SubmitFormResult>((done) => (settle = done)))
const earlier = await findSubmitAttempt(payload, attemptKey)
if (settled) {return}
if (earlier) {return stop(earlier)}
}
if (checked.validation.fileFields.length > 0 && !canCarryFiles(checked.validation.form)) {return stop({ reason: 'delivery', success: false })}
gate = createFileGate({ fields: checked.validation.fileFields, options, transportMaxBytes: await mailAttachmentLimit(payload) })
const transportMaxBytes = await mailAttachmentLimit(payload)
if (settled) {return}
gate = createFileGate({ fields: checked.validation.fileFields, options, transportMaxBytes })
stored = { attemptKey, formId, locale, payload, validation: checked.validation }
}
+34
View File
@@ -854,6 +854,40 @@ describe('options a project can set', () => {
await backToNormal(attempt) // the browser's retry with the same attempt key is not left waiting
})
// Re-review of 1.16.0: the abort can land while the gates before the first file byte are still waiting
// (the form look-up, the attempt look-up, Turnstile). The work that resumes afterwards must not leave the
// attempt key registered — or every retry with that key would wait on a promise nobody settles.
test.each([
['the form look-up (before the key is registered)', 'findByID'],
['the attempt look-up (after the key is registered)', 'find'],
] as const)('the connection drops while %s is still pending: the key is not left behind', async (_name, method) => {
const attempt = `attempt-pending-${method.padEnd(8, '0')}`
const original = other[method].bind(other) as (...args: unknown[]) => Promise<unknown>
const slow = vi.spyOn(other, method as 'find').mockImplementation((async (...args: unknown[]) => {
await new Promise((resolve) => setTimeout(resolve, 300))
return original(...args)
}) as never)
const dropped = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(Buffer.concat([prelude(attempt), PDF.subarray(0, 2000)]))
setTimeout(() => controller.error(new Error('ECONNRESET')), 30)
},
})
const response = await within(raw(dropped), 3000)
expect(response).not.toBe('HUNG')
expect((response as Response).status).toBe(400)
expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
// …and it is still so once the pending look-ups have finished
await new Promise((resolve) => setTimeout(resolve, 1000))
expect(slow).toHaveBeenCalled()
slow.mockRestore()
expect(formSubmitState()).toEqual({ active: 0, inflight: 0 })
// the browser's retry with the same key is answered at once
const started = Date.now()
await backToNormal(attempt)
expect(Date.now() - started).toBeLessThan(1000)
})
test('two dropped uploads do not use up the concurrency slots (maxConcurrent: 1 here)', async () => {
for (let i = 0; i < 2; i++) {
const dropped = new ReadableStream<Uint8Array>({