Skip to content
Closed
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
15 changes: 10 additions & 5 deletions packages/codegen/__tests__/platform-target.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,24 +144,29 @@ describe("gatePlatformFeatures", () => {
// through the actual registry lookup — the thing `platformMatrixIds`
// reports and `resolveCodegenTarget`/`lunora.json`'s `target` field select.
it("gates a project declaring an unsupported ctx.* for the node target", async () => {
expect.assertions(4);
expect.assertions(5);

const { gatePlatformFeatures } = await import("../src/platform-target");
// `browser` and `container` are rated "unsupported" for node
// (`NODE_CAPABILITIES` — no headless-browser or container binding is
// implemented by `@lunora/platform-node`); `kv` and `scheduler` are
// rated "emulated" (a real, if non-durable, better-sqlite3-backed
// implementation), so they must survive gating unchanged.
// implemented by `@lunora/platform-node`); as of plan 267, `scheduler`
// is ALSO rated "unsupported" — the Node host stores and times jobs but
// never dispatches them, so codegen must gate it off the same as
// `browser`/`container`. `kv` stays rated "emulated" (a real, if
// non-durable, better-sqlite3-backed implementation), so it must
// survive gating unchanged.
const usage: FeatureUsage = { ...ALL_OFF, browser: true, container: true, kv: true, scheduler: true };

const result = gatePlatformFeatures(usage, "node");

expect(result.usage.browser).toBe(false);
expect(result.usage.container).toBe(false);
expect({ kv: result.usage.kv, scheduler: result.usage.scheduler }).toStrictEqual({ kv: true, scheduler: true });
expect(result.usage.scheduler).toBe(false);
expect(result.usage.kv).toBe(true);
expect(result.diagnostics.map((diagnostic) => diagnostic.feature).toSorted((a, b) => String(a).localeCompare(String(b)))).toStrictEqual([
"browser",
"container",
"scheduler",
]);
});
});
Expand Down
9 changes: 9 additions & 0 deletions packages/codegen/src/platform-target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,15 @@ type PlatformFeatureKey = keyof PlatformCapabilities["features"];
* app-level add-on with no platform-portability meaning (feature flags, the
* Cloudflare-Access identity facade, Cloudflare Images, R2 SQL, payments,
* x402) — never gated, always emitted, on every target.
*
* `shardAlarms` is deliberately unmapped here, and not because it was
* forgotten: `CapabilityKey` is derived from `CAPABILITY_ROWS`, which
* enumerates app-imported `ctx.*` add-on modules, and there is no such usage
* key for alarms because they are an engine-internal contract member, never
* something an app imports. There is nothing for this map to gate on. Its
* `PlatformCapabilities` rating still matters for Studio parity reporting and
* any future target-level check — see its `shardAlarms` entry in the Node
* capability matrix (`NODE_CAPABILITIES` in `@lunora/platform`, plan 267).
*/
const CAPABILITY_TO_FEATURE: Partial<Record<CapabilityKey, PlatformFeatureKey>> = {
ai: "ai",
Expand Down
12 changes: 9 additions & 3 deletions packages/do/__tests__/workerd/cloudflare-host.workerd.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import type { ConformanceHost } from "@lunora/platform/conformance";
import { defineHostContractSuite } from "@lunora/platform/conformance/suite";
import { createShardDirectory, createShardPlatform } from "@lunora/platform-cloudflare";
import { env, runInDurableObject } from "cloudflare:test";
import type { TestContext } from "vitest";
import { describe, expect, it } from "vitest";

/**
Expand Down Expand Up @@ -89,19 +90,24 @@ const createCloudflareHost = (): ConformanceHost => {
/**
* `it`, but the body runs inside a fresh Durable Object. Each test gets its own
* object so SQL tables, sockets, and alarms from one never bleed into the next.
*
* The real vitest `TestContext` is forwarded into `body` (plan 268, W2): the
* suite's dynamic-skip legs call `context.skip()`, which only works against
* the context the runner itself created for this test — a context this
* wrapper invented would not be wired to anything the runner recognizes.
*/
const itInDurableObject = ((name: string, body: () => Promise<void> | void) => {
const itInDurableObject = ((name: string, body: (context: TestContext) => Promise<void> | void) => {
// The assertions live in the injected suite's bodies, not here — this
// wrapper only supplies the Durable Object context they run in.
// eslint-disable-next-line vitest/expect-expect, vitest/require-top-level-describe, vitest/prefer-expect-assertions, sonarjs/assertions-in-tests -- generic test-runner adapter; `defineHostContractSuite` owns the describe blocks and the assertions
it(name, async () => {
it(name, async (context) => {
const stub = env.SHARD.get(env.SHARD.newUniqueId());

await runInDurableObject(stub, async (_instance, state) => {
currentState = state;

try {
await body();
await body(context);
} finally {
currentState = undefined;
liveSockets = [];
Expand Down
55 changes: 55 additions & 0 deletions packages/platform-node/__tests__/lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,5 +197,60 @@ describe("lifecycle disposers", () => {

expect(readdirSync(workdir)).toContain("platform.sqlite3");
});

it("makes schedule() throw instead of arming a fresh, never-cleared timer", async () => {
expect.assertions(2);

vi.useFakeTimers();

try {
const platform = createNodePlatform();

platform.close();

await expect(platform.scheduler.schedule("some/fn", {}, { delayMs: 5000 })).rejects.toThrow("platform closed");
expect(vi.getTimerCount()).toBe(0);
} finally {
vi.useRealTimers();
}
});

it("reports no pending jobs and refuses to cancel a pre-close job once closed", async () => {
expect.assertions(2);

vi.useFakeTimers();

try {
const platform = createNodePlatform();

const { id } = await platform.scheduler.schedule("some/fn", {}, { delayMs: 5000 });

platform.close();

// `list` is optional on the contract (a host may omit it); this
// host always implements it — see `createNodeSchedulerHost`.
await expect(platform.scheduler.list?.()).resolves.toStrictEqual([]);
await expect(platform.scheduler.cancel(id)).resolves.toBe(false);
} finally {
vi.useRealTimers();
}
});

it("makes alarms.set() throw before mutating state, leaving get() reporting no alarm", async () => {
expect.assertions(2);

vi.useFakeTimers();

try {
const platform = createNodePlatform();

platform.close();

expect(() => platform.shard.alarms.set(Date.now() + 1000)).toThrow("platform closed");
expect(platform.shard.alarms.get()).toBeNull();
} finally {
vi.useRealTimers();
}
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { describe, expect, it } from "vitest";

import { createNodeShardHost } from "../src/node-shard-host";

/**
* Plan 267 §4/§5 (S4): `transaction` runs raw `BEGIN`/`COMMIT`/`ROLLBACK`
* against a single shared connection. Two overlapping `transaction()` calls
* used to race that connection directly — the second `BEGIN` while the first
* was still open either threw `cannot start a transaction within a
* transaction` or, worse, silently interleaved commits/rollbacks. This pins
* the fix: a dedicated `transactionTail` serialization lane, distinct from
* `runSerialized`'s own tail (routing through the same one would deadlock the
* engine's `runSerialized(() => transaction(work))` composition).
*/
describe("createNodeShardHost transaction concurrency", () => {
const sleep = (ms: number): Promise<void> =>
new Promise((resolve) => {
setTimeout(resolve, ms);
});

it("serializes two overlapping bare transaction() calls instead of corrupting each other's commits", async () => {
expect.assertions(1);

const { dispose, host } = createNodeShardHost();

try {
host.sql.exec("CREATE TABLE rows_ (id TEXT PRIMARY KEY)");

const first = host.transaction(async () => {
host.sql.exec("INSERT INTO rows_ (id) VALUES ('A')");

await sleep(20);

host.sql.exec("INSERT INTO rows_ (id) VALUES ('B')");
});

// Started without awaiting `first` — this is the overlap that
// corrupts an un-serialized raw BEGIN/COMMIT.
const second = host.transaction(async () => {
host.sql.exec("INSERT INTO rows_ (id) VALUES ('C')");
});

await Promise.all([first, second]);

const rows = host.sql.exec<{ id: string }>("SELECT id FROM rows_ ORDER BY id").toArray();

expect(rows.map((row) => row.id)).toStrictEqual(["A", "B", "C"]);
} finally {
dispose();
}
});

it("rolls back only the throwing transaction's own writes, leaving earlier committed rows intact", async () => {
expect.assertions(2);

const { dispose, host } = createNodeShardHost();

try {
host.sql.exec("CREATE TABLE rows_ (id TEXT PRIMARY KEY)");

await host.transaction(async () => {
host.sql.exec("INSERT INTO rows_ (id) VALUES ('A')");
});

await expect(
host.transaction(async () => {
host.sql.exec("INSERT INTO rows_ (id) VALUES ('D')");

throw new Error("boom");
}),
).rejects.toThrow("boom");

const rows = host.sql.exec<{ id: string }>("SELECT id FROM rows_ ORDER BY id").toArray();

expect(rows.map((row) => row.id)).toStrictEqual(["A"]);
} finally {
dispose();
}
});
});
3 changes: 1 addition & 2 deletions packages/platform-node/src/conformance/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const createNodeConformanceHost = (): ConformanceHost => {
const kv = createNodeShardKvStore(database);
const directory = createNodeShardDirectory();
const { readFrames, restoreSocket, simulateRecycle, socket } = createNodeSocketHost();
const { dispose: disposeScheduler, scheduler, simulateDeadLetter } = createNodeSchedulerHost();
const { dispose: disposeScheduler, scheduler } = createNodeSchedulerHost();

return {
awaitAlarmFired: async (target) => {
Expand Down Expand Up @@ -57,7 +57,6 @@ export const createNodeConformanceHost = (): ConformanceHost => {
restoreSocket,
scheduler,
shard,
simulateDeadLetter,
simulateRecycle,
socket,
};
Expand Down
12 changes: 12 additions & 0 deletions packages/platform-node/src/node-platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,18 @@ export interface NodePlatform {
* its own — a `NodePlatform` a caller stops using without calling `close()`
* leaks the open file handle (plus its WAL/SHM sidecar files) and keeps
* the process alive on outstanding timers. Safe to call more than once.
*
* **`close()` is a terminal state, not merely a cleanup step.** After it
* runs: `scheduler.schedule()` throws instead of arming a fresh timer
* nothing would ever clear; `scheduler.list()` returns `[]` and
* `scheduler.cancel()` answers `false` (the job map is empty, so this
* happens naturally, without a throw — keeping teardown-order races
* benign); `shard.alarms.set()`/`delete()` throw before mutating any
* in-memory state (checked against the connection's own open/closed state,
* the single source of truth); `shard.alarms.get()` keeps answering
* whatever it last held. A no-op instead of a throw would be
* indistinguishable from a working call — exactly the silent-vanishing
* this lifecycle exists to end.
*/
close: () => void;
/** In-process shard directory (see `createNodeShardDirectory`'s docstring for what it cannot do). */
Expand Down
Loading