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
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ The bot's tests live in `apps/bot/test/` and use [`@effect/vitest`](https://www.
- `HeadlineWriter.layerProviders` takes fake language models, so the provider fallback can be tested without calling a real one.
- Database code runs against [PGlite](https://pglite.dev), an in-process Postgres, with the real migrations. Give it `columnNaming` from `apps/bot/src/database/Database.ts` so column names convert the same way as in production. `apps/bot/test/fakes.ts` also has a fake recorder for program tests.

The Console's page tests sit next to its code in `apps/console/src/`. Foldkit stories, from `foldkit/story`, run an update function and resolve its Commands by hand, and scenes, from `foldkit/scene`, drive the view the way a person would, so neither needs a server or a timer. The page calls the Worker through an `HttpApiClient` built from the contract in `office-domain`, so a change to an endpoint breaks the page's typecheck. [`apps/console/src/app/fakes.ts`](apps/console/src/app/fakes.ts) has two fakes. `fakeWorker` serves that same contract through `HttpApiBuilder`, with typed fake handlers for the groups a test cares about, so a fake can't answer with something the real Worker couldn't. `fakeServer` answers at the HTTP level, for what only a proxy does: no answer at all, a hang, a 502. The Discord sign-in and the saving of edits are tested as Effects against them, and `console.spec.ts` runs the whole program against the fake Worker, with the polling for the bot's answer sped up through `RequestAnswer`. The built page has a smoke test of its own in `apps/console/smoke/`, run by the `smoke` task after the build: it opens the page in Chromium with `/api/*` answered by hand, and holds its scripts to a gzipped budget, so raising the budget is a decision rather than an accident.
The Console's page tests sit next to its code in `apps/console/src/`. Foldkit stories, from `foldkit/story`, run an update function and resolve its Commands by hand, and scenes, from `foldkit/scene`, drive the view the way a person would, so neither needs a server or a timer. The page calls the Worker through an `HttpApiClient` built from the contract in `office-domain`, so a change to an endpoint breaks the page's typecheck. [`apps/console/src/app/fakes.ts`](apps/console/src/app/fakes.ts) has two fakes. `fakeWorker` serves that same contract through `HttpApiBuilder`, with typed fake handlers for the groups a test cares about, so a fake can't answer with something the real Worker couldn't. `fakeServer` answers at the HTTP level, for what only a proxy does: no answer at all, a hang, a 502. The Discord sign-in and the saving of edits are tested as Effects against them, and `console.spec.ts` runs the whole program against the fake Worker, with the polling for the bot's answer sped up through `RequestAnswer`. The built page has a smoke test of its own in `apps/console/smoke/`, run by the `smoke` task after the build: it opens the page in Chromium with `/api/*` answered by hand, and holds the scripts it loads at start to a gzipped budget, so raising the budget is a decision rather than an accident. `@sentry/browser` is imported only once `/api/telemetry` says where to report, or when there's a crash or a failed request to report, so a page without Sentry never downloads it; the smoke test checks that nothing beyond the start-up scripts loads.

### Adding a configuration variable

Expand Down Expand Up @@ -95,7 +95,7 @@ The pieces, which you can run on their own:
| `pnpm vp run check` | Check formatting with Oxfmt and lint with Oxlint, across the whole repo, with the `fmt` and `lint` config in the root `vite.config.ts`. Lint includes the Effect rules. `pnpm vp check --fix` formats every file and applies the automatic lint fixes. |
| `pnpm vp run -r test` | Run every package's tests with Vitest. |
| `pnpm vp run -r build` | Bundle the bot to `apps/bot/dist/main.js` with a source map, and build the Console to `apps/console/dist`: the page in `client/`, and the Worker with its generated `wrangler.json` in `worker/`. |
| `pnpm vp run console#smoke` | Build the Console and open its page in Playwright's Chromium: it has to start, be styled, switch tabs from the keyboard and keep its scripts under the gzipped budget in [`apps/console/smoke/page.spec.ts`](apps/console/smoke/page.spec.ts). Run `pnpm --filter console exec playwright install chromium` once first. |
| `pnpm vp run console#smoke` | Build the Console and open its page in Playwright's Chromium: it has to start, be styled, switch tabs from the keyboard and keep the scripts it loads at start under the gzipped budget in [`apps/console/smoke/page.spec.ts`](apps/console/smoke/page.spec.ts). Run `pnpm --filter console exec playwright install chromium` once first. |
| `pnpm --filter bot dev` | Run the bot from source with `.env`. |
| `pnpm --filter bot start` | Run the bot's bundle with `.env`. |
| `pnpm --filter console dev` | Serve the Console's page with live reload and run its Worker in the Workers runtime on the same origin. See [Toolchain](#toolchain) for the database it needs. |
Expand Down
43 changes: 37 additions & 6 deletions apps/console/smoke/page.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { readdir, readFile } from "node:fs/promises";
import { readFile } from "node:fs/promises";
import { createServer, type Server } from "node:http";
import { extname, join, normalize } from "node:path";
import { gzipSync } from "node:zlib";
Expand All @@ -9,9 +9,15 @@ import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test";

const CLIENT = join(import.meta.dirname, "../dist/client");

const ASSETS = join(CLIENT, "assets");
const SCRIPT_BUDGET_KB = 220;

const SCRIPT_BUDGET_KB = 260;
const STARTUP_SCRIPT = /<(?:script[^>]+src|link[^>]+rel="modulepreload"[^>]+href)="\/([^"]+\.js)"/g;

const startupScripts = async (): Promise<ReadonlyArray<string>> =>
Array.from(
(await readFile(join(CLIENT, "index.html"), "utf8")).matchAll(STARTUP_SCRIPT),
(match) => match[1] ?? "",
);

const TYPES = new Map([
[".html", "text/html"],
Expand Down Expand Up @@ -112,11 +118,11 @@ afterAll(async () => {
});

describe("the built page", () => {
it(`keeps its scripts under ${SCRIPT_BUDGET_KB} kB gzipped`, async () => {
const scripts = (await readdir(ASSETS)).filter((name) => name.endsWith(".js"));
it(`starts with under ${SCRIPT_BUDGET_KB} kB of script, gzipped`, async () => {
const scripts = await startupScripts();

const sizes = await Promise.all(
scripts.map(async (name) => gzipSync(await readFile(join(ASSETS, name))).byteLength),
scripts.map(async (path) => gzipSync(await readFile(join(CLIENT, path))).byteLength),
);

const total = sizes.reduce((sum, size) => sum + size, 0) / 1000;
Expand All @@ -125,6 +131,31 @@ describe("the built page", () => {
expect(total).toBeLessThanOrEqual(SCRIPT_BUDGET_KB);
});

it("loads no other script when the Worker has no Sentry to report to", async () => {
const expected = await startupScripts();
const page = await browser.newPage();
const loaded: Array<string> = [];

page.on("request", (request) => {
const { pathname } = new URL(request.url());

if (pathname.endsWith(".js")) loaded.push(pathname.slice(1));
});
await page.route("**/api/**", (route) => {
const answer = API.get(new URL(route.request().url()).pathname);

return answer === undefined
? route.fulfill({ status: 404 })
: route.fulfill({ status: 200, json: answer });
});
await page.goto(`http://127.0.0.1:${portOf(server)}/`);
await expect.poll(() => page.getByRole("heading", { name: "Couldn't start" }).count()).toBe(1);

expect(loaded.sort()).toEqual([...expected].sort());

await page.close();
});

it("starts in a real browser, and says it couldn't start outside Discord", async () => {
const { page, errors } = await openPage();

Expand Down
35 changes: 20 additions & 15 deletions apps/console/src/app/telemetry/gateway-failures.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as Sentry from "@sentry/browser";
import { Array, Context, Effect, pipe, Record, String } from "effect";

import { loadSentry } from "./sentry.ts";

export const BODY_LIMIT = 200;

const SAFE_HEADERS = ["retry-after", "cf-ray", "server", "via", "content-type"] as const;
Expand Down Expand Up @@ -42,22 +43,26 @@ interface GatewayFailuresService {

const sentryGatewayFailures: GatewayFailuresService = {
retrying: (failure) =>
Effect.sync(() =>
Sentry.addBreadcrumb({
category: "http.retry",
level: "warning",
message: `${failure.path} answered ${failure.status}, asking again`,
data: failure.details,
}),
Effect.promise(loadSentry).pipe(
Effect.map((Sentry) =>
Sentry.addBreadcrumb({
category: "http.retry",
level: "warning",
message: `${failure.path} answered ${failure.status}, asking again`,
data: failure.details,
}),
),
),
gaveUp: (failure) =>
Effect.sync(() => {
Sentry.captureMessage(`${failure.path} kept answering ${failure.status}`, {
level: "warning",
fingerprint: ["gateway-failure", `${failure.status}`],
contexts: { response: failure.details },
});
}),
Effect.promise(loadSentry).pipe(
Effect.map((Sentry) => {
Sentry.captureMessage(`${failure.path} kept answering ${failure.status}`, {
level: "warning",
fingerprint: ["gateway-failure", `${failure.status}`],
contexts: { response: failure.details },
});
}),
),
};

export const GatewayFailures = Context.Reference<GatewayFailuresService>(
Expand Down
3 changes: 3 additions & 0 deletions apps/console/src/app/telemetry/sentry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export type SentryModule = typeof import("@sentry/browser");

export const loadSentry = (): Promise<SentryModule> => import("@sentry/browser");
6 changes: 3 additions & 3 deletions apps/console/src/app/telemetry/telemetry.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ describe("the telemetry", () => {
const errors: Array<string | undefined> = [];

Sentry.init({
...sentryOptionsFor(telemetry),
...sentryOptionsFor(Sentry, telemetry),
transport: (options) =>
Sentry.createTransport(options, () => {
sentTo.push(options.url);
Expand All @@ -75,7 +75,7 @@ describe("the telemetry", () => {
},
});

reportCrash(new Error("The page caught fire"));
yield* Effect.promise(() => reportCrash(new Error("The page caught fire")));
yield* Effect.promise(() => Sentry.flush(2000));

expect(errors).toEqual(["The page caught fire"]);
Expand All @@ -84,6 +84,6 @@ describe("the telemetry", () => {
);

it("leaves the release out when the Worker has none", () => {
expect(sentryOptionsFor({ ...telemetry, release: null }).release).toBeUndefined();
expect(sentryOptionsFor(Sentry, { ...telemetry, release: null }).release).toBeUndefined();
});
});
25 changes: 15 additions & 10 deletions apps/console/src/app/telemetry/telemetry.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import * as Sentry from "@sentry/browser";
import type { BrowserOptions } from "@sentry/browser";
import { Array, Effect } from "effect";
import { type Telemetry, TUNNEL_PATH } from "office-domain/Telemetry";

import { ConsoleApi } from "../api/api.ts";
import { loadSentry, type SentryModule } from "./sentry.ts";

export const sentryOptionsFor = ({
dsn,
environment,
release,
}: Telemetry): Sentry.BrowserOptions => ({
export const sentryOptionsFor = (
Sentry: SentryModule,
{ dsn, environment, release }: Telemetry,
): BrowserOptions => ({
dsn,
environment,
release: release ?? undefined,
Expand All @@ -24,11 +24,16 @@ export const sentryOptionsFor = ({

export const startTelemetry = ConsoleApi.use((api) => api.telemetry.config()).pipe(
Effect.flatMap((telemetry) =>
telemetry === null ? Effect.void : Effect.sync(() => Sentry.init(sentryOptionsFor(telemetry))),
telemetry === null
? Effect.void
: Effect.promise(loadSentry).pipe(
Effect.map((Sentry) => Sentry.init(sentryOptionsFor(Sentry, telemetry))),
),
),
Effect.ignore,
);

export const reportCrash = (error: Error): void => {
Sentry.captureException(error);
};
export const reportCrash = (error: Error): Promise<void> =>
loadSentry().then((Sentry) => {
Sentry.captureException(error);
});