openstreetmap-ng
openstreetmap-ng copied to clipboard
feat: background recompression of trace files
Resolves #100.
What
Adds an async background task that recompresses a freshly uploaded trace file with a heavier zstd level (22) without delaying the upload response, mirroring the existing fire-and-forget pattern used by AuditService / ImageProxyService.
How
TraceFile.compress(buffer, *, level=...)— new optionallevelargument. The default (level 6) path is unchanged and still reuses the cached options/metadata; the heavy path builds level-derived options and records the realzstd_levelin the file metadata.TraceService.upload— once the DB transaction has committed andtrace_idis known, it schedules_recompress_trace(trace_id, file_id, file)on a module-levelTaskGroupand returns immediately. The response is not delayed by heavy compression._recompress_trace— recompresses off the event loop (to_thread, GIL released by the zstd C extension), saves the new file, then swapstrace.file_idand deletes the now-unreferenced file.TraceService.context()— registered in the app lifespan so the background tasks are awaited on shutdown (DB pool is still open at that point).
Correctness / race handling
- The swap is
UPDATE ... WHERE id = trace_id AND file_id = old_file_id. If the trace was deleted or its file already changed, the update affects 0 rows and the freshly written file is removed instead — no dangling reference, no orphan. - If the new file is saved but the DB swap fails, the new file is cleaned up.
TraceService.deletenow deletes atomically withDELETE ... RETURNING file_idand removes exactly the file the row referenced at deletion time, closing the delete/recompression race that could otherwise orphan the recompressed file. Existingtrace_not_foundvstrace_access_deniedbehaviour is preserved.- Read path is unaffected:
decompress_if_neededkeys off the.zstsuffix and is level-agnostic.
Tests
tests/services/test_trace_service.py::test_trace_background_recompression uploads a trace, waits for the background task to settle, and asserts the stored file matches a level-22 reference and still round-trips back to the original bytes.