Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

fix: recover a sliced upload whose slice was accepted but whose response was lost, by resyncing from session status and draining the body before an early 409 (#381)

Murtaza Nasir193b02263596
diff --git a/src/api/recording_sessions.py b/src/api/recording_sessions.py
index 8d9ba91d..8da8985d 100644
--- a/src/api/recording_sessions.py
+++ b/src/api/recording_sessions.py
@@ -458,6 +458,18 @@ def upload_chunk(session_id, chunk_index):
expected_index = session.chunk_count + 1
if chunk_index != expected_index:
+ # Read the body before answering. This 409 carries the index the
+ # client should continue from, and the usual reason a client sends
+ # the wrong index is that it never saw our previous answer. Replying
+ # while megabytes of its body are still in flight makes an HTTP/2
+ # front end reset the stream, and the browser then reports a
+ # protocol error instead of this response, so the hint is lost and
+ # the client keeps re-sending the same slice. Draining costs one
+ # slice of bandwidth on a rare path; losing the hint costs the upload.
+ try:
+ request.get_data(cache=False)
+ except Exception:
+ pass
return jsonify({
'error': 'Out-of-order chunk',
'expected_chunk_index': expected_index,
diff --git a/static/js/modules/db/sliced-file-upload.js b/static/js/modules/db/sliced-file-upload.js
index cfb3c7c1..e17aa42f 100644
--- a/static/js/modules/db/sliced-file-upload.js
+++ b/static/js/modules/db/sliced-file-upload.js
@@ -262,6 +262,21 @@ async function deleteFileSession(sessionId, token) {
* about them says the next attempt would fail too: the transport, and
* the statuses a gateway returns while something behind it restarts.
*/
+/**
+ * How many slices the server already holds for a session, or null when the
+ * status could not be read. Null is deliberately not zero: a failed read must
+ * fall back to a retry, not be mistaken for "the server has nothing".
+ */
+async function slicesHeldByServer(sessionId, token) {
+ try {
+ const status = await readSessionStatus(sessionId, token);
+ const n = status && status.chunk_count;
+ return Number.isInteger(n) ? n : null;
+ } catch (_) {
+ return null;
+ }
+}
+
async function sendSlice(sessionId, index, blob, tokenRef, options) {
const url = `${SESSION_BASE}/${encodeURIComponent(sessionId)}/chunks/${index}`;
for (let attempt = 1; ; attempt++) {
@@ -275,6 +290,19 @@ async function sendSlice(sessionId, index, blob, tokenRef, options) {
onXhr: options.onXhr,
});
} catch (transportError) {
+ // A transport failure does not mean the slice was lost. The
+ // common case is the opposite: the server took it and answered,
+ // and the answer never arrived. That includes a 409 the server
+ // sends before it has read the whole body: under HTTP/2 that
+ // resets the stream, and the browser reports a protocol error
+ // instead of a response we could read `expected_chunk_index`
+ // from. Blindly re-sending then draws the same 409 every time
+ // until the attempt cap and fails an upload the server has
+ // already accepted in full. So ask the server what it holds; a
+ // GET has no body to cut short.
+ const held = await slicesHeldByServer(sessionId, tokenRef.token);
+ if (held !== null && held >= index) return held + 1;
+
if (attempt >= MAX_SLICE_ATTEMPTS) {
transportError.resumable = true;
throw transportError;
diff --git a/static/js/modules/db/sliced-file-upload.test.js b/static/js/modules/db/sliced-file-upload.test.js
index 61458b0a..59322d18 100644
--- a/static/js/modules/db/sliced-file-upload.test.js
+++ b/static/js/modules/db/sliced-file-upload.test.js
@@ -209,6 +209,73 @@ describe('uploadFileInSlices', () => {
]);
});
+ it('advances past a slice the server already holds when only the response was lost', async () => {
+ // Seen against a real NPM/HTTP2 proxy: the server accepted slice 2
+ // and answered, but the answer never reached the client as a
+ // readable response (an early 409 resets the stream; the browser
+ // reports a protocol error). The client used to re-send the same
+ // slice until MAX_SLICE_ATTEMPTS and then fail an upload the server
+ // had accepted in full. It must instead ask the server what it holds.
+ vi.useFakeTimers();
+ const file = fakeFile(40 * MB); // 3 slices
+ sliceResponses = [
+ { status: 204 }, // slice 1
+ { networkError: true }, // slice 2: sent, but the answer is lost
+ { status: 204 }, // slice 3
+ ];
+ // The status read after the failure shows the server already has 2.
+ sessionStatus = { kind: 'sliced_upload', status: 'recording', chunk_count: 2, upload_total_bytes: 40 * MB };
+
+ const upload = uploadFileInSlices(file, new Map(), {});
+ await vi.advanceTimersByTimeAsync(5000);
+
+ expect(await upload).toMatchObject({ id: 42 });
+ const chunk2Posts = slicePosts().filter(c => c.url.endsWith('/chunks/2'));
+ expect(chunk2Posts).toHaveLength(1); // never re-sent
+ expect(slicePosts().map(c => c.url.slice(-1))).toEqual(['1', '2', '3']);
+ });
+
+ it('re-sends a slice after a transport failure when the server really does not have it', async () => {
+ // The converse, so the resync cannot turn a genuine loss into a skip.
+ vi.useFakeTimers();
+ const file = fakeFile(40 * MB);
+ sliceResponses = [
+ { status: 204 }, // slice 1
+ { networkError: true }, // slice 2 genuinely lost
+ { status: 204 }, // slice 2 again
+ { status: 204 }, // slice 3
+ ];
+ sessionStatus = { kind: 'sliced_upload', status: 'recording', chunk_count: 1, upload_total_bytes: 40 * MB };
+
+ const upload = uploadFileInSlices(file, new Map(), {});
+ await vi.advanceTimersByTimeAsync(10000);
+
+ expect(await upload).toMatchObject({ id: 42 });
+ expect(slicePosts().map(c => c.url.slice(-1))).toEqual(['1', '2', '2', '3']);
+ });
+
+ it('falls back to a plain retry when the status read itself fails', async () => {
+ // A failed status read is "unknown", never "the server has nothing";
+ // treating it as zero would re-send everything after any blip.
+ // httpStatus makes the mocked GET answer 502, which readSessionStatus
+ // throws on (only 404/403 mean "no such session").
+ vi.useFakeTimers();
+ const file = fakeFile(40 * MB);
+ sliceResponses = [
+ { status: 204 },
+ { networkError: true },
+ { status: 204 },
+ { status: 204 },
+ ];
+ sessionStatus = { httpStatus: 502 };
+
+ const upload = uploadFileInSlices(file, new Map(), {});
+ await vi.advanceTimersByTimeAsync(10000);
+
+ expect(await upload).toMatchObject({ id: 42 });
+ expect(slicePosts().map(c => c.url.slice(-1))).toEqual(['1', '2', '2', '3']);
+ });
+
it('gives up on a rejected slice and deletes the half-uploaded session', async () => {
sliceResponses = [
{ status: 204, text: '' },