scaling-swarms / backend /src /utils.ts
tfrere's picture
tfrere HF Staff
Cursor
feat(collab)!: migrate to Hocuspocus v4 and harden persistence
3557a6a
Raw History Blame Contribute Delete
1.27 kB
import { writeFileSync, renameSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const DEFAULT_DATA_DIR = join(__dirname, "..", "data");
let _dataDir: string | undefined;
/** Override DATA_DIR for testing. Pass undefined to reset to default. */
export function setDataDir(dir: string | undefined) {
_dataDir = dir;
}
export function getDataDir(): string {
return _dataDir ?? process.env.DATA_DIR ?? DEFAULT_DATA_DIR;
}
/** @deprecated Use getDataDir() instead */
export const DATA_DIR = DEFAULT_DATA_DIR;
export function sanitizeName(name: string): string {
return name.replace(/[^a-zA-Z0-9_-]/g, "_");
}
export function docPath(name: string): string {
return join(getDataDir(), `${sanitizeName(name)}.yjs`);
}
/**
* Write-to-temp + rename so a crash mid-write can never leave a
* truncated file at `path`. A corrupt `.yjs` snapshot is a data-loss
* vector: on reboot it would fail to load (or worse, load partially)
* and the recovery path could end up overwriting the good cloud copy.
*/
export function atomicWriteFileSync(path: string, data: Buffer): void {
const tmp = `${path}.tmp`;
writeFileSync(tmp, data);
renameSync(tmp, path);
}