mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-08 20:42:43 +00:00
An account of 1.25 million measurements could not export its data or be restored from any backup (#1031). Measured in a 1 GB container: - The full export and the passphrase export built the whole payload and its JSON string in memory; the app ran out of heap and restarted. - The weekly backup's JSON is 662 MB, longer than any string V8 can hold, so `unpackBackupBlob` threw on every read. Restore, download and the restore preview all answered "could not be decrypted". - Upload accepted 10 MB, a fraction of a large export. Every reader and writer of a backup file now streams it: - `scanBackupJson` reads a backup's bytes once, keeps every section but the named bulk arrays, and hands their elements out one at a time. `readStreamedBackup` uses it twice: a first pass that validates each measurement against the element schema and keeps the rest of the file, and a second pass that hands the measurements to the writer in batches. Stored copies and off-host objects are authenticated whole on their compressed ciphertext before any plaintext is read; only the decompression is streamed. - Restore writes the measurements with one `INSERT … FROM unnest` per batch. Prisma caches a query plan per `createMany` row count, and one 1 000-row plan kept about 145 MB alive, which alone put the restore past the heap limit. The transaction budget grows with the measurement count. The awards and ECG sections are handed the ids they reference that were written, not every written id. - The export routes write the file into the response as it is produced. The passphrase export spools its ciphertext to a temporary file because the HLX1 format puts the tag first; the format is unchanged, so existing archives open as before. - Upload accepts the raw body, JSON or gzip, up to the 512 MB request ceiling, checks it as it arrives and stores it in the same pass; the admin page compresses the file in the browser before sending it. Multipart stays for small files. - Download streams the stored JSON; the preview counts measurements from the stream. The monthly restore drill and `scripts/restore-backup.ts` read the off-host object the same way; the script can write `.json.gz`. On the seeded account in a 1 GB container: export 25 s at 389 MB peak, passphrase export 25 s, both uploads 19 s, restore of the weekly backup 94 s at 554 MB peak, and export, upload and restore round-trip to exactly the same rows. The encrypted-column guard now also recognises the raw SQL statement that writes `DataBackup.data`.
83 lines
2.7 KiB
TypeScript
83 lines
2.7 KiB
TypeScript
/**
|
|
* Turn a producer of text or bytes into a response body, with backpressure
|
|
* and cancellation.
|
|
*
|
|
* The export routes used to build their whole file as one string and hand it
|
|
* to the response. For an account of 1.25 million measurements that string
|
|
* and the object graph behind it did not fit a 1 GB container: one export
|
|
* took the app down for every user of the instance (#1031). The file is now
|
|
* written into the response as it is produced.
|
|
*
|
|
* Backpressure: the producer's `write` waits while the client is slower than
|
|
* the database, so nothing piles up in between. Cancellation: when the client
|
|
* goes away, the next `write` throws `ResponseStreamClosedError`, which stops
|
|
* the producer instead of leaving it to finish a file nobody reads.
|
|
*/
|
|
import { PassThrough, Readable } from "node:stream";
|
|
|
|
/** The client closed the response before the producer finished. */
|
|
export class ResponseStreamClosedError extends Error {
|
|
constructor() {
|
|
super("The response was closed before the file was complete");
|
|
this.name = "ResponseStreamClosedError";
|
|
}
|
|
}
|
|
|
|
export type ResponseProducer = (
|
|
write: (chunk: string | Buffer) => Promise<void>,
|
|
) => Promise<unknown>;
|
|
|
|
export interface ResponseStreamHooks {
|
|
/** Runs once the producer has written everything. */
|
|
onComplete?: () => unknown;
|
|
/**
|
|
* Runs when the producer failed or the client left. The response has
|
|
* already started, so the client receives a truncated file; a truncated
|
|
* JSON file does not parse, and a truncated archive fails its tag.
|
|
*/
|
|
onError?: (err: unknown) => unknown;
|
|
}
|
|
|
|
/** Start `producer` and return the web stream its output flows into. */
|
|
export function streamToResponseBody(
|
|
producer: ResponseProducer,
|
|
hooks: ResponseStreamHooks = {},
|
|
): ReadableStream<Uint8Array> {
|
|
const out = new PassThrough();
|
|
|
|
const write = async (chunk: string | Buffer): Promise<void> => {
|
|
if (out.destroyed || out.writableEnded)
|
|
throw new ResponseStreamClosedError();
|
|
if (out.write(chunk)) return;
|
|
await new Promise<void>((resolve, reject) => {
|
|
const onDrain = () => {
|
|
out.off("close", onClose);
|
|
resolve();
|
|
};
|
|
const onClose = () => {
|
|
out.off("drain", onDrain);
|
|
reject(new ResponseStreamClosedError());
|
|
};
|
|
out.once("drain", onDrain);
|
|
out.once("close", onClose);
|
|
});
|
|
};
|
|
|
|
void (async () => {
|
|
try {
|
|
await producer(write);
|
|
out.end();
|
|
await hooks.onComplete?.();
|
|
} catch (err) {
|
|
out.destroy(err instanceof Error ? err : new Error(String(err)));
|
|
try {
|
|
await hooks.onError?.(err);
|
|
} catch {
|
|
// Reporting a failure must not raise another one.
|
|
}
|
|
}
|
|
})();
|
|
|
|
return Readable.toWeb(out) as ReadableStream<Uint8Array>;
|
|
}
|