Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 .jscpd.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"gitignore": true,
"exitCode": 1,
"minLines": 1,
"minTokens": 23,
"minTokens": 22,
"path": [
"src",
"e2e-payments",
Expand Down
23 changes: 18 additions & 5 deletions e2e-payments/src/flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* confirm the booking is recorded as paid.
*/

import type { Locator } from "playwright";
import type { BrowserSession } from "./browser.ts";
import { config } from "./config.ts";
import { log, step } from "./log.ts";
Expand Down Expand Up @@ -145,11 +146,7 @@ export const submitBooking = async (
const qty = page
.locator('input[name^="quantity"], select[name^="quantity"]')
.first();
if (await qty.count()) {
const tag = await qty.evaluate((el) => el.tagName.toLowerCase());
if (tag === "select") await qty.selectOption("1");
else await qty.fill("1");
}
if (await qty.count()) await setSelectOrInput(qty, "1");

const submit = page
.getByRole("button", { name: /continue|book|pay|checkout|reserve/i })
Expand All @@ -167,6 +164,22 @@ const fillIfPresent = async (
if (await loc.count()) await loc.fill(value);
};

/**
* Set a quantity control that renders as either a `<select>` (small caps) or a
* plain `<input>` (large caps): choose the option on a select, type the value
* into an input. Any Playwright options (force / timeout) apply to whichever
* action runs.
*/
export const setSelectOrInput = async (
control: Locator,
value: string,
options?: { force?: boolean; timeout?: number },
): Promise<void> => {
const tag = await control.evaluate((el) => el.tagName.toLowerCase());
if (tag === "select") await control.selectOption(value, options);
else await control.fill(value, options);
};

/**
* Before filling a hosted checkout, assert the booking actually left the app
* for the provider. If payment-session creation fails server-side the app
Expand Down
32 changes: 14 additions & 18 deletions e2e-payments/src/order-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@

import type { BrowserSession } from "./browser.ts";
import { config } from "./config.ts";
import { createListing, incomeLedgerText, waitForAppReturn } from "./flow.ts";
import {
createListing,
incomeLedgerText,
setSelectOrInput,
waitForAppReturn,
} from "./flow.ts";
import { log, step } from "./log.ts";

/** The one catalog this journey builds and orders. Prices are minor units;
Expand Down Expand Up @@ -138,23 +143,14 @@ const fillBookingPage = async (session: BrowserSession): Promise<void> => {
.selectOption("1", { force: true, timeout: config.actionTimeoutMs });
// A listing's quantity control renders as a <select> for small caps and an
// <input> for large ones — set whichever the row carries.
const setRowQty = async (name: string, value: string): Promise<void> => {
const control = page
.locator(`.ticket-row:has-text("${name}") [name^="quantity_"]`)
.first();
const tag = await control.evaluate((el) => el.tagName.toLowerCase());
if (tag === "select") {
await control.selectOption(value, {
force: true,
timeout: config.actionTimeoutMs,
});
} else {
await control.fill(value, {
force: true,
timeout: config.actionTimeoutMs,
});
}
};
const setRowQty = (name: string, value: string): Promise<void> =>
setSelectOrInput(
page
.locator(`.ticket-row:has-text("${name}") [name^="quantity_"]`)
.first(),
value,
{ force: true, timeout: config.actionTimeoutMs },
);
await setRowQty(MEMBER_A, "1");
await setRowQty(PLAIN, "2");
await session.fill("name", BUYER_NAME);
Expand Down
5 changes: 4 additions & 1 deletion scripts/bench/bunny-crypto-smoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ const KEY = crypto.getRandomValues(new Uint8Array(32));
const SAMPLE = "attendee-pii-value-12345@example.com";
const ITERS = 2000;

/** A fresh random 12-byte AES-GCM nonce. */
const randomIv = (): Uint8Array => crypto.getRandomValues(new Uint8Array(12));

Comment thread
stefan-burke marked this conversation as resolved.
Resolved
/** Run `body` ITERS times and return the elapsed milliseconds. */
const timeLoop = async (body: () => Promise<void> | void): Promise<number> => {
const t0 = performance.now();
Expand Down Expand Up @@ -62,7 +65,7 @@ const run = async (): Promise<Result> => {

// node:crypto helpers — match WebCrypto layout (tag appended to ciphertext)
const nodeEnc = (pt: Uint8Array) => {
const iv = crypto.getRandomValues(new Uint8Array(12));
const iv = randomIv();
const c = nc.createCipheriv("aes-256-gcm", KEY, iv);
const body = Buffer.concat([c.update(pt), c.final()]);
const ct = new Uint8Array(Buffer.concat([body, c.getAuthTag()]));
Expand Down
4 changes: 2 additions & 2 deletions scripts/bench/cold-start/first-request-child.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
setBuildTimestampForTest,
} from "#shared/update.ts";
import { serveHandler } from "#src/serve-app.ts";
import { serveAndDrainRoot } from "./serve-root.ts";

// Keep stdout clean for the JSON result line the parent parses.
setSuppressDebugLogs(true);
Expand Down Expand Up @@ -131,8 +132,7 @@ setDb(wrapClient(createClient({ url: dbUrl })));

const timedRequest = async (): Promise<{ ms: number; status: number }> => {
requestStart = performance.now();
const response = await serveHandler(new Request("http://localhost/"));
await response.text();
const response = await serveAndDrainRoot(serveHandler);
return { ms: performance.now() - requestStart, status: response.status };
};

Expand Down
4 changes: 2 additions & 2 deletions scripts/bench/cold-start/first-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
*/

import { encodeBase64 } from "jsr:@std/encoding@^1.0.0/base64";
import { serveAndDrainRoot } from "./serve-root.ts";
import { spawnChildJson } from "./spawn-child.ts";

const LATENCIES_MS = [0, 25, 50, 100];
Expand Down Expand Up @@ -52,8 +53,7 @@ const prepareDatabase = async (): Promise<void> => {
// One warm-up request so first-ever housekeeping (prune stamps, backfill
// markers) lands in prep, not in a measured child.
const { serveHandler } = await import("#src/serve-app.ts");
const response = await serveHandler(new Request("http://localhost/"));
await response.text();
const response = await serveAndDrainRoot(serveHandler);
requireHealthyStatus(response.status, "database preparation request");
};

Expand Down
12 changes: 12 additions & 0 deletions scripts/bench/cold-start/serve-root.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/** Serve `GET /` through the production handler and drain the body, returning
* the response. `serve` is passed in so the parent can hand over its
* dynamically imported handler (nothing may read the environment before it sets
* it) while the child hands over its statically imported one. Both the parent's
* warm-up prep and the child's timed requests hit the root request one way. */
export const serveAndDrainRoot = async (
serve: (request: Request) => Promise<Response>,
): Promise<Response> => {
const response = await serve(new Request("http://localhost/"));
await response.text();
return response;
};
9 changes: 5 additions & 4 deletions scripts/bunny-regions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,11 @@ console.log(fmt(config.primary_regions));
console.log("\nReplica regions:");
console.log(fmt(config.replica_regions));

const eu = (r: BunnyRegion) => r.group === "EU";
const euIds = (rs: BunnyRegion[]) =>
rs.filter((r) => r.group === "EU").map((r) => r.id);
console.log("\nEuropean storage zone ids:");
console.log(config.storage_region_available.filter(eu).map((r) => r.id));
console.log(euIds(config.storage_region_available));
console.log("European primary region ids:");
console.log(config.primary_regions.filter(eu).map((r) => r.id));
console.log(euIds(config.primary_regions));
console.log("European replica region ids:");
console.log(config.replica_regions.filter(eu).map((r) => r.id));
console.log(euIds(config.replica_regions));
56 changes: 27 additions & 29 deletions scripts/edge-bundle-lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,22 @@ globalThis.Buffer ??= Buffer;
globalThis.global ??= globalThis;
`;

// Swaps a real module for a generated one at build time: esbuild resolves any
// import matching `filter` into its own private namespace, then loads that
// namespace from the TypeScript source `buildContents` returns.
const inlineGeneratedModule = (
build: Parameters<Plugin["setup"]>[0],
filter: RegExp,
namespace: string,
buildContents: () => string,
): void => {
build.onResolve({ filter }, (args) => ({ namespace, path: args.path }));
build.onLoad({ filter: /.*/, namespace }, () => ({
contents: buildContents(),
loader: "ts",
}));
};

/**
* Plugin to inline static assets and handle Deno-specific imports.
* Replaces Deno.readTextFileSync calls with the pre-read content and the
Expand All @@ -132,40 +148,22 @@ const inlineAssetsPlugin = (
name: "inline-assets",
setup(build) {
// Replace build-info module with actual build metadata
build.onResolve({ filter: /build-info\.ts$/ }, (args) => ({
namespace: "inline-build-info",
path: args.path,
}));
build.onLoad({ filter: /.*/, namespace: "inline-build-info" }, () => ({
contents: buildBuildInfoModule(
buildIso,
Deno.env.get("BUILD_COMMIT") ?? "",
),
loader: "ts",
}));
inlineGeneratedModule(build, /build-info\.ts$/, "inline-build-info", () =>
buildBuildInfoModule(buildIso, Deno.env.get("BUILD_COMMIT") ?? ""),
);

// Replace asset paths module with cache-busted version
build.onResolve({ filter: /asset-paths\.ts$/ }, (args) => ({
namespace: "inline-asset-paths",
path: args.path,
}));
build.onLoad({ filter: /.*/, namespace: "inline-asset-paths" }, () => ({
contents: buildAssetPathsModule(ASSET_DEFS, buildTs, published),
loader: "ts",
}));
inlineGeneratedModule(build, /asset-paths\.ts$/, "inline-asset-paths", () =>
buildAssetPathsModule(ASSET_DEFS, buildTs, published),
);

// Replace the assets module with inlined content
build.onResolve(
{ filter: /(features\/assets\.ts$|#routes\/assets\.ts$)/ },
(args) => ({
namespace: "inline-assets",
path: args.path,
}),
inlineGeneratedModule(
build,
/(features\/assets\.ts$|#routes\/assets\.ts$)/,
"inline-assets",
() => buildAssetsModule(ASSET_DEFS, staticAssets, published),
);
build.onLoad({ filter: /.*/, namespace: "inline-assets" }, () => ({
contents: buildAssetsModule(ASSET_DEFS, staticAssets, published),
loader: "ts",
}));
},
});

Expand Down
19 changes: 13 additions & 6 deletions scripts/mutation/isolation-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,15 @@ export const runsRoot = (root = projectRoot): string =>
export const runRoot = (id: string, root = projectRoot): string =>
join(runsRoot(root), id);

export const workRoot = (id: string, root = projectRoot): string =>
join(runRoot(id, root), MUTATION_WORK_DIR);
/** Path to a named child (dir or file) inside a run's own folder. */
const runChildPath =
(childName: string) =>
(id: string, root = projectRoot): string =>
join(runRoot(id, root), childName);

export const recordPath = (id: string, root = projectRoot): string =>
join(runRoot(id, root), MUTATION_RECORD_FILE);
export const workRoot = runChildPath(MUTATION_WORK_DIR);

export const recordPath = runChildPath(MUTATION_RECORD_FILE);

export const runLockPath = (record: Pick<MutationRunRecord, "root">): string =>
join(record.root, MUTATION_RUN_LOCK_FILE);
Expand Down Expand Up @@ -332,11 +336,14 @@ export const rewriteProjectPathArg = (
return join(resolvedSnapshot, resolvedValue.slice(rootPrefix.length));
};

export const rewriteMutationArgs = (
/** Turn a run's arguments into the ones the child sees inside its snapshot. */
export type SnapshotArgsFn = (
root: string,
snapshotRoot: string,
args: string[],
): string[] =>
) => string[];

export const rewriteMutationArgs: SnapshotArgsFn = (root, snapshotRoot, args) =>
args.map((arg) => rewriteProjectPathArg(root, snapshotRoot, arg));

export const parseIsolationCommand = (args: string[]): IsolationCommand => {
Expand Down
31 changes: 14 additions & 17 deletions scripts/mutation/isolation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { relative } from "@std/path";
import { errorMessage } from "#shared/error-message.ts";
import { processExists, stopProcess, stopProcessNow } from "../process.ts";
import { projectRoot } from "../project-root.ts";
import {
Expand All @@ -31,11 +32,15 @@ import {
rewriteMutationArgs,
runLockIsHeld,
runStartedRecently,
type SnapshotArgsFn,
selectedRuns,
withMutationRunLock,
writeRunRecord,
} from "./isolation-state.ts";

/** Runs a mutation command from its argv and returns a process exit code. */
type MutationCommandRunner = (args: string[], root?: string) => Promise<number>;

const processBelongsToRun = async (
record: MutationRunRecord,
): Promise<boolean> => {
Expand Down Expand Up @@ -138,11 +143,7 @@ const childEnv = (
[MUTATION_WORK_ROOT_ENV]: snapshotRoot,
});

const childArgs = (
root: string,
snapshotRoot: string,
args: string[],
): string[] => [
const childArgs: SnapshotArgsFn = (root, snapshotRoot, args) => [
"run",
"-A",
"scripts/mutation.ts",
Expand Down Expand Up @@ -170,10 +171,10 @@ const settleRecord = (
): MutationRunRecord =>
interrupted ? markInterrupted(record) : markFinished(record, code);

export const runMutationInSnapshot = async (
args: string[],
export const runMutationInSnapshot: MutationCommandRunner = async (
args,
root = projectRoot,
): Promise<number> => {
) => {
const id = createRunId();
let record = newRunRecord(id, args, root);
await writeRunRecord(record);
Expand Down Expand Up @@ -230,7 +231,7 @@ export const runMutationInSnapshot = async (
} catch {
// A failed write should not mask the original error.
}
console.error(error instanceof Error ? error.message : String(error));
console.error(errorMessage(error));
}
offTerminationSignals(stopChild);
return exitCode;
Expand Down Expand Up @@ -308,11 +309,7 @@ const removeMatchedRuns = async (

for (const record of removed) console.log(`Removed ${record.id}.`);
for (const { error, record } of failed) {
console.error(
`Failed to remove ${record.id}: ${
error instanceof Error ? error.message : String(error)
}`,
);
console.error(`Failed to remove ${record.id}: ${errorMessage(error)}`);
}
for (const record of skipped) {
console.error(`Skipped active isolated mutation run ${record.id}.`);
Expand All @@ -330,10 +327,10 @@ const cleanRuns = (target: string, root = projectRoot): Promise<number> =>
removeMatchedRuns(records, target),
);

export const runIsolatedMutationCommand = async (
args: string[],
export const runIsolatedMutationCommand: MutationCommandRunner = async (
args,
root = projectRoot,
): Promise<number> => {
) => {
const command = parseIsolationCommand(args);
if (command.kind === "invalid") {
console.error(command.message);
Expand Down
Loading