sailfork / t3code-github / .repos/ alchemy-effect/ packages/ alchemy-test/ src/ Bun.ts

/** @effect-diagnostics anyUnknownInErrorContext:off */

import bun from "bun:test";
import type { HookOptions } from "node:test";
import type { AlchemyContext } from "alchemy/AlchemyContext";
import type { CompiledStack, StackDefinition } from "alchemy/Stack";
import type { Stage } from "alchemy/Stage";
import * as Cause from "effect/Cause";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Scope from "effect/Scope";
import * as Core from "./Core.ts";

export {
  executeWhenReady,
  getWhenReady,
  guardContentType,
  guardedFetchLayer,
  rpcClientLayer,
  WorkerNotReady,
  type EdgeGuardOptions,
  type WhenReadyOptions,
} from "./Http.ts";

export type MakeOptions<ROut = any> = Core.MakeOptions<ROut>;
export type ScratchStack = Core.ScratchStack;
export type TestEffect<A, R = never> = Core.TestEffect<A, R>;
export const defaultStage = Core.defaultStage;
export const resolveStage = Core.resolveStage;

export interface TestApi {
  test: TestFn;
  beforeAll: BeforeAllFn;
  beforeEach: BeforeEachFn;
  afterAll: AfterAllFn;
  afterEach: AfterEachFn;
  deploy: Core.Deploy;
  destroy: <ROut>(
    stack: StackDefinition<ROut>,
    options?: { stage?: string; include?: never; exclude?: never },
  ) => ReturnType<typeof Core.destroy>;
}

interface TestFn {
  (name: string, eff: TestEffect<void>, options?: bun.TestOptions): void;
  skip: (name: string, eff: TestEffect<void>, options?: bun.TestOptions) => void;
  skipIf: (
    condition: boolean,
  ) => (name: string, eff: TestEffect<void>, options?: bun.TestOptions) => void;
  only: (name: string, eff: TestEffect<void>, options?: bun.TestOptions) => void;
  todo: (name: string, eff: TestEffect<void>, options?: bun.TestOptions) => void;
  provider: ProviderFn;
}

interface ProviderFn {
  (
    name: string,
    fn: (stack: ScratchStack) => Effect.Effect<void, any, any>,
    options?: bun.TestOptions,
  ): void;
  skip: (
    name: string,
    fn: (stack: ScratchStack) => Effect.Effect<void, any, any>,
    options?: bun.TestOptions,
  ) => void;
  skipIf: (
    condition: boolean,
  ) => (
    name: string,
    fn: (stack: ScratchStack) => Effect.Effect<void, any, any>,
    options?: bun.TestOptions,
  ) => void;
}

interface BeforeAllFn {
  <A>(eff: TestEffect<A>, options?: HookOptions): Effect.Effect<A>;
}

interface BeforeEachFn {
  (eff: TestEffect<void>, options?: HookOptions): void;
}

interface AfterAllFn {
  (eff: TestEffect<any>, options?: HookOptions): void;
  skipIf: (predicate: boolean) => (eff: TestEffect<any>, options?: HookOptions) => void;
}

interface AfterEachFn {
  (eff: TestEffect<void>, options?: HookOptions): void;
}

const DEFAULT_HOOK_TIMEOUT: HookOptions = { timeout: 120_000 };

/** The timeout bun applies to a test, from its options. */
const timeoutOf = (options: bun.TestOptions | undefined): number | undefined =>
  typeof options === "number" ? options : options?.timeout;

/**
 * Interrupt `eff` shortly before bun's own timeout. When bun times a test or
 * hook out it only stops waiting: the effect keeps running, so the file's
 * `afterAll` destroy races a deploy still creating resources, and whatever
 * that deploy creates afterwards is never cleaned up. Interrupting it first
 * lets the engine record what it created, so the destroy that follows finds
 * it.
 */
const DEADLINE_MARGIN_MS = 5_000;
const withDeadline = <A, E, R>(
  eff: Effect.Effect<A, E, R>,
  timeout: number | undefined,
): Effect.Effect<A, E | Cause.TimeoutError, R> =>
  timeout === undefined || timeout <= DEADLINE_MARGIN_MS * 2
    ? eff
    : eff.pipe(Effect.timeout(Duration.millis(timeout - DEADLINE_MARGIN_MS)));

/**
 * Build the per-file test API. Configure providers / state once at the top of
 * the test file:
 *
 * ```ts
 * import * as Test from "@alchemy.run/test/Bun";
 * import * as Cloudflare from "@alchemy.run/cloudflare";
 *
 * const { test, deploy, destroy, beforeAll, afterAll } = Test.make({
 *   providers: Cloudflare.providers(),
 *   state: Cloudflare.state(),
 * });
 * ```
 */
export const make = <ROut = any>(options: MakeOptions<ROut>): TestApi => {
  // Single scope shared across `beforeAll`, every `test`, and `afterAll`.
  // Scoped resources in dev mode (the Cloudflare sidecar process and its
  // workerd children) must outlive a single `Effect.runPromise` boundary,
  // otherwise the proxy is killed the moment `beforeAll(deploy(Stack))`
  // resolves and every later `HttpClient.get(workerUrl)` hits a dead port.
  // The scope is closed by `destroy(...)` (or never — the next test run
  // reclaims any leaked sidecar via the lock file).
  const sharedScope = Scope.makeUnsafe("sequential");
  // In dev mode, run local providers behind one file-scoped RPC sidecar
  // (the `alchemy dev` topology). Lives in its own scope — NOT sharedScope,
  // which `destroy(Stack)` closes mid-file in self-contained tests — and is
  // closed by the fallback afterAll below.
  const sidecar = Core.makeSidecarHandle(options);
  const runEff = <A>(eff: TestEffect<A>, timeout?: number) =>
    Core.run(withDeadline(eff, timeout), options, sharedScope, sidecar);

  const test = ((name, eff, opts) => {
    bun.test(name, () => runEff(eff, timeoutOf(opts)), opts);
  }) as TestFn;

  test.skip = (name, eff, opts) => {
    bun.test.skip(name, () => runEff(eff, timeoutOf(opts)), opts);
  };
  test.skipIf = (condition) => (name, eff, opts) => {
    bun.test.skipIf(condition)(name, () => runEff(eff, timeoutOf(opts)), opts);
  };
  test.only = (name, eff, opts) => {
    bun.test.only(name, () => runEff(eff, timeoutOf(opts)), opts);
  };
  test.todo = (name, eff, opts) => {
    bun.test.todo(name, () => runEff(eff, timeoutOf(opts)), opts);
  };

  const runProvider = (
    name: string,
    fn: (stack: ScratchStack) => Effect.Effect<void, any, any>,
    timeout?: number,
  ) => {
    const scratch = Core.scratchStack(options, name);
    return Core.run(
      withDeadline(Core.withProviders(fn(scratch), options, scratch.name), timeout),
      { ...options, state: scratch.state },
      sharedScope,
      sidecar,
    );
  };

  const provider = ((name, fn, opts) => {
    bun.test(name, () => runProvider(name, fn, timeoutOf(opts)), opts);
  }) as ProviderFn;
  provider.skip = (name, fn, opts) => {
    bun.test.skip(name, () => runProvider(name, fn, timeoutOf(opts)), opts);
  };
  provider.skipIf = (condition) => (name, fn, opts) => {
    bun.test.skipIf(condition)(name, () => runProvider(name, fn, timeoutOf(opts)), opts);
  };
  test.provider = provider;

  const beforeAll: BeforeAllFn = <A>(eff: TestEffect<A>, hookOptions?: HookOptions) => {
    let result: A;
    const options = hookOptions ?? DEFAULT_HOOK_TIMEOUT;
    bun.beforeAll(() => runEff(eff, options.timeout).then((v) => (result = v)), options);
    return Effect.sync(() => result);
  };

  const beforeEach: BeforeEachFn = (eff, hookOptions) => {
    bun.beforeEach(() => runEff(eff), hookOptions);
  };

  // bun:test stops running later `afterAll` hooks once one throws, which
  // would skip the fallback cleanup hook below — leaking the shared scope
  // and the sidecar for the rest of the process whenever a teardown
  // assertion fails. Guard every user teardown: on failure, run the
  // (idempotent) cleanup before rethrowing so the failure still fails the
  // suite. (`closeAll` is initialized below; hooks only run after `make`
  // returns.)
  const guardTeardown = (eff: TestEffect<any>) => () =>
    runEff(eff).catch(async (error) => {
      await Effect.runPromise(closeAll);
      throw error;
    });

  const afterAll = ((eff, hookOptions) => {
    bun.afterAll(guardTeardown(eff), hookOptions ?? DEFAULT_HOOK_TIMEOUT);
  }) as AfterAllFn;
  afterAll.skipIf = (predicate) => (eff, hookOptions) => {
    if (predicate) return;
    bun.afterAll(guardTeardown(eff), hookOptions ?? DEFAULT_HOOK_TIMEOUT);
  };

  const afterEach: AfterEachFn = (eff, hookOptions) => {
    bun.afterEach(() => runEff(eff), hookOptions);
  };

  // `destroy(Stack)` needs the dev sidecar alive so it can call `sidecar.stop`
  // for each worker. We close the shared scope only AFTER destroy completes.
  // `Scope.close` on an already-closed scope is a no-op, so it's safe for both
  // the destroy wrapper AND the fallback cleanup hook below to call it.
  const closeScope = Effect.suspend(() => Scope.close(sharedScope, Exit.void)).pipe(Effect.ignore);

  // Fallback cleanup: if the user never calls `destroy(Stack)` (e.g.
  // `NO_DESTROY=1`), nothing else closes the shared scope and the sidecar
  // child process leaks past the test process. Register an `afterAll` that
  // closes it (and the RPC sidecar, which lives in its own scope so that
  // mid-file `destroy(Stack)` calls can't kill it for later tests). We defer
  // registration to a microtask so it runs AFTER any user-registered
  // `afterAll` (including `destroy(Stack)`); bun runs afterAll hooks in
  // registration order.
  const closeAll = sidecar ? Effect.andThen(closeScope, sidecar.close) : closeScope;
  queueMicrotask(() => {
    bun.afterAll(() => Effect.runPromise(closeAll), DEFAULT_HOOK_TIMEOUT);
  });

  return {
    test,
    beforeAll,
    beforeEach,
    afterAll,
    afterEach,
    deploy: Core.makeDeploy(options, sharedScope),
    destroy: (stack, callOpts) =>
      Core.destroy(options, stack, { ...callOpts, scope: sharedScope }).pipe(
        Effect.ensuring(closeScope),
      ),
  };
};