Skip to content

Commit 66b4ea4

Browse files
authored
test(service): Share the test setup, and fix the timing checks for coverage (#63)
2 parents dceb3ed + a2a6712 commit 66b4ea4

7 files changed

Lines changed: 211 additions & 282 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
- Use functions and plain objects, not classes.
3838
- Start each source file with a comment that says what the file owns. Give each export a short JSDoc.
3939
- Update `README.md` in the same change when behavior, config, or the control API changes.
40-
- Test through a real proxy and a local upstream server in `packages/service/tests/`. Do not mock modules. Do not reach the internet.
40+
- Test through a real proxy and a local upstream server in `packages/service/tests/`. Start them with `startTestService()` and `startUpstream()` of `tests/harness.ts`. Wrap a tight timing limit in `budget()`, so that it allows for coverage, unless coverage barely slows that check. Do not mock modules. Do not reach the internet.
4141
- The proxy decrypts HTTPS. Never write a credential: every recording goes through `packages/service/src/secrets.ts`.
4242
- The upstream host always comes from `allow`, never from the client.
4343
- Write docs in ASD-STE100 English: common words, active voice, short sentences.

‎packages/service/tests/harness.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/**
2+
* The shared setup of the service tests: a local upstream and a service in
3+
* the test process. Each one closes when its test finishes.
4+
*/
5+
import { createHash } from "node:crypto";
6+
import { createServer, type RequestListener, type Server } from "node:http";
7+
import { mkdtemp, rm } from "node:fs/promises";
8+
import { tmpdir } from "node:os";
9+
import path from "node:path";
10+
import { onTestFinished } from "vitest";
11+
import {
12+
startRoachService,
13+
type RoachService,
14+
type RoachServiceConfig,
15+
} from "../src/service.ts";
16+
17+
/**
18+
* The time limit of a timing check: `ms`, or 3 times `ms` with coverage.
19+
* Coverage makes the service slower (`vitest.config.ts`).
20+
*/
21+
export const budget = (ms: number) =>
22+
ms * Number(process.env.ROACH_TEST_SLOWDOWN ?? "1");
23+
24+
/** The write token of a test service. */
25+
export const TOKEN = "write-token";
26+
27+
/** The SHA-256 of a token in hex, as `writeTokenHash` keeps it. */
28+
const hash = (token: string) =>
29+
createHash("sha256").update(token).digest("hex");
30+
31+
/**
32+
* Start an HTTP upstream on 127.0.0.1 with `handler`. Returns the server
33+
* and its origin. It closes when the test finishes.
34+
*/
35+
export async function startUpstream(
36+
handler: RequestListener,
37+
): Promise<{ server: Server; origin: string }> {
38+
const server = createServer(handler);
39+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
40+
onTestFinished(
41+
() => new Promise<void>((resolve) => server.close(() => resolve())),
42+
);
43+
const address = server.address();
44+
if (!address || typeof address === "string") throw new Error("No port");
45+
return { server, origin: `http://127.0.0.1:${address.port}` };
46+
}
47+
48+
/**
49+
* Start a service in this process, with the recordings in a new directory.
50+
* It can reach the upstream on 127.0.0.1 (`privateNetworks`), and its write
51+
* token is `TOKEN`. `extra` adds to or replaces this config. The service
52+
* closes, and its directory goes, when the test finishes.
53+
*/
54+
export async function startTestService(
55+
extra: Partial<RoachServiceConfig> = {},
56+
): Promise<{ service: RoachService; directory: string }> {
57+
const directory = await mkdtemp(path.join(tmpdir(), "roach-"));
58+
const service = await startRoachService({
59+
directory,
60+
privateNetworks: true,
61+
writeTokenHash: hash(TOKEN),
62+
...extra,
63+
});
64+
onTestFinished(async () => {
65+
await service.close();
66+
await rm(directory, { recursive: true, force: true });
67+
});
68+
return { service, directory };
69+
}

‎packages/service/tests/recording.test.ts‎

Lines changed: 6 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,7 @@
22
* Recording and replay: modes, sessions, changing values, and misses. Each
33
* test starts runs on a service with a local upstream.
44
*/
5-
import { createHash } from "node:crypto";
6-
import { createServer, type Server } from "node:http";
7-
import {
8-
mkdir,
9-
mkdtemp,
10-
readdir,
11-
readFile,
12-
rm,
13-
writeFile,
14-
} from "node:fs/promises";
15-
import { tmpdir } from "node:os";
5+
import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
166
import path from "node:path";
177
import { ProxyAgent, request } from "undici";
188
import {
@@ -28,15 +18,14 @@ import {
2818
describeRecordingMisses,
2919
describeRecordingStats,
3020
} from "@sentry/roach/report";
31-
import { startRoachService, type RoachService } from "../src/service.ts";
21+
import type { RoachService } from "../src/service.ts";
22+
import { startTestService, startUpstream, TOKEN } from "./harness.ts";
3223
import { keyRequest } from "../src/request-key.ts";
3324
import type { RecordingMode, RecordingRule } from "@sentry/roach/types";
3425
import { extractValues, VALUE_PATTERNS } from "@sentry/roach/values";
3526

36-
const TOKEN = "write-token";
3727
const TENANT = "acme/alpha";
3828

39-
let upstream: Server;
4029
let origin: string;
4130
let liveRequests: number;
4231
/** The event stream that the upstream sends for a request body. */
@@ -184,7 +173,7 @@ beforeEach(async () => {
184173
liveRequests = 0;
185174
respond = () => `data: ${liveRequests}\n\n`;
186175
upstreamGate = Promise.resolve();
187-
upstream = createServer((incoming, outgoing) => {
176+
({ origin } = await startUpstream((incoming, outgoing) => {
188177
liveRequests += 1;
189178
const chunks: Buffer[] = [];
190179
incoming.on("data", (chunk: Buffer) => chunks.push(chunk));
@@ -193,28 +182,14 @@ beforeEach(async () => {
193182
outgoing.writeHead(200, { "content-type": "text/event-stream" });
194183
outgoing.end(respond(Buffer.concat(chunks).toString("utf8")));
195184
});
196-
});
197-
await new Promise<void>((resolve) =>
198-
upstream.listen(0, "127.0.0.1", resolve),
199-
);
200-
const address = upstream.address();
201-
if (!address || typeof address === "string") throw new Error("No port");
202-
origin = `http://127.0.0.1:${address.port}`;
203-
directory = await mkdtemp(path.join(tmpdir(), "roach-"));
204-
service = await startRoachService({
205-
directory,
206-
privateNetworks: true,
207-
writeTokenHash: createHash("sha256").update(TOKEN).digest("hex"),
208-
});
185+
}));
186+
({ service, directory } = await startTestService());
209187
});
210188

211189
afterEach(async () => {
212190
await agent?.close();
213191
agent = undefined;
214192
await Promise.all(runs.splice(0).map((run) => run.close().catch(() => {})));
215-
await service.close();
216-
await new Promise<void>((resolve) => upstream.close(() => resolve()));
217-
await rm(directory, { recursive: true, force: true });
218193
});
219194

220195
describe("recording", () => {

0 commit comments

Comments
 (0)