Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/local-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,6 @@ jobs:
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$(id -u)/bus"
notify-send -u critical "local-ci FAILED: metaobjects" \
notify-send -u normal "local-ci FAILED: metaobjects" \
"$(printf '%s' "$HEAD_MSG" | head -n1)
$RUN_URL" || echo "notify-send unavailable; GitHub email still fires"
4 changes: 4 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ The Stryker mutation gate (`bun run conformance:mutation` in
`$DEV_SCRATCH` when that is set, else the system temp directory, and removes it on exit. Point
`DEV_SCRATCH` at a RAM-backed directory to keep that scratch off disk.

In `server/typescript/packages/codegen-ts`, a new test that needs a temp directory uses `makeScratchDir`
and `removeTree` (`src/scratch-dir.ts`), not `mkdtempSync` and `rmSync(..., { recursive: true })`:
Bun's recursive `rmSync` can fail with `EFAULT` under parallel test load and fail the test.

### Local CI (the checks GitHub runs — run it before opening a PR)

GitHub Actions is enabled on this repository. The check workflows in
Expand Down
10 changes: 5 additions & 5 deletions server/typescript/packages/codegen-ts/src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { join, relative, resolve, isAbsolute, dirname, sep } from "node:path";
import { warnMissingPromptGenerators } from "./prompt-generator-gate.js";
import { runEmitsEntityModule, runEmitsHonoRoutes, runEmitsQueries, runEmitsRestRoutes, runEmitsUiTier, runRoutesExpose, warnUnmarkedRoutesGenerators, warnUnmarkedUiGenerators } from "./ui-tier-gate.js";
import { warnRetiredCodegenAttrs } from "./retired-codegen-attrs.js";
import { tmpdir } from "node:os";
import { removeTree, scratchRoot } from "./scratch-dir.js";
import { randomUUID } from "node:crypto";
import { fileURLToPath } from "node:url";
import { existsSync, readFileSync, rmSync } from "node:fs";
import { existsSync, readFileSync } from "node:fs";
import type { MetaData, MetaObject } from "@metaobjectsdev/metadata";
import {
isMetaRoot, FIELD_SUBTYPE_TIMESTAMP, FIELD_ATTR_FILTERABLE,
Expand Down Expand Up @@ -382,7 +382,7 @@ export async function runGen(opts: RunGenOpts): Promise<RunGenResult> {
: resolve(projectRoot ?? process.cwd(), opts.genStateDir))
: (projectRoot !== undefined
? join(projectRoot, ".metaobjects", ".gen-state")
: join(tmpdir(), `meta-gen-state-${process.pid}`));
: join(scratchRoot(), `meta-gen-state-${process.pid}`));
// A file written OUTSIDE the project has no place in the project's gen-state: its
// manifest key would be `../..`-relative, committed into the hash manifest, and its snapshot
// body — stored at `<gen-state>/<key>` — would walk out of `.gen-state/` and land a second
Expand All @@ -391,7 +391,7 @@ export async function runGen(opts: RunGenOpts): Promise<RunGenResult> {
// Unique to THIS run, not just this process: a second runGen in one process (an embedder,
// a watch loop, a test) would otherwise find the first run's snapshot and three-way merge,
// which is exactly the record-keeping an untracked file does not have.
const untrackedGenStateDir = join(tmpdir(), `meta-gen-untracked-${process.pid}-${randomUUID()}`);
const untrackedGenStateDir = join(scratchRoot(), `meta-gen-untracked-${process.pid}-${randomUUID()}`);
const untrackedOutDirs = opts.untrackedOutDirs ?? [];
const outsideProject = (fullPath: string): boolean => {
if (projectRoot === undefined) return false;
Expand All @@ -418,7 +418,7 @@ export async function runGen(opts: RunGenOpts): Promise<RunGenResult> {
};
const noteUntracked = (): void => {
// The per-run state held nothing anyone reads again; do not leave it in the tmpdir.
rmSync(untrackedGenStateDir, { recursive: true, force: true });
removeTree(untrackedGenStateDir);
if (untrackedCount === 0) return;
warnings.push(
`${untrackedCount} generated file(s) were written outside the project root and are not ` +
Expand Down
49 changes: 49 additions & 0 deletions server/typescript/packages/codegen-ts/src/scratch-dir.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Throwaway directories: where they live and how they are removed.
//
// Bun's `rmSync(dir, { recursive: true })` has been seen failing with
// `EFAULT: bad address in system call argument` while other tests in the same process
// were also touching the filesystem (observed on Bun 1.3.x; local Bun 1.3.14). The failure
// is in the remover, not in the directory, so removal never calls it: it always walks the
// tree with readdir/unlink/rmdir. A path that is already gone is success, never an error:
// another remover may have beaten us to it.
import { mkdtempSync, readdirSync, rmdirSync, unlinkSync, lstatSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

/** `$DEV_SCRATCH` (RAM-backed) when set and non-empty, else the OS temp directory. */
export function scratchRoot(): string {
const scratch = process.env.DEV_SCRATCH;
return scratch !== undefined && scratch !== "" ? scratch : tmpdir();
}

/** A fresh, uniquely named directory under {@link scratchRoot}. */
export function makeScratchDir(prefix: string): string {
return mkdtempSync(join(scratchRoot(), prefix));
}

const isGone = (e: unknown): boolean => (e as NodeJS.ErrnoException).code === "ENOENT";

function walkRemove(path: string): void {
let isDir: boolean;
try {
isDir = lstatSync(path).isDirectory();
} catch (e) {
if (isGone(e)) return;
throw e;
}
try {
if (!isDir) {
unlinkSync(path);
return;
}
for (const name of readdirSync(path)) walkRemove(join(path, name));
rmdirSync(path);
} catch (e) {
if (!isGone(e)) throw e;
}
}

/** Remove a directory tree, tolerating it being absent. Never uses Bun's recursive `rmSync`. */
export function removeTree(path: string): void {
walkRemove(path);
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
// barrel exports to name a file the run actually wrote.

import { describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, readdirSync, statSync, readFileSync } from "node:fs";
import { readdirSync, statSync, readFileSync } from "node:fs";
import { makeScratchDir, removeTree } from "../src/scratch-dir.js";
import { join, relative } from "node:path";
import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata";

Expand Down Expand Up @@ -78,7 +79,7 @@ async function emit(model: unknown, outputLayout: "flat" | "package"): Promise<s
]);
expect(errors.map((e) => e.message)).toEqual([]);

const dir = mkdtempSync(join(import.meta.dir, "tmp-pkg-layout-"));
const dir = makeScratchDir("tmp-pkg-layout-");
try {
await runGen({
config: defineConfig({
Expand All @@ -102,7 +103,7 @@ async function emit(model: unknown, outputLayout: "flat" | "package"): Promise<s
walk(dir);
return out.sort();
} finally {
rmSync(dir, { recursive: true, force: true });
removeTree(dir);
}
}

Expand All @@ -119,7 +120,7 @@ async function emitWithBarrel(
]);
expect(errors.map((e) => e.message)).toEqual([]);

const dir = mkdtempSync(join(import.meta.dir, "tmp-pkg-barrel-"));
const dir = makeScratchDir("tmp-pkg-barrel-");
try {
await runGen({
config: defineConfig({
Expand All @@ -145,7 +146,7 @@ async function emitWithBarrel(
const specifiers = [...index.matchAll(/from\s+"([^"]+)"/g)].map((m) => m[1]!);
return { specifiers, files: files.sort() };
} finally {
rmSync(dir, { recursive: true, force: true });
removeTree(dir);
}
}

Expand Down Expand Up @@ -237,7 +238,7 @@ describe("every relative import resolves in package layout, shared enums include
new InMemoryStringSource(JSON.stringify(ENUM_MODEL), { id: "meta.json" }),
]);
expect(errors.map((e) => e.message)).toEqual([]);
const dir = mkdtempSync(join(import.meta.dir, "tmp-pkg-enum-"));
const dir = makeScratchDir("tmp-pkg-enum-");
try {
await runGen({
config: defineConfig({
Expand Down Expand Up @@ -277,7 +278,7 @@ describe("every relative import resolves in package layout, shared enums include
expect(enumImports).toBeGreaterThan(0);
expect(unresolved).toEqual([]);
} finally {
rmSync(dir, { recursive: true, force: true });
removeTree(dir);
}
});
});
10 changes: 5 additions & 5 deletions server/typescript/packages/codegen-ts/test/run-gen.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, test, expect, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, rmSync, readFileSync, existsSync, readdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { readFileSync, existsSync, readdirSync, writeFileSync } from "node:fs";
import { makeScratchDir, removeTree } from "../src/scratch-dir.js";
import { join, resolve } from "node:path";
import type { MetaRoot, MetaObject } from "@metaobjectsdev/metadata";
import {
Expand All @@ -24,8 +24,8 @@ import { MetaDataLoader } from "@metaobjectsdev/metadata";
import { FileSource } from "@metaobjectsdev/metadata/core";

let tmp: string;
beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-run-gen-")); });
afterEach(() => { rmSync(tmp, { recursive: true, force: true }); });
beforeEach(() => { tmp = makeScratchDir("codegen-run-gen-"); });
afterEach(() => { removeTree(tmp); });

const FIXTURE_DIR = resolve(import.meta.dir, "fixtures");

Expand Down Expand Up @@ -305,7 +305,7 @@ describe("runGen — entityFilter", () => {
const fullBarrel = readFileSync(join(tmp, "index.ts"), "utf-8");
expect(fullBarrel).toContain('export * from "./Post"');
expect(fullBarrel).toContain('export * from "./User"');
for (const f of readdirSync(tmp)) rmSync(join(tmp, f), { recursive: true, force: true });
for (const f of readdirSync(tmp)) removeTree(join(tmp, f));

const out = await runGen({ config, metadata: result.root, entityFilter: ["Post"] });
expect(out.warnings).toEqual([]);
Expand Down
25 changes: 25 additions & 0 deletions server/typescript/packages/codegen-ts/test/scratch-dir.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, test, expect } from "bun:test";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { makeScratchDir, removeTree, scratchRoot } from "../src/scratch-dir.js";

describe("scratch-dir", () => {
test("makeScratchDir is unique, under the scratch root, and removeTree clears a populated tree", () => {
const a = makeScratchDir("scratch-dir-test-");
const b = makeScratchDir("scratch-dir-test-");
expect(a).not.toBe(b);
expect(a.startsWith(scratchRoot())).toBe(true);
mkdirSync(join(a, "x", "y"), { recursive: true });
writeFileSync(join(a, "x", "y", "f.txt"), "1");
removeTree(a);
removeTree(b);
expect(existsSync(a)).toBe(false);
expect(existsSync(b)).toBe(false);
});

test("removeTree of an absent path is not an error", () => {
const a = makeScratchDir("scratch-dir-test-");
removeTree(a);
expect(() => removeTree(a)).not.toThrow();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
// could not use it. It is now demanded at the point of USE, by the generator that
// needs it, naming that generator.
import { describe, test, expect, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { makeScratchDir, removeTree } from "../src/scratch-dir.js";
import { join } from "node:path";
import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata";
import { runGen } from "../src/runner.js";
Expand All @@ -22,8 +21,8 @@ import { entityFile as referenceEntityFile } from "../src/reference/entity.js";
import type { MetaobjectsGenConfig } from "../src/metaobjects-config.js";

let tmp: string;
beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-vo-only-")); });
afterEach(() => { rmSync(tmp, { recursive: true, force: true }); });
beforeEach(() => { tmp = makeScratchDir("codegen-vo-only-"); });
afterEach(() => { removeTree(tmp); });

async function load(children: unknown[]) {
const json = JSON.stringify({ "metadata.root": { package: "app", children } });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
*/

import { describe, test, expect, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { lstatSync, mkdtempSync, readdirSync, rmdirSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Kysely, sql } from "kysely";
Expand All @@ -44,17 +44,34 @@ function literalColumns<T>(root: T): T {
return root;
}

/** Walks the tree instead of Bun's recursive rmSync, which intermittently throws EFAULT under load. */
function removeTree(path: string): void {
try {
if (!lstatSync(path).isDirectory()) { unlinkSync(path); return; }
for (const n of readdirSync(path)) removeTree(join(path, n));
rmdirSync(path);
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
}
}

let tmpDir: string;
let k: Kysely<Record<string, unknown>>;

beforeEach(() => {
tmpDir = mkdtempSync(join(tmpdir(), "report-views-sqlite-"));
beforeEach(async () => {
// The database file lives in RAM ($DEV_SCRATCH when set): libsql commits every DDL statement
// with an fsync, and the canonical model applies dozens of them per test, so on a disk that is
// ~1.3 s per test setup (14 tests, ~20 s) and past the default timeout when the disk is busy.
tmpDir = mkdtempSync(join(process.env.DEV_SCRATCH || tmpdir(), "report-views-sqlite-"));
k = new Kysely({ dialect: new LibsqlDialect({ url: `file:${join(tmpDir, "test.db")}` }) });
// A throwaway database needs no crash safety, so skip the per-statement fsync even when
// $DEV_SCRATCH is unset and the file lands on a real disk.
await sql.raw("PRAGMA synchronous = OFF").execute(k);
});

afterEach(async () => {
await k.destroy();
rmSync(tmpDir, { recursive: true, force: true });
removeTree(tmpDir);
});

// libsql execute() is single-statement: split on ";" (no view body or seed carries an inner ";").
Expand Down
Loading