fix: replace the home and profile folders exactly in the Journal (#497)
withoutFolders guesses where a path starts and ends, and five review
passes each found a line it let a folder through: blanks, soft stops, a
kept stop in a folder name, the fallback after a cut, a path glued to a
character that starts nothing. The new src/services/logFolders.ts knows
the two folders that hold the OS user name instead: the home folder
(homeDir) becomes "~" and the folder of the profile databases
(appConfigDir) "<profile folder>", the latter first.
- replaceKnownFolders: either separator and any run of them between
segments (JSON.stringify doubles each backslash), case ignored with a
drive letter, trailing separator of the folder dropped, and a
boundary after it, so /home/max leaves /home/maxime alone. Never
throws.
- setKnownFolders builds the patterns once, every segment escaped
(CWE-185: a raw "(" would make every captured console call throw),
and ignores an empty or root folder.
- initKnownFolders resolves both folders once, independently
(Promise.allSettled), never rejected; knownFoldersReady resolves when
they are known or 2 s after initKnownFolders, and at once when it was
never called.
logService replaces them in every entry, whatever its channel, and
replayLogEntries rewrites the entries written before they arrived,
sessionStorage included; main.tsx wires it right after initLogCapture.
db.ts waits for knownFoldersReady inside the exclusive section of
connectToProfile, before repair_migrations, and its four sites clean a
line with cleanLogLine: the exact folders, then withoutFolders, which
does not change. "Migration checksums repaired for" goes through
logWarn, and startupConnection writes through a logError that App.tsx
passes: neither file writes to the Journal through console.* any more.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e3e043644d
commit
c1d69d23c5
10 changed files with 1047 additions and 24 deletions
|
|
@ -31,6 +31,7 @@ import ProfileSelectionPage from "./pages/ProfileSelectionPage";
|
|||
import ErrorPage from "./components/shared/ErrorPage";
|
||||
import RequireFeature from "./components/shared/RequireFeature";
|
||||
import { startProfileConnection } from "./utils/startupConnection";
|
||||
import { logError } from "./services/logService";
|
||||
|
||||
export default function App() {
|
||||
const { t } = useTranslation();
|
||||
|
|
@ -44,6 +45,7 @@ export default function App() {
|
|||
connect: connectActiveProfile,
|
||||
setDbReady,
|
||||
setStartupError,
|
||||
logError,
|
||||
timeoutMessage: t("error.startupTimeout"),
|
||||
});
|
||||
}, [activeProfile, isLoading, connectActiveProfile, t]);
|
||||
|
|
|
|||
|
|
@ -4,11 +4,16 @@ import App from "./App";
|
|||
import { LicenseProvider } from "./contexts/LicenseContext";
|
||||
import { ProfileProvider } from "./contexts/ProfileContext";
|
||||
import ErrorBoundary from "./components/shared/ErrorBoundary";
|
||||
import { initLogCapture } from "./services/logService";
|
||||
import { initLogCapture, replayLogEntries } from "./services/logService";
|
||||
import { initKnownFolders } from "./services/logFolders";
|
||||
import "./i18n/config";
|
||||
import "./styles.css";
|
||||
|
||||
initLogCapture();
|
||||
// The home and profile folders, replaced exactly in every Journal entry
|
||||
// (#497): the entries written before they arrive are rewritten then, even
|
||||
// after the 2 s that connectToProfile waits for them at most.
|
||||
void initKnownFolders().then(replayLogEntries);
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
|
|
|
|||
|
|
@ -30,13 +30,19 @@ vi.mock("@tauri-apps/plugin-sql", () => ({
|
|||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
invoke: vi.fn(async (command: string) => (command === "prepare_profile_db" ? h.prepare() : false)),
|
||||
}));
|
||||
// The path API that logFolders.ts calls (#497), mocked on its own: its real
|
||||
// module imports `./core.js`, so the fake invoke above would answer homeDir()
|
||||
// with `false` and add calls to the invoke order the tests read.
|
||||
vi.mock("@tauri-apps/api/path", () => ({ homeDir: vi.fn(), appConfigDir: vi.fn() }));
|
||||
vi.mock("./logService", () => ({ logInfo: vi.fn(), logWarn: vi.fn(), logError: vi.fn() }));
|
||||
|
||||
import Database from "@tauri-apps/plugin-sql";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { logError, logInfo, logWarn } from "./logService";
|
||||
import { KNOWN_FOLDERS_DELAY_MS, setKnownFolders } from "./logFolders";
|
||||
import {
|
||||
BLOCKED_ALERT_MS,
|
||||
cleanLogLine,
|
||||
closeDb,
|
||||
connectToProfile,
|
||||
DbConnectionClosedError,
|
||||
|
|
@ -628,8 +634,9 @@ describe("a profile is prepared before the plugin opens it (#390)", () => {
|
|||
});
|
||||
|
||||
it("writes no folder when the checksum repair fails with a path (#478)", async () => {
|
||||
// rusqlite appends the full path of a database it cannot open, and
|
||||
// repair_migrations returns that message as it is.
|
||||
// rusqlite appends the full path of a database it cannot open. Since
|
||||
// #497 repair_migrations replaces the profile folder (`scrub`); a path it
|
||||
// left whole, as below, is the heuristic's alone.
|
||||
vi.mocked(invoke).mockImplementationOnce(async () => {
|
||||
throw "Cannot open database: unable to open database file: C:\\Users\\Jean (Work) Smith\\AppData\\Roaming\\com.simpl.resultat\\profile_0a1b2c3d.db";
|
||||
});
|
||||
|
|
@ -643,6 +650,15 @@ describe("a profile is prepared before the plugin opens it (#390)", () => {
|
|||
]);
|
||||
});
|
||||
|
||||
it("writes a checksum repair through logWarn, never console.warn (#497)", async () => {
|
||||
vi.mocked(invoke).mockImplementationOnce(async () => true);
|
||||
|
||||
await connectToProfile("profile_0a1b2c3d.db");
|
||||
|
||||
expect(vi.mocked(logWarn).mock.calls).toEqual([["Migration checksums repaired for", "profile_0a1b2c3d.db"]]);
|
||||
expect(consoleLines).toEqual([]);
|
||||
});
|
||||
|
||||
it("names the copy in the Journal when the catch-up stopped after taking it (#395)", async () => {
|
||||
h.prepare = async () =>
|
||||
report({
|
||||
|
|
@ -839,3 +855,195 @@ describe("describePreparation (#390)", () => {
|
|||
}
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Two curtains: the exact known folders, then the heuristic (#497)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("cleanLogLine: the known folders first, then withoutFolders (#497)", () => {
|
||||
afterEach(() => {
|
||||
setKnownFolders({});
|
||||
});
|
||||
|
||||
// The five leaks that five passes found, one after the other, in the
|
||||
// heuristic alone (#497), each with the folder that holds the user name
|
||||
// known. Invented names only: the repository is public.
|
||||
it.each([
|
||||
[
|
||||
"blanks in a folder name (#436 review, S1)",
|
||||
{ home: "C:\\Users\\Jean Dupont", profileFolder: "C:\\Users\\Jean Dupont\\AppData\\Roaming\\com.simpl.resultat" },
|
||||
"Migration repair failed: unable to open database file: C:\\Users\\Jean Dupont\\AppData\\Roaming\\com.simpl.resultat\\profile_0a1b2c3d.db",
|
||||
"Migration repair failed: unable to open database file: profile_0a1b2c3d.db",
|
||||
/Users|Jean|Dupont|AppData|Roaming|simpl\.resultat/,
|
||||
],
|
||||
[
|
||||
"a former soft stop in a folder name (#473 review)",
|
||||
{ home: "C:\\Users\\Jean (Work) Smith" },
|
||||
"Profile x.db: database preparation failed: cannot read C:\\Users\\Jean (Work) Smith\\AppData\\x.db",
|
||||
"Profile x.db: database preparation failed: cannot read x.db",
|
||||
/Users|Jean|Work|Smith/,
|
||||
],
|
||||
[
|
||||
"a kept stop in a folder name (#491 self-review)",
|
||||
{ home: "C:\\Users\\Smith, Jean", profileFolder: "C:\\Users\\Smith, Jean\\AppData\\Roaming\\com.simpl.resultat" },
|
||||
"Migration repair failed: unable to open database file: C:\\Users\\Smith, Jean\\AppData\\Roaming\\com.simpl.resultat\\profile_0a1b2c3d.db",
|
||||
"Migration repair failed: unable to open database file: profile_0a1b2c3d.db",
|
||||
/Users|Smith|Jean|AppData|Roaming|simpl\.resultat/,
|
||||
],
|
||||
[
|
||||
"the fallback after a path already cut (review 27073 of #491)",
|
||||
{ home: "C:\\Users\\Smith, Jean" },
|
||||
"Profile x.db: database preparation failed: cannot read C:\\Users\\Smith, Jean\\Notes,\\x.db",
|
||||
"Profile x.db: database preparation failed: cannot read x.db",
|
||||
/Users|Smith|Jean/,
|
||||
],
|
||||
[
|
||||
"a path glued to a character that starts nothing (review 27245 of #491)",
|
||||
{ home: "/home/jean dupont" },
|
||||
"Profile x.db: database preparation failed: x;/home/jean dupont/x.db",
|
||||
"Profile x.db: database preparation failed: x;~-x.db",
|
||||
/home|jean|dupont/,
|
||||
],
|
||||
])("leaves no segment of the folder after %s", (_case, folders, line, expected, segments) => {
|
||||
setKnownFolders(folders);
|
||||
const cleaned = cleanLogLine(line);
|
||||
expect(cleaned).toBe(expected);
|
||||
expect(cleaned).not.toMatch(segments);
|
||||
expect(cleaned).not.toMatch(/[\\/]/);
|
||||
});
|
||||
|
||||
// Why the exact folders come first: the heuristic alone lets these through.
|
||||
it.each([
|
||||
[
|
||||
{ home: "C:\\Users\\Smith, Jean" },
|
||||
"Migration repair failed: unable to open database file: C:\\Users\\Smith, Jean\\AppData\\x.db",
|
||||
/Smith/,
|
||||
],
|
||||
[{ home: "C:\\Users\\Smith, Jean" }, "cannot read C:\\Users\\Smith, Jean\\Notes,\\x.db", /Smith, Jean/],
|
||||
[{ home: "/home/jean dupont" }, "failed: x;/home/jean dupont/x.db", /jean dupont/],
|
||||
])("cleans what withoutFolders alone leaks, whatever the order would leave: %j", (folders, line, leak) => {
|
||||
expect(withoutFolders(line)).toMatch(leak);
|
||||
setKnownFolders(folders);
|
||||
expect(cleanLogLine(line)).not.toMatch(leak);
|
||||
});
|
||||
|
||||
it("is withoutFolders alone while no folder is known", () => {
|
||||
const line = "Profile x.db: database preparation failed: cannot read C:\\Users\\Jean Dupont\\x.db";
|
||||
expect(cleanLogLine(line)).toBe(withoutFolders(line));
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// connectToProfile waits for the known folders (#497). initKnownFolders()
|
||||
// runs once per module instance, so each test takes a fresh db.ts with its own
|
||||
// logFolders.ts. Keep this block last: vi.resetModules() leaves the fresh
|
||||
// modules in the registry, and an earlier test imports "./db" again
|
||||
// ("withTransaction rejects when no profile is connected").
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("connectToProfile waits for the known folders (#497)", () => {
|
||||
async function freshDb() {
|
||||
vi.resetModules();
|
||||
const db = await import("./db");
|
||||
const folders = await import("./logFolders");
|
||||
const core = await import("@tauri-apps/api/core");
|
||||
const path = await import("@tauri-apps/api/path");
|
||||
const log = await import("./logService");
|
||||
const homeDir = vi.mocked(path.homeDir);
|
||||
const appConfigDir = vi.mocked(path.appConfigDir);
|
||||
homeDir.mockReset();
|
||||
appConfigDir.mockReset();
|
||||
vi.mocked(core.invoke).mockClear();
|
||||
vi.mocked(log.logError).mockClear();
|
||||
return {
|
||||
db,
|
||||
folders,
|
||||
invoke: vi.mocked(core.invoke),
|
||||
logError: vi.mocked(log.logError),
|
||||
homeDir,
|
||||
appConfigDir,
|
||||
commands: () => vi.mocked(core.invoke).mock.calls.map((call) => call[0]),
|
||||
};
|
||||
}
|
||||
|
||||
const never = () => new Promise<string>(() => {});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("calls repair_migrations only once the folders are known", async () => {
|
||||
const m = await freshDb();
|
||||
let answer: (home: string) => void = () => {};
|
||||
m.homeDir.mockImplementation(
|
||||
() =>
|
||||
new Promise<string>((resolve) => {
|
||||
answer = resolve;
|
||||
})
|
||||
);
|
||||
m.appConfigDir.mockResolvedValue("/home/max/.config/com.simpl.resultat");
|
||||
void m.folders.initKnownFolders();
|
||||
|
||||
const connecting = m.db.connectToProfile("profile_0a1b2c3d.db");
|
||||
// Give an invoke started too early every chance to show up.
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
expect(m.invoke).not.toHaveBeenCalled();
|
||||
|
||||
answer("/home/max");
|
||||
await connecting;
|
||||
// The path API never goes through invoke: the order stays the one of #390.
|
||||
expect(m.commands()).toEqual(["repair_migrations", "prepare_profile_db"]);
|
||||
});
|
||||
|
||||
it("goes on 2 s after initKnownFolders() when homeDir() never answers", async () => {
|
||||
vi.useFakeTimers();
|
||||
const m = await freshDb();
|
||||
m.homeDir.mockImplementation(never);
|
||||
m.appConfigDir.mockImplementation(never);
|
||||
void m.folders.initKnownFolders();
|
||||
|
||||
const connecting = m.db.connectToProfile("profile_0a1b2c3d.db");
|
||||
await vi.advanceTimersByTimeAsync(KNOWN_FOLDERS_DELAY_MS - 1);
|
||||
expect(m.invoke).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await connecting;
|
||||
|
||||
expect(m.commands()).toEqual(["repair_migrations", "prepare_profile_db"]);
|
||||
});
|
||||
|
||||
it("goes on at once when homeDir() rejects, with the folder that resolved", async () => {
|
||||
vi.useFakeTimers();
|
||||
const m = await freshDb();
|
||||
m.homeDir.mockRejectedValue(new Error("no home folder"));
|
||||
m.appConfigDir.mockResolvedValue("/home/jean dupont/.config/com.simpl.resultat");
|
||||
void m.folders.initKnownFolders();
|
||||
m.invoke.mockImplementationOnce(async () => {
|
||||
throw "Cannot open database: x;/home/jean dupont/.config/com.simpl.resultat/profile_0a1b2c3d.db";
|
||||
});
|
||||
|
||||
const connecting = m.db.connectToProfile("profile_0a1b2c3d.db");
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await connecting;
|
||||
|
||||
expect(m.commands()).toEqual(["repair_migrations", "prepare_profile_db"]);
|
||||
expect(m.logError.mock.calls.map((call) => call[0])).toEqual([
|
||||
"Migration repair failed: Cannot open database: x;profile_0a1b2c3d.db",
|
||||
]);
|
||||
});
|
||||
|
||||
it("writes the repair failure without any segment of the known folders", async () => {
|
||||
const m = await freshDb();
|
||||
m.homeDir.mockResolvedValue("/home/jean dupont");
|
||||
m.appConfigDir.mockResolvedValue("/home/jean dupont/.config/com.simpl.resultat");
|
||||
await m.folders.initKnownFolders();
|
||||
m.invoke.mockImplementationOnce(async () => {
|
||||
throw "Cannot open database: unable to open database file: x;/home/jean dupont/Documents/profile_0a1b2c3d.db";
|
||||
});
|
||||
|
||||
await m.db.connectToProfile("profile_0a1b2c3d.db");
|
||||
|
||||
const lines = m.logError.mock.calls.map((call) => String(call[0]));
|
||||
expect(lines).toEqual(["Migration repair failed: Cannot open database: unable to open database file: profile_0a1b2c3d.db"]);
|
||||
expect(lines.join("\n")).not.toMatch(/home|jean|dupont|Documents|[\\/]/);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import Database from "@tauri-apps/plugin-sql";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { knownFoldersReady, replaceKnownFolders } from "./logFolders";
|
||||
import { logError, logInfo, logWarn } from "./logService";
|
||||
|
||||
let rawInstance: Database | null = null;
|
||||
|
|
@ -284,7 +285,7 @@ async function closeUnlocked(): Promise<void> {
|
|||
await closing.close();
|
||||
} catch (e) {
|
||||
logWarn(
|
||||
withoutFolders(
|
||||
cleanLogLine(
|
||||
`DB: closing the previous connection failed, continuing without it: ${e instanceof Error ? e.message : String(e)}`
|
||||
)
|
||||
);
|
||||
|
|
@ -418,6 +419,18 @@ export function withoutFolders(text: string): string {
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One Journal line of this file, cleaned by two curtains (#497): the exact
|
||||
* home and profile folders first (`replaceKnownFolders`), then the heuristic
|
||||
* for any other path (`withoutFolders`). In that order: the heuristic can cut
|
||||
* a path in the wrong place (`x;/home/jean dupont/x.db` gives
|
||||
* `jean dupont-x.db`), and the exact replacement no longer finds the folder in
|
||||
* what it left. ADR 0021, section 7.
|
||||
*/
|
||||
export function cleanLogLine(text: string): string {
|
||||
return withoutFolders(replaceKnownFolders(text));
|
||||
}
|
||||
|
||||
/**
|
||||
* Journal lines for one preparation: only what changed. Names files, never
|
||||
* folders: an error line can be attached to a feedback report, and the
|
||||
|
|
@ -450,9 +463,9 @@ export function describePreparation(
|
|||
info.push(`Profile ${dbFilename}: ${rows} row(s) of ${table} point to a missing row`);
|
||||
}
|
||||
if (report.catch_up_error) {
|
||||
const copy = report.catch_up_backup ? withoutFolders(report.catch_up_backup) : "";
|
||||
const copy = report.catch_up_backup ? cleanLogLine(report.catch_up_backup) : "";
|
||||
errors.push(
|
||||
withoutFolders(
|
||||
cleanLogLine(
|
||||
`Profile ${dbFilename}: database update stopped: ${report.catch_up_error}` +
|
||||
(copy ? `; copy of the previous state kept as ${copy}` : "")
|
||||
)
|
||||
|
|
@ -466,19 +479,25 @@ export function describePreparation(
|
|||
|
||||
export function connectToProfile(dbFilename: string): Promise<void> {
|
||||
return runExclusive("profile opening", async () => {
|
||||
// The lines below may carry a folder: wait for the exact folders of the
|
||||
// Journal (#497). Bounded: at once without initKnownFolders(), 2 s at
|
||||
// most after it. Inside the section, so an operation queued after this
|
||||
// call still runs after the profile opened.
|
||||
await knownFoldersReady();
|
||||
// The old pool is fully closed before the preparation touches the file.
|
||||
await closeUnlocked();
|
||||
// Repair migration checksums before loading (fixes "migration was modified" error)
|
||||
try {
|
||||
const repaired = await invoke<boolean>("repair_migrations", { dbFilename });
|
||||
if (repaired) {
|
||||
console.warn("Migration checksums repaired for", dbFilename);
|
||||
logWarn("Migration checksums repaired for", dbFilename);
|
||||
}
|
||||
} catch (e) {
|
||||
// repair_migrations returns rusqlite's error unscrubbed, and rusqlite
|
||||
// appends the full path of a database it cannot open: only the file
|
||||
// name may reach the Journal (#478).
|
||||
logError(withoutFolders(`Migration repair failed: ${e instanceof Error ? e.message : String(e)}`));
|
||||
// rusqlite appends the full path of a database it cannot open.
|
||||
// repair_migrations replaces the profile folder (`scrub`, #497); the
|
||||
// rest of a path is the heuristic's: only the file name may reach the
|
||||
// Journal (#478).
|
||||
logError(cleanLogLine(`Migration repair failed: ${e instanceof Error ? e.message : String(e)}`));
|
||||
}
|
||||
// Catch a secondary profile up on the migrations tauri-plugin-sql never
|
||||
// runs for it, and repair legacy values in every profile (#390). Fails
|
||||
|
|
@ -490,7 +509,7 @@ export function connectToProfile(dbFilename: string): Promise<void> {
|
|||
lines.errors.forEach((line) => logError(line));
|
||||
} catch (e) {
|
||||
logError(
|
||||
withoutFolders(
|
||||
cleanLogLine(
|
||||
`Profile ${dbFilename}: database preparation failed: ${e instanceof Error ? e.message : String(e)}`
|
||||
)
|
||||
);
|
||||
|
|
|
|||
343
src/services/logFolders.test.ts
Normal file
343
src/services/logFolders.test.ts
Normal file
|
|
@ -0,0 +1,343 @@
|
|||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
// Exact replacement of the home and profile folders in the Journal (#497).
|
||||
// The path API is mocked: in the app, homeDir() and appConfigDir() go
|
||||
// through invoke, which these tests do not have.
|
||||
vi.mock("@tauri-apps/api/path", () => ({ homeDir: vi.fn(), appConfigDir: vi.fn() }));
|
||||
|
||||
import {
|
||||
HOME_PLACEHOLDER,
|
||||
KNOWN_FOLDERS_DELAY_MS,
|
||||
PROFILE_FOLDER_PLACEHOLDER,
|
||||
replaceKnownFolders,
|
||||
setKnownFolders,
|
||||
type KnownFolders,
|
||||
} from "./logFolders";
|
||||
|
||||
const LINUX: KnownFolders = { home: "/home/max", profileFolder: "/home/max/.config/com.simpl.resultat" };
|
||||
const WINDOWS: KnownFolders = {
|
||||
home: "C:\\Users\\Max",
|
||||
profileFolder: "C:\\Users\\Max\\AppData\\Roaming\\com.simpl.resultat",
|
||||
};
|
||||
|
||||
describe("replaceKnownFolders (#497)", () => {
|
||||
it("names its two placeholders without any separator", () => {
|
||||
expect(PROFILE_FOLDER_PLACEHOLDER).toBe("<profile folder>");
|
||||
expect(HOME_PLACEHOLDER).toBe("~");
|
||||
});
|
||||
|
||||
it.each([
|
||||
// The profile folder first: it sits under the home folder.
|
||||
[
|
||||
"cannot open /home/max/.config/com.simpl.resultat/profile_0a1b2c3d.db",
|
||||
"cannot open <profile folder>/profile_0a1b2c3d.db",
|
||||
],
|
||||
["read /home/max/Documents/bank.csv", "read ~/Documents/bank.csv"],
|
||||
[
|
||||
"/home/max/.config/com.simpl.resultat/a.db then /home/max/b.csv",
|
||||
"<profile folder>/a.db then ~/b.csv",
|
||||
],
|
||||
// Glued to a character the heuristic does not take for a path start.
|
||||
["x;/home/max/x.db", "x;~/x.db"],
|
||||
["HOME=/home/max", "HOME=~"],
|
||||
// Any run of separators, either one.
|
||||
["//home//max//x.db", "~//x.db"],
|
||||
["\\home\\max\\x.db", "~\\x.db"],
|
||||
// JSON.stringify, which logService applies to an argument that is not a string.
|
||||
[JSON.stringify({ path: "/home/max/x.db" }), '{"path":"~/x.db"}'],
|
||||
])("replaces the Linux folders in %j", (text, expected) => {
|
||||
expect(replaceKnownFolders(text, LINUX)).toBe(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"C:\\Users\\Max\\AppData\\Roaming\\com.simpl.resultat\\profile_0a1b2c3d.db",
|
||||
"<profile folder>\\profile_0a1b2c3d.db",
|
||||
],
|
||||
["C:/Users\\Max/Documents\\bank.csv", "~/Documents\\bank.csv"],
|
||||
["C:/Users/Max/AppData/Roaming/com.simpl.resultat/x.db", "<profile folder>/x.db"],
|
||||
// JSON.stringify doubles every `\`, twice over for a string stringified again.
|
||||
[JSON.stringify({ path: "C:\\Users\\Max\\x.db" }), '{"path":"~\\\\x.db"}'],
|
||||
[JSON.stringify(JSON.stringify({ path: "C:\\Users\\Max\\x.db" })), '"{\\"path\\":\\"~\\\\\\\\x.db\\"}"'],
|
||||
// A drive letter: the case is ignored.
|
||||
["c:\\users\\max\\x.db", "~\\x.db"],
|
||||
["C:\\USERS\\MAX\\APPDATA\\ROAMING\\COM.SIMPL.RESULTAT\\x.db", "<profile folder>\\x.db"],
|
||||
])("replaces the Windows folders in %j", (text, expected) => {
|
||||
expect(replaceKnownFolders(text, WINDOWS)).toBe(expected);
|
||||
});
|
||||
|
||||
it("keeps the case of a Linux folder", () => {
|
||||
expect(replaceKnownFolders("/Home/Max/x.db", LINUX)).toBe("/Home/Max/x.db");
|
||||
});
|
||||
|
||||
it("drops a separator at the end of the resolved folder", () => {
|
||||
expect(replaceKnownFolders("/home/max/x.db", { home: "/home/max/" })).toBe("~/x.db");
|
||||
expect(replaceKnownFolders("C:\\Users\\Max\\x.db", { home: "C:\\Users\\Max\\" })).toBe("~\\x.db");
|
||||
});
|
||||
|
||||
// `/home/max` must not touch another folder that starts like it.
|
||||
it.each([
|
||||
["/home/maxime/x.db"],
|
||||
["/home/max2/x.db"],
|
||||
["/home/max.old/x.db"],
|
||||
["/home/max-dev/x.db"],
|
||||
["/home/max_b/x.db"],
|
||||
["/home/maxé/x.db"],
|
||||
["C:\\Users\\Maxime\\x.db"],
|
||||
])("stops at the end of the folder name: %s stays", (text) => {
|
||||
const folders = text.startsWith("C:") ? WINDOWS : LINUX;
|
||||
expect(replaceKnownFolders(text, folders)).toBe(text);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["see /home/max) and", "see ~) and"],
|
||||
['"/home/max"', '"~"'],
|
||||
["'/home/max'", "'~'"],
|
||||
["/home/max, then", "~, then"],
|
||||
["/home/max: no such file", "~: no such file"],
|
||||
["/home/max then", "~ then"],
|
||||
["/home/max", "~"],
|
||||
])("replaces the folder followed by what ends a name: %j", (text, expected) => {
|
||||
expect(replaceKnownFolders(text, LINUX)).toBe(expected);
|
||||
});
|
||||
|
||||
// A folder name may hold a character that means something in a pattern.
|
||||
it.each([
|
||||
["C:\\Users\\Jean (Work)", "C:\\Users\\Jean (Work)\\x.db", "~\\x.db", "C:\\Users\\Jean Work\\x.db"],
|
||||
["/home/jean.dupont", "/home/jean.dupont/x.db", "~/x.db", "/home/jeanXdupont/x.db"],
|
||||
["C:\\Users\\A$b", "C:\\Users\\A$b\\x.db", "~\\x.db", "C:\\Users\\A\\x.db"],
|
||||
["/home/a^b{1}+c", "/home/a^b{1}+c/x.db", "~/x.db", "/home/ab/x.db"],
|
||||
["C:\\Users\\Jean (Work", "C:\\Users\\Jean (Work\\x.db", "~\\x.db", "C:\\Users\\Jean Work\\x.db"],
|
||||
])("replaces %s exactly", (home, text, expected, other) => {
|
||||
expect(replaceKnownFolders(text, { home })).toBe(expected);
|
||||
expect(replaceKnownFolders(other, { home })).toBe(other);
|
||||
});
|
||||
|
||||
it.each([[""], ["/"], ["//"], ["\\"], ["C:\\"], ["C:"], ["c:/"], [null], [undefined], [42]])(
|
||||
"ignores the folder %j: no pattern, no exception",
|
||||
(home) => {
|
||||
for (const text of ["/home/max/x.db", "C:\\Users\\Max\\x.db", "plain text"]) {
|
||||
expect(replaceKnownFolders(text, { home: home as string })).toBe(text);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it("changes nothing without known folders, nor in a line without them", () => {
|
||||
expect(replaceKnownFolders("cannot open /home/max/x.db")).toBe("cannot open /home/max/x.db");
|
||||
expect(replaceKnownFolders("cannot open /home/max/x.db", {})).toBe("cannot open /home/max/x.db");
|
||||
expect(replaceKnownFolders("disk I/O error at /var/tmp/x.db", LINUX)).toBe("disk I/O error at /var/tmp/x.db");
|
||||
});
|
||||
|
||||
it("never throws, whatever it is given", () => {
|
||||
expect(replaceKnownFolders(42 as never, LINUX)).toBe(42);
|
||||
expect(replaceKnownFolders("x", { home: "/home/\ud800" })).toBe("x");
|
||||
expect(replaceKnownFolders("x", null as never)).toBe("x");
|
||||
});
|
||||
});
|
||||
|
||||
describe("setKnownFolders (#497)", () => {
|
||||
afterEach(() => {
|
||||
setKnownFolders({});
|
||||
});
|
||||
|
||||
it("builds the patterns once for every later call without folders", () => {
|
||||
setKnownFolders(LINUX);
|
||||
expect(replaceKnownFolders("cannot open /home/max/.config/com.simpl.resultat/x.db")).toBe(
|
||||
"cannot open <profile folder>/x.db"
|
||||
);
|
||||
expect(replaceKnownFolders("read /home/max/a.csv")).toBe("read ~/a.csv");
|
||||
});
|
||||
|
||||
it("replaces the folders of a previous call, and an empty set clears them", () => {
|
||||
setKnownFolders(LINUX);
|
||||
setKnownFolders(WINDOWS);
|
||||
expect(replaceKnownFolders("/home/max/a.csv")).toBe("/home/max/a.csv");
|
||||
expect(replaceKnownFolders("C:\\Users\\Max\\a.csv")).toBe("~\\a.csv");
|
||||
setKnownFolders({});
|
||||
expect(replaceKnownFolders("C:\\Users\\Max\\a.csv")).toBe("C:\\Users\\Max\\a.csv");
|
||||
});
|
||||
|
||||
it("ignores a root folder and keeps the other", () => {
|
||||
setKnownFolders({ home: "/", profileFolder: "/home/max/.config/com.simpl.resultat" });
|
||||
expect(replaceKnownFolders("/home/max/.config/com.simpl.resultat/x.db and /home/max/a.csv")).toBe(
|
||||
"<profile folder>/x.db and /home/max/a.csv"
|
||||
);
|
||||
setKnownFolders({ home: "C:\\" });
|
||||
expect(replaceKnownFolders("C:\\Users\\Max\\a.csv")).toBe("C:\\Users\\Max\\a.csv");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Resolution of the folders. initKnownFolders() runs once per module
|
||||
// instance: each test takes a fresh one.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function freshFolders() {
|
||||
vi.resetModules();
|
||||
const folders = await import("./logFolders");
|
||||
const path = await import("@tauri-apps/api/path");
|
||||
const homeDir = vi.mocked(path.homeDir);
|
||||
const appConfigDir = vi.mocked(path.appConfigDir);
|
||||
homeDir.mockReset();
|
||||
appConfigDir.mockReset();
|
||||
return { ...folders, homeDir, appConfigDir };
|
||||
}
|
||||
|
||||
/** Whether a promise has settled, read without awaiting it. */
|
||||
function track(promise: Promise<unknown>) {
|
||||
const state = { settled: false };
|
||||
void promise.then(() => {
|
||||
state.settled = true;
|
||||
});
|
||||
return state;
|
||||
}
|
||||
|
||||
const never = () => new Promise<string>(() => {});
|
||||
|
||||
describe("initKnownFolders and knownFoldersReady (#497)", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("resolves knownFoldersReady() at once while initKnownFolders() was never called", async () => {
|
||||
const m = await freshFolders();
|
||||
const ready = track(m.knownFoldersReady());
|
||||
await Promise.resolve();
|
||||
expect(ready.settled).toBe(true);
|
||||
expect(m.homeDir).not.toHaveBeenCalled();
|
||||
expect(m.appConfigDir).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resolves both as soon as the two folders are known", async () => {
|
||||
const m = await freshFolders();
|
||||
m.homeDir.mockResolvedValue("/home/max");
|
||||
m.appConfigDir.mockResolvedValue("/home/max/.config/com.simpl.resultat");
|
||||
|
||||
const resolution = track(m.initKnownFolders());
|
||||
const ready = track(m.knownFoldersReady());
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(resolution.settled).toBe(true);
|
||||
expect(ready.settled).toBe(true);
|
||||
expect(m.replaceKnownFolders("/home/max/.config/com.simpl.resultat/x.db, /home/max/a.csv")).toBe(
|
||||
"<profile folder>/x.db, ~/a.csv"
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves knownFoldersReady() 2 s after initKnownFolders() when homeDir() never answers", async () => {
|
||||
const m = await freshFolders();
|
||||
m.homeDir.mockImplementation(never);
|
||||
m.appConfigDir.mockImplementation(never);
|
||||
|
||||
const resolution = track(m.initKnownFolders());
|
||||
await vi.advanceTimersByTimeAsync(KNOWN_FOLDERS_DELAY_MS / 2);
|
||||
// Asked halfway: the delay still runs from initKnownFolders().
|
||||
const ready = track(m.knownFoldersReady());
|
||||
await vi.advanceTimersByTimeAsync(KNOWN_FOLDERS_DELAY_MS / 2 - 1);
|
||||
expect(ready.settled).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
|
||||
expect(ready.settled).toBe(true);
|
||||
expect(resolution.settled).toBe(false);
|
||||
expect(m.replaceKnownFolders("/home/max/a.csv")).toBe("/home/max/a.csv");
|
||||
});
|
||||
|
||||
it("does not wait for the delay when homeDir() rejects", async () => {
|
||||
const m = await freshFolders();
|
||||
m.homeDir.mockRejectedValue(new Error("no home"));
|
||||
m.appConfigDir.mockRejectedValue(new Error("no config"));
|
||||
|
||||
const resolution = track(m.initKnownFolders());
|
||||
const ready = track(m.knownFoldersReady());
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(resolution.settled).toBe(true);
|
||||
expect(ready.settled).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["homeDir() rejects", "home"],
|
||||
["appConfigDir() rejects", "profileFolder"],
|
||||
])("uses the folder that resolved when %s", async (_case, failing) => {
|
||||
const m = await freshFolders();
|
||||
if (failing === "home") {
|
||||
m.homeDir.mockRejectedValue(new Error("no home"));
|
||||
m.appConfigDir.mockResolvedValue("/home/max/.config/com.simpl.resultat");
|
||||
} else {
|
||||
m.homeDir.mockResolvedValue("/home/max");
|
||||
m.appConfigDir.mockRejectedValue(new Error("no config"));
|
||||
}
|
||||
|
||||
await m.initKnownFolders();
|
||||
|
||||
const line = m.replaceKnownFolders("/home/max/.config/com.simpl.resultat/x.db, /home/max/a.csv");
|
||||
expect(line).toBe(
|
||||
failing === "home"
|
||||
? "<profile folder>/x.db, /home/max/a.csv"
|
||||
: "~/.config/com.simpl.resultat/x.db, ~/a.csv"
|
||||
);
|
||||
});
|
||||
|
||||
it.each([[""], [null], [undefined], [42], [{ path: "/home/max" }]])(
|
||||
"counts a resolved value %j that is not a non-empty string as a failure",
|
||||
async (value) => {
|
||||
const m = await freshFolders();
|
||||
m.homeDir.mockResolvedValue(value as never);
|
||||
m.appConfigDir.mockResolvedValue("/home/max/.config/com.simpl.resultat");
|
||||
|
||||
await expect(m.initKnownFolders()).resolves.toBeUndefined();
|
||||
|
||||
expect(m.replaceKnownFolders("/home/max/a.csv")).toBe("/home/max/a.csv");
|
||||
expect(m.replaceKnownFolders("/home/max/.config/com.simpl.resultat/x.db")).toBe("<profile folder>/x.db");
|
||||
}
|
||||
);
|
||||
|
||||
it("is never rejected, a synchronous throw of the path API included", async () => {
|
||||
const m = await freshFolders();
|
||||
m.homeDir.mockImplementation(() => {
|
||||
throw new Error("no IPC");
|
||||
});
|
||||
m.appConfigDir.mockRejectedValue(new Error("no IPC"));
|
||||
|
||||
await expect(m.initKnownFolders()).resolves.toBeUndefined();
|
||||
await expect(m.knownFoldersReady()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves the folders once: a second call returns the same promise", async () => {
|
||||
const m = await freshFolders();
|
||||
m.homeDir.mockResolvedValue("/home/max");
|
||||
m.appConfigDir.mockResolvedValue("/home/max/.config/com.simpl.resultat");
|
||||
|
||||
const first = m.initKnownFolders();
|
||||
const second = m.initKnownFolders();
|
||||
|
||||
expect(second).toBe(first);
|
||||
await first;
|
||||
expect(m.homeDir).toHaveBeenCalledTimes(1);
|
||||
expect(m.appConfigDir).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("still uses folders resolved after the delay, and resolves its promise then", async () => {
|
||||
// main.tsx replays the Journal when this promise resolves.
|
||||
const m = await freshFolders();
|
||||
m.homeDir.mockImplementation(
|
||||
() => new Promise((resolve) => setTimeout(() => resolve("/home/max"), KNOWN_FOLDERS_DELAY_MS + 1_000))
|
||||
);
|
||||
m.appConfigDir.mockResolvedValue("/home/max/.config/com.simpl.resultat");
|
||||
|
||||
const resolution = track(m.initKnownFolders());
|
||||
const ready = track(m.knownFoldersReady());
|
||||
await vi.advanceTimersByTimeAsync(KNOWN_FOLDERS_DELAY_MS);
|
||||
expect(ready.settled).toBe(true);
|
||||
expect(resolution.settled).toBe(false);
|
||||
expect(m.replaceKnownFolders("/home/max/a.csv")).toBe("/home/max/a.csv");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
|
||||
expect(resolution.settled).toBe(true);
|
||||
expect(m.replaceKnownFolders("/home/max/a.csv")).toBe("~/a.csv");
|
||||
});
|
||||
});
|
||||
168
src/services/logFolders.ts
Normal file
168
src/services/logFolders.ts
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
// Exact replacement of the two folders a Journal line must never carry (#497):
|
||||
// the home folder of the OS user and the folder of the profile databases.
|
||||
// Both hold the OS user name, and a warning or error line of the Journal can
|
||||
// leave with a feedback report (Loi 25). The heuristic of db.ts
|
||||
// (`withoutFolders`) guesses where a path starts and ends; this module knows
|
||||
// the two folders themselves, so a path glued to another character, or a
|
||||
// folder whose name holds a stop of the heuristic, loses them all the same.
|
||||
// ADR 0021, section 7.
|
||||
//
|
||||
// It keeps a state (the patterns of the resolved folders) and calls the path
|
||||
// API of Tauri: not a pure module. It imports neither logService.ts nor db.ts,
|
||||
// which both import it.
|
||||
|
||||
import { appConfigDir, homeDir } from "@tauri-apps/api/path";
|
||||
|
||||
/** The two folders, as Tauri resolves them (the resolver of the Rust side). */
|
||||
export interface KnownFolders {
|
||||
/** Folder of the profile databases: `appConfigDir()`, `profile_db_dir` in Rust. */
|
||||
profileFolder?: string | null;
|
||||
/** Home folder of the OS user: `homeDir()`. */
|
||||
home?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What each folder becomes. Neither holds a separator, so a line gains no `/`
|
||||
* nor `\`, and the heuristic of db.ts still reads `<profile folder>/` and `~/`
|
||||
* as the start of a path. `<profile folder>` is the placeholder of Rust's
|
||||
* `scrub`.
|
||||
*/
|
||||
export const PROFILE_FOLDER_PLACEHOLDER = "<profile folder>";
|
||||
export const HOME_PLACEHOLDER = "~";
|
||||
|
||||
/** `knownFoldersReady()` resolves at the latest this long after `initKnownFolders()`. */
|
||||
export const KNOWN_FOLDERS_DELAY_MS = 2_000;
|
||||
|
||||
interface FolderPattern {
|
||||
pattern: RegExp;
|
||||
replacement: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A character that continues a folder name. The match needs anything else
|
||||
* right after the folder (a separator, the end of the text, a blank, a quote,
|
||||
* a parenthesis...), so `/home/max` touches neither `/home/maxime` nor
|
||||
* `/home/max.old`.
|
||||
*/
|
||||
const NAME_GOES_ON = "[\\p{L}\\p{M}\\p{N}_.-]";
|
||||
|
||||
/** Every character with a meaning in a pattern, escaped: a folder name may hold `(`, `)`, `$`, `^`, `{` or `.` (CWE-185). */
|
||||
function escapeSegment(segment: string): string {
|
||||
return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/**
|
||||
* The pattern of one folder, or null when it is ignored: not a string, empty,
|
||||
* a root (`/`, `C:\`), or a pattern that does not build. A separator at its
|
||||
* end is dropped. Its segments are joined by any run of `\` and `/`: the two
|
||||
* separators are interchangeable, and `JSON.stringify`, which logService
|
||||
* applies to an argument that is not a string, doubles every `\`. The case is
|
||||
* ignored when the folder starts with a drive letter (Windows).
|
||||
*/
|
||||
function folderPattern(folder: unknown, replacement: string): FolderPattern | null {
|
||||
if (typeof folder !== "string") return null;
|
||||
const segments = folder.replace(/[\\/]+$/, "").split(/[\\/]+/);
|
||||
const drive = /^[A-Za-z]:$/.test(segments[0]);
|
||||
if (!segments.some((segment, i) => segment !== "" && !(i === 0 && drive))) return null;
|
||||
try {
|
||||
return {
|
||||
pattern: new RegExp(
|
||||
segments.map(escapeSegment).join("[\\\\/]+") + `(?!${NAME_GOES_ON})`,
|
||||
drive ? "giu" : "gu"
|
||||
),
|
||||
replacement,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The profile folder first: it sits under the home folder. */
|
||||
function patternsOf(folders: KnownFolders | null | undefined): FolderPattern[] {
|
||||
if (!folders || typeof folders !== "object") return [];
|
||||
return [
|
||||
folderPattern(folders.profileFolder, PROFILE_FOLDER_PLACEHOLDER),
|
||||
folderPattern(folders.home, HOME_PLACEHOLDER),
|
||||
].filter((pattern): pattern is FolderPattern => pattern !== null);
|
||||
}
|
||||
|
||||
let knownPatterns: FolderPattern[] = [];
|
||||
|
||||
/**
|
||||
* Build the patterns of the folders once, for every later call of
|
||||
* `replaceKnownFolders` without `folders`; a second call replaces them. An
|
||||
* empty or root folder is ignored. Never throws.
|
||||
*/
|
||||
export function setKnownFolders(folders: KnownFolders): void {
|
||||
knownPatterns = patternsOf(folders);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the known folders in `text`: the profile folder with
|
||||
* `<profile folder>`, then the home folder with `~`. With `folders`, those
|
||||
* instead of the ones `setKnownFolders` set. Never throws: on a failure the
|
||||
* text comes back as it was (db.ts still runs its heuristic after it).
|
||||
*/
|
||||
export function replaceKnownFolders(text: string, folders?: KnownFolders): string {
|
||||
if (typeof text !== "string") return text;
|
||||
try {
|
||||
let out = text;
|
||||
for (const { pattern, replacement } of folders === undefined ? knownPatterns : patternsOf(folders)) {
|
||||
out = out.replace(pattern, () => replacement);
|
||||
}
|
||||
return out;
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
let resolution: Promise<void> | null = null;
|
||||
let ready: Promise<void> | null = null;
|
||||
|
||||
/** A folder resolved as a non-empty string; anything else counts as a failure. */
|
||||
function folderOf(result: PromiseSettledResult<unknown>): string | null {
|
||||
return result.status === "fulfilled" && typeof result.value === "string" && result.value !== ""
|
||||
? result.value
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Call a resolver as a promise, a synchronous throw included. */
|
||||
function attempt(resolve: () => Promise<string>): Promise<string> {
|
||||
try {
|
||||
return Promise.resolve(resolve());
|
||||
} catch (e) {
|
||||
return Promise.reject(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the two folders, once: a second call returns the same promise.
|
||||
* `homeDir()` and `appConfigDir()` run independently, so a folder that
|
||||
* resolves serves even when the other fails. Starts the delay of
|
||||
* `knownFoldersReady()`. Returns the promise of the whole resolution, never
|
||||
* rejected; folders that arrive after the delay still serve, and main.tsx
|
||||
* replays the Journal when it resolves.
|
||||
*/
|
||||
export function initKnownFolders(): Promise<void> {
|
||||
if (resolution) return resolution;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const delay = new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, KNOWN_FOLDERS_DELAY_MS);
|
||||
});
|
||||
resolution = Promise.allSettled([attempt(homeDir), attempt(appConfigDir)]).then(([home, profileFolder]) => {
|
||||
clearTimeout(timer);
|
||||
setKnownFolders({ home: folderOf(home), profileFolder: folderOf(profileFolder) });
|
||||
});
|
||||
ready = Promise.race([resolution, delay]);
|
||||
return resolution;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves once the folders are known, or `KNOWN_FOLDERS_DELAY_MS` after
|
||||
* `initKnownFolders()`, whichever comes first; at once while
|
||||
* `initKnownFolders()` was never called (tests, another entry point). Never
|
||||
* rejected: `connectToProfile` waits for it inside its exclusive section.
|
||||
*/
|
||||
export function knownFoldersReady(): Promise<void> {
|
||||
return ready ?? Promise.resolve();
|
||||
}
|
||||
|
|
@ -1,10 +1,23 @@
|
|||
import { describe, it, expect, beforeEach, beforeAll, vi } from "vitest";
|
||||
import { describe, it, expect, beforeEach, beforeAll, afterEach, vi } from "vitest";
|
||||
import { readFileSync } from "fs";
|
||||
import { resolve } from "path";
|
||||
|
||||
// The path API, which the folder resolution calls (#497): through invoke in
|
||||
// the app, which these tests do not have.
|
||||
vi.mock("@tauri-apps/api/path", () => ({ homeDir: vi.fn(), appConfigDir: vi.fn() }));
|
||||
|
||||
import {
|
||||
getRecentErrorLogs,
|
||||
getLogs,
|
||||
clearLogs,
|
||||
initLogCapture,
|
||||
logError,
|
||||
logInfo,
|
||||
logWarn,
|
||||
replayLogEntries,
|
||||
subscribe,
|
||||
} from "./logService";
|
||||
import { KNOWN_FOLDERS_DELAY_MS, setKnownFolders } from "./logFolders";
|
||||
|
||||
beforeAll(() => {
|
||||
// Patch console.* so addEntry runs. Idempotent.
|
||||
|
|
@ -95,3 +108,209 @@ describe("getLogs — live-update snapshot", () => {
|
|||
expect(after).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The home and profile folders, replaced exactly in every entry (#497).
|
||||
// Invented names only: the repository is public.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const LINUX = {
|
||||
home: "/home/jean dupont",
|
||||
profileFolder: "/home/jean dupont/.config/com.simpl.resultat",
|
||||
};
|
||||
const STORAGE_KEY = "simpl-resultat-logs";
|
||||
|
||||
function lastEntry() {
|
||||
const logs = getLogs();
|
||||
return logs[logs.length - 1];
|
||||
}
|
||||
|
||||
/** A sessionStorage: the test environment has none, so the Journal keeps nothing there otherwise. */
|
||||
function fakeStorage(initial: Record<string, string> = {}) {
|
||||
const items = new Map(Object.entries(initial));
|
||||
return {
|
||||
getItem: (key: string) => items.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => {
|
||||
items.set(key, value);
|
||||
},
|
||||
removeItem: (key: string) => {
|
||||
items.delete(key);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("known folders in every entry (#497)", () => {
|
||||
beforeEach(() => {
|
||||
clearLogs();
|
||||
setKnownFolders(LINUX);
|
||||
});
|
||||
afterEach(() => {
|
||||
setKnownFolders({});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["console.log", () => console.log("read /home/jean dupont/Documents/bank.csv"), "info"],
|
||||
["console.warn", () => console.warn("read /home/jean dupont/Documents/bank.csv"), "warn"],
|
||||
["console.error", () => console.error("read /home/jean dupont/Documents/bank.csv"), "error"],
|
||||
["logInfo", () => logInfo("read /home/jean dupont/Documents/bank.csv"), "info"],
|
||||
["logWarn", () => logWarn("read", "/home/jean dupont/Documents/bank.csv"), "warn"],
|
||||
["logError", () => logError("read /home/jean dupont/Documents/bank.csv"), "error"],
|
||||
])("replaces the folders in an entry written by %s", (_channel, write, level) => {
|
||||
write();
|
||||
expect(lastEntry().level).toBe(level);
|
||||
expect(lastEntry().message).toBe("read ~/Documents/bank.csv");
|
||||
});
|
||||
|
||||
it("replaces the profile folder first, then the home folder", () => {
|
||||
console.error("cannot open /home/jean dupont/.config/com.simpl.resultat/profile_0a1b2c3d.db, see /home/jean dupont/a.csv");
|
||||
expect(lastEntry().message).toBe("cannot open <profile folder>/profile_0a1b2c3d.db, see ~/a.csv");
|
||||
});
|
||||
|
||||
it("replaces them in an argument that went through JSON.stringify", () => {
|
||||
setKnownFolders({ home: "C:\\Users\\Jean (Work)" });
|
||||
console.error("failed:", { path: "C:\\Users\\Jean (Work)\\AppData\\x.db" });
|
||||
expect(lastEntry().message).toBe('failed: {"path":"~\\\\AppData\\\\x.db"}');
|
||||
});
|
||||
|
||||
it("leaves the folders out of what a feedback report takes", () => {
|
||||
console.error("cannot open /home/jean dupont/.config/com.simpl.resultat/profile_0a1b2c3d.db");
|
||||
const sent = getRecentErrorLogs(20);
|
||||
expect(sent).toContain("ERROR: cannot open <profile folder>/profile_0a1b2c3d.db");
|
||||
expect(sent).not.toMatch(/jean|dupont/);
|
||||
});
|
||||
|
||||
it("never throws out of a console call", () => {
|
||||
// A lone parenthesis in a folder name, and an argument that cannot be printed.
|
||||
setKnownFolders({ home: "C:\\Users\\Jean (Work" });
|
||||
const unprintable = {
|
||||
toJSON() {
|
||||
throw new Error("no JSON");
|
||||
},
|
||||
toString() {
|
||||
throw new Error("no text");
|
||||
},
|
||||
};
|
||||
expect(() => console.error("C:\\Users\\Jean (Work\\x.db", unprintable)).not.toThrow();
|
||||
expect(lastEntry().message).toBe("~\\x.db [unprintable]");
|
||||
});
|
||||
});
|
||||
|
||||
describe("replayLogEntries (#497)", () => {
|
||||
beforeEach(() => {
|
||||
clearLogs();
|
||||
});
|
||||
afterEach(() => {
|
||||
setKnownFolders({});
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("rewrites an entry written before the folders, in memory and in sessionStorage", () => {
|
||||
const storage = fakeStorage();
|
||||
vi.stubGlobal("sessionStorage", storage);
|
||||
console.error("cannot open /home/jean dupont/.config/com.simpl.resultat/profile_0a1b2c3d.db");
|
||||
// Written before the folders were known: kept as it was, for now.
|
||||
expect(storage.getItem(STORAGE_KEY)).toContain("jean dupont");
|
||||
const before = getLogs();
|
||||
const listener = vi.fn();
|
||||
const unsubscribe = subscribe(listener);
|
||||
|
||||
setKnownFolders(LINUX);
|
||||
replayLogEntries();
|
||||
unsubscribe();
|
||||
|
||||
expect(lastEntry().message).toBe("cannot open <profile folder>/profile_0a1b2c3d.db");
|
||||
expect(getLogs()).not.toBe(before);
|
||||
expect(before[before.length - 1].message).toContain("jean dupont");
|
||||
const stored: Array<{ message: string }> = JSON.parse(storage.getItem(STORAGE_KEY) ?? "[]");
|
||||
expect(stored.map((entry) => entry.message)).toEqual(["cannot open <profile folder>/profile_0a1b2c3d.db"]);
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps the snapshot and notifies nobody when no entry changes", () => {
|
||||
console.warn("nothing to replace");
|
||||
const before = getLogs();
|
||||
const listener = vi.fn();
|
||||
const unsubscribe = subscribe(listener);
|
||||
|
||||
setKnownFolders(LINUX);
|
||||
replayLogEntries();
|
||||
unsubscribe();
|
||||
|
||||
expect(getLogs()).toBe(before);
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rewrites the entries read back from sessionStorage at startup", async () => {
|
||||
// A fresh module, as at a reload of the window: initLogCapture() reads
|
||||
// back what the previous page wrote.
|
||||
vi.resetModules();
|
||||
const storage = fakeStorage({
|
||||
[STORAGE_KEY]: JSON.stringify([
|
||||
{
|
||||
timestamp: 1,
|
||||
level: "error",
|
||||
message:
|
||||
"cannot open C:\\Users\\Jean Dupont\\AppData\\Roaming\\com.simpl.resultat\\profile_0a1b2c3d.db",
|
||||
},
|
||||
null,
|
||||
]),
|
||||
});
|
||||
vi.stubGlobal("sessionStorage", storage);
|
||||
const saved = { log: console.log, warn: console.warn, error: console.error };
|
||||
try {
|
||||
const log = await import("./logService");
|
||||
const folders = await import("./logFolders");
|
||||
log.initLogCapture();
|
||||
expect(log.getLogs()[0].message).toContain("Jean Dupont");
|
||||
|
||||
folders.setKnownFolders({
|
||||
home: "C:\\Users\\Jean Dupont",
|
||||
profileFolder: "C:\\Users\\Jean Dupont\\AppData\\Roaming\\com.simpl.resultat",
|
||||
});
|
||||
log.replayLogEntries();
|
||||
|
||||
expect(log.getLogs()[0].message).toBe("cannot open <profile folder>\\profile_0a1b2c3d.db");
|
||||
expect(storage.getItem(STORAGE_KEY)).not.toMatch(/Jean|Dupont/);
|
||||
} finally {
|
||||
Object.assign(console, saved);
|
||||
}
|
||||
});
|
||||
|
||||
it("cleans a line written before folders that arrive past the delay, wired as in main.tsx", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.resetModules();
|
||||
const saved = { log: console.log, warn: console.warn, error: console.error };
|
||||
try {
|
||||
const log = await import("./logService");
|
||||
const folders = await import("./logFolders");
|
||||
const path = await import("@tauri-apps/api/path");
|
||||
vi.mocked(path.homeDir).mockReset();
|
||||
vi.mocked(path.appConfigDir).mockReset();
|
||||
vi.mocked(path.homeDir).mockImplementation(
|
||||
() => new Promise((done) => setTimeout(() => done("/home/jean dupont"), KNOWN_FOLDERS_DELAY_MS + 1_000))
|
||||
);
|
||||
vi.mocked(path.appConfigDir).mockRejectedValue(new Error("no config"));
|
||||
log.initLogCapture();
|
||||
void folders.initKnownFolders().then(log.replayLogEntries);
|
||||
console.error("cannot open /home/jean dupont/Documents/x.db");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(KNOWN_FOLDERS_DELAY_MS);
|
||||
await folders.knownFoldersReady();
|
||||
expect(log.getLogs()[log.getLogs().length - 1].message).toContain("jean dupont");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
expect(log.getLogs()[log.getLogs().length - 1].message).toBe("cannot open ~/Documents/x.db");
|
||||
} finally {
|
||||
Object.assign(console, saved);
|
||||
}
|
||||
});
|
||||
|
||||
it("is wired in main.tsx, right after the capture starts", () => {
|
||||
const source = readFileSync(resolve(import.meta.dirname, "../main.tsx"), "utf8");
|
||||
const capture = source.indexOf("initLogCapture();");
|
||||
const replay = source.indexOf("void initKnownFolders().then(replayLogEntries);");
|
||||
expect(capture).toBeGreaterThan(-1);
|
||||
expect(replay).toBeGreaterThan(capture);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import { replaceKnownFolders } from "./logFolders";
|
||||
|
||||
export type LogLevel = "info" | "warn" | "error";
|
||||
|
||||
export interface LogEntry {
|
||||
|
|
@ -48,17 +50,26 @@ function saveToStorage() {
|
|||
}
|
||||
}
|
||||
|
||||
/** One argument as text: a string as is, anything else as JSON, else `String()`. Never throws. */
|
||||
function argText(a: unknown): string {
|
||||
if (typeof a === "string") return a;
|
||||
try {
|
||||
return JSON.stringify(a);
|
||||
} catch {
|
||||
try {
|
||||
return String(a);
|
||||
} catch {
|
||||
return "[unprintable]";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Called by every captured console.* (logInfo, logWarn and logError go through
|
||||
// them): it must never throw, or the caller's console call would.
|
||||
function addEntry(level: LogLevel, args: unknown[]) {
|
||||
const message = args
|
||||
.map((a) => {
|
||||
if (typeof a === "string") return a;
|
||||
try {
|
||||
return JSON.stringify(a);
|
||||
} catch {
|
||||
return String(a);
|
||||
}
|
||||
})
|
||||
.join(" ");
|
||||
// The home and profile folders, replaced exactly in every entry whatever
|
||||
// its channel (#497). replaceKnownFolders never throws.
|
||||
const message = replaceKnownFolders(args.map(argText).join(" "));
|
||||
|
||||
logs.push({ timestamp: Date.now(), level, message });
|
||||
if (logs.length > MAX_ENTRIES) {
|
||||
|
|
@ -122,6 +133,32 @@ export function clearLogs() {
|
|||
listeners.forEach((fn) => fn());
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite the entries already written, those read back from sessionStorage
|
||||
* included, with the known folders (#497): main.tsx calls it once
|
||||
* `initKnownFolders()` resolves, even past its delay, so a line written before
|
||||
* the folders arrived loses them too. A line that db.ts already passed through
|
||||
* `withoutFolders` keeps what the heuristic left (ADR 0021, section 7).
|
||||
*/
|
||||
export function replayLogEntries(): void {
|
||||
let changed = false;
|
||||
for (let i = 0; i < logs.length; i++) {
|
||||
const entry = logs[i];
|
||||
// An entry read back from a corrupted sessionStorage may be anything.
|
||||
if (!entry || typeof entry.message !== "string") continue;
|
||||
const message = replaceKnownFolders(entry.message);
|
||||
if (message !== entry.message) {
|
||||
// A new object: the previous snapshot keeps its entries as they were.
|
||||
logs[i] = { ...entry, message };
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) return;
|
||||
refreshSnapshot();
|
||||
saveToStorage();
|
||||
listeners.forEach((fn) => fn());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// App logging API. Prefer these over raw `console.*` in application code so
|
||||
// meaningful events land in the in-app log console (Settings → Systems →
|
||||
|
|
|
|||
|
|
@ -22,10 +22,12 @@ function deferred() {
|
|||
function setup(connect: () => Promise<void>) {
|
||||
const setDbReady = vi.fn();
|
||||
const setStartupError = vi.fn();
|
||||
const logError = vi.fn();
|
||||
const cleanup = startProfileConnection({
|
||||
connect,
|
||||
setDbReady,
|
||||
setStartupError,
|
||||
logError,
|
||||
timeoutMessage: "startup timeout",
|
||||
});
|
||||
// The state React would hold: the last value each setter received.
|
||||
|
|
@ -34,6 +36,7 @@ function setup(connect: () => Promise<void>) {
|
|||
cleanup,
|
||||
setDbReady,
|
||||
setStartupError,
|
||||
logError,
|
||||
error: () => last(setStartupError),
|
||||
ready: () => last(setDbReady),
|
||||
};
|
||||
|
|
@ -101,6 +104,22 @@ describe("startProfileConnection", () => {
|
|||
expect(s.error()).toBe("no database");
|
||||
});
|
||||
|
||||
it("writes each failed attempt through the logError it is given, never console.error (#497)", async () => {
|
||||
const failure = new Error("no database");
|
||||
const s = setup(async () => {
|
||||
throw failure;
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(RETRY_DELAY_MS * MAX_RETRIES);
|
||||
|
||||
expect(s.logError.mock.calls).toEqual([
|
||||
["Failed to connect profile (attempt 1/3):", failure],
|
||||
["Failed to connect profile (attempt 2/3):", failure],
|
||||
["Failed to connect profile (attempt 3/3):", failure],
|
||||
]);
|
||||
expect(console.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does nothing more once cleaned up", async () => {
|
||||
const opening = deferred();
|
||||
const s = setup(() => opening.promise);
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@ export interface StartupConnection {
|
|||
connect: () => Promise<void>;
|
||||
setDbReady: (ready: boolean) => void;
|
||||
setStartupError: (error: string | null) => void;
|
||||
/** Writes a failed attempt to the Journal: `logError` of logService, passed by App.tsx (#497). */
|
||||
logError: (...args: unknown[]) => void;
|
||||
/** Shown when the opening outlasts `STARTUP_TIMEOUT_MS`. */
|
||||
timeoutMessage: string;
|
||||
}
|
||||
|
|
@ -26,6 +28,7 @@ export function startProfileConnection({
|
|||
connect,
|
||||
setDbReady,
|
||||
setStartupError,
|
||||
logError,
|
||||
timeoutMessage,
|
||||
}: StartupConnection): () => void {
|
||||
let cancelled = false;
|
||||
|
|
@ -46,7 +49,7 @@ export function startProfileConnection({
|
|||
setDbReady(true);
|
||||
} catch (err) {
|
||||
if (cancelled) return;
|
||||
console.error(`Failed to connect profile (attempt ${attempt}/${MAX_RETRIES}):`, err);
|
||||
logError(`Failed to connect profile (attempt ${attempt}/${MAX_RETRIES}):`, err);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
|
||||
if (!cancelled) return attemptConnect(attempt + 1);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue