45 lines · 1.7 KB
import { describe, expect, test } from "bun:test";
import { configurePerf, countD1, countDo, countDoRows, setPerfReporter, withJobPerf, withPerf } from "./perf";

const HEAVY_UNIT_QUERIES = 30;

describe("perf accounting", () => {
  test("counts the unit's own D1 and object calls and always reports expensive ones", async () => {
    const events: Array<[string, Record<string, unknown>]> = [];
    setPerfReporter((event, properties) => events.push([event, properties]));
    configurePerf("0.000001");
    await withPerf(
      () => ({ event: "server_request", properties: { route: "/:owner/:repo" } }),
      async () => {
        for (let index = 0; index < HEAVY_UNIT_QUERIES; index++) countD1(1);
        countDo(2);
        countDoRows(7, 1);
        await withJobPerf("nested", async () => countD1(5));
      },
    );
    const request = events.find(([event]) => event === "server_request")?.[1];
    expect(request).toMatchObject({
      route: "/:owner/:repo",
      d1_queries: HEAVY_UNIT_QUERIES,
      do_calls: 1,
      do_rows_read: 7,
      do_rows_written: 1,
      expensive: true,
      sample_weight: 1,
    });
  });

  test("cheap units are sampled with a weight; failures are always reported", async () => {
    const events: Array<Record<string, unknown>> = [];
    setPerfReporter((_event, properties) => events.push(properties));
    configurePerf("1");
    await withJobPerf("cheap", async () => undefined);
    expect(events[0]).toMatchObject({ job: "cheap", expensive: false, sample_weight: 1 });
    configurePerf("0.000001");
    await withJobPerf("boom", async () => {
      throw new Error("x");