Skip to content

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

Python

fix: harden the sliced upload path against the review findings

François Catuhe7a7981ca9ae9
diff --git a/docs/admin-guide/recording-sessions.md b/docs/admin-guide/recording-sessions.md
index e29fd314..41a6cbcf 100644
--- a/docs/admin-guide/recording-sessions.md
+++ b/docs/admin-guide/recording-sessions.md
@@ -46,23 +46,34 @@ request.
A few differences from a recorder session are worth knowing when reading
logs:
-- Its `recording_session` row has `upload_filename` set. That is what
- distinguishes the two, and each finalize route rejects the other's
- sessions with a 409.
+- Its `recording_session` row has `kind = 'sliced_upload'`, and each
+ finalize route rejects the other kind with a 409.
- The slices are byte ranges of one complete container, not
MediaRecorder timeslices, so finalize does a plain byte-join with no
- ffmpeg concat, no remux, and no container sniffing. The stored file is
- byte-identical to what the user picked.
+ ffmpeg concat, no remux, and no container sniffing. What reaches
+ ingestion is byte-identical to what the user picked, and from there it
+ is treated exactly like a single-shot upload, conversion included.
+- The client declares the file size when it opens the session, and
+ finalize refuses to ingest slices that do not add up to it. A missing
+ or short slice fails loudly rather than becoming a truncated recording.
- `finalize-upload` is synchronous: hashing, probing and any conversion
happen in-request exactly as they do for `POST /upload`, so it holds
the connection for as long as that takes and needs the same generous
- proxy read timeout.
+ proxy read timeout. A retry after a lost response gets the first
+ call's recording back rather than re-ingesting the file.
- An abandoned one is expired by the cleanup sweep rather than
auto-finalized. The user still has the original file, and its slices
are a truncated container rather than a playable partial recording.
-- Losing the finalize response loses the upload: unlike the recorder's
- `/finalize`, it is not replayable. The client re-uploads, and
- duplicate detection flags the second copy if the first landed.
+- A failed finalize deletes the slices with it. They cannot be reused,
+ since finalize only accepts a session that is still recording.
+
+!!! warning "`RECORDING_SESSION_COMMIT_BATCH_SIZE` must stay at 1"
+
+ Above 1, the chunk endpoint flushes its bookkeeping without
+ committing and the request teardown rolls it back, so the server
+ keeps asking for the same chunk index forever. A sliced upload gives
+ up after a few non-advancing retries and reports it; a recorder
+ session silently overwrites its first chunk and loses the recording.
## Configuration
@@ -195,7 +206,7 @@ on the server, or discard them.
| Method | Path | Purpose |
|---|---|---|
-| POST | `/upload/session` | Create a new session. Body: `{mime_type}`, plus `{filename}` for a sliced file upload. |
+| POST | `/upload/session` | Create a new session. Body: `{mime_type}`, plus `{filename, total_bytes}` for a sliced file upload. |
| POST | `/upload/session/{id}/chunks/{N}` | Append chunk N (must be `chunk_count + 1`). Body is raw bytes. |
| GET | `/upload/session/{id}` | Status of an existing session. |
| POST | `/upload/session/{id}/finalize` | Request asynchronous stitch + transcribe kickoff. |
diff --git a/src/api/recording_sessions.py b/src/api/recording_sessions.py
index 13de1a91..7d744007 100644
--- a/src/api/recording_sessions.py
+++ b/src/api/recording_sessions.py
@@ -21,13 +21,14 @@ All endpoints require login. They write the on-disk layout described in
Creating a session with a ``filename`` makes it a sliced upload of a file
the user already has on disk (used to cross a reverse proxy whose body
-limit is below the file size) rather than a recorder session. Those
-sessions share create / chunk / abort with the recorder but finalize
-through ``/finalize-upload``, which byte-joins the slices and hands the
-result to the same ingestion pipeline ``POST /upload`` uses. The declared
-mime type is not checked against ``RECORDING_SESSION_ALLOWED_MIME_TYPES``
-for them: the user picks the container, and ffprobe gates it at ingest.
-The two finalize routes reject each other's sessions.
+limit is below the file size) rather than a recorder session; the row's
+``kind`` records which it is. Those sessions share create / chunk / abort
+with the recorder but finalize through ``/finalize-upload``, which
+byte-joins the slices and hands the result to the same ingestion pipeline
+``POST /upload`` uses. The declared mime type is not checked against
+``RECORDING_SESSION_ALLOWED_MIME_TYPES`` for them: the user picks the
+container, and ffprobe gates it at ingest. The two finalize routes reject
+each other's sessions.
Finalize is async: the endpoint creates a placeholder Recording row in
``STITCHING`` status, enqueues a ``stitch`` job via the existing
@@ -56,6 +57,7 @@ from datetime import datetime, timedelta
from flask import Blueprint, request, jsonify, current_app
from flask_login import login_required, current_user
+from werkzeug.datastructures import FileStorage
from src.database import db
from src.models import RecordingSession, Recording, RECORDING_SESSION_STATUSES
@@ -276,18 +278,26 @@ def create_session():
"""Create a new in-progress recording session.
Body (JSON, all optional): ``{"mime_type": "audio/webm"}`` for a
- recorder session, plus ``{"filename": "talk.mp4"}`` to make it a
- sliced upload of a file the user already has on disk.
+ recorder session. ``{"filename": "talk.mp4", "total_bytes": 1234}``
+ makes it a sliced upload of a file the user already has on disk;
+ ``total_bytes`` is what the reassembled file must weigh at finalize.
Returns ``{session_id, expires_at, max_chunk_bytes}`` on success.
"""
data = request.get_json(silent=True) or {}
declared_mime = (data.get('mime_type') or '').strip().lower()
upload_filename = (data.get('filename') or '').strip()
+ total_bytes = None
if upload_filename:
if len(upload_filename) > 255:
return jsonify({'error': 'filename must be 255 characters or fewer'}), 400
+ try:
+ total_bytes = int(data.get('total_bytes'))
+ except (TypeError, ValueError):
+ return jsonify({'error': 'total_bytes is required for a sliced upload'}), 400
+ if total_bytes <= 0:
+ return jsonify({'error': 'total_bytes must be a positive integer'}), 400
mime_type = declared_mime or 'application/octet-stream'
else:
mime_type = declared_mime or 'audio/webm'
@@ -307,7 +317,9 @@ def create_session():
session = RecordingSession(
user_id=current_user.id,
mime_type=mime_type,
+ kind='sliced_upload' if upload_filename else 'recorder',
upload_filename=upload_filename or None,
+ upload_total_bytes=total_bytes,
status='recording',
)
db.session.add(session)
@@ -327,6 +339,7 @@ def create_session():
return jsonify({
'session_id': session.id,
'mime_type': session.mime_type,
+ 'kind': session.kind,
'upload_filename': session.upload_filename,
'status': session.status,
'expires_at': expires_at.isoformat(),
@@ -462,7 +475,7 @@ def finalize_session(session_id):
if err is not None:
return err
- if session.upload_filename:
+ if session.is_sliced_upload:
return jsonify({
'error': 'Session is a sliced file upload; finalize it with /finalize-upload',
}), 409
@@ -552,35 +565,27 @@ def finalize_session(session_id):
}), 202
-class ReassembledUpload:
- """A Werkzeug ``FileStorage``-shaped view of reassembled slices.
+class ReassembledUpload(FileStorage):
+ """The reassembled slices, presented as the upload they stand for.
- Exposes only what :func:`ingest_uploaded_recording` asks of an upload
- (``filename``, ``seek``, ``tell``, ``save``) so a sliced upload runs
- through the same ingestion pipeline as a single-shot one. ``save``
- moves the joined file rather than copying it, so a large upload is
- written once.
+ A real ``FileStorage`` over the joined file, so a sliced upload runs
+ through :func:`ingest_uploaded_recording` exactly as a single-shot one
+ does and gains no dependency on which of the class's members that
+ function happens to touch. ``save`` moves the joined file instead of
+ copying it, so a large upload is written once.
"""
def __init__(self, path, filename):
+ super().__init__(
+ stream=open(path, 'rb'),
+ filename=filename,
+ content_type='application/octet-stream',
+ content_length=os.path.getsize(path),
+ )
self._path = path
- self.filename = filename
- self._size = os.path.getsize(path)
- self._pos = 0
-
- def seek(self, offset, whence=os.SEEK_SET):
- if whence == os.SEEK_END:
- self._pos = self._size + offset
- elif whence == os.SEEK_CUR:
- self._pos += offset
- else:
- self._pos = offset
- return self._pos
-
- def tell(self):
- return self._pos
- def save(self, dst):
+ def save(self, dst, buffer_size=None):
+ self.close()
shutil.move(self._path, dst)
@@ -594,37 +599,37 @@ def finalize_sliced_upload(session_id):
response is that endpoint's response, so a client can treat the two
transports interchangeably.
- Unlike the recorder's ``/finalize``, this is synchronous and not
- replayable: ingestion (hash, probe, convert) happens in-request
- exactly as it does for a single-shot upload. A client that loses the
- response has to re-upload, and Speakr's duplicate detection flags the
- second copy. Concurrent calls are claimed atomically so only one of
- them ingests.
+ Ingestion (hash, probe, convert) happens in-request exactly as it does
+ for a single-shot upload, so unlike the recorder's ``/finalize`` this
+ holds the connection for its whole duration. Concurrent calls are
+ claimed atomically so only one of them ingests, and a client that
+ lost the response gets the same recording back on its retry.
+
+ The session is claimed BEFORE its directory is read, because a slice
+ POST still in flight would otherwise be able to land between the
+ listing and the join, and the ingested file would be a prefix of the
+ user's. What the slices weigh together is checked against the size
+ declared at create, so a short or missing slice fails loudly instead
+ of ingesting as a truncated recording.
"""
session = db.session.get(RecordingSession, session_id)
err = _ensure_owned(session)
if err is not None:
return err
- if not session.upload_filename:
+ if not session.is_sliced_upload:
return jsonify({
'error': 'Session is a recorder session; finalize it with /finalize',
}), 409
+ if session.status == 'finalized':
+ return _replay_sliced_upload_response(session)
+
if session.status != 'recording':
return jsonify({
'error': f'Session is in status {session.status!r}; cannot finalize',
}), 409
- dir_path = _session_dir(session.id)
- slice_paths = session_chunk_paths(dir_path)
- if not slice_paths or len(slice_paths) != session.chunk_count:
- return jsonify({
- 'error': 'Slices on disk do not match the session',
- 'expected_chunk_index': len(slice_paths) + 1,
- 'chunk_count': session.chunk_count,
- }), 409
-
claimed = db.session.query(RecordingSession).filter(
RecordingSession.id == session.id,
RecordingSession.status == 'recording',
@@ -635,6 +640,20 @@ def finalize_sliced_upload(session_id):
session.last_seen_at = datetime.utcnow()
db.session.commit()
+ dir_path = _session_dir(session.id)
+ slice_paths = session_chunk_paths(dir_path)
+ slice_bytes = sum(os.path.getsize(p) for p in slice_paths)
+ if not slice_paths or slice_bytes != session.upload_total_bytes:
+ _fail_sliced_upload(session, (
+ f'Reassembled {slice_bytes} bytes from {len(slice_paths)} slices, '
+ f'expected {session.upload_total_bytes}'
+ ))
+ return jsonify({
+ 'error': 'Uploaded slices do not add up to the declared file size',
+ 'received_bytes': slice_bytes,
+ 'expected_bytes': session.upload_total_bytes,
+ }), 409
+
joined_path = os.path.join(dir_path, 'joined.bin')
try:
byte_join(slice_paths, joined_path)
@@ -659,18 +678,43 @@ def finalize_sliced_upload(session_id):
session.finalized_recording_id = body.get('id')
session.last_seen_at = datetime.utcnow()
db.session.commit()
+ _remove_session_dir(session_id)
else:
_fail_sliced_upload(session, f'Ingestion rejected the upload (HTTP {status})')
-
- _remove_session_dir(session_id)
return result
+def _replay_sliced_upload_response(session):
+ """Answer a retry of a finalize whose response the client lost.
+
+ Without this, a lost response costs the user the whole upload again:
+ the slices are gone and the session can no longer be finalized, so
+ the client would start over on a file it already delivered in full.
+ """
+ existing = (db.session.get(Recording, session.finalized_recording_id)
+ if session.finalized_recording_id else None)
+ if existing is None or existing.user_id != current_user.id:
+ return jsonify({
+ 'error': 'Session was already finalized and its recording no longer exists',
+ }), 409
+ response_data = existing.to_dict(viewer_user=current_user)
+ response_data['idempotent_replay'] = True
+ return jsonify(response_data), 202
+
+
def _fail_sliced_upload(session, message):
+ """Mark a sliced upload failed and reclaim its slices.
+
+ The slices cannot be reused: finalize only accepts a session still in
+ ``recording``, and no sweep collects a terminal one, so leaving them
+ behind leaks the whole file until an operator notices. Which is the
+ worst possible moment, the common cause being a full disk.
+ """
session.status = 'failed'
session.error_message = message
session.last_seen_at = datetime.utcnow()
db.session.commit()
+ _remove_session_dir(session.id)
@recording_sessions_bp.route('/upload/session/<string:session_id>', methods=['DELETE'])
@@ -679,7 +723,9 @@ def abort_session(session_id):
"""Abort an in-progress session and clean up its on-disk chunks.
If the session has already finalized, this returns 409; finalized
- sessions are owned by the stitch worker, not the user.
+ sessions are owned by the stitch worker, not the user. A sliced
+ upload that is finalizing is refused too: its slices are being read
+ in-request, so removing them would fail the ingestion under way.
"""
session = db.session.get(RecordingSession, session_id)
err = _ensure_owned(session)
@@ -689,6 +735,9 @@ def abort_session(session_id):
if session.status == 'finalized':
return jsonify({'error': 'Session already finalized'}), 409
+ if session.status == 'finalizing' and session.is_sliced_upload:
+ return jsonify({'error': 'Session is being finalized'}), 409
+
session.status = 'aborted'
session.last_seen_at = datetime.utcnow()
db.session.commit()
@@ -713,9 +762,13 @@ def cleanup_expired_sessions(app=None):
what was uploaded and land it in the user's library (same path as a
manual finalize), rather than discarding it.
- ``recording`` with no chunks → expire and delete the empty directory.
- - a sliced file upload (``upload_filename`` set) → expire, whatever it
- holds: the user still has the original file, and its slices are a
- truncated container rather than a playable partial recording.
+ - a sliced file upload → expire, whatever it holds: the user still has
+ the original file, and its slices are a truncated container rather
+ than a playable partial recording.
+
+ Expiry claims the row conditionally, so a session that came back to
+ life between the candidate query and the claim (a resumed upload, a
+ finalize) keeps its files instead of having them swept.
- ``finalizing`` (already has a placeholder recording) but never reached
a terminal stitch state → **re-enqueue** the stitch to unstick it
(enqueue dedupes an already-active job). Bumping ``last_seen_at`` here
@@ -737,7 +790,7 @@ def cleanup_expired_sessions(app=None):
finalized = rekicked = expired = 0
for s in candidates:
try:
- if s.status == 'recording' and (s.chunk_count or 0) > 0 and not s.upload_filename:
+ if s.status == 'recording' and (s.chunk_count or 0) > 0 and not s.is_sliced_upload:
when = s.created_at.strftime('%Y-%m-%d %H:%M') if s.created_at else ''
title = f"Recovered recording {when}".strip()
recovered_rec, _enq_err = _finalize_session_into_stitch(
@@ -771,8 +824,14 @@ def cleanup_expired_sessions(app=None):
else:
# No chunks to save (or finalizing without a recording):
# nothing recoverable — expire and remove the directory.
- s.status = 'expired'
+ claimed = db.session.query(RecordingSession).filter(
+ RecordingSession.id == s.id,
+ RecordingSession.status == s.status,
+ RecordingSession.last_seen_at < cutoff,
+ ).update({'status': 'expired'}, synchronize_session=False)
db.session.commit()
+ if not claimed:
+ continue
_remove_session_dir(s.id, app)
expired += 1
except Exception as e:
diff --git a/src/init_db.py b/src/init_db.py
index d9676c3f..e1c79093 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -653,8 +653,12 @@ def _run_migrations(app, engine):
app.logger.warning("New recordings will work correctly, but existing dates may need manual migration")
with _migration_section(app, failures, "sliced file upload sessions"):
+ if add_column_if_not_exists(engine, 'recording_session', 'kind', "VARCHAR(20) DEFAULT 'recorder'"):
+ app.logger.info("Added kind column to recording_session table")
if add_column_if_not_exists(engine, 'recording_session', 'upload_filename', 'VARCHAR(255)'):
app.logger.info("Added upload_filename column to recording_session table")
+ if add_column_if_not_exists(engine, 'recording_session', 'upload_total_bytes', 'BIGINT'):
+ app.logger.info("Added upload_total_bytes column to recording_session table")
with _migration_section(app, failures, "performance and uniqueness indexes"):
# Add index on TranscriptChunk.speaker_name for performance
diff --git a/src/models/__init__.py b/src/models/__init__.py
index d1666f2c..17e73bce 100644
--- a/src/models/__init__.py
+++ b/src/models/__init__.py
@@ -30,7 +30,7 @@ from .system import SystemSetting
from .audit import ShareAuditLog
from .push_subscription import PushSubscription
from .processing_job import ProcessingJob
-from .recording_session import RecordingSession, RECORDING_SESSION_STATUSES
+from .recording_session import RecordingSession, RECORDING_SESSION_KINDS, RECORDING_SESSION_STATUSES
from .token_usage import TokenUsage
from .transcription_usage import TranscriptionUsage
from .webhook import (
@@ -75,6 +75,7 @@ __all__ = [
'PushSubscription',
'ProcessingJob',
'RecordingSession',
+ 'RECORDING_SESSION_KINDS',
'RECORDING_SESSION_STATUSES',
'TokenUsage',
'TranscriptionUsage',
diff --git a/src/models/recording_session.py b/src/models/recording_session.py
index 73136d88..10111cb1 100644
--- a/src/models/recording_session.py
+++ b/src/models/recording_session.py
@@ -23,13 +23,12 @@ audio_path and the session directory is removed.
The same session machinery also carries sliced uploads of files the user
already has on disk, so those can cross a reverse proxy with a body-size
-limit below the file size. Such a session has ``upload_filename`` set,
-which is what distinguishes it from a recorder session. Its chunks are
-fixed-size byte slices of one complete container rather than
-MediaRecorder timeslices, so it finalizes through the normal upload
-ingestion path (plain byte-join, no stitch, no remux) and is never
-auto-finalized when abandoned: the user's original file still exists, so
-there is nothing to recover.
+limit below the file size. ``kind`` says which of the two a session is.
+A sliced upload's chunks are fixed-size byte slices of one complete
+container rather than MediaRecorder timeslices, so it finalizes through
+the normal upload ingestion path (plain byte-join, no stitch, no remux)
+and is never auto-finalized when abandoned: the user's original file
+still exists, so there is nothing to recover.
"""
import uuid
@@ -47,7 +46,12 @@ RECORDING_SESSION_STATUSES = (
'finalized', # stitch completed; session dir may already be removed
'aborted', # user (or admin) cancelled before finalize
'expired', # TTL elapsed without finalize; cleanup ran
- 'failed', # stitch job hit a permanent error
+ 'failed', # stitch or ingestion hit a permanent error
+)
+
+RECORDING_SESSION_KINDS = (
+ 'recorder', # in-app recorder streaming MediaRecorder timeslices
+ 'sliced_upload', # byte slices of a file the user already has on disk
)
@@ -73,8 +77,12 @@ class RecordingSession(db.Model):
# the declared type) and pick the right ffmpeg input args at stitch time.
mime_type = db.Column(db.String(100), nullable=False, default='audio/webm')
+ kind = db.Column(db.String(20), nullable=False, default='recorder', index=True)
+
upload_filename = db.Column(db.String(255), nullable=True)
+ upload_total_bytes = db.Column(db.BigInteger, nullable=True)
+
# Status transitions are guarded by the API; see RECORDING_SESSION_STATUSES.
status = db.Column(db.String(20), nullable=False, default='recording', index=True)
@@ -115,6 +123,10 @@ class RecordingSession(db.Model):
)
finalized_recording = db.relationship('Recording', foreign_keys=[finalized_recording_id])
+ @property
+ def is_sliced_upload(self):
+ return self.kind == 'sliced_upload'
+
def __repr__(self): # pragma: no cover - debugging aid
return f'<RecordingSession {self.id} user={self.user_id} status={self.status} chunks={self.chunk_count}>'
@@ -124,7 +136,9 @@ class RecordingSession(db.Model):
'session_id': self.id,
'status': self.status,
'mime_type': self.mime_type,
+ 'kind': self.kind,
'upload_filename': self.upload_filename,
+ 'upload_total_bytes': self.upload_total_bytes,
'chunk_count': self.chunk_count,
'bytes_received': self.bytes_received,
'created_at': self.created_at.isoformat() if self.created_at else None,
diff --git a/static/js/modules/db/sliced-file-upload.js b/static/js/modules/db/sliced-file-upload.js
index cb7c447b..8371500a 100644
--- a/static/js/modules/db/sliced-file-upload.js
+++ b/static/js/modules/db/sliced-file-upload.js
@@ -32,6 +32,7 @@ const SESSION_BASE = '/upload/session';
export const SLICE_BYTES = 16 * 1024 * 1024;
const MAX_SLICE_ATTEMPTS = 6;
+const MAX_STALLED_RESYNCS = 2;
const BASE_RETRY_MS = 1000;
const MAX_RETRY_MS = 30000;
@@ -82,7 +83,11 @@ async function createFileSession(file, token) {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': token },
credentials: 'same-origin',
- body: JSON.stringify({ filename: file.name, mime_type: file.type || '' }),
+ body: JSON.stringify({
+ filename: file.name,
+ mime_type: file.type || '',
+ total_bytes: file.size,
+ }),
});
const body = parseJson(await response.text());
if (response.status !== 201 || !body?.session_id) {
@@ -173,7 +178,7 @@ async function finalize(sessionId, formData, tokenRef, options) {
onXhr: options.onXhr,
});
const body = parseJson(result.text);
- if (result.status === 202 && body?.id) return body;
+ if (result.status >= 200 && result.status < 300 && body?.id) return body;
if (isCsrfRejection(result.status, result.text) && attempt === 1) {
tokenRef.token = await getUploadCsrfToken();
continue;
@@ -199,6 +204,8 @@ export async function uploadFileInSlices(file, formData, options = {}) {
try {
let index = 1;
+ let highWaterMark = 0;
+ let stalledResyncs = 0;
while ((index - 1) * sliceBytes < file.size) {
const start = (index - 1) * sliceBytes;
const end = Math.min(start + sliceBytes, file.size);
@@ -206,6 +213,14 @@ export async function uploadFileInSlices(file, formData, options = {}) {
onXhr: options.onXhr,
onSliceProgress: (loaded) => onProgress(Math.min(1, (start + loaded) / file.size)),
});
+ if (index > highWaterMark) {
+ highWaterMark = index;
+ stalledResyncs = 0;
+ } else if (++stalledResyncs > MAX_STALLED_RESYNCS) {
+ throw new Error(
+ `Server keeps asking for slice ${index} after accepting it; `
+ + 'its slice bookkeeping is not advancing');
+ }
onProgress(Math.min(1, ((index - 1) * sliceBytes) / file.size));
}
return await finalize(session.session_id, formData, tokenRef, {
diff --git a/static/js/modules/db/sliced-file-upload.test.js b/static/js/modules/db/sliced-file-upload.test.js
index 3cd0d3ed..c976fc9d 100644
--- a/static/js/modules/db/sliced-file-upload.test.js
+++ b/static/js/modules/db/sliced-file-upload.test.js
@@ -116,6 +116,7 @@ describe('uploadFileInSlices', () => {
expect(JSON.parse(fetchCalls[0].options.body)).toEqual({
filename: 'talk.mp4',
mime_type: 'video/mp4',
+ total_bytes: 40 * MB,
});
expect(slicePosts().map((call) => call.url)).toEqual([
'/upload/session/sess-1/chunks/1',
@@ -189,6 +190,29 @@ describe('uploadFileInSlices', () => {
});
});
+ // A server running RECORDING_SESSION_COMMIT_BATCH_SIZE > 1 rolls its slice bookkeeping back per request.
+ it('stops uploading when the server keeps asking for a slice it accepted', async () => {
+ vi.useFakeTimers();
+ global.XMLHttpRequest = class extends global.XMLHttpRequest {
+ send(body) {
+ sent.push({ url: this.url, body, headers: this.headers });
+ const accepted = this.url.endsWith('/chunks/1');
+ queueMicrotask(() => {
+ this.status = accepted ? 204 : 409;
+ this.responseText = accepted ? '' : JSON.stringify({ expected_chunk_index: 1 });
+ this.onload();
+ });
+ }
+ };
+
+ const upload = uploadFileInSlices(fakeFile(40 * MB), new Map(), {});
+ const assertion = expect(upload).rejects.toThrow('bookkeeping is not advancing');
+ await vi.advanceTimersByTimeAsync(60000);
+ await assertion;
+
+ expect(slicePosts().length).toBeLessThan(10);
+ });
+
it('blames the reverse proxy for a 413 with no Speakr error body', async () => {
sliceResponses = [{ status: 413, text: '<html><head><title>413 Request Entity Too Large</title></head></html>' }];
diff --git a/tests/test_sliced_file_upload.py b/tests/test_sliced_file_upload.py
index f3ebe163..3f165eef 100644
--- a/tests/test_sliced_file_upload.py
+++ b/tests/test_sliced_file_upload.py
@@ -22,6 +22,7 @@ import sys
import tempfile
import uuid
from datetime import datetime, timedelta
+from unittest.mock import patch
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -45,8 +46,12 @@ def _payload(size):
return bytes(range(256)) * (size // 256) + b"\xab" * (size % 256)
-def _open_session(client, filename="talk.mp4", mime_type="video/mp4"):
- response = client.post("/upload/session", json={"filename": filename, "mime_type": mime_type})
+def _open_session(client, filename="talk.mp4", mime_type="video/mp4", total_bytes=SLICE_BYTES):
+ response = client.post("/upload/session", json={
+ "filename": filename,
+ "mime_type": mime_type,
+ "total_bytes": total_bytes,
+ })
assert response.status_code == 201, response.data
return response.get_json()
@@ -69,9 +74,13 @@ def test_create_session_with_filename_marks_it_a_file_upload():
client = app.test_client()
_login(client, user)
- body = _open_session(client)
+ body = _open_session(client, total_bytes=4096)
+ assert body["kind"] == "sliced_upload"
assert body["upload_filename"] == "talk.mp4"
- assert db.session.get(RecordingSession, body["session_id"]).upload_filename == "talk.mp4"
+ session = db.session.get(RecordingSession, body["session_id"])
+ assert session.is_sliced_upload
+ assert session.upload_filename == "talk.mp4"
+ assert session.upload_total_bytes == 4096
client.delete(f"/upload/session/{body['session_id']}")
_cleanup(user)
@@ -94,6 +103,9 @@ def test_create_session_with_filename_skips_the_recorder_mime_whitelist():
accepted = _open_session(client, filename="lecture.mkv", mime_type="video/x-matroska")
assert accepted["mime_type"] == "video/x-matroska"
+ no_size = client.post("/upload/session", json={"filename": "lecture.mkv"})
+ assert no_size.status_code == 400
+
client.delete(f"/upload/session/{accepted['session_id']}")
_cleanup(user)
shutil.rmtree(upload_folder, ignore_errors=True)
@@ -108,7 +120,8 @@ def test_finalize_upload_ingests_the_reassembled_original_bytes():
_login(client, user)
payload = _payload(SLICE_BYTES * 3 + 17)
- session_id = _open_session(client, filename="sample.mp3", mime_type="audio/mpeg")["session_id"]
+ session_id = _open_session(client, filename="sample.mp3", mime_type="audio/mpeg",
+ total_bytes=len(payload))["session_id"]
_send_slices(client, session_id, payload)
staging = os.path.join(upload_folder, f"stg_{uuid.uuid4().hex[:6]}")
@@ -143,7 +156,8 @@ def test_finalize_upload_carries_the_upload_form_through_ingestion():
client = app.test_client()
_login(client, user)
- session_id = _open_session(client, filename="sample.mp3", mime_type="audio/mpeg")["session_id"]
+ session_id = _open_session(client, filename="sample.mp3", mime_type="audio/mpeg",
+ total_bytes=SLICE_BYTES * 2)["session_id"]
_send_slices(client, session_id, _payload(SLICE_BYTES * 2))
staging = os.path.join(upload_folder, f"stg_{uuid.uuid4().hex[:6]}")
@@ -164,29 +178,88 @@ def test_finalize_upload_carries_the_upload_form_through_ingestion():
shutil.rmtree(upload_folder, ignore_errors=True)
-def test_finalize_upload_rejects_a_slice_count_that_disagrees_with_disk():
- """A slice lost between the write and the bookkeeping commit would
- otherwise be silently ingested as a truncated file."""
+def test_finalize_upload_rejects_slices_that_do_not_weigh_the_declared_size():
+ """A missing or short slice would otherwise be ingested as a truncated
+ file, which ffprobe accepts for most containers, so the user would get
+ a silently broken recording instead of an error."""
upload_folder = _tmp_upload_folder()
with app.app_context():
app.config["UPLOAD_FOLDER"] = upload_folder
- user = _mk_user("slice_short")
+ client = app.test_client()
+
+ for label, damage in (
+ ("missing", lambda path: os.remove(path)),
+ ("truncated", lambda path: open(path, "wb").write(b"short")),
+ ):
+ user = _mk_user(f"slice_{label}")
+ _login(client, user)
+ session_id = _open_session(client, filename="sample.mp3", mime_type="audio/mpeg",
+ total_bytes=SLICE_BYTES * 2)["session_id"]
+ _send_slices(client, session_id, _payload(SLICE_BYTES * 2))
+ damage(os.path.join(upload_folder, "_sessions", session_id, "chunk-000002.bin"))
+
+ response = client.post(
+ f"/upload/session/{session_id}/finalize-upload",
+ data={},
+ content_type="multipart/form-data",
+ )
+ assert response.status_code == 409, (label, response.data)
+ assert response.get_json()["expected_bytes"] == SLICE_BYTES * 2
+ assert Recording.query.filter_by(user_id=user.id).count() == 0
+ _cleanup(user)
+ shutil.rmtree(upload_folder, ignore_errors=True)
+
+
+def test_a_failed_finalize_upload_reclaims_the_slices_it_cannot_use():
+ """Finalize only accepts a session in 'recording' and no sweep collects
+ a terminal one, so slices left behind here leak the whole file until an
+ operator notices, the common cause being the disk that just filled."""
+ upload_folder = _tmp_upload_folder()
+ with app.app_context():
+ app.config["UPLOAD_FOLDER"] = upload_folder
+ user = _mk_user("slice_reclaim")
client = app.test_client()
_login(client, user)
session_id = _open_session(client, filename="sample.mp3", mime_type="audio/mpeg")["session_id"]
- _send_slices(client, session_id, _payload(SLICE_BYTES * 2))
- os.remove(os.path.join(upload_folder, "_sessions", session_id, "chunk-000002.bin"))
+ _send_slices(client, session_id, _payload(SLICE_BYTES))
- response = client.post(
- f"/upload/session/{session_id}/finalize-upload",
- data={},
- content_type="multipart/form-data",
- )
+ with patch("src.api.recording_sessions.byte_join",
+ side_effect=OSError("No space left on device")):
+ response = client.post(
+ f"/upload/session/{session_id}/finalize-upload",
+ data={}, content_type="multipart/form-data")
+
+ assert response.status_code == 500
+ assert db.session.get(RecordingSession, session_id).status == "failed"
+ assert not os.path.isdir(os.path.join(upload_folder, "_sessions", session_id))
+
+ _cleanup(user)
+ shutil.rmtree(upload_folder, ignore_errors=True)
+
+
+def test_a_finalize_upload_cannot_be_aborted_while_it_is_ingesting():
+ """The slices are being read in-request, so honouring the abort would
+ delete the ingesting file out from under the request."""
+ upload_folder = _tmp_upload_folder()
+ with app.app_context():
+ app.config["UPLOAD_FOLDER"] = upload_folder
+ user = _mk_user("slice_abort")
+ client = app.test_client()
+ _login(client, user)
+
+ session_id = _open_session(client, filename="sample.mp3", mime_type="audio/mpeg")["session_id"]
+ _send_slices(client, session_id, _payload(SLICE_BYTES))
+ session = db.session.get(RecordingSession, session_id)
+ session.status = "finalizing"
+ db.session.commit()
+
+ response = client.delete(f"/upload/session/{session_id}")
assert response.status_code == 409
- assert response.get_json()["expected_chunk_index"] == 2
+ assert os.path.isdir(os.path.join(upload_folder, "_sessions", session_id))
- client.delete(f"/upload/session/{session_id}")
+ session.status = "aborted"
+ db.session.commit()
_cleanup(user)
shutil.rmtree(upload_folder, ignore_errors=True)
@@ -254,9 +327,10 @@ def test_cleanup_expires_an_abandoned_sliced_upload_instead_of_assembling_it():
shutil.rmtree(upload_folder, ignore_errors=True)
-def test_a_replayed_finalize_upload_does_not_ingest_the_file_twice():
+def test_a_replayed_finalize_upload_returns_the_first_call_s_recording():
"""Finalize is synchronous, so a client that retries it after a lost
- response would otherwise land the same file in the library twice."""
+ response would otherwise be told 409 and re-upload the whole file it
+ had already delivered."""
upload_folder = _tmp_upload_folder()
with app.app_context():
app.config["UPLOAD_FOLDER"] = upload_folder
@@ -275,7 +349,9 @@ def test_a_replayed_finalize_upload_does_not_ingest_the_file_twice():
data={}, content_type="multipart/form-data")
assert first.status_code == 202, first.data
- assert second.status_code == 409
+ assert second.status_code == 202, second.data
+ assert second.get_json()["id"] == first.get_json()["id"]
+ assert second.get_json()["idempotent_replay"] is True
assert Recording.query.filter_by(user_id=user.id).count() == 1
_cleanup(db.session.get(Recording, first.get_json()["id"]), user)
@@ -303,3 +379,50 @@ def test_another_user_cannot_finalize_someone_elses_sliced_upload():
client.delete(f"/upload/session/{session_id}")
_cleanup(owner, intruder)
shutil.rmtree(upload_folder, ignore_errors=True)
+
+
+def test_an_existing_recorder_session_survives_the_migration_as_a_recorder_session():
+ """The migration adds the discriminator to a table that already holds
+ live recorder sessions. If they came out the other side looking like
+ sliced uploads, /finalize would refuse them and the cleanup sweep would
+ stop rescuing abandoned recordings, which is the one thing that policy
+ exists to prevent."""
+ import sqlite3
+ from flask import Flask
+ from sqlalchemy import inspect
+ from src.init_db import initialize_database
+
+ fixture = os.path.join(os.path.dirname(os.path.abspath(__file__)),
+ "fixtures", "schemas", "v0.10.3-alpha.sql")
+ db_dir = tempfile.mkdtemp(prefix="speakr-test-upgrade-")
+ db_path = os.path.join(db_dir, "old.db")
+
+ con = sqlite3.connect(db_path)
+ with open(fixture) as f:
+ con.executescript(f.read())
+ con.execute('INSERT INTO "user" (id, username, email, password) VALUES (1, "u", "[email protected]", "h")')
+ con.execute(
+ "INSERT INTO recording_session"
+ " (id, user_id, mime_type, status, chunk_count, bytes_received, created_at, last_seen_at)"
+ " VALUES ('sess-old', 1, 'audio/webm', 'recording', 7, 4096, '2026-01-01', '2026-01-01')"
+ )
+ con.commit()
+ con.close()
+
+ upgrading = Flask("upgrade_sliced_upload")
+ upgrading.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{db_path}"
+ upgrading.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
+ upgrading.config["UPLOAD_FOLDER"] = db_dir
+ db.init_app(upgrading)
+ with upgrading.app_context():
+ initialize_database(upgrading)
+ columns = {c["name"] for c in inspect(db.engine).get_columns("recording_session")}
+ survivor = db.session.get(RecordingSession, "sess-old")
+
+ assert {"kind", "upload_filename", "upload_total_bytes"} <= columns
+ assert survivor.chunk_count == 7
+ assert survivor.bytes_received == 4096
+ assert survivor.kind == "recorder"
+ assert survivor.is_sliced_upload is False
+
+ shutil.rmtree(db_dir, ignore_errors=True)