Skip to content
Myr

bindings.test.ts

This file

Path

apps/platform/test/bindings.test.ts

519 lines · 16.1 KiB · TypeScript

Last changed by

Merge infra/drop-demo into mainoscabrielbefore adoptionc49b6bf

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import type { D1Client } from "@effect/sql-d1";3import { describe, expect, expectTypeOf, it } from "@effect/vitest";4import type { RepoHostBinding } from "@repo/artifacts/repo-host/binding";5import type { CodeStoreR2 } from "@repo/project/code-store/binding";6import type { MetricsBinding } from "@repo/project/metrics/binding";7import type { RulesEvaluatorWorker } from "@repo/rules/rules-evaluator/worker";8import {9  Array,10  Effect,11  Exit,12  FileSystem,13  Order,14  Schema,15  SchemaAST,16} from "effect";1718import type { AnswerRunsWorkflow } from "../src/adapters/answer-runs-workflow.ts";19import type {20  CheckRunnerSandbox,21  SandboxBinding,22} from "../src/adapters/check-runner-sandbox.ts";23import type { DoProjects } from "../src/adapters/do-projects.ts";24import type { LanderSandbox } from "../src/adapters/lander-sandbox.ts";25import type { WorkerRateLimits } from "../src/adapters/rate-limits.ts";26import type { SignInAttemptsBinding } from "../src/auth/attempts/binding.ts";27import type { MailerBinding } from "../src/auth/mailer/binding.ts";28import type { tokenReader } from "../src/auth/provider.ts";29import {30  PlatformBindings,31  PlatformSecrets,32  PlatformVars,33} from "../src/platform.ts";34import type { PlatformConfig } from "../src/platform.ts";3536const stringEnd = (text: string, start: number) => {37  let at = start + 1;3839  while (at < text.length && text[at] !== '"') {40    at += text[at] === "\\" ? 2 : 1;41  }4243  return at + 1;44};4546const tokenEnd = (text: string, at: number) => {47  if (text[at] === '"') {48    return stringEnd(text, at);49  }5051  if (text.startsWith("//", at)) {52    const end = text.indexOf("\n", at);5354    return end === -1 ? text.length : end;55  }5657  if (text.startsWith("/*", at)) {58    const end = text.indexOf("*/", at + 2);5960    return end === -1 ? text.length : end + 2;61  }6263  return at + 1;64};6566const tokensOf = (text: string) => {67  const tokens: string[] = [];68  let at = 0;6970  while (at < text.length) {71    const end = tokenEnd(text, at);7273    tokens.push(text.slice(at, end));74    at = end;75  }7677  return tokens;78};7980const isComment = (token: string) =>81  token.startsWith("//") || token.startsWith("/*");8283const closesAfter = (tokens: readonly string[], index: number) => {84  const next = tokens.find((token, at) => at > index && token.trim() !== "");8586  return next === "]" || next === "}";87};8889const fromJsonc = (text: string) => {90  const tokens = tokensOf(text).filter((token) => !isComment(token));9192  return tokens93    .filter((token, index) => token !== "," || !closesAfter(tokens, index))94    .join("");95};9697const Bound = Schema.Array(Schema.Struct({ binding: Schema.String }));9899const Named = Schema.Array(Schema.Struct({ name: Schema.String }));100101const BindingKinds = Schema.Struct({102  ai: Schema.optionalKey(Schema.Struct({ binding: Schema.String })),103  analytics_engine_datasets: Schema.optionalKey(Bound),104  artifacts: Schema.optionalKey(Bound),105  d1_databases: Schema.optionalKey(Bound),106  durable_objects: Schema.optionalKey(Schema.Struct({ bindings: Named })),107  kv_namespaces: Schema.optionalKey(Bound),108  r2_buckets: Schema.optionalKey(Bound),109  ratelimits: Schema.optionalKey(Named),110  send_email: Schema.optionalKey(Named),111  services: Schema.optionalKey(Bound),112  worker_loaders: Schema.optionalKey(Bound),113  workflows: Schema.optionalKey(Bound),114});115116const NOT_BINDINGS: ReadonlySet<string> = new Set([117  "$schema",118  "compatibility_date",119  "compatibility_flags",120  "containers",121  "env",122  "keep_names",123  "main",124  "migrations",125  "minify",126  "name",127  "observability",128  "preview_urls",129  "secrets",130  "triggers",131  "upload_source_maps",132  "vars",133  "workers_dev",134]);135136const Block = Schema.Struct({137  ...BindingKinds.fields,138  secrets: Schema.optionalKey(139    Schema.Struct({ required: Schema.Array(Schema.String) })140  ),141  vars: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),142});143144const Raw = Schema.Record(Schema.String, Schema.Unknown);145146const readJsonc = (text: string) =>147  Schema.decodeEffect(Schema.fromJsonString(Raw))(fromJsonc(text));148149const Staged = Schema.Struct({150  env: Schema.optionalKey(Schema.Record(Schema.String, Raw)),151});152153const decodeBlock = Schema.decodeUnknownEffect(Block);154155const sorted = (names: Iterable<string>) =>156  Array.sort(Array.fromIterable(names), Order.String);157158const declaredIn = (raw: typeof Raw.Type) =>159  Effect.map(decodeBlock(raw), (block) => ({160    bindings: sorted([161      ...(block.ai === undefined ? [] : [block.ai.binding]),162      ...(block.analytics_engine_datasets ?? []).map(({ binding }) => binding),163      ...(block.artifacts ?? []).map(({ binding }) => binding),164      ...(block.d1_databases ?? []).map(({ binding }) => binding),165      ...(block.durable_objects?.bindings ?? []).map(({ name }) => name),166      ...(block.kv_namespaces ?? []).map(({ binding }) => binding),167      ...(block.r2_buckets ?? []).map(({ binding }) => binding),168      ...(block.ratelimits ?? []).map(({ name }) => name),169      ...(block.send_email ?? []).map(({ name }) => name),170      ...(block.services ?? []).map(({ binding }) => binding),171      ...(block.worker_loaders ?? []).map(({ binding }) => binding),172      ...(block.workflows ?? []).map(({ binding }) => binding),173    ]),174    secrets: sorted(block.secrets?.required ?? []),175    unknown: Object.keys(raw).filter(176      (key) => !NOT_BINDINGS.has(key) && !(key in BindingKinds.fields)177    ),178    vars: sorted(Object.keys(block.vars ?? {})),179  }));180181const fileText = (path: string) =>182  Effect.flatMap(FileSystem.FileSystem, (fs) =>183    fs.readFileString(new URL(`../${path}`, import.meta.url).pathname)184  );185186const wranglerOf = (path: string) =>187  Effect.gen(function* () {188    const raw = yield* Effect.flatMap(fileText(path), readJsonc);189190    const { env = {} } = yield* Schema.decodeUnknownEffect(Staged)(raw);191192    const top = yield* declaredIn(raw);193194    const stages = yield* Effect.forEach(195      Object.entries(env),196      ([stage, block]) =>197        Effect.map(declaredIn(block), (declared) => [stage, declared] as const)198    );199200    return { stages: Object.fromEntries(stages), top };201  });202203const keysOf = (204  fields: Readonly<Record<string, Schema.Top>>,205  only: "all" | "required" = "all"206) =>207  sorted(208    Object.entries(fields)209      .filter(210        ([, schema]) => only === "all" || !SchemaAST.isOptional(schema.ast)211      )212      .map(([key]) => key)213  );214215const sandboxEnvKeys = Effect.map(216  fileText("../sandbox/worker-configuration.d.ts"),217  (text) =>218    sorted(219      [220        ...(221          /interface __BaseEnv_Env \{(?<body>[^}]*)\}/u.exec(text)?.groups222            ?.body ?? ""223        ).matchAll(/^\s*(?<key>\w+):/gmu),224      ].flatMap(({ groups }) => (groups?.key === undefined ? [] : [groups.key]))225    )226);227228const draftLimit = (id: string) => ({229  name: "DRAFT_LIMIT",230  namespace_id: id,231  simple: { limit: 2, period: 60 },232});233234describe("a wrangler.jsonc, read as data", () => {235  it.effect(236    "loses its comments and trailing commas, a comment between a comma and its bracket too, and keeps every string whole",237    () =>238      Effect.gen(function* () {239        const text = [240          "{",241          '  "vars": {',242          '    "STAGE": "local", // the stage',243          "    // more vars go here",244          "  },",245          '  "note": "a // b, } /* c */", /* the last key */',246          "}",247        ].join("\n");248249        expect(yield* Effect.exit(readJsonc(text))).toStrictEqual(250          Exit.succeed({251            note: "a // b, } /* c */",252            vars: { STAGE: "local" },253          })254        );255      })256  );257});258259describe("the platform Worker's bindings", () => {260  it.effect(261    "are the ones its env decodes, at the top level and in every stage",262    () =>263      Effect.gen(function* () {264        const { stages, top } = yield* wranglerOf("wrangler.jsonc");265266        const decoded = {267          bindings: keysOf(PlatformBindings.fields),268          secrets: keysOf(PlatformSecrets.fields, "required"),269          unknown: [],270          vars: keysOf(PlatformVars.fields),271        };272273        expect(Object.keys(stages)).toStrictEqual(["dev-oscabriel", "prod"]);274        expect({ top, ...stages }).toStrictEqual({275          "dev-oscabriel": decoded,276          prod: decoded,277          top: decoded,278        });279      }).pipe(Effect.provide(NodeServices.layer))280  );281282  it.effect(283    "set the drafter's model, the web's address and the draft limit in every stage",284    () =>285      Effect.gen(function* () {286        const raw = yield* Effect.flatMap(287          fileText("wrangler.jsonc"),288          readJsonc289        );290291        const { env = {} } = yield* Schema.decodeUnknownEffect(Staged)(raw);292293        const DraftBlock = Schema.Struct({294          ai: Schema.Struct({ binding: Schema.String }),295          ratelimits: Schema.Array(296            Schema.Struct({297              name: Schema.String,298              namespace_id: Schema.String,299              simple: Schema.Struct({300                limit: Schema.Int,301                period: Schema.Int,302              }),303            })304          ),305          vars: PlatformVars,306        });307308        const read = (block: typeof Raw.Type | undefined) =>309          Effect.map(310            Schema.decodeUnknownEffect(DraftBlock)(block),311            ({ ai, ratelimits, vars }) => ({312              ai: ai.binding,313              draftLimit: ratelimits.find(({ name }) => name === "DRAFT_LIMIT"),314              model: vars.DRAFT_MODEL,315              web: vars.PUBLIC_WEB_URL,316            })317          );318319        const model = "@cf/moonshotai/kimi-k2.7-code";320321        expect({322          "dev-oscabriel": yield* read(env["dev-oscabriel"]),323          prod: yield* read(env.prod),324          top: yield* read(raw),325        }).toStrictEqual({326          "dev-oscabriel": {327            ai: "AI",328            draftLimit: draftLimit("1104"),329            model,330            web: "https://web-dev-oscabriel.oscargabriel.workers.dev",331          },332          prod: {333            ai: "AI",334            draftLimit: draftLimit("1304"),335            model,336            // A stand-in: on the brand's own domain, `infra/deploy.ts` passes337            // the web's address as a `--var` (`packages/config/test/deploy.test.ts`).338            web: "https://from-infra-deploy.invalid",339          },340          top: {341            ai: "AI",342            draftLimit: draftLimit("1004"),343            model,344            web: "http://localhost:5173",345          },346        });347      }).pipe(Effect.provide(NodeServices.layer))348  );349350  it.effect("keep code history in each block's own code-cache bucket", () =>351    Effect.gen(function* () {352      const raw = yield* Effect.flatMap(fileText("wrangler.jsonc"), readJsonc);353354      const { env = {} } = yield* Schema.decodeUnknownEffect(Staged)(raw);355356      const Buckets = Schema.Struct({357        r2_buckets: Schema.Array(358          Schema.Struct({ binding: Schema.String, bucket_name: Schema.String })359        ),360      });361362      const codeCache = (block: typeof Raw.Type | undefined) =>363        Effect.map(364          Schema.decodeUnknownEffect(Buckets)(block),365          ({ r2_buckets }) =>366            r2_buckets.find(({ binding }) => binding === "CODE_CACHE")367              ?.bucket_name368        );369370      expect({371        "dev-oscabriel": yield* codeCache(env["dev-oscabriel"]),372        prod: yield* codeCache(env.prod),373        top: yield* codeCache(raw),374      }).toStrictEqual({375        "dev-oscabriel": "code-cache-dev-oscabriel",376        prod: "code-cache-prod",377        top: "code-cache-local",378      });379    }).pipe(Effect.provide(NodeServices.layer))380  );381382  it.effect(383    "write domain metrics to each block's own dataset, so no stage's counts mix with another's",384    () =>385      Effect.gen(function* () {386        const raw = yield* Effect.flatMap(387          fileText("wrangler.jsonc"),388          readJsonc389        );390391        const { env = {} } = yield* Schema.decodeUnknownEffect(Staged)(raw);392393        const Datasets = Schema.Struct({394          analytics_engine_datasets: Schema.Array(395            Schema.Struct({ binding: Schema.String, dataset: Schema.String })396          ),397        });398399        const datasets = (block: typeof Raw.Type | undefined) =>400          Effect.map(401            Schema.decodeUnknownEffect(Datasets)(block),402            ({ analytics_engine_datasets }) => analytics_engine_datasets403          );404405        expect({406          "dev-oscabriel": yield* datasets(env["dev-oscabriel"]),407          prod: yield* datasets(env.prod),408          top: yield* datasets(raw),409        }).toStrictEqual({410          "dev-oscabriel": [411            { binding: "METRICS", dataset: "metrics_dev_oscabriel" },412          ],413          prod: [{ binding: "METRICS", dataset: "metrics_prod" }],414          top: [{ binding: "METRICS", dataset: "metrics_local" }],415        });416      }).pipe(Effect.provide(NodeServices.layer))417  );418419  it("are all the Env the Worker is given, and nothing else", () => {420    expectTypeOf<keyof Env>().toEqualTypeOf<421      Exclude<422        keyof PlatformConfig,423        "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET" | "SESSION_TOKENS"424      >425    >();426  });427428  it("hold the private namespace, decoded as the public one is", () => {429    expectTypeOf<Env>().toHaveProperty("ARTIFACTS_PRIVATE");430    expectTypeOf<PlatformConfig["ARTIFACTS_PRIVATE"]>().toEqualTypeOf<431      Env["ARTIFACTS_PRIVATE"]432    >();433    expectTypeOf<Env["ARTIFACTS_PRIVATE"]>().toExtend<434      Parameters<(typeof RepoHostBinding)["layer"]>[0]435    >();436  });437438  it("are each taken by its port's factory as Env types it, without a cast", () => {439    expectTypeOf<Env["ARTIFACTS"]>().toExtend<440      Parameters<(typeof RepoHostBinding)["layer"]>[0]441    >();442    expectTypeOf<Env["PROJECT"]>().toExtend<Parameters<typeof DoProjects>[0]>();443    expectTypeOf<Env["ANSWER"]>().toExtend<444      Parameters<typeof AnswerRunsWorkflow>[0]445    >();446    expectTypeOf<Env["LOADER"]>().toExtend<447      Parameters<typeof RulesEvaluatorWorker>[0]448    >();449    expectTypeOf<Env["CLAIM_LIMIT"]>().toExtend<450      Parameters<typeof WorkerRateLimits>[0]["claim"]451    >();452    expectTypeOf<Env["PROPOSAL_LIMIT"]>().toExtend<453      Parameters<typeof WorkerRateLimits>[0]["proposal"]454    >();455    expectTypeOf<Env["DRAFT_LIMIT"]>().toExtend<456      Parameters<typeof WorkerRateLimits>[0]["draft"]457    >();458    expectTypeOf<PlatformConfig["AI"]>().toEqualTypeOf<Env["AI"]>();459    expectTypeOf<Env["FRONT_PAGE"]>().toExtend<460      Parameters<typeof D1Client.layer>[0]["db"]461    >();462    expectTypeOf<Env["OAUTH_KV"]>().toExtend<463      Parameters<typeof tokenReader>[0]464    >();465    expectTypeOf<Env["SIGN_IN_LIMIT"]>().toExtend<466      Parameters<typeof SignInAttemptsBinding>[0]467    >();468    expectTypeOf<Env["EMAIL"]>().toExtend<469      Parameters<typeof MailerBinding>[0]470    >();471    expectTypeOf<Env["CODE_CACHE"]>().toExtend<472      Parameters<typeof CodeStoreR2>[0]473    >();474    expectTypeOf<PlatformConfig["CODE_CACHE"]>().toEqualTypeOf<475      Env["CODE_CACHE"]476    >();477    expectTypeOf<Env["METRICS"]>().toExtend<478      Parameters<typeof MetricsBinding>[0]479    >();480    expectTypeOf<PlatformConfig["METRICS"]>().toEqualTypeOf<Env["METRICS"]>();481  });482483  it("type the sandbox service binding by the entrypoint the platform calls", () => {484    // If the generated `Env` ever types `SANDBOX`'s methods, or turns `any`, this fails:485    // drop the `SandboxBinding` declaration, or find what made the binding untyped.486    expectTypeOf<Env["SANDBOX"]>().not.toExtend<SandboxBinding>();487    expectTypeOf<PlatformConfig["SANDBOX"]>().toExtend<Env["SANDBOX"]>();488    expectTypeOf<PlatformConfig["SANDBOX"]>().toExtend<489      Parameters<typeof CheckRunnerSandbox>[0]490    >();491    expectTypeOf<PlatformConfig["SANDBOX"]>().toExtend<492      Parameters<typeof LanderSandbox>[0]493    >();494  });495});496497describe("the sandbox Worker's bindings", () => {498  it.effect(499    "are the ones its Env gives its code, at the top level and in every stage",500    () =>501      Effect.gen(function* () {502        const { stages, top } = yield* wranglerOf("../sandbox/wrangler.jsonc");503504        const read = {505          bindings: yield* sandboxEnvKeys,506          secrets: [],507          unknown: [],508          vars: [],509        };510511        expect(Object.keys(stages)).toStrictEqual(["dev-oscabriel", "prod"]);512        expect({ top, ...stages }).toStrictEqual({513          "dev-oscabriel": read,514          prod: read,515          top: read,516        });517      }).pipe(Effect.provide(NodeServices.layer))518  );519});