marmar-context / web / context / test / support / fault-provider.mjs
fault-provider.mjs
Raw
// Test-only preload. Never imported by the application. Blocks real provider access.
import fs from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
const modeFile = process.env.CONTEXT_FAULT_FILE;
if (!modeFile || process.env.CONTEXT_PORT !== "4198")
  throw new Error("Fault provider requires isolated loopback test port 4198.");
let epoch,
  calls = 0,
  active = 0,
  peak = 0,
  aborted = 0;
const record = () =>
  fs.writeFileSync(
    modeFile + ".stats",
    JSON.stringify({ epoch, calls, active, peak, aborted }),
  );
globalThis.fetch = async (url, options) => {
  if (
    url !== "https://synthetic.services.ai.azure.com/openai/v1/chat/completions"
  )
    throw new Error("Fault tests prohibit real provider calls.");
  const mode = JSON.parse(fs.readFileSync(modeFile, "utf8"));
  if (epoch !== mode.epoch) {
    epoch = mode.epoch;
    calls = 0;
    active = 0;
    peak = 0;
    aborted = 0;
  }
  calls++;
  active++;
  peak = Math.max(peak, active);
  record();
  const call = calls;
  try {
    if (mode.kind === "hang")
      await delay(60000, undefined, { signal: options.signal });
    if (mode.kind === "slow")
      await delay(mode.ms || 6000, undefined, { signal: options.signal });
    if (mode.kind === "network") throw new Error("PRIVATE PROVIDER ERROR");
    if (mode.kind === "503" || (mode.kind === "recover" && call === 1))
      return new Response("", { status: 503 });
    if (mode.kind === "401")
      return new Response("PRIVATE KEY", { status: 401 });
    if (mode.kind === "rate-date")
      return new Response("", {
        status: 429,
        headers: { "Retry-After": new Date(Date.now() + 30000).toUTCString() },
      });
    if (mode.kind === "rate-short" && call === 1)
      return new Response("", { status: 429, headers: { "Retry-After": "1" } });
    if (mode.kind === "null") return new Response("null");
    if (mode.kind === "body-hang") {
      return new Response(
        new ReadableStream({
          start(controller) {
            options.signal.addEventListener(
              "abort",
              () => controller.error(new Error("body aborted")),
              { once: true },
            );
          },
        }),
      );
    }
    const lines = JSON.parse(JSON.parse(options.body).messages[1].content);
    const line = lines.find(([, text]) => /Metformin/i.test(text));
    const content =
      mode.kind === "malformed"
        ? "not JSON"
        : JSON.stringify({
            facts: line
              ? [
                  [
                    line[0],
                    "Medication: Metformin; strength: 500 mg; frequency: 2/day",
                  ],
                ]
              : [],
          });
    return new Response(
      JSON.stringify({
        choices: [
          {
            finish_reason: mode.kind === "truncated" ? "length" : "stop",
            message: { content },
          },
        ],
      }),
    );
  } catch (e) {
    if (options.signal.aborted) aborted++;
    throw e;
  } finally {
    active--;
    record();
  }
};