Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

noCopyOnWrite.ts

36 lines1.6 KB

1// @effect-diagnostics nodeBuiltinImport:off
2// The service launcher shares this and runs without an Effect runtime.
3import * as NodeChildProcess from "node:child_process";
4import * as NodeFSP from "node:fs/promises";
5​
6const BTRFS_SUPER_MAGIC = 0x9123683e;
7​
8async function onBtrfs(target: string): Promise<boolean> {
9 // oxlint-disable-next-line t3code/no-global-process-runtime -- Shared with the standalone launcher.
10 if (process.platform !== "linux") return false;
11 const stats = await NodeFSP.statfs(target).catch(() => undefined);
12 return stats?.type === BTRFS_SUPER_MAGIC;
14​
15const run = (command: string, args: ReadonlyArray<string>) =>
16 new Promise<string | undefined>((resolve) => {
17 NodeChildProcess.execFile(command, args, (error, stdout) =>
18 resolve(error === null ? stdout : undefined),
19 );
20 });
21​
22/**
23 * SQLite rewrites pages in place, which fragments copy-on-write files on btrfs. Files created
24 * in a No_COW directory inherit the flag, as systemd-journald does for its journals. Node has no
25 * ioctl, so this runs chattr. Btrfs refuses reflinks between No_COW and copy-on-write files.
26 */
27export async function markNoCopyOnWrite(directory: string): Promise<void> {
28 if (await onBtrfs(directory)) await run("chattr", ["+C", directory]);
30​
31export async function isNoCopyOnWrite(file: string): Promise<boolean> {
32 if (!(await onBtrfs(file))) return false;
33 // lsattr skips symlinks; its first field is the flag string, e.g. "---------------C------".
34 const output = await run("lsattr", ["-d", await NodeFSP.realpath(file).catch(() => file)]);
35 return output?.trimStart().split(/\s/, 1)[0]?.includes("C") ?? false;