dev-backend.test.ts
This file
Path
apps/web/test/dev-backend.test.ts
506 lines · 14.7 KiB · TypeScript
Last changed by
Merge redesign into mainoscabrielbefore adoptioncaedd21
History of this fileTake it
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Client, Contracts } from "@repo/protocol/contracts";4import { forkRev } from "@repo/protocol/domain/code";5import { ProjectEvent } from "@repo/protocol/domain/event";6import { Handle, ProjectName } from "@repo/protocol/ids";7import {8 Context,9 DateTime,10 Duration,11 Effect,12 Equal,13 Layer,14 Stream,15} from "effect";16import type { Scope } from "effect";17import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";18import { RpcClient, RpcSerialization } from "effect/rpc";1920import { devStart } from "../src/dev/clock.ts";21import { devServer } from "../src/dev/server.ts";22import { devToken } from "../src/dev/sessions.ts";2324const PROJECTS = [25 ProjectName.make("oscabriel/burrow"),26 ProjectName.make("oscabriel/datekit"),27];2829const decider = devToken(Handle.make("ines-v"));3031const contributor = devToken(Handle.make("bram"));3233const inFreshWorld = <A, E>(34 read: (35 as: (token?: string) => Layer.Layer<Client>36 ) => Effect.Effect<A, E, Scope.Scope>37) =>38 Effect.scoped(39 Effect.gen(function* () {40 const { dispose, handler } = devServer();4142 yield* Effect.addFinalizer(() => Effect.promise(dispose));4344 const as = (token?: string) =>45 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(46 Layer.provide(47 RpcClient.layerProtocolHttp({48 transformClient: HttpClient.mapRequest((request) =>49 token === undefined50 ? request51 : HttpClientRequest.bearerToken(request, token)52 ),53 url: "http://localhost/rpc",54 })55 ),56 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),57 Layer.provide(58 Layer.succeed(FetchHttpClient.Fetch, (input, init) =>59 handler(new Request(input, init))60 )61 )62 );6364 return yield* read(as);65 })66 );6768const clientOf = (layer: Layer.Layer<Client>) =>69 Effect.map(Layer.build(layer), Context.get(Client));7071const pages = inFreshWorld((as) =>72 Effect.gen(function* () {73 const anyone = yield* clientOf(as());74 const { entries } = yield* anyone.frontPage({});75 const { projects } = yield* anyone.listProjects({});7677 return { entries, projects };78 })79);8081const instants = inFreshWorld((as) =>82 Effect.gen(function* () {83 const anyone = yield* clientOf(as());84 const ines = yield* clientOf(as(decider));85 const bram = yield* clientOf(as(contributor));8687 const events = yield* Effect.forEach(PROJECTS, (project) =>88 Stream.runCollect(anyone.watch({ project }))89 );9091 const today = yield* ines.today({});92 const { claims } = yield* bram.status({});9394 return [95 ...events96 .flat()97 .flatMap((event) => [98 event.at,99 ...(ProjectEvent.guards.Landed(event)100 ? [event.landing.landedAt]101 : []),102 ]),103 ...today.decisions.flatMap(({ expiresAt, openedAt }) => [104 openedAt,105 expiresAt,106 ]),107 ...today.unattended.map(({ landedAt }) => landedAt),108 ...claims.flatMap(({ lapsesAt, openedAt, warnsAt }) => [109 openedAt,110 warnsAt,111 lapsesAt,112 ]),113 ];114 })115);116117const landedAnswer = inFreshWorld((as) =>118 Effect.gen(function* () {119 const anyone = yield* clientOf(as());120 const ines = yield* clientOf(as(decider));121 const { unattended } = yield* ines.today({});122 const [sampled] = unattended;123124 if (sampled === undefined) {125 return yield* Effect.die("datekit has no landed answer");126 }127128 const { landing } = yield* anyone.landing({129 project: sampled.project,130 sha: sampled.sha,131 });132133 return { landing, sampled };134 })135);136137const listedWithLanding = inFreshWorld((as) =>138 Effect.gen(function* () {139 const anyone = yield* clientOf(as());140 const ines = yield* clientOf(as(decider));141 const { projects } = yield* anyone.listProjects({});142 const { unattended } = yield* ines.today({});143 const burrow = ProjectName.make("oscabriel/burrow");144145 const landed = yield* Effect.orDie(146 Effect.fromNullishOr((yield* anyone.listRefs({ project: burrow })).landed)147 );148149 // burrow has only its asks' openings, each a landing; the last is main.150 const { landing: opening } = yield* anyone.landing({151 project: burrow,152 sha: landed,153 });154155 return {156 landedAt: unattended.map(({ landedAt }) => landedAt),157 opening,158 projects,159 };160 })161);162163const listedWithLedgers = inFreshWorld((as) =>164 Effect.gen(function* () {165 const anyone = yield* clientOf(as());166 const { projects } = yield* anyone.listProjects({});167168 const ledgers = yield* Effect.forEach(PROJECTS, (project) =>169 anyone.ledger({ project })170 );171172 return { ledgers, projects };173 })174);175176const recentWithLast = inFreshWorld((as) =>177 Effect.gen(function* () {178 const anyone = yield* clientOf(as());179 const { landings } = yield* anyone.recentLandings({});180 const { projects } = yield* anyone.listProjects({});181182 const [latest] = projects.toSorted((one, other) =>183 DateTime.Order(184 other.landedAt ?? DateTime.makeUnsafe(0),185 one.landedAt ?? DateTime.makeUnsafe(0)186 )187 );188189 const { project } = yield* Effect.orDie(Effect.fromNullishOr(latest));190191 const sha = yield* Effect.orDie(192 Effect.fromNullishOr((yield* anyone.listRefs({ project })).landed)193 );194195 const { landing } = yield* anyone.landing({ project, sha });196197 const named = yield* Effect.orDie(198 Effect.fromNullishOr(landing.ask ?? landing.opened)199 );200201 const { ask } = yield* anyone.showAsk({ ask: named, project });202203 return { landing, landings, want: ask.brief.want };204 })205);206207// Each test seeds whole worlds while turbo runs every package's tests at once: near vitest's 5 s default.208const seededWorlds = { timeout: 30_000 };209210describe("the dev seed", seededWorlds, () => {211 it.live("gives two fresh worlds equal front pages and project lists", () =>212 Effect.gen(function* () {213 const first = yield* pages;214 const second = yield* pages;215216 expect(first.entries).toHaveLength(10);217 expect(first.projects.map(({ project }) => project)).toStrictEqual(218 PROJECTS219 );220 expect(Equal.equals(first, second)).toBeTruthy();221 })222 );223224 it.live("adds none of the fixtures without their switch", () =>225 Effect.gen(function* () {226 const { entries, projects } = yield* pages;227 const listed = new Set(projects.map(({ project }) => project));228229 for (const fixture of [230 "oscabriel/vellum",231 "okafor/amberlog",232 "lin-h/cinderbox",233 "okonkwo/fernwick",234 "lin-h/mossgate",235 "okafor/quillon",236 "okonkwo/tidepool",237 ]) {238 expect(listed.has(ProjectName.make(fixture))).toBeFalsy();239 }240241 expect(242 entries.every(({ project }) => PROJECTS.includes(project))243 ).toBeTruthy();244 })245 );246247 it.live("counts every time it holds in whole minutes from one start", () =>248 Effect.gen(function* () {249 const seen = yield* instants;250 const minute = Duration.toMillis(Duration.minutes(1));251252 expect(seen.length).toBeGreaterThan(20);253254 for (const instant of seen) {255 const since = Duration.toMillis(DateTime.distance(devStart, instant));256257 expect(since).toBeGreaterThanOrEqual(0);258 expect(since % minute).toBe(0);259 }260 })261 );262263 it.live(264 "lists each project with when it last landed, as D1's project list does",265 () =>266 Effect.gen(function* () {267 const { landedAt, opening, projects } = yield* listedWithLanding;268269 expect(270 projects.map(({ landedAt: at, project }) => [project, at])271 ).toStrictEqual([272 ["oscabriel/burrow", opening.landedAt],273 ["oscabriel/datekit", landedAt[0]],274 ]);275 expect(opening.opened).toBeDefined();276 expect(landedAt).toHaveLength(1);277 })278 );279280 it.live("lists each project at the posture its own ledger gives", () =>281 Effect.gen(function* () {282 const { ledgers, projects } = yield* listedWithLedgers;283284 expect(285 projects.map(({ posture, project }) => [project, posture])286 ).toStrictEqual(287 ledgers.map(({ posture, project }) => [project, posture])288 );289 // The dev world composes no visibility cartridge, so every ledger,290 // and the list with it, reads Open.291 expect(ledgers.map(({ posture }) => posture)).toStrictEqual([292 "open",293 "open",294 ]);295 })296 );297298 it.live("lands bram's answer to datekit with its credit trailers", () =>299 Effect.gen(function* () {300 const { landing, sampled } = yield* landedAnswer;301302 expect(landing).toStrictEqual(sampled);303 expect(landing.ask).toBe("diff-in-days-dst");304 expect(landing.author).toBe("bram");305 expect(306 landing.credits.map(({ handle, role }) => `${role}: ${handle}`)307 ).toStrictEqual(["Asked-by: ines-v", "Signed-off-by: bram"]);308 })309 );310311 it.live(312 "lists the latest landings across projects, the dev world's last landing first with its ask's want",313 () =>314 Effect.gen(function* () {315 const { landing, landings, want } = yield* recentWithLast;316317 expect(landings[0]?._tag).toBe("Landed");318 expect(landings[0]).toMatchObject({319 at: landing.landedAt,320 project: landing.project,321 sha: landing.sha,322 want,323 });324 expect(325 landings.map(({ at }) => DateTime.toEpochMillis(at))326 ).toStrictEqual(327 landings328 .map(({ at }) => DateTime.toEpochMillis(at))329 .toSorted((a, b) => b - a)330 );331 })332 );333334 it.live(335 "discloses the harness bram pushed through as Assisted-by, credited to nobody",336 () =>337 Effect.gen(function* () {338 const { landing } = yield* landedAnswer;339340 expect(landing.assisted).toStrictEqual([341 { harness: "claude-code", model: "haiku", verified: false },342 ]);343 expect(landing.credits.map(({ handle }) => handle)).not.toContain(344 "claude-code"345 );346 })347 );348});349350const fetched = (paths: readonly string[]) =>351 Effect.scoped(352 Effect.gen(function* () {353 const { dispose, handler } = devServer();354355 yield* Effect.addFinalizer(() => Effect.promise(dispose));356357 return yield* Effect.forEach(paths, (path) =>358 Effect.gen(function* () {359 const response = yield* Effect.promise(() =>360 handler(new Request(`http://localhost${path}`))361 );362363 return {364 cache: response.headers.get("cache-control"),365 csp: response.headers.get("content-security-policy") ?? "",366 nosniff: response.headers.get("x-content-type-options"),367 status: response.status,368 text: yield* Effect.promise(() => response.text()),369 };370 })371 );372 })373 );374375describe("the dev world's raw files", seededWorlds, () => {376 it.live(377 "answer a project's file as the platform does, and a path that climbs out with a 404",378 () =>379 Effect.gen(function* () {380 const [manifest, climbed] = yield* fetched([381 "/oscabriel/datekit/raw/main/package.json",382 "/oscabriel/datekit/raw/main/..%2F..%2Fpackage.json",383 ]);384385 expect(manifest).toMatchObject({386 cache: "public, max-age=60",387 nosniff: "nosniff",388 status: 200,389 });390 expect(manifest?.csp).toContain("sandbox");391 expect(manifest?.text).toContain('"name": "datekit"');392 expect([climbed?.status, climbed?.text]).toStrictEqual([404, ""]);393 })394 );395});396397const forkReads = inFreshWorld((as) =>398 Effect.gen(function* () {399 const anyone = yield* clientOf(as());400 const project = ProjectName.make("oscabriel/datekit");401 const { forks } = yield* anyone.listRefs({ project });402403 const answers = forks.flatMap((fork) =>404 fork.kind === "claim" && fork.ask !== undefined405 ? [forkRev({ ask: fork.ask, handle: fork.handle })]406 : []407 );408409 const read = Effect.forEach(answers, (at) =>410 Effect.gen(function* () {411 const tree = yield* anyone.readTree({ at, project });412 const { commits } = yield* anyone.log({ at, limit: 1, project });413414 const { commit } = yield* anyone.showCommit({415 at,416 project,417 sha: tree.at,418 });419420 return [tree.entries.length > 0, commits[0]?.sha, commit.sha, tree.at];421 })422 );423424 const refused = yield* Effect.flip(425 anyone.readTree({ at: "@nobody/parse-iso", project })426 );427428 return { answers, read: yield* read, refused };429 })430);431432describe("the dev world's answer forks", seededWorlds, () => {433 it.live(434 "read each at its address, and refuse an address the project does not list",435 () =>436 Effect.gen(function* () {437 const { answers, read, refused } = yield* forkReads;438439 expect(answers.length).toBeGreaterThan(0);440 expect(441 read.filter(442 ([listed, logged, shown, at]) =>443 !(listed === true && logged === at && shown === at)444 )445 ).toStrictEqual([]);446 expect(refused._tag).toBe("UnknownRevision");447 })448 );449});450451const drafted = inFreshWorld((as) =>452 Effect.gen(function* () {453 const anyone = yield* clientOf(as());454 const ines = yield* clientOf(as(decider));455 const bram = yield* clientOf(as(contributor));456 const project = ProjectName.make("oscabriel/datekit");457 const before = yield* ines.today({ project });458459 const { proposal } = yield* bram.proposeAsk({460 draft: true,461 project,462 want: "datekit reads ordinal dates such as 2026-280.",463 });464465 const shown = yield* anyone.showProposal({466 project,467 proposal: proposal.id,468 });469470 return {471 after: yield* ines.today({ project }),472 before,473 proposed: proposal,474 shown,475 };476 })477);478479describe("a draft in the dev world", seededWorlds, () => {480 it.live(481 "is drafted as it is proposed, red first on the scripted Checker, and its decision joins the maintainer's Today",482 () =>483 Effect.gen(function* () {484 const { after, before, proposed, shown } = yield* drafted;485486 // The seeded decisions expire first and fill the day's budget, so487 // the draft's decision waits on Today as its overflow.488 expect({489 files: shown.files.map(({ path }) => path),490 overflow: [before.overflow, after.overflow],491 proposed: proposed.draft?._tag,492 ready: shown.proposal.draft?._tag,493 shown: after.decisions.map(({ id }) => id),494 }).toStrictEqual({495 files: [496 `${Brand.configDir}/asks/parse-ordinal.ask.ts`,497 "test/asks/parse-ordinal.test.ts",498 ],499 overflow: [0, 1],500 proposed: "Drafting",501 ready: "Ready",502 shown: before.decisions.map(({ id }) => id),503 });504 })505 );506});