mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 16:12:11 +00:00
The unit suite reported all 1937 files green and then failed the job with `EnvironmentTeardownError: Closing rpc while "onUserConsoleLog" was pending`, naming a different scoring test each time. Vitest replaces globalThis.console with a sink that forwards every write to the main thread as an onUserConsoleLog RPC call. When a worker finishes a test file it awaits the calls in flight and then rejects whatever was started after that point, so a console write from work that outlived its test lands in the gap and fails the run. The blame goes to the file being torn down rather than to the test that started the work, which is why the named file never logged anything itself. Three paths detach a promise and log on the handle: fireAndForget, the stale-while-revalidate cache refresh, and the offline query persister. They now register the handled handle in a set that both suite setups drain in afterEach, so no test leaves work in flight. The registry is inert outside test: nothing there awaits it, and holding a reference to an unsettled promise would retain it for the life of a worker. No production behaviour changes, so there is no changelog entry. Evidence. A focused harness that starts failing background tasks and returns hit the teardown error 10 runs out of 10 before the change and 0 out of 10 after. Instrumenting the real suite showed two detached console writes per run escaping their test, both from the rollup tail; after the change, none, and thirteen writes per run now complete inside the test that started them. The guard asserts the behaviour, not a count: a registered task must keep settleBackgroundTasks from resolving ahead of it, and the set must drain back to empty. It goes red on unregistered work, on a disabled registry, on an unwrapped call site, on a sweep that matches nothing, and on a setup that drops the hook.
62 lines
2.5 KiB
TypeScript
62 lines
2.5 KiB
TypeScript
/**
|
|
* Shared post-mutation tail for every surface that creates, updates,
|
|
* deletes, or restores `Measurement` rows.
|
|
*
|
|
* Two consumers hang off every measurement write and both were being
|
|
* re-remembered by hand at each write surface (the documented two-ended
|
|
* failure class):
|
|
*
|
|
* 1. the `(type, day)` rollup buckets the mutation dirtied — recomputed
|
|
* inline (DAY) + enqueued (WEEK/MONTH/YEAR) via
|
|
* `recomputeBucketsForMeasurement`. The recompute handles deletions
|
|
* inherently: a day left empty drops its rollup row.
|
|
* 2. the cached per-metric status assessments — re-warmed via
|
|
* `invalidateStatusInsightsForTypes` (fire-and-forget).
|
|
*
|
|
* Both legs are best-effort: a populator hiccup never fails the user's
|
|
* mutation. Callers collect the affected `(type, measuredAt)` pairs
|
|
* (for deletes: BEFORE the destructive statement, while the rows are
|
|
* still readable) and hand them here.
|
|
*/
|
|
import {
|
|
collapseToTypeDayKeys,
|
|
recomputeBucketsForMeasurement,
|
|
} from "@/lib/rollups/measurement-rollups";
|
|
import { invalidateStatusInsightsForTypes } from "@/lib/insights/status-invalidation";
|
|
import { trackBackgroundTask } from "@/lib/logging/background-tasks";
|
|
import type { MeasurementType } from "@/generated/prisma/client";
|
|
|
|
export async function afterMeasurementMutation(
|
|
userId: string,
|
|
rows: Array<{ type: MeasurementType; measuredAt: Date }>,
|
|
/** Log prefix identifying the calling surface in the warn lines. */
|
|
label = "measurements",
|
|
): Promise<void> {
|
|
if (rows.length === 0) return;
|
|
|
|
// Collapse to the distinct `(type, day)` set BEFORE recomputing so a
|
|
// 500-row batch fires at most one DAY recompute per touched bucket.
|
|
const keys = collapseToTypeDayKeys(rows);
|
|
try {
|
|
for (const k of keys) {
|
|
await recomputeBucketsForMeasurement(userId, k.type, k.measuredAt);
|
|
}
|
|
} catch (err) {
|
|
console.warn(`[${label}] rollup recompute failed`, err);
|
|
}
|
|
|
|
// Status-insight re-warm is fire-and-forget — it must run even when
|
|
// the rollup leg above failed, so the two legs never gate each other.
|
|
const types = Array.from(new Set(keys.map((k) => k.type)));
|
|
if (types.length > 0) {
|
|
// Registered so the test suite can await it: the warn below is a console
|
|
// write on a detached handle, and one that lands while a vitest worker is
|
|
// closing its RPC channel fails the whole run. No-op outside test.
|
|
trackBackgroundTask(
|
|
invalidateStatusInsightsForTypes(userId, types).catch((err) => {
|
|
console.warn(`[${label}] status-insight invalidate failed`, err);
|
|
}),
|
|
);
|
|
}
|
|
}
|