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.

6.9 KB
Raw Blame
import * as AWS from "@/AWS";
import * as Core from "@/Test/Core";
import * as Test from "@/Test/Alchemy";
import * as eventbridge from "@distilled.cloud/aws/eventbridge";
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 MediaPackageV2TestFunctionLive, {
  MediaPackageV2TestFunction,
} from "./fixtures/handler";

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

// 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;
let functionArn: 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),
      ]),
    }),
  );

const getJson = (path: string) =>
  send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(
    Effect.flatMap((r) => r.json),
  );

const postJson = (path: string) =>
  send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(
    Effect.flatMap((r) => r.json),
  );

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

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

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

      const readinessUrl = `${baseUrl}/bindings`;
      yield* Effect.logInfo(
        `MediaPackageV2 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(
            `MediaPackageV2 test setup: fixture not ready yet (${String(error)})`,
          ),
        ),
        Effect.retry({ schedule: readinessPolicy }),
      );
    }),
    { timeout: 300_000 },
  );

  afterAll.skipIf(!!process.env.NO_DESTROY)(sharedStack.destroy(), {
    timeout: 240_000,
  });

  describe("binding registration", () => {
    test.provider("all six capabilities initialize in the runtime", () =>
      Effect.gen(function* () {
        const response = (yield* getJson("/bindings")) as { bound: string[] };
        expect(response.bound).toHaveLength(6);
      }),
    );
  });

  describe("ResetChannelState", () => {
    test.provider("resetting the idle channel's ingest state succeeds", () =>
      Effect.gen(function* () {
        const response = (yield* postJson("/reset-channel")) as {
          arn?: string;
          tag?: string;
        };
        // A retained stack (NO_DESTROY) can hit MediaPackage's reset rate
        // limit; the typed tag is then the observable outcome.
        if (response.tag === undefined) {
          expect(response.arn).toContain("/channel/");
        } else {
          expect(["ConflictException", "ThrottlingException"]).toContain(
            response.tag,
          );
        }
      }),
    );
  });

  describe("ResetOriginEndpointState", () => {
    test.provider("resetting the idle endpoint's state succeeds", () =>
      Effect.gen(function* () {
        const response = (yield* postJson("/reset-endpoint")) as {
          arn?: string;
          tag?: string;
        };
        if (response.tag === undefined) {
          expect(response.arn).toContain("/originEndpoint/");
        } else {
          expect(["ConflictException", "ThrottlingException"]).toContain(
            response.tag,
          );
        }
      }),
    );
  });

  describe("ListHarvestJobs", () => {
    test.provider("enumerating the group's harvest jobs succeeds", () =>
      Effect.gen(function* () {
        const response = (yield* getJson("/harvest-jobs")) as {
          count: number;
        };
        expect(response.count).toBeGreaterThanOrEqual(0);
      }),
    );
  });

  describe("CreateHarvestJob + GetHarvestJob + CancelHarvestJob", () => {
    test.provider("create → get → cancel roundtrips (or typed rejection)", () =>
      Effect.gen(function* () {
        const response = (yield* postJson("/harvest-cycle")) as {
          created: boolean;
          status?: string;
          cancelled: boolean;
          tag?: string;
        };
        if (response.created) {
          expect([
            "QUEUED",
            "IN_PROGRESS",
            "CANCELLED",
            "COMPLETED",
            "FAILED",
          ]).toContain(response.status);
        } else {
          // The idle channel has no harvestable content; MediaPackage may
          // reject the job upfront with the typed ValidationException.
          expect(["ValidationException", "ConflictException"]).toContain(
            response.tag,
          );
        }
      }),
    );
  });

  describe("consumeHarvestJobEvents", () => {
    test.provider(
      "the deploy created an EventBridge rule targeting the function",
      () =>
        Effect.gen(function* () {
          // Out-of-band via distilled: the fixture's consumeHarvestJobEvents
          // must have materialized as a rule on the default bus with the
          // Lambda as target.
          const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
            TargetArn: functionArn,
          });
          expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
        }),
    );
  });
});