Merge build/312-contract-handlers: every contract is served by its project's Durable Object or the front-page projection
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 57c8372, a92e5d4 · Browse files · 5 files·+1580 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+1580 added−0 removed
- tests:+1114 added−0 removed
- other:+466 added−0 removed
Provenance
- Commit
7026edb- Tree
3ad1769- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
57c8372- Parent 2
a92e5d4
5 files changed+1580 added−0 removed
added:apps/platform/src/adapters/rate-limits.ts+83 added
1+/**2+ * `RateLimits` adapters. `WorkerRateLimits` asks the Worker's rate-limit3+ * bindings, one per kind, keyed by the caller's handle in lowercase (handles4+ * compare without case). `MemoryRateLimits` counts in a `Ref` its layer5+ * makes, for tests: a whole test is one window, so a count never resets.6+ */7+import { sameHandle } from "@repo/protocol/ids";8+import type { Handle } from "@repo/protocol/ids";9+import { CapReached } from "@repo/protocol/refusal";10+import { Effect, Layer, Ref } from "effect";11+12+import { RateLimits } from "../rate-limits.ts";13+import type { Limited } from "../rate-limits.ts";14+15+/** How many of each kind one person may make. */16+export interface Limits {17+ readonly claim: number;18+ readonly proposal: number;19+}20+21+/**22+ * What `wrangler.jsonc` lets each binding admit per person, every 60 s, in23+ * every stage: `CLAIM_LIMIT` and `PROPOSAL_LIMIT`'s `simple.limit`. A binding24+ * can't say its own limit, so a refusal reads its cap here.25+ */26+export const WorkerCaps = { claim: 10, proposal: 5 } as const satisfies Limits;27+28+/** A refusal for one more of `kind` than `limits` allow. */29+const capped = (limits: Limits, kind: Limited) =>30+ new CapReached({ cap: limits[kind] });31+32+/**33+ * The Worker's rate limits, one binding per kind. A binding that fails is a34+ * defect: a call it could not count is not let through.35+ */36+export const WorkerRateLimits = (bindings: {37+ readonly claim: RateLimit;38+ readonly proposal: RateLimit;39+}): Layer.Layer<RateLimits> =>40+ Layer.succeed(41+ RateLimits,42+ RateLimits.of({43+ check: (kind, handle) =>44+ Effect.tryPromise(() =>45+ bindings[kind].limit({ key: handle.toLowerCase() })46+ ).pipe(47+ Effect.orDie,48+ Effect.flatMap(({ success }) =>49+ success ? Effect.void : Effect.fail(capped(WorkerCaps, kind))50+ )51+ ),52+ })53+ );54+55+/** One spend: of which kind, by whom. */56+interface Spent {57+ readonly handle: Handle;58+ readonly kind: Limited;59+}60+61+/** `limits` of each kind per person, counted in memory. */62+export const MemoryRateLimits = (limits: Limits): Layer.Layer<RateLimits> =>63+ Layer.effect(64+ RateLimits,65+ Effect.gen(function* () {66+ const spent = yield* Ref.make<readonly Spent[]>([]);67+68+ return RateLimits.of({69+ check: (kind, handle) =>70+ Effect.flatMap(71+ Ref.modify(spent, (all) => {72+ const count = all.filter(73+ (each) => each.kind === kind && sameHandle(each.handle, handle)74+ ).length;75+76+ return [count < limits[kind], [...all, { handle, kind }]];77+ }),78+ (allowed) =>79+ allowed ? Effect.void : Effect.fail(capped(limits, kind))80+ ),81+ });82+ })83+ );added:apps/platform/src/handlers.ts+356 added
1+/**2+ * The contracts' handlers: routing, the rate limit and the fan-out, nothing3+ * more (spec §4.3 `src/handlers.ts`). A contract that names a project calls4+ * that project's `ProjectApi` (its Durable Object, through `Projects`) as5+ * the caller `Authenticated` named; the cross-project reads (`listProjects`,6+ * `frontPage`, `credits`) come from the front-page projection; `status` and7+ * `today` without a project ask every project the projection lists and8+ * merge what each says. `claim`, `proposeAsk` and `flagAsk` spend the9+ * caller's rate limit first, so a call past it reaches no project.10+ *11+ * Every `remote` a caller gets back is the platform's git URL for the repo,12+ * at the origin the caller reached the platform by: never a storage URL.13+ */14+import { envSchemaMethod } from "@repo/project/deciders";15+import { FrontPage } from "@repo/project/front-page";16+import { GatewayUrl } from "@repo/project/project";17+import type { ProjectApi } from "@repo/project/project";18+import { Projects } from "@repo/project/projects";19+import { Contracts, EnvSchemaOf } from "@repo/protocol/contracts";20+import type { AnswerView } from "@repo/protocol/domain/answer";21+import type { ClaimView } from "@repo/protocol/domain/claim";22+import type { Decision, Today } from "@repo/protocol/domain/decision";23+import { sameHandle } from "@repo/protocol/ids";24+import type { ProjectName, RepoName } from "@repo/protocol/ids";25+import { CurrentPrincipal, Principal } from "@repo/protocol/principal";26+import type { Person } from "@repo/protocol/principal";27+import { NotDecider } from "@repo/protocol/refusal";28+import type { Layer } from "effect";29+import { Array, DateTime, Effect, Number, Option, Order, Stream } from "effect";30+import { HttpServerRequest } from "effect/http";31+import type { Rpc, RpcGroup } from "effect/rpc";32+33+import { RateLimits } from "./rate-limits.ts";34+35+/** How many projects a call without one asks at once. */36+const FAN_OUT = 8;37+38+/** How many events `watch` reads from its project at a time. */39+const EVENT_PAGE = 100;40+41+/** The caller, as the `Authenticated` server side named them. */42+const caller = Effect.service(CurrentPrincipal);43+44+/**45+ * The caller of a contract only a person may call. `Authenticated` lets an46+ * anonymous call reach only a `public` contract, so anyone else here is a47+ * defect in the server side, never a caller to serve.48+ */49+const person = Effect.flatMap(caller, (principal) =>50+ Principal.match(principal, {51+ Anonymous: () =>52+ Effect.die("a contract for signed-in people was called anonymously"),53+ Person: (named) => Effect.succeed<Person>(named),54+ })55+);56+57+/** The incoming request's origin: its URL's when whole, else from its host. */58+const originOf = (request: HttpServerRequest.HttpServerRequest) =>59+ URL.canParse(request.originalUrl)60+ ? Option.some(new URL(request.originalUrl).origin)61+ : Option.map(HttpServerRequest.toURL(request), ({ origin }) => origin);62+63+/**64+ * Where the caller reached the platform, which is where its git lives: the65+ * incoming request's origin, or the platform's own URL for a call that came66+ * from no request.67+ */68+const gateway = Effect.gen(function* () {69+ const request = yield* Effect.serviceOption(70+ HttpServerRequest.HttpServerRequest71+ );72+73+ return yield* Option.match(Option.flatMap(request, originOf), {74+ onNone: () => Effect.service(GatewayUrl),75+ onSome: Effect.succeed,76+ });77+});78+79+/** A repo's git URL at the gateway the caller came through. */80+const remoteOf = (repo: RepoName | ProjectName) =>81+ Effect.map(gateway, (origin) => `${origin}/${repo}.git`);82+83+/** A claim, with its fork's URL at the caller's gateway. */84+const atGateway = (claim: ClaimView) =>85+ Effect.map(remoteOf(claim.fork), (remote): ClaimView => ({86+ ...claim,87+ remote,88+ }));89+90+/** The caller's claims and answers, each claim at the caller's gateway. */91+const statusAtGateway = (status: {92+ readonly answers: readonly AnswerView[];93+ readonly claims: readonly ClaimView[];94+}) =>95+ Effect.map(Effect.forEach(status.claims, atGateway), (claims) => ({96+ answers: status.answers,97+ claims,98+ }));99+100+/** Decisions across projects: soonest to expire first, then oldest, then by project and id. */101+const byExpiry: Order.Order<Decision> = Order.combineAll([102+ Order.mapInput(DateTime.Order, ({ expiresAt }: Decision) => expiresAt),103+ Order.mapInput(DateTime.Order, ({ openedAt }: Decision) => openedAt),104+ Order.mapInput(Order.String, ({ project }: Decision) => project),105+ Order.mapInput(Order.String, ({ id }: Decision) => id),106+]);107+108+/**109+ * One decider's Today across the projects they decide in: each project's110+ * budget added up, its decisions in one order of expiry, and the rest111+ * side by side. A person who decides in none has no Today.112+ */113+const acrossProjects = (114+ decider: Person,115+ pages: readonly Today[]116+): Effect.Effect<Today, NotDecider> => {117+ const sumOf = (pick: (page: Today) => number) =>118+ Number.sumAll(pages.map(pick));119+120+ return Array.isReadonlyArrayNonEmpty(pages)121+ ? Effect.succeed({122+ budget: {123+ finishes: sumOf(({ budget }) => budget.finishes),124+ total: sumOf(({ budget }) => budget.total),125+ used: sumOf(({ budget }) => budget.used),126+ },127+ decider: decider.handle,128+ decisions: Array.sort(129+ pages.flatMap(({ decisions }) => decisions),130+ byExpiry131+ ),132+ expiringSoon: pages.flatMap(({ expiringSoon }) => expiringSoon),133+ newcomers: Array.dedupeWith(134+ pages.flatMap(({ newcomers }) => newcomers),135+ sameHandle136+ ),137+ overflow: sumOf(({ overflow }) => overflow),138+ unattended: pages.flatMap(({ unattended }) => unattended),139+ })140+ : Effect.fail(new NotDecider({}));141+};142+143+/**144+ * Every contract, served by the project it names or by the projection. A145+ * missing contract is a type error here (`Contracts.toLayer`).146+ */147+export const Handlers: Layer.Layer<148+ Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>,149+ never,150+ Projects | FrontPage | RateLimits151+> = Contracts.toLayer(152+ Effect.gen(function* () {153+ const projects = yield* Projects;154+ const frontPage = yield* FrontPage;155+ const rateLimits = yield* RateLimits;156+157+ /** `call` on the project named `project`; one never made is `UnknownProject`. */158+ const on = <A, E>(159+ project: ProjectName,160+ call: (api: ProjectApi) => Effect.Effect<A, E>161+ ) => Effect.flatMap(projects.get(project), call);162+163+ /**164+ * `call` on every project the projection lists, in name order. A165+ * project the platform never made adds nothing, and so does one where166+ * `call` finds nothing for the caller; any other failure is the call's.167+ */168+ const everywhere = <A, E>(169+ call: (api: ProjectApi) => Effect.Effect<Option.Option<A>, E>170+ ) =>171+ Effect.gen(function* () {172+ const listed = yield* frontPage.projects();173+174+ const names = Array.sort(175+ Array.dedupe(listed.map(({ project }) => project)),176+ Order.String177+ );178+179+ const each = yield* Effect.forEach(180+ names,181+ (project) =>182+ Effect.flatMap(183+ Effect.option(projects.get(project)),184+ Option.match({ onNone: () => Effect.succeedNone, onSome: call })185+ ),186+ { concurrency: FAN_OUT }187+ );188+189+ return Array.getSomes(each);190+ });191+192+ return {193+ claim: ({ ask, project }) =>194+ Effect.gen(function* () {195+ const who = yield* person;196+197+ yield* rateLimits.check("claim", who.handle);198+199+ const { claim } = yield* on(project, (api) => api.claim(who, ask));200+201+ return { claim: yield* atGateway(claim) };202+ }),203+ credits: ({ handle }) =>204+ Effect.map(frontPage.credits(handle), (credits) => ({ credits })),205+ decide: ({ project, ...input }) =>206+ Effect.flatMap(person, (who) =>207+ on(project, (api) => api.decide(who, input))208+ ),209+ [EnvSchemaOf._tag]: ({ project }) =>210+ Effect.flatMap(caller, (who) =>211+ on(project, (api) => api[envSchemaMethod](who))212+ ),213+ finish: ({ project, ...input }) =>214+ Effect.flatMap(person, (who) =>215+ on(project, (api) => api.finish(who, input))216+ ),217+ flagAsk: ({ project, ...input }) =>218+ Effect.gen(function* () {219+ const who = yield* person;220+221+ yield* rateLimits.check("proposal", who.handle);222+223+ return yield* on(project, (api) => api.flagAsk(who, input));224+ }),225+ fork: ({ project }) =>226+ Effect.gen(function* () {227+ const who = yield* person;228+ const { fork } = yield* on(project, (api) => api.fork(who));229+230+ return { fork, remote: yield* remoteOf(fork) };231+ }),232+ frontPage: (filter) =>233+ Effect.map(frontPage.entries(filter), (entries) => ({ entries })),234+ initProject: ({ project, ...input }) =>235+ Effect.gen(function* () {236+ const who = yield* person;237+238+ // A project an earlier call made but could not start is this239+ // call's to start; one already started refuses it itself.240+ const api = yield* projects241+ .create(project)242+ .pipe(243+ Effect.catchTag("ProjectExists", () =>244+ Effect.orDie(projects.get(project))245+ )246+ );247+248+ const made = yield* api.initProject(who, input);249+250+ return { ...made, remote: yield* remoteOf(made.project) };251+ }),252+ land: ({ project, ...input }) =>253+ Effect.flatMap(person, (who) =>254+ on(project, (api) => api.land(who, input))255+ ),256+ landing: ({ project, sha }) =>257+ Effect.flatMap(caller, (who) =>258+ on(project, (api) => api.landing(who, sha))259+ ),260+ ledger: ({ project }) =>261+ Effect.flatMap(caller, (who) => on(project, (api) => api.ledger(who))),262+ listAsks: ({ project }) =>263+ Effect.flatMap(caller, (who) =>264+ on(project, (api) => api.listAsks(who))265+ ),266+ listProjects: () =>267+ Effect.map(frontPage.projects(), (listed) => ({ projects: listed })),268+ openAsk: ({ project, ...input }) =>269+ Effect.flatMap(person, (who) =>270+ on(project, (api) => api.openAsk(who, input))271+ ),272+ proposeAsk: ({ project, ...input }) =>273+ Effect.gen(function* () {274+ const who = yield* person;275+276+ yield* rateLimits.check("proposal", who.handle);277+278+ return yield* on(project, (api) => api.proposeAsk(who, input));279+ }),280+ release: ({ ask, project }) =>281+ Effect.flatMap(person, (who) =>282+ on(project, (api) => api.release(who, ask))283+ ),284+ setEnv: ({ project, ...input }) =>285+ Effect.flatMap(person, (who) =>286+ on(project, (api) => api.setEnv(who, input))287+ ),288+ showAsk: ({ ask, project }) =>289+ Effect.flatMap(caller, (who) =>290+ on(project, (api) => api.showAsk(who, ask))291+ ),292+ status: ({ project }) =>293+ Effect.gen(function* () {294+ const who = yield* person;295+296+ if (project !== undefined) {297+ return yield* statusAtGateway(298+ yield* on(project, (api) => api.status(who))299+ );300+ }301+302+ const each = yield* everywhere((api) =>303+ Effect.map(api.status(who), Option.some)304+ );305+306+ return yield* statusAtGateway({307+ answers: each.flatMap(({ answers }) => answers),308+ claims: each.flatMap(({ claims }) => claims),309+ });310+ }),311+ submitAnswer: ({ project, ...input }) =>312+ Effect.flatMap(person, (who) =>313+ on(project, (api) => api.submitAnswer(who, input))314+ ),315+ today: ({ project }) =>316+ Effect.gen(function* () {317+ const who = yield* person;318+319+ if (project !== undefined) {320+ return yield* on(project, (api) => api.today(who));321+ }322+323+ // A project the caller decides nothing in has no page for them.324+ const pages = yield* everywhere((api) =>325+ api.today(who).pipe(326+ Effect.map(Option.some),327+ Effect.catchTag("NotDecider", () => Effect.succeedNone)328+ )329+ );330+331+ return yield* acrossProjects(who, pages);332+ }),333+ verdict: ({ project, ...input }) =>334+ Effect.flatMap(caller, (who) =>335+ on(project, (api) => api.verdict(who, input))336+ ),337+ vouch: ({ project, ...input }) =>338+ Effect.flatMap(person, (who) =>339+ on(project, (api) => api.vouch(who, input))340+ ),341+ watch: ({ project, since = 0 }) =>342+ Stream.unwrap(343+ Effect.map(projects.get(project), (api) =>344+ Stream.paginate(since, (after) =>345+ Effect.map(api.events(after, EVENT_PAGE), (rows) => [346+ rows.map(({ event }) => event),347+ rows.length < EVENT_PAGE348+ ? Option.none()349+ : Option.fromUndefinedOr(rows.at(-1)?.seq),350+ ])351+ )352+ )353+ ),354+ };355+ })356+);added:apps/platform/src/rate-limits.ts+27 added
123456789101112131415161718192021222324252627/** * The `RateLimits` port: how often one person may claim and propose across * the platform, whatever project they call (synthesis §4.3 row 36). It sits * in front of the projects' own caps: a call past it reaches no project. * A flag on an ask is a proposal, so it spends the proposal limit. * * Adapters: `WorkerRateLimits` over the Worker's rate-limit bindings, and * `MemoryRateLimits` for tests (both in `adapters/rate-limits.ts`). */import type { Handle } from "@repo/protocol/ids";import type { CapReached } from "@repo/protocol/refusal";import { Context } from "effect";import type { Effect } from "effect";
/** What a rate limit counts: claims, or proposals (flags among them). */export type Limited = "claim" | "proposal";
export class RateLimits extends Context.Service< RateLimits, { /** Spends one of `handle`'s `kind`; past the limit, `CapReached`. */ readonly check: ( kind: Limited, handle: Handle ) => Effect.Effect<void, CapReached>; }>()("platform/RateLimits") {}added:apps/platform/test/handlers.fixtures.ts+199 added
1+/**2+ * The world the contracts' handlers run over in tests: `ProjectsMemory`3+ * over memory adapters (the isomorphic-git Lander on `RepoHostMemory`, a4+ * Checker that fails every lane by an assertion, a rules evaluator that5+ * returns each scenario's policy), a seeded `FrontPageMemory`, and memory6+ * rate limits. `seeded` makes a scenario's project the way its initializer7+ * would: made, its first commit pushed, and each of its asks opened red8+ * first. Callers reach the handlers through the in-process RPC client, each9+ * as the person `as` names.10+ */11+import { RefName, RepoHost } from "@repo/artifacts/repo-host";12+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";13+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";14+import { CheckRunner } from "@repo/checks/check-runner";15+import { AlarmsMemory } from "@repo/project/alarms/memory";16+import { AnswerRunsInline } from "@repo/project/answer-runs/inline";17+import type { FrontPageSeed } from "@repo/project/front-page/memory";18+import { FrontPageMemory } from "@repo/project/front-page/memory";19+import { LanderIsogit } from "@repo/project/lander/isogit";20+import { FinishersFromChecks } from "@repo/project/project";21+import { ProjectionMemory } from "@repo/project/projection/memory";22+import { Projects } from "@repo/project/projects";23+import { ProjectsMemory } from "@repo/project/projects/memory";24+import { Contracts } from "@repo/protocol/contracts";25+import type { Ask } from "@repo/protocol/domain/ask";26+import { CheckSpec } from "@repo/protocol/domain/check";27+import type { Policy } from "@repo/protocol/domain/policy";28+import { Handle, RepoName, RepoPath } from "@repo/protocol/ids";29+import { Person } from "@repo/protocol/principal";30+import { asPerson } from "@repo/protocol/testing";31+import { Finishers } from "@repo/rules/finish";32+import { RulesEvaluator } from "@repo/rules/rules-evaluator";33+import { gitClient } from "@repo/testkit/git-client";34+import type { Files } from "@repo/testkit/git-client";35+import type { Scenario } from "@repo/testkit/scenarios";36+import { Array, Effect, Layer, Option } from "effect";37+import { RpcTest } from "effect/rpc";38+39+import { MemoryRateLimits } from "../src/adapters/rate-limits.ts";40+41+const mainRef = RefName.make("refs/heads/main");42+43+/** A library of four small packages, as each project's first commit holds it. */44+const start = (name: string): Files => [45+ ["package.json", `{ "name": "${name}", "workspaces": ["packages/*"] }\n`],46+ [47+ "packages/format/src/format.ts",48+ "export const format = (d) => String(d);\n",49+ ],50+ ["packages/lexer/src/lex.ts", "export const lex = (s) => s.split(' ');\n"],51+ ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],52+ ["packages/trim/src/trim.ts", "export const trim = (s) => s;\n"],53+];54+55+/** An ask's own files: its file in the config folder, and its check. */56+const askFiles = ({ check, file, id, territory }: Ask) =>57+ Array.make(58+ { content: `export default "${id}";\n`, path: file },59+ {60+ content: [61+ `import { expect, it } from "vitest";`,62+ `import { ${territory.module} } from "../src/${territory.module}.ts";`,63+ ``,64+ `it("${id}", () => {`,65+ ` expect(${territory.module}("2026-10-07")).toStrictEqual({ year: 2026 });`,66+ `});`,67+ ``,68+ ].join("\n"),69+ path: CheckSpec.guards.RedThenGreen(check)70+ ? check.path71+ : RepoPath.make(`test/${id}.test.ts`),72+ }73+ );74+75+/**76+ * A Checker before any answer: every lane fails by the same assertion each77+ * time, so every ask a test opens is red first on main.78+ */79+const allRed = Layer.succeed(80+ CheckRunner,81+ CheckRunner.of({82+ run: ({ lanes }) =>83+ Effect.succeed({84+ durationMs: lanes.length,85+ evidence: lanes.map(({ lane }) => ({86+ lane,87+ signature: `${lane}: red`,88+ })),89+ heldBack: [],90+ lanes: lanes.map(({ command, lane }) => ({91+ command,92+ durationMs: 1,93+ lane,94+ result: "failed" as const,95+ })),96+ }),97+ })98+);99+100+/**101+ * A `RulesEvaluator` that evaluates nothing: for a project it returns its102+ * scenario's policy, holding the asks whose files the commit's config folder103+ * has, and the judge closure `checks` derives.104+ */105+const rulesOf = (scenarios: readonly Scenario[]) =>106+ Layer.effect(107+ RulesEvaluator,108+ Effect.gen(function* () {109+ const finishers = yield* Finishers;110+111+ return RulesEvaluator.of({112+ call: () => Effect.succeed(false),113+ evaluate: ({ at, facts, modules }) =>114+ Effect.sync(() => {115+ const { policy } = Option.getOrThrow(116+ Array.findFirst(117+ scenarios,118+ ({ project }) => project === facts.project119+ )120+ );121+122+ return {123+ ...policy,124+ asks: policy.asks.filter(({ file }) => file in modules.modules),125+ at,126+ judge: finishers.judgeClosure(policy.run, facts.ci),127+ } satisfies Policy;128+ }),129+ });130+ })131+ ).pipe(Layer.provide(FinishersFromChecks));132+133+/** What the world is made of besides its scenarios' projects. */134+export interface WorldOptions {135+ /** What the front page reads back; nothing by default. */136+ readonly frontPage?: FrontPageSeed;137+ /** Claims and proposals each person may make; 100 of each by default. */138+ readonly limits?: { readonly claim: number; readonly proposal: number };139+}140+141+const noFrontPage: FrontPageSeed = { credits: [], entries: [], projects: [] };142+143+/**144+ * The ports the handlers run on, `RepoHost` beside them for `seeded`, fresh145+ * for each test.146+ */147+export const worldOf = (148+ scenarios: readonly Scenario[],149+ options: WorldOptions = {}150+) =>151+ Layer.mergeAll(152+ ProjectsMemory.pipe(153+ Layer.provide(154+ Layer.mergeAll(155+ AlarmsMemory,156+ AnswerRunsInline,157+ ProjectionMemory,158+ rulesOf(scenarios)159+ ).pipe(Layer.provideMerge(LanderIsogit), Layer.provideMerge(allRed))160+ )161+ ),162+ FrontPageMemory.layer(options.frontPage ?? noFrontPage),163+ MemoryRateLimits(options.limits ?? { claim: 100, proposal: 100 })164+ ).pipe(Layer.provideMerge(RepoHostMemory));165+166+/**167+ * The scenario's project as its initializer makes it: made, its first168+ * commit pushed to `main`, then each of its asks opened, red first.169+ */170+export const seeded = (scenario: Scenario) =>171+ Effect.gen(function* () {172+ const host = yield* RepoHost;173+ const api = yield* (yield* Projects).create(scenario.project);174+ const initializer = Person.make({ handle: scenario.initializer });175+ const repo = RepoName.make(scenario.project);176+ const client = yield* gitClient(memoryFs());177+178+ yield* api.initProject(initializer, {});179+180+ const first = yield* client.commit("Start", start(scenario.project), []);181+182+ yield* host.push(repo, client.source, [183+ { from: Option.none(), ref: mainRef, to: first },184+ ]);185+186+ yield* api.recordFirstPush(initializer, first);187+188+ yield* Effect.forEach(189+ scenario.policy.asks,190+ (ask) => api.openAsk(initializer, { ask: ask.id, files: askFiles(ask) }),191+ { discard: true }192+ );193+ }).pipe(Effect.orDie);194+195+/** A client of the contracts in process, each call made as `handle`. */196+export const as = (handle: string) =>197+ RpcTest.makeClient(Contracts).pipe(198+ Effect.provide(asPerson(Handle.make(handle)))199+ );added:apps/platform/test/handlers.test.ts+915 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Brand } from "@repo/brand";4+import type { FrontPageSeed } from "@repo/project/front-page/memory";5+import { Projects } from "@repo/project/projects";6+import { Contracts } from "@repo/protocol/contracts";7+import { DecisionSubject } from "@repo/protocol/domain/decision";8+import type { Decision } from "@repo/protocol/domain/decision";9+import type { FrontPageEntry } from "@repo/protocol/domain/front-page";10+import type { Proposal } from "@repo/protocol/domain/proposal";11+import {12+ AskId,13+ CommitSha,14+ EnvKey,15+ Handle,16+ KindName,17+ ProjectName,18+ RepoPath,19+ RequestId,20+} from "@repo/protocol/ids";21+import {22+ Anonymous,23+ Authenticated,24+ CurrentPrincipal,25+ Person,26+} from "@repo/protocol/principal";27+import {28+ AskFull,29+ CapReached,30+ NotClaimed,31+ NotDecider,32+ NotSensitive,33+ ProjectExists,34+ UnknownCommit,35+ UnknownProject,36+} from "@repo/protocol/refusal";37+import { advanceTo } from "@repo/testkit/clock";38+import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";39+import {40+ Array,41+ DateTime,42+ Effect,43+ Exit,44+ FileSystem,45+ Layer,46+ Redacted,47+ Result,48+ Stream,49+} from "effect";50+import { HttpServerRequest } from "effect/http";51+import { RpcTest } from "effect/rpc";52+53+import { WorkerCaps, WorkerRateLimits } from "../src/adapters/rate-limits.ts";54+import { Handlers } from "../src/handlers.ts";55+import { RateLimits } from "../src/rate-limits.ts";56+import { as, seeded, worldOf } from "./handlers.fixtures.ts";57+import type { WorldOptions } from "./handlers.fixtures.ts";58+59+const people = ["bob", "carol"];60+61+/** datekit: alice decides; bob and carol are vouched for. */62+const datekit = aProject({ people }).pipe(63+ withVouches(people),64+ withAsk({ id: "parse-iso", territory: "packages/parser" }),65+ withAsk({ id: "trim-input", territory: "packages/trim" })66+);67+68+/** burrow: alice decides here too; one ask of its own. */69+const burrow = aProject({ name: "burrow", people }).pipe(70+ withVouches(people),71+ withAsk({ id: "lex-tokens", territory: "packages/lexer" })72+);73+74+const parseIso = AskId.make("parse-iso");75+76+const trimInput = AskId.make("trim-input");77+78+const lexTokens = AskId.make("lex-tokens");79+80+const nowhere = ProjectName.make("nowhere");81+82+/**83+ * Both projects as the projection lists them, and one it lists that the84+ * platform never made, which a call across projects passes over.85+ */86+const listed: FrontPageSeed["projects"] = [87+ { openAsks: 2, posture: "open", project: datekit.project },88+ { openAsks: 1, posture: "open", project: burrow.project },89+ { openAsks: 0, posture: "open", project: nowhere },90+];91+92+/** The handlers over both projects' world. */93+const platform = (options: WorldOptions = {}) =>94+ Handlers.pipe(Layer.provideMerge(worldOf([datekit, burrow], options)));95+96+/** Both projects made, at the scenarios' noon. */97+const made = Effect.gen(function* () {98+ yield* advanceTo("2026-10-07T12:00:00Z");99+ yield* seeded(datekit);100+ yield* seeded(burrow);101+});102+103+/** A call made while serving an HTTP request that reached the platform at `url`. */104+const reachedAt =105+ (url: string) =>106+ <A, E, R>(call: Effect.Effect<A, E, R>) =>107+ Effect.provideService(108+ call,109+ HttpServerRequest.HttpServerRequest,110+ HttpServerRequest.fromWeb(new Request(url, { method: "POST" }))111+ );112+113+/** The open decision on `proposal` among a Today's; none fails the test. */114+const decisionOn = (115+ decisions: readonly Decision[],116+ proposal: Pick<Proposal, "id">117+) =>118+ Effect.fromOption(119+ Array.findFirst(120+ decisions,121+ ({ subject }) =>122+ DecisionSubject.guards.OpenProposal(subject) &&123+ subject.proposal === proposal.id124+ )125+ );126+127+describe("project reads", () => {128+ it.effect("list and show a project's asks, and know no other project", () =>129+ Effect.gen(function* () {130+ yield* made;131+132+ const bob = yield* as("bob");133+134+ const asks = yield* Effect.result(135+ bob.listAsks({ project: datekit.project })136+ );137+138+ const shown = yield* Effect.result(139+ bob.showAsk({ ask: parseIso, project: datekit.project })140+ );141+142+ const elsewhere = yield* Effect.result(143+ bob.listAsks({ project: burrow.project })144+ );145+146+ expect(147+ Result.map(asks, (found) => found.asks.map(({ ask }) => ask))148+ ).toStrictEqual(Result.succeed(["parse-iso", "trim-input"]));149+ expect(150+ Result.map(shown, ({ ask, brief }) => ({151+ ask: ask.id,152+ names: brief.includes("parse-iso"),153+ }))154+ ).toStrictEqual(Result.succeed({ ask: "parse-iso", names: true }));155+ expect(156+ Result.map(elsewhere, (found) => found.asks.map(({ ask }) => ask))157+ ).toStrictEqual(Result.succeed(["lex-tokens"]));158+ expect(159+ yield* Effect.flip(bob.listAsks({ project: nowhere }))160+ ).toStrictEqual(new UnknownProject({ project: nowhere }));161+ expect(162+ yield* Effect.flip(bob.showAsk({ ask: parseIso, project: nowhere }))163+ ).toStrictEqual(new UnknownProject({ project: nowhere }));164+ }).pipe(Effect.provide(platform()))165+ );166+167+ it.effect(168+ "stream a project's events from a sequence number, and none of a project never made",169+ () =>170+ Effect.gen(function* () {171+ yield* made;172+173+ const bob = yield* as("bob");174+175+ const all = yield* Stream.runCollect(176+ bob.watch({ project: datekit.project })177+ );178+179+ const later = yield* Stream.runCollect(180+ bob.watch({ project: datekit.project, since: 1 })181+ );182+183+ expect(all.map(({ _tag }) => _tag)).toStrictEqual([184+ "AskOpened",185+ "AskOpened",186+ ]);187+ expect(later).toStrictEqual(all.slice(1));188+ expect(189+ yield* Effect.flip(Stream.runCollect(bob.watch({ project: nowhere })))190+ ).toStrictEqual(new UnknownProject({ project: nowhere }));191+ }).pipe(Effect.provide(platform()))192+ );193+194+ it.effect("replay every event of a project that has more than a page", () =>195+ Effect.gen(function* () {196+ yield* made;197+198+ const api = yield* (yield* Projects).get(datekit.project);199+ const bobs = Person.make({ handle: Handle.make("bob") });200+201+ // 60 claims, each released: 120 events after datekit's two asks opened.202+ yield* Effect.forEach(203+ Array.range(1, 60),204+ () =>205+ Effect.andThen(206+ api.claim(bobs, parseIso),207+ api.release(bobs, parseIso)208+ ),209+ { discard: true }210+ );211+212+ const bob = yield* as("bob");213+214+ const all = yield* Stream.runCollect(215+ bob.watch({ project: datekit.project })216+ );217+218+ const tail = yield* Stream.runCollect(219+ bob.watch({ project: datekit.project, since: 120 })220+ );221+222+ expect({223+ count: all.length,224+ first: all[0]?._tag,225+ last: all.at(-1)?._tag,226+ }).toStrictEqual({ count: 122, first: "AskOpened", last: "Released" });227+ expect(tail.map(({ _tag }) => _tag)).toStrictEqual([228+ "Claimed",229+ "Released",230+ ]);231+ }).pipe(Effect.provide(platform()))232+ );233+});234+235+describe("claims", () => {236+ it.effect(237+ "give the claimant a fork at the platform's git URL, and refuse a second claimant",238+ () =>239+ Effect.gen(function* () {240+ yield* made;241+242+ const alice = yield* as("alice");243+ const bob = yield* as("bob");244+245+ const { claim } = yield* alice246+ .claim({ ask: parseIso, project: datekit.project })247+ .pipe(reachedAt("https://platform-dev.example.workers.dev/rpc"));248+249+ expect({250+ claimant: claim.claimant,251+ fork: claim.fork,252+ remote: claim.remote,253+ }).toStrictEqual({254+ claimant: "alice",255+ fork: "datekit--parse-iso--alice",256+ remote:257+ "https://platform-dev.example.workers.dev/datekit--parse-iso--alice.git",258+ });259+ expect(260+ yield* Effect.flip(261+ bob.claim({ ask: parseIso, project: datekit.project })262+ )263+ ).toStrictEqual(new AskFull({ ask: parseIso }));264+ }).pipe(Effect.provide(platform()))265+ );266+267+ it.effect(268+ "name the platform's own URL for a claim made with no request to read it from",269+ () =>270+ Effect.gen(function* () {271+ yield* made;272+273+ const alice = yield* as("alice");274+275+ const { claim } = yield* alice.claim({276+ ask: parseIso,277+ project: datekit.project,278+ });279+280+ expect(claim.remote).toBe(281+ `https://${Brand.domain}/datekit--parse-iso--alice.git`282+ );283+ }).pipe(Effect.provide(platform()))284+ );285+286+ it.effect(287+ "past one person's rate limit are refused before any project hears them; another person's are not",288+ () =>289+ Effect.gen(function* () {290+ yield* made;291+292+ const alice = yield* as("alice");293+ const bob = yield* as("bob");294+295+ yield* alice.claim({ ask: parseIso, project: datekit.project });296+297+ const past = yield* Effect.flip(298+ alice.claim({ ask: trimInput, project: datekit.project })299+ );300+301+ // alice's refused claim never reached datekit, so trim-input is free.302+ const bobs = yield* bob.claim({303+ ask: trimInput,304+ project: datekit.project,305+ });306+307+ expect(past).toStrictEqual(new CapReached({ cap: 1 }));308+ expect(bobs.claim.claimant).toBe("bob");309+ }).pipe(Effect.provide(platform({ limits: { claim: 1, proposal: 5 } })))310+ );311+});312+313+describe("proposals and flags", () => {314+ it.effect("share one rate limit per person", () =>315+ Effect.gen(function* () {316+ yield* made;317+318+ const bob = yield* as("bob");319+ const carol = yield* as("carol");320+321+ const proposed = yield* bob.proposeAsk({322+ project: datekit.project,323+ want: "Parse ISO week dates.",324+ });325+326+ const flagged = yield* Effect.flip(327+ bob.flagAsk({328+ ask: parseIso,329+ project: datekit.project,330+ reason: "The want names a file.",331+ })332+ );333+334+ const carols = yield* carol.flagAsk({335+ ask: parseIso,336+ project: datekit.project,337+ reason: "The want names a file.",338+ });339+340+ expect(proposed.proposal.proposer).toBe("bob");341+ expect(flagged).toStrictEqual(new CapReached({ cap: 1 }));342+ expect({343+ flags: carols.proposal.flags,344+ proposer: carols.proposal.proposer,345+ }).toStrictEqual({ flags: "parse-iso", proposer: "carol" });346+ }).pipe(Effect.provide(platform({ limits: { claim: 5, proposal: 1 } })))347+ );348+});349+350+describe("calls that name no project", () => {351+ it.effect(352+ "show the caller's claims in every project the projection lists",353+ () =>354+ Effect.gen(function* () {355+ yield* made;356+357+ const alice = yield* as("alice");358+ const bob = yield* as("bob");359+360+ yield* alice.claim({ ask: parseIso, project: datekit.project });361+ yield* alice.claim({ ask: lexTokens, project: burrow.project });362+ yield* bob.claim({ ask: trimInput, project: datekit.project });363+364+ const status = yield* alice365+ .status({})366+ .pipe(reachedAt("https://platform-dev.example.workers.dev/rpc"));367+368+ expect(369+ status.claims.map(({ fork, remote }) => ({ fork, remote }))370+ ).toStrictEqual([371+ {372+ fork: "burrow--lex-tokens--alice",373+ remote:374+ "https://platform-dev.example.workers.dev/burrow--lex-tokens--alice.git",375+ },376+ {377+ fork: "datekit--parse-iso--alice",378+ remote:379+ "https://platform-dev.example.workers.dev/datekit--parse-iso--alice.git",380+ },381+ ]);382+ expect(status.answers).toStrictEqual([]);383+ }).pipe(384+ Effect.provide(385+ platform({386+ frontPage: { credits: [], entries: [], projects: listed },387+ })388+ )389+ )390+ );391+392+ it.effect(393+ "give a decider one Today across their projects, and anyone else none",394+ () =>395+ Effect.gen(function* () {396+ yield* made;397+398+ const alice = yield* as("alice");399+ const bob = yield* as("bob");400+ const carol = yield* as("carol");401+402+ // bob is new in both projects; datekit's second proposal opens403+ // before burrow's, so it expires first.404+ yield* bob.claim({ ask: parseIso, project: datekit.project });405+ yield* bob.claim({ ask: lexTokens, project: burrow.project });406+407+ const declined = yield* bob.proposeAsk({408+ project: datekit.project,409+ want: "Parse ISO week dates.",410+ });411+412+ yield* advanceTo("2026-10-07T12:05:00Z");413+ yield* carol.proposeAsk({414+ project: datekit.project,415+ want: "Trim tabs too.",416+ });417+ yield* advanceTo("2026-10-07T12:10:00Z");418+ yield* bob.proposeAsk({419+ project: burrow.project,420+ want: "Lex comments.",421+ });422+423+ const { decisions: inDatekit } = yield* alice.today({424+ project: datekit.project,425+ });426+427+ const first = yield* decisionOn(inDatekit, declined.proposal);428+429+ yield* alice.decide({430+ choice: "decline",431+ decision: first.id,432+ project: datekit.project,433+ });434+435+ const today = yield* alice.today({});436+437+ expect({438+ budget: today.budget,439+ decider: today.decider,440+ decisions: today.decisions.map(({ openedAt, project }) => ({441+ openedAt: DateTime.formatIso(openedAt),442+ project,443+ })),444+ expiringSoon: today.expiringSoon,445+ newcomers: today.newcomers,446+ overflow: today.overflow,447+ unattended: today.unattended,448+ }).toStrictEqual({449+ // Five decisions a day in each project; one spent in datekit.450+ budget: { finishes: 0, total: 10, used: 1 },451+ decider: "alice",452+ decisions: [453+ { openedAt: "2026-10-07T12:05:00.000Z", project: "datekit" },454+ { openedAt: "2026-10-07T12:10:00.000Z", project: "burrow" },455+ ],456+ expiringSoon: [],457+ newcomers: ["bob"],458+ overflow: 0,459+ unattended: [],460+ });461+ expect(yield* Effect.flip(bob.today({}))).toStrictEqual(462+ new NotDecider({})463+ );464+ expect(465+ yield* Effect.flip(bob.today({ project: datekit.project }))466+ ).toStrictEqual(new NotDecider({}));467+ }).pipe(468+ Effect.provide(469+ platform({470+ frontPage: { credits: [], entries: [], projects: listed },471+ })472+ )473+ )474+ );475+476+ it.effect("decide nothing when the projection lists no project", () =>477+ Effect.gen(function* () {478+ yield* made;479+480+ const alice = yield* as("alice");481+482+ expect(yield* alice.status({})).toStrictEqual({483+ answers: [],484+ claims: [],485+ });486+ expect(yield* Effect.flip(alice.today({}))).toStrictEqual(487+ new NotDecider({})488+ );489+ }).pipe(Effect.provide(platform()))490+ );491+});492+493+const entry = (494+ project: ProjectName,495+ ask: string,496+ kind: string497+): FrontPageEntry => ({498+ ask: {499+ ask: AskId.make(ask),500+ blockedBy: [],501+ claimed: false,502+ kind: KindName.make(kind),503+ territory: "parser",504+ want: `${ask}: its check passes`,505+ },506+ posture: "open",507+ project,508+ takeable: true,509+});510+511+const projection: FrontPageSeed = {512+ credits: [513+ {514+ credit: {515+ area: "parser",516+ count: 2,517+ project: datekit.project,518+ role: "Signed-off-by",519+ },520+ handle: Handle.make("bob"),521+ },522+ {523+ credit: {524+ area: "lexer",525+ count: 1,526+ project: burrow.project,527+ role: "Asked-by",528+ },529+ handle: Handle.make("alice"),530+ },531+ ],532+ entries: [533+ entry(datekit.project, "parse-iso", "fix"),534+ entry(burrow.project, "drop-legacy", "migrate"),535+ ],536+ projects: listed,537+};538+539+describe("reads across projects", () => {540+ it.effect(541+ "come from the front-page projection, without waking any project",542+ () =>543+ Effect.gen(function* () {544+ // No project is made: only the projection answers.545+ const bob = yield* as("bob");546+547+ expect(yield* bob.listProjects({})).toStrictEqual({548+ projects: listed,549+ });550+ expect(yield* bob.frontPage({})).toStrictEqual({551+ entries: projection.entries,552+ });553+ expect(554+ yield* bob.frontPage({ kind: KindName.make("migrate") })555+ ).toStrictEqual({ entries: [projection.entries[1]] });556+ expect(557+ yield* bob.credits({ handle: Handle.make("Bob") })558+ ).toStrictEqual({559+ credits: [560+ {561+ area: "parser",562+ count: 2,563+ project: datekit.project,564+ role: "Signed-off-by",565+ },566+ ],567+ });568+ }).pipe(Effect.provide(platform({ frontPage: projection })))569+ );570+});571+572+/** A server side that takes every call as nobody signed in. */573+const anonymous = Layer.succeed(Authenticated, (effect) =>574+ Effect.provideService(effect, CurrentPrincipal, Anonymous.make({}))575+);576+577+describe("each call", () => {578+ it.effect(579+ "reaches its project as the person who made it, so the project answers that person",580+ () =>581+ Effect.gen(function* () {582+ yield* made;583+584+ const alice = yield* as("alice");585+ const bob = yield* as("bob");586+ const { project } = datekit;587+588+ yield* bob.claim({ ask: parseIso, project });589+590+ const bobsStatus = yield* bob.status({ project });591+ const alicesStatus = yield* alice.status({ project });592+593+ const aliceReleases = yield* Effect.flip(594+ alice.release({ ask: parseIso, project })595+ );596+597+ const bobReleases = yield* bob.release({ ask: parseIso, project });598+599+ const bobOpens = yield* Effect.flip(600+ bob.openAsk({601+ ask: AskId.make("tidy-all"),602+ files: [603+ {604+ content: 'export default "tidy-all";\n',605+ path: RepoPath.make(`${Brand.configDir}/asks/tidy-all.ask.ts`),606+ },607+ ],608+ project,609+ })610+ );611+612+ // Until W6 gives the project a vault, no item takes a value.613+ const setPaymentsKey = {614+ key: EnvKey.make("PAYMENTS_KEY"),615+ project,616+ value: Redacted.make("not-a-real-value-0123456789abcdef"),617+ };618+619+ const bobSets = yield* Effect.flip(bob.setEnv(setPaymentsKey));620+ const aliceSets = yield* Effect.flip(alice.setEnv(setPaymentsKey));621+622+ const alicesFork = yield* alice623+ .fork({ project })624+ .pipe(reachedAt("https://platform-dev.example.workers.dev/rpc"));625+626+ const { proposal } = yield* bob.proposeAsk({627+ project,628+ want: "Parse ISO week dates.",629+ });630+631+ const today = yield* alice.today({ project });632+633+ const decision = yield* decisionOn(today.decisions, proposal);634+635+ const bobDecides = yield* Effect.flip(636+ bob.decide({ choice: "decline", decision: decision.id, project })637+ );638+639+ const aliceDecides = yield* alice.decide({640+ choice: "decline",641+ decision: decision.id,642+ project,643+ });644+645+ expect({646+ aliceDecides: aliceDecides.decision.decided?.by,647+ aliceReleases,648+ aliceSets,649+ alicesClaims: alicesStatus.claims,650+ alicesFork,651+ bobDecides,652+ bobOpens,653+ bobReleases,654+ bobSets,655+ bobsClaims: bobsStatus.claims.map(({ claimant }) => claimant),656+ }).toStrictEqual({657+ aliceDecides: "alice",658+ aliceReleases: NotClaimed.of(parseIso),659+ aliceSets: new NotSensitive({ key: setPaymentsKey.key }),660+ alicesClaims: [],661+ alicesFork: {662+ fork: "datekit--me--alice",663+ remote:664+ "https://platform-dev.example.workers.dev/datekit--me--alice.git",665+ },666+ bobDecides: new NotDecider({}),667+ bobOpens: new NotDecider({}),668+ bobReleases: { released: true },669+ bobSets: new NotDecider({}),670+ bobsClaims: ["bob"],671+ });672+ }).pipe(Effect.provide(platform()))673+ );674+675+ it.effect(676+ "reaches the project it names, not another, for every other read and write",677+ () =>678+ Effect.gen(function* () {679+ yield* made;680+681+ const bob = yield* as("bob");682+ const { project } = burrow;683+ const unseen = CommitSha.make("0".repeat(40));684+ const requestId = RequestId.make("request-0001");685+ const answer = { base: unseen, head: unseen, project, requestId };686+687+ const ledger = yield* bob.ledger({ project });688+ const envItems = yield* bob.envShape({ project });689+ const verdict = yield* bob.verdict({ ask: lexTokens, project });690+691+ const landing = yield* Effect.flip(692+ bob.landing({ project, sha: unseen })693+ );694+695+ const submits = yield* Effect.flip(696+ bob.submitAnswer({ ...answer, ask: lexTokens })697+ );698+699+ const finishes = yield* Effect.flip(700+ bob.finish({ ...answer, ask: lexTokens })701+ );702+703+ const lands = yield* Effect.flip(704+ bob.land({ ...answer, message: "Tidy the lexer." })705+ );706+707+ const vouches = yield* Effect.flip(708+ bob.vouch({ handle: Handle.make("dave"), project, verdict: "vouch" })709+ );710+711+ expect({712+ envItems: envItems.project,713+ finishes,714+ landing,715+ lands,716+ ledger: ledger.project,717+ submits,718+ verdict,719+ vouches,720+ }).toStrictEqual({721+ envItems: "burrow",722+ finishes: new NotDecider({}),723+ landing: new UnknownCommit({ sha: unseen }),724+ lands: new NotDecider({}),725+ ledger: "burrow",726+ submits: NotClaimed.of(lexTokens),727+ verdict: {},728+ vouches: new NotDecider({}),729+ });730+ }).pipe(Effect.provide(platform()))731+ );732+733+ it.effect(734+ "by nobody signed in reads public contracts, and can't reach one for people",735+ () =>736+ Effect.gen(function* () {737+ yield* made;738+739+ const anyone = yield* RpcTest.makeClient(Contracts).pipe(740+ Effect.provide(anonymous)741+ );742+743+ const asks = yield* anyone.listAsks({ project: datekit.project });744+745+ const claimed = yield* Effect.exit(746+ anyone.claim({ ask: parseIso, project: datekit.project })747+ );748+749+ expect(asks.asks.map(({ ask }) => ask)).toStrictEqual([750+ "parse-iso",751+ "trim-input",752+ ]);753+ expect(Exit.hasDies(claimed)).toBeTruthy();754+ }).pipe(Effect.provide(platform()))755+ );756+});757+758+describe("making a project", () => {759+ it.effect(760+ "starts it empty with its maker as its decider, at the platform's git URL, once",761+ () =>762+ Effect.gen(function* () {763+ yield* advanceTo("2026-10-07T12:00:00Z");764+765+ const carol = yield* as("carol");766+ const fresh = ProjectName.make("fresh");767+768+ const first = yield* carol769+ .initProject({ project: fresh })770+ .pipe(reachedAt("https://platform-dev.example.workers.dev/rpc"));771+772+ const again = yield* Effect.flip(carol.initProject({ project: fresh }));773+774+ expect(first).toStrictEqual({775+ project: "fresh",776+ remote: "https://platform-dev.example.workers.dev/fresh.git",777+ });778+ expect(again).toStrictEqual(new ProjectExists({ project: fresh }));779+ }).pipe(Effect.provide(platform()))780+ );781+782+ it.effect(783+ "converges: a name an import failed to fill is the next call's to start",784+ () =>785+ Effect.gen(function* () {786+ yield* advanceTo("2026-10-07T12:00:00Z");787+788+ const carol = yield* as("carol");789+ const fresh = ProjectName.make("fresh");790+791+ const failed = yield* Effect.flip(792+ carol.initProject({793+ import: { url: "https://example.com/missing.git" },794+ project: fresh,795+ })796+ );797+798+ const second = yield* carol.initProject({ project: fresh });799+800+ expect(failed._tag).toBe("ImportFailed");801+ expect(second.project).toBe("fresh");802+ }).pipe(Effect.provide(platform()))803+ );804+});805+806+/**807+ * A rate-limit binding that admits `allowed` calls per key, and keeps every808+ * key it was asked about, in order.809+ */810+const fakeLimit = (allowed: number) => {811+ const keys: string[] = [];812+813+ const binding: RateLimit = {814+ limit: ({ key }) => {815+ keys.push(key);816+817+ return Promise.resolve({818+ success: keys.filter((each) => each === key).length <= allowed,819+ });820+ },821+ };822+823+ return { binding, keys };824+};825+826+describe("the Worker's rate limits", () => {827+ it.effect(828+ "count claims and proposals apart, per person whatever the case of their handle",829+ () =>830+ Effect.gen(function* () {831+ const claims = fakeLimit(2);832+ const proposals = fakeLimit(1);833+834+ const spent = yield* RateLimits.use(({ check }) =>835+ Effect.all([836+ Effect.result(check("claim", Handle.make("Alice"))),837+ Effect.result(check("claim", Handle.make("alice"))),838+ Effect.result(check("claim", Handle.make("alice"))),839+ Effect.result(check("claim", Handle.make("bob"))),840+ Effect.result(check("proposal", Handle.make("alice"))),841+ Effect.result(check("proposal", Handle.make("alice"))),842+ ])843+ ).pipe(844+ Effect.provide(845+ WorkerRateLimits({846+ claim: claims.binding,847+ proposal: proposals.binding,848+ })849+ )850+ );851+852+ expect(spent).toStrictEqual([853+ Result.void,854+ Result.void,855+ Result.fail(new CapReached({ cap: WorkerCaps.claim })),856+ Result.void,857+ Result.void,858+ Result.fail(new CapReached({ cap: WorkerCaps.proposal })),859+ ]);860+ expect(claims.keys).toStrictEqual(["alice", "alice", "alice", "bob"]);861+ expect(proposals.keys).toStrictEqual(["alice", "alice"]);862+ })863+ );864+865+ it.effect("die when the binding fails, rather than let a call through", () =>866+ Effect.gen(function* () {867+ const broken: RateLimit = {868+ limit: () => Promise.reject(new Error("rate limiter unavailable")),869+ };870+871+ const spent = yield* Effect.exit(872+ RateLimits.use(({ check }) =>873+ check("claim", Handle.make("alice"))874+ ).pipe(875+ Effect.provide(WorkerRateLimits({ claim: broken, proposal: broken }))876+ )877+ );878+879+ expect(Exit.hasDies(spent)).toBeTruthy();880+ })881+ );882+883+ it.effect(884+ "report the caps wrangler.jsonc gives each binding, in every stage",885+ () =>886+ Effect.gen(function* () {887+ const fs = yield* FileSystem.FileSystem;888+889+ const config = yield* fs.readFileString(890+ new URL("../wrangler.jsonc", import.meta.url).pathname891+ );892+893+ const limitsOf = (name: string) =>894+ [895+ ...config.matchAll(896+ new RegExp(897+ `"name": "${name}",\\s*"namespace_id": "\\d+",\\s*"simple": \\{ "limit": (?<limit>\\d+)`,898+ "gu"899+ )900+ ),901+ ].map(({ groups }) => Number(groups?.limit));902+903+ expect(limitsOf("CLAIM_LIMIT")).toStrictEqual([904+ WorkerCaps.claim,905+ WorkerCaps.claim,906+ WorkerCaps.claim,907+ ]);908+ expect(limitsOf("PROPOSAL_LIMIT")).toStrictEqual([909+ WorkerCaps.proposal,910+ WorkerCaps.proposal,911+ WorkerCaps.proposal,912+ ]);913+ }).pipe(Effect.provide(NodeServices.layer))914+ );915+});