feat: client log with request ids, joined to the server's

The browser now keeps its half of the one event shape logs.py defines:
lib/log.ts is a levelled, redacted, bounded (2000 events) in-memory ring
with the server's level names and severity numbers. Nothing leaves the
browser yet; sending is the consented diagnostics level (S5).

- lib/http.ts `send` is the one fetch: every request carries an
  X-Request-Id and becomes one http.request event. The server echoes the
  matched route template in X-Route (only for a matched route, so a raw
  path with a value in it is never sent back); without one the client
  templates the path itself. req, beacon, the upload XHR, the public
  watch page and the legal pages all go through it.
- Hooks: app start snapshot, uncaught errors and rejections, History
  push/replace/popstate (a scroll-only replace is not an event; parameter
  values only at DEBUG, typed search only at TRACE), notifications, the
  error dialog, the crash boundary, failed queries and mutations (key
  head only), and the messages socket (lifecycle, frame types at DEBUG).
- Redaction is one contract: backend/tests/fixtures/log_redaction_cases.json
  runs against both redact() implementations.
- Lint: fetch, XMLHttpRequest and WebSocket each belong to one logging
  module, console to none; a contract test proves the rules fire.

Fixes a socket takeover: the close of a socket released by the last
subscriber cleared the newer socket a quick re-subscribe had opened and
scheduled a third, leaving two live sockets that delivered every message
twice (measured in Chromium: 3 created / 2 live before, 2 / 1 after).
This commit is contained in:
2026-09-17 01:44:29 +02:00
parent 0517de1f59
commit a210992bfc
24 changed files with 1207 additions and 34 deletions
+7 -2
View File
@@ -1,6 +1,7 @@
import { Component, type ReactNode } from "react";
import { Component, type ErrorInfo, type ReactNode } from "react";
import i18n from "../i18n";
import { notify } from "../lib/notifications";
import { errorAttrs, log } from "../lib/log";
interface Props {
children: ReactNode;
@@ -18,7 +19,11 @@ export default class ErrorBoundary extends Component<Props, State> {
return { crashed: true };
}
componentDidCatch(error: Error) {
componentDidCatch(error: Error, info: ErrorInfo) {
log.fatal("ui.crash", "the app crashed while rendering", {
...errorAttrs(error),
...(info.componentStack ? { component_stack: info.componentStack } : {}),
});
notify({
level: "fatal",
title: i18n.t("errors.boundary.notifTitle"),
+3 -2
View File
@@ -4,6 +4,7 @@ import { Button } from "./ui/Button";
import { formatBytes } from "../lib/format";
import { exposeVideoToBackgroundPlay } from "../lib/browserBackgroundPlay";
import { LS, readJSON, writeJSON } from "../lib/storage";
import { send } from "../lib/http";
// Standalone, login-free video page for a shared /watch/<token> link. Rendered OUTSIDE the app
// tree (no auth, no providers) — like the /privacy and /terms pages. Uses plain fetch and a tiny
@@ -169,7 +170,7 @@ export default function WatchPage() {
setStatus("gone");
return;
}
fetch(`/api/public/watch/${encodeURIComponent(token)}`)
send(`/api/public/watch/${encodeURIComponent(token)}`)
.then((r) => {
// Only a 404 says the link is gone (unknown, expired, revoked, or its file removed). Anything
// else — a 5xx while the server restarts, a dropped connection — is a failure worth retrying,
@@ -197,7 +198,7 @@ export default function WatchPage() {
setUnlocking(true);
setError(null);
try {
const r = await fetch(`/api/public/watch/${encodeURIComponent(token)}/unlock`, {
const r = await send(`/api/public/watch/${encodeURIComponent(token)}/unlock`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password }),
@@ -0,0 +1,82 @@
// @vitest-environment jsdom
//
// E22 S4: what the user was SHOWN — a toast, the blocking error dialog, the crash screen — and what
// failed behind the scenes (a query, a mutation) all land in the client log. Each producer is its
// own module, so each is asserted here through the real thing, not a mock of it.
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, render } from "@testing-library/react";
import { clear, events } from "../lib/log";
import { notify } from "../lib/notifications";
import { reportError } from "../lib/errorDialog";
import { createQueryClient } from "../lib/queryClient";
import ErrorBoundary from "./ErrorBoundary";
import { HttpError } from "../lib/api/core";
afterEach(() => {
cleanup();
clear();
vi.restoreAllMocks();
});
const logged = (code: string) => events().filter((e) => e.event === code);
describe("client log wiring", () => {
it("records every notification at its level", () => {
notify({ level: "success", title: "Saved", message: "Playlist renamed" });
notify({ level: "error", message: "Could not reach someone@mail.example" });
expect(logged("ui.notify").map((e) => [e.level, e.msg, e.attrs])).toEqual([
["INFO", "Playlist renamed", { level: "success", title: "Saved" }],
["ERROR", "Could not reach [email]", { level: "error" }],
]);
});
it("records the blocking error dialog", () => {
reportError("The server refused", "Couldn't save");
expect(logged("ui.error_dialog")).toMatchObject([
{ level: "ERROR", msg: "The server refused", attrs: { title: "Couldn't save" } },
]);
});
it("records a failed query by its resource only — the rest of the key is filter state", async () => {
const client = createQueryClient();
await client
.fetchQuery({
queryKey: ["videos", { tags: ["private-tag"] }],
queryFn: () => Promise.reject(new HttpError(503, "down")),
})
.catch(() => {});
expect(logged("query.failed")).toMatchObject([
{ level: "WARNING", attrs: { key: "videos", status: 503, message: "down" } },
]);
expect(JSON.stringify(events())).not.toContain("private-tag");
});
it("records a failed mutation", async () => {
const client = createQueryClient();
const mutation = client.getMutationCache().build(client, {
mutationKey: ["playlists", 42],
mutationFn: () => Promise.reject(new HttpError(409, "conflict")),
meta: { errorShownInline: true },
});
await mutation.execute(undefined).catch(() => {});
expect(logged("mutation.failed")).toMatchObject([
{ level: "WARNING", attrs: { key: "playlists", status: 409 } },
]);
});
it("records a render crash with its component stack", () => {
vi.spyOn(console, "error").mockImplementation(() => {}); // React reports the crash itself too
const Boom = () => {
throw new Error("render exploded");
};
render(
<ErrorBoundary>
<Boom />
</ErrorBoundary>,
);
const [crash] = logged("ui.crash");
expect(crash).toMatchObject({ level: "CRITICAL", attrs: { message: "render exploded" } });
expect(String(crash!.attrs!.component_stack)).toContain("Boom");
});
});
@@ -1,8 +1,9 @@
// Shared shell for the public, login-free legal pages (/privacy, /terms). These must be
// reachable unauthenticated — Google's OAuth consent screen links to them and reviewers
// fetch them directly — so they render outside the authenticated App tree (see main.tsx),
// with no react-query provider: the operator contact is fetched with a plain fetch below.
// with no react-query provider: the operator contact is fetched with a bare `send` below.
import { useEffect, useState } from "react";
import { send } from "../../lib/http";
const LAST_UPDATED = "June 14, 2026";
@@ -11,7 +12,7 @@ const LAST_UPDATED = "June 14, 2026";
let contactPromise: Promise<string | null> | null = null;
function fetchOperatorContact(): Promise<string | null> {
if (!contactPromise) {
contactPromise = fetch("/auth/config")
contactPromise = send("/auth/config")
.then((r) => (r.ok ? r.json() : null))
.then((c) => (c?.operator_contact as string | undefined) ?? null)
.catch(() => null);