Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

7.3 KB
Raw Blame
import * as AWS from "@/AWS";
import * as Core from "@/Test/Core";
import * as Test from "@/Test/Alchemy";
import { describe, expect } from "alchemy-test";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
import AccountTestFunctionLive, { AccountTestFunction } from "./handler";

const testOptions = { providers: AWS.providers() };
const { test, beforeAll, afterAll } = Test.make(testOptions);
const sharedStack = Core.scratchStack(testOptions, "AccountBindings");

// Lambda function URL cold-start (DNS, IAM propagation, init) can take well
// over 60s on a fresh deploy.
const readinessPolicy = Schedule.max([
  Schedule.fixed("2 seconds"),
  Schedule.recurs(75),
]);

let baseUrl: string;

class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
  readonly status: number;
  readonly body: string;
}> {}

// The shared Lambda fixture occasionally answers a transient 5xx under load
// (cold re-init, IAM propagation on the freshly attached policy that the
// handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
// 4xx/assertion failure surfaces immediately.
const send = (request: HttpClientRequest.HttpClientRequest) =>
  HttpClient.execute(request).pipe(
    Effect.flatMap((response) =>
      response.status >= 500
        ? response.text.pipe(
            Effect.flatMap((body) =>
              Effect.fail(
                new TransientUpstream({ status: response.status, body }),
              ),
            ),
          )
        : Effect.succeed(response),
    ),
    Effect.retry({
      while: (e) => e._tag === "TransientUpstream",
      schedule: Schedule.max([
        Schedule.exponential("500 millis"),
        Schedule.recurs(6),
      ]),
    }),
  );

// The freshly attached IAM policy can take ~10-30s to propagate to the
// Lambda's role; until it does, granted calls surface a transient
// AccessDeniedException. Poll (bounded) until the response is no longer
// access-denied so grant-proof assertions see steady-state behavior.
const getJson = (path: string) =>
  send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(
    Effect.flatMap((r) => r.json),
    Effect.repeat({
      schedule: Schedule.spaced("3 seconds"),
      until: (response): boolean =>
        (response as { tag?: string }).tag !== "AccessDeniedException",
      times: 10,
    }),
  );

describe.sequential("Account Bindings", () => {
  beforeAll(
    Effect.gen(function* () {
      yield* Effect.logInfo(
        "Account test setup: destroying previous resources",
      );
      yield* sharedStack.destroy();

      yield* Effect.logInfo("Account test setup: deploying fixture");
      const attrs = yield* sharedStack.deploy(
        Effect.gen(function* () {
          return yield* AccountTestFunction;
        }).pipe(Effect.provide(AccountTestFunctionLive)),
      );

      expect(attrs.functionUrl).toBeTruthy();
      baseUrl = attrs.functionUrl!.replace(/\/+$/, "");

      const readinessUrl = `${baseUrl}/bindings`;
      yield* Effect.logInfo(
        `Account test setup: probing readiness at ${readinessUrl}`,
      );
      yield* HttpClient.get(readinessUrl).pipe(
        Effect.flatMap((response) =>
          response.status === 200
            ? Effect.succeed(response)
            : Effect.fail(new Error(`Function not ready: ${response.status}`)),
        ),
        Effect.tapError((error) =>
          Effect.logWarning(
            `Account test setup: fixture not ready yet (${String(error)})`,
          ),
        ),
        Effect.retry({ schedule: readinessPolicy }),
      );
    }),
    { timeout: 240_000 },
  );

  afterAll(sharedStack.destroy(), { timeout: 120_000 });

  describe("binding registration", () => {
    test.provider("all 5 capabilities initialize in the runtime", (_stack) =>
      Effect.gen(function* () {
        const response = (yield* getJson("/bindings")) as { bound: string[] };
        expect(response.bound).toEqual([
          "getAccountInformation",
          "getContactInformation",
          "getAlternateContact",
          "listRegions",
          "getRegionOptStatus",
        ]);
      }),
    );
  });

  describe("GetAccountInformation", () => {
    test.provider("reads the account's metadata", (_stack) =>
      Effect.gen(function* () {
        const response = (yield* getJson("/account-info")) as
          | {
              ok: true;
              accountId: string | null;
              accountState: string | null;
              hasAccountName: boolean;
            }
          | { ok: false; tag: string };
        expect(response.ok).toBe(true);
        if (response.ok) {
          expect(response.accountId).toMatch(/^\d{12}$/);
          expect(response.accountState).toBe("ACTIVE");
        }
      }),
    );
  });

  describe("GetContactInformation", () => {
    test.provider("reads the account's primary contact", (_stack) =>
      Effect.gen(function* () {
        const response = (yield* getJson("/contact-info")) as
          | { ok: true; hasFullName: boolean; hasCountryCode: boolean }
          | { ok: false; tag: string };
        expect(response.ok).toBe(true);
        if (response.ok) {
          // Every account has a primary contact with a name and country.
          expect(response.hasFullName).toBe(true);
          expect(response.hasCountryCode).toBe(true);
        }
      }),
    );
  });

  describe("GetAlternateContact", () => {
    test.provider(
      "reads the billing contact or surfaces the typed not-found tag",
      (_stack) =>
        Effect.gen(function* () {
          const response = (yield* getJson("/alternate-contact")) as
            | { ok: true; contactType: string | null }
            | { ok: false; tag: string };
          if (response.ok) {
            expect(response.contactType).toBe("BILLING");
          } else {
            // The BILLING alternate contact isn't set on the account — the
            // typed tag proves the grant (an IAM gap would surface
            // AccessDeniedException, which getJson polls away and would
            // fail the assertion below).
            expect(response.tag).toBe("ResourceNotFoundException");
          }
        }),
    );
  });

  describe("ListRegions", () => {
    test.provider("lists the account's regions with opt statuses", (_stack) =>
      Effect.gen(function* () {
        const response = (yield* getJson("/regions")) as
          | { ok: true; count: number; regionNames: string[] }
          | { ok: false; tag: string };
        expect(response.ok).toBe(true);
        if (response.ok) {
          expect(response.count).toBeGreaterThanOrEqual(1);
          expect(response.regionNames).toContain("us-east-1");
        }
      }),
    );
  });

  describe("GetRegionOptStatus", () => {
    test.provider("reads us-east-1's opt status", (_stack) =>
      Effect.gen(function* () {
        const response = (yield* getJson("/region-opt-status")) as
          | {
              ok: true;
              regionName: string | null;
              regionOptStatus: string | null;
            }
          | { ok: false; tag: string };
        expect(response.ok).toBe(true);
        if (response.ok) {
          expect(response.regionName).toBe("us-east-1");
          expect(response.regionOptStatus).toBe("ENABLED_BY_DEFAULT");
        }
      }),
    );
  });
});