fix: dockview, sprite, auth, and CLI db backup improvements (#1075)
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { backupProductionDb, isProductionDb } from "./backup";
|
||||
|
||||
describe("isProductionDb", () => {
|
||||
it("returns false for dev-isolated paths under .kandev-dev", () => {
|
||||
expect(isProductionDb("/repo/.kandev-dev/data/kandev.db")).toBe(false);
|
||||
expect(isProductionDb("/.kandev-dev/kandev.db")).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true for production and custom paths", () => {
|
||||
expect(isProductionDb("/home/user/.kandev/data/kandev.db")).toBe(true);
|
||||
expect(isProductionDb("/tmp/custom.db")).toBe(true);
|
||||
expect(isProductionDb("/data/kandev.db")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("backupProductionDb", () => {
|
||||
let tmpDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "kandev-backup-test-"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("returns null when the db does not exist", () => {
|
||||
const result = backupProductionDb(path.join(tmpDir, "missing.db"));
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("creates a backup and keeps only the 5 newest", () => {
|
||||
const dbPath = path.join(tmpDir, ".kandev", "data", "kandev.db");
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
fs.writeFileSync(dbPath, "original-db-content");
|
||||
|
||||
// Create 6 backups with explicit per-iteration timestamps so both the
|
||||
// filename clock and mtime advance deterministically - no spin loop, no
|
||||
// dependence on Date.now() resolution.
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const stamp = new Date(1_700_000_000_000 + i * 1000);
|
||||
const result = backupProductionDb(dbPath, tmpDir, stamp);
|
||||
expect(result).not.toBeNull();
|
||||
}
|
||||
|
||||
const backupDir = path.join(tmpDir, ".kandev", "data", "backups");
|
||||
const files = fs
|
||||
.readdirSync(backupDir)
|
||||
.filter((f) => f.startsWith("dev-prod-db-") && f.endsWith(".db"))
|
||||
.sort();
|
||||
|
||||
expect(files.length).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
// Prefix for dev-prod-db automatic snapshots. Distinct from the backend's
|
||||
// "kandev-*" auto-snapshots and "manual-*" user snapshots so the families
|
||||
// don't interfere with each other's retention policies.
|
||||
const BACKUP_PREFIX = "dev-prod-db-";
|
||||
const BACKUP_SUFFIX = ".db";
|
||||
const MAX_BACKUPS = 5;
|
||||
|
||||
/**
|
||||
* Returns true if the given dbPath points to a non-dev database that should
|
||||
* be backed up before running dev mode. Dev-isolated databases live under
|
||||
* <repo>/.kandev-dev/ and are considered disposable.
|
||||
*/
|
||||
export function isProductionDb(dbPath: string): boolean {
|
||||
const normalized = path.normalize(dbPath);
|
||||
const segments = normalized.split(path.sep).filter(Boolean);
|
||||
return !segments.includes(".kandev-dev");
|
||||
}
|
||||
|
||||
/**
|
||||
* Backs up the database at dbPath to <data-dir>/backups/ before dev mode
|
||||
* runs against it. Keeps only the newest MAX_BACKUPS snapshots.
|
||||
*
|
||||
* Returns the path of the created backup, or null if the DB didn't exist
|
||||
* or no backup was needed.
|
||||
*
|
||||
* The optional `homeDir` parameter is exposed for tests so they can redirect
|
||||
* the backup location without mocking os.homedir(). The optional `now`
|
||||
* parameter lets tests pass an explicit timestamp so back-to-back calls in
|
||||
* the same millisecond produce distinct filenames + mtimes without sleeping.
|
||||
*/
|
||||
export function backupProductionDb(dbPath: string, homeDir?: string, now?: Date): string | null {
|
||||
if (!fs.existsSync(dbPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const root = homeDir ?? os.homedir();
|
||||
// Backups are always placed under ~/.kandev/data/backups/ (or the
|
||||
// caller-supplied homeDir in tests), even when dbPath points elsewhere.
|
||||
// This matches the dev-prod-db default flow; custom KANDEV_DATABASE_PATH
|
||||
// values are advanced usage where the user is responsible for backup location.
|
||||
const dataDir = path.join(root, ".kandev", "data");
|
||||
const backupDir = path.join(dataDir, "backups");
|
||||
fs.mkdirSync(backupDir, { recursive: true });
|
||||
|
||||
const stamp = now ?? new Date();
|
||||
const ts = stamp.toISOString().replace(/[:.]/g, "");
|
||||
const name = `${BACKUP_PREFIX}${ts}${BACKUP_SUFFIX}`;
|
||||
const dest = path.join(backupDir, name);
|
||||
|
||||
fs.copyFileSync(dbPath, dest);
|
||||
// Stamp both atime + mtime so pruning (which sorts by mtime) is deterministic.
|
||||
fs.utimesSync(dest, stamp, stamp);
|
||||
|
||||
pruneBackups(backupDir, MAX_BACKUPS);
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps only the `keep` newest dev-prod-db backup files in `dir`, deleting
|
||||
* older ones. Non-matching files are left untouched.
|
||||
*/
|
||||
function pruneBackups(dir: string, keep: number): void {
|
||||
let entries: fs.Dirent[];
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const files = entries
|
||||
.filter((e) => e.isFile() && e.name.startsWith(BACKUP_PREFIX) && e.name.endsWith(BACKUP_SUFFIX))
|
||||
.map((e) => {
|
||||
const fullPath = path.join(dir, e.name);
|
||||
try {
|
||||
const stat = fs.statSync(fullPath);
|
||||
return { path: fullPath, mtime: stat.mtime };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter((f): f is { path: string; mtime: Date } => f !== null);
|
||||
|
||||
if (files.length <= keep) {
|
||||
return;
|
||||
}
|
||||
|
||||
files.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
||||
|
||||
for (const f of files.slice(keep)) {
|
||||
try {
|
||||
fs.unlinkSync(f.path);
|
||||
} catch {
|
||||
// Non-critical: don't fail the launch if one old backup can't be removed.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { backupProductionDb, isProductionDb } from "./backup";
|
||||
import { devKandevHome, HEALTH_TIMEOUT_MS_DEV } from "./constants";
|
||||
import { resolveHealthTimeoutMs, waitForHealth, waitForUrlReady } from "./health";
|
||||
import { isInsideKandevTask } from "./kandev-env";
|
||||
@@ -24,6 +25,23 @@ export type DevOptions = {
|
||||
export async function runDev({ repoRoot, backendPort, webPort }: DevOptions): Promise<void> {
|
||||
const ports = await pickPorts(backendPort, webPort);
|
||||
const { dbPath, extra } = resolveDevBackendEnv(repoRoot);
|
||||
|
||||
if (isProductionDb(dbPath)) {
|
||||
try {
|
||||
const backupPath = backupProductionDb(dbPath);
|
||||
if (backupPath) {
|
||||
const name = path.basename(backupPath);
|
||||
console.log(`[kandev] backed up production db → ${name}`);
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
// Abort rather than continue: the backup exists precisely to protect the
|
||||
// production db before dev mode touches it. Proceeding on failure would
|
||||
// remove the safety guarantee that justified introducing this guard.
|
||||
throw new Error(`failed to back up production db (${message}); aborting dev startup`);
|
||||
}
|
||||
}
|
||||
|
||||
const backendEnv = buildBackendEnv({ ports, extra });
|
||||
const webEnv = buildWebEnv({ ports, debug: true });
|
||||
const logLevel =
|
||||
|
||||
@@ -137,6 +137,15 @@ describe("resolveRuntime", () => {
|
||||
|
||||
describe("no runtime found", () => {
|
||||
it("throws an actionable error message mentioning install paths", () => {
|
||||
// Ensure require.resolve fails so we reach the "no runtime found" path.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const ModuleAny = Module as unknown as { _resolveFilename: any };
|
||||
vi.spyOn(ModuleAny, "_resolveFilename").mockImplementationOnce(() => {
|
||||
const err = new Error("Cannot find module") as Error & { code: string };
|
||||
err.code = "MODULE_NOT_FOUND";
|
||||
throw err;
|
||||
});
|
||||
|
||||
let error: Error | null = null;
|
||||
try {
|
||||
resolveRuntime();
|
||||
|
||||
Reference in New Issue
Block a user