project-do.fixtures.ts
This file
Path
apps/platform/test/project-do.fixtures.ts
422 lines · 11.5 KiB · TypeScript
Last changed by
Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
History of this fileTake it
1import { NodeServices } from "@effect/platform-node";2import { SqliteClient } from "@effect/sql-sqlite-node";3import { RefName, RepoHost } from "@repo/artifacts/repo-host";4import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";5import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";6import { CheckAt } from "@repo/checks/check-runner";7import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";8import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";9import { Lander } from "@repo/project/lander";10import { LanderIsogit } from "@repo/project/lander/isogit";11import { FinishersFromChecks } from "@repo/project/project";12import { ProjectionMemory } from "@repo/project/projection/memory";13import type { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";14import { CheckSpec } from "@repo/protocol/domain/check";15import type { Policy } from "@repo/protocol/domain/policy";16import {17 AskId,18 LandedSha,19 LaneName,20 RepoName,21 keyOf,22 RepoPath,23} from "@repo/protocol/ids";24import type { CommitSha, ProjectName } from "@repo/protocol/ids";25import { Anonymous, Person } from "@repo/protocol/principal";26import { Finishers } from "@repo/rules/finish";27import { RulesEvaluator } from "@repo/rules/rules-evaluator";28import { gitClient } from "@repo/testkit/git-client";29import type { Files } from "@repo/testkit/git-client";30import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";31import {32 Array,33 Cause,34 Context,35 Effect,36 Exit,37 FileSystem,38 Layer,39 Option,40 Predicate,41} from "effect";4243import { DoAlarms } from "../src/adapters/alarms.ts";44import type { AlarmStorage } from "../src/adapters/alarms.ts";45import { AnswerRunsWorkflow } from "../src/adapters/answer-runs-workflow.ts";46import type { AnswerWorkflow } from "../src/adapters/answer-runs-workflow.ts";47import type { AnswerParams } from "../src/answer-runs.ts";48import { decodeReply, encodeCall } from "../src/project-calls.ts";49import type {50 ArgsOf,51 ErrorOf,52 ProjectMethod,53 SuccessOf,54} from "../src/project-calls.ts";55import { projectShell } from "../src/project-shell.ts";56import type { ProjectShell } from "../src/project-shell.ts";57import { inProcessNamespace } from "./project-namespace.ts";5859const mainRef = RefName.make("refs/heads/main");6061export const scenario = aProject({ people: ["bob", "carol"] }).pipe(62 withVouches(["bob", "carol"]),63 withAsk({ id: "parse-iso", territory: "packages/parser" })64);6566export const { project } = scenario;6768export const repo = RepoName.make(keyOf(project));6970export const parseIso = AskId.make("parse-iso");7172const person = (name: string) =>73 Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });7475export const alice = person("alice");7677export const bob = person("bob");7879export const carol = person("carol");8081export const anyone = Anonymous.make({});8283export const redThenGreen = LaneName.make("redThenGreen");8485const start: Files = [86 ["package.json", '{ "name": "datekit", "workspaces": ["packages/*"] }\n'],87 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],88];8990export const askFiles = () => {91 const ask = Option.getOrThrow(92 Array.findFirst(scenario.policy.asks, ({ id }) => id === parseIso)93 );9495 return Array.make(96 { content: `export default "${parseIso}";\n`, path: ask.file },97 {98 content: [99 `import { expect, it } from "vitest";`,100 `import { parse } from "../src/parse.ts";`,101 ``,102 `it("${parseIso}", () => {`,103 ` expect(parse("2026-10-07")).toStrictEqual({ year: 2026 });`,104 `});`,105 ``,106 ].join("\n"),107 path: CheckSpec.guards.RedThenGreen(ask.check)108 ? ask.check.path109 : RepoPath.make(`test/${parseIso}.test.ts`),110 }111 );112};113114export const fixedFiles: Files = [115 ...start.filter(([path]) => path !== "packages/parser/src/parse.ts"),116 ...askFiles().map(({ content, path }) => [path, content] as const),117 [118 "packages/parser/src/parse.ts",119 "export const parse = (s) => ({ year: 2026 });\n",120 ],121];122123export const forkOf = (who: Person) =>124 RepoName.make(`${keyOf(project)}--${parseIso}--${who.handle}`);125126export class CheckScript extends Context.Service<127 CheckScript,128 {129 readonly script: (130 at: CheckAt,131 lane: LaneName,132 results: readonly LaneOutcome[]133 ) => Effect.Effect<void>;134 }135>()("test/CheckScript") {}136137export class Pusher extends Context.Service<138 Pusher,139 {140 readonly push: (141 repo: RepoName,142 parent: Option.Option<CommitSha>,143 files: Files,144 message?: string145 ) => Effect.Effect<CommitSha>;146 }147>()("test/Pusher") {}148149export class SetAlarms extends Context.Service<150 SetAlarms,151 { readonly all: Effect.Effect<readonly number[]> }152>()("test/SetAlarms") {}153154export type InstanceState = Awaited<155 ReturnType<Awaited<ReturnType<AnswerWorkflow["get"]>>["status"]>156>["status"];157158export class Instances extends Context.Service<159 Instances,160 {161 readonly end: (id: string, state: InstanceState) => Effect.Effect<void>;162 readonly made: Effect.Effect<163 readonly {164 readonly id: string;165 readonly params: typeof AnswerParams.Encoded;166 }[]167 >;168 readonly restarts: Effect.Effect<readonly string[]>;169 readonly tries: Effect.Effect<number>;170 }171>()("test/Instances") {}172173const rules = Layer.effect(174 RulesEvaluator,175 Effect.gen(function* () {176 const finishers = yield* Finishers;177 const { policy } = scenario;178179 return RulesEvaluator.of({180 call: () => Effect.succeed(false),181 evaluate: ({ at, facts, modules }) =>182 Effect.succeed({183 ...policy,184 asks: policy.asks.filter(({ file }) => file in modules.modules),185 at,186 judge: finishers.judgeClosure(policy.run, facts.ci),187 } satisfies Policy),188 });189 })190);191192const checker = Layer.effectContext(193 Effect.gen(function* () {194 // The Checker reads its script when it runs, so the test may add to it later.195 const script = new Map<string, readonly LaneResult[]>();196 const runner = yield* Layer.build(CheckRunnerMemory.layer(script));197198 return runner.pipe(199 Context.add(CheckScript, {200 script: (at, lane, results) =>201 Effect.sync(() => {202 script.set(203 scriptKey(at, lane),204 results.map((result) => ({205 command: `run ${lane}`,206 durationMs: 1,207 lane,208 result,209 }))210 );211 }),212 })213 );214 })215);216217const pusher = Layer.effect(218 Pusher,219 Effect.gen(function* () {220 const host = yield* RepoHost;221 const client = yield* gitClient(memoryFs());222223 return Pusher.of({224 push: (target, parent, files, message = "Work") =>225 Effect.gen(function* () {226 const sha = yield* client.commit(227 message,228 files,229 Option.toArray(parent)230 );231232 yield* host233 .push(target, client.source, [234 { from: parent, ref: mainRef, to: sha },235 ])236 .pipe(Effect.orDie);237238 return sha;239 }),240 });241 })242);243244const alarms = Layer.unwrap(245 Effect.sync(() => {246 const set: number[] = [];247248 const storage: AlarmStorage = {249 setAlarm: (at) => {250 set.push(Predicate.isDate(at) ? at.getTime() : at);251252 return Promise.resolve();253 },254 };255256 return Layer.merge(257 DoAlarms(storage),258 Layer.succeed(SetAlarms, { all: Effect.sync(() => [...set]) })259 );260 })261);262263export const answerWorkflow = () => {264 const made = new Map<string, typeof AnswerParams.Encoded>();265 const states = new Map<string, InstanceState>();266 const tries: string[] = [];267 const restarts: string[] = [];268269 const instance = (id: string) => ({270 id,271 restart: () => {272 restarts.push(id);273 states.set(id, "running");274275 return Promise.resolve();276 },277 status: () => Promise.resolve({ status: states.get(id) ?? "running" }),278 });279280 const workflow: AnswerWorkflow = {281 create: ({ id, params }) => {282 tries.push(id);283284 if (made.has(id)) {285 return Promise.reject(new Error(`instance ${id} already exists`));286 }287288 made.set(id, params);289 states.set(id, "running");290291 return Promise.resolve({ id });292 },293 get: (id) =>294 made.has(id)295 ? Promise.resolve(instance(id))296 : Promise.reject(new Error(`no instance ${id}`)),297 };298299 const instances = Instances.of({300 end: (id, state) =>301 Effect.sync(() => {302 states.set(id, state);303 }),304 made: Effect.sync(() => [...made].map(([id, params]) => ({ id, params }))),305 restarts: Effect.sync(() => [...restarts]),306 tries: Effect.sync(() => tries.length),307 });308309 return { instances, workflow };310};311312const answers = Layer.unwrap(313 Effect.sync(() => {314 const { instances, workflow } = answerWorkflow();315316 return Layer.merge(317 AnswerRunsWorkflow(workflow, project),318 Layer.succeed(Instances, instances)319 );320 })321);322323export const world = Layer.mergeAll(324 alarms,325 answers,326 checker,327 EvidenceStoreMemory,328 ProjectionMemory,329 pusher,330 rules331).pipe(332 Layer.provideMerge(FinishersFromChecks),333 Layer.provideMerge(LanderIsogit),334 Layer.provideMerge(RepoHostMemory)335);336337export type World = Layer.Success<typeof world>;338339export const databaseFile = FileSystem.FileSystem.pipe(340 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "project-do-" })),341 Effect.map((folder) => `${folder}/project.sqlite`),342 Effect.orDie,343 Effect.provide(NodeServices.layer)344);345346export const shellOver = (347 filename: string,348 name: Option.Option<ProjectName> = Option.some(project)349) =>350 Effect.gen(function* () {351 const ports = yield* Effect.context<World>();352353 return yield* projectShell({354 name: Option.getOrUndefined(name),355 ports: Layer.succeedContext(ports),356 sql: SqliteClient.layer({ filename }).pipe(Layer.orDie),357 });358 });359360export type Call = <M extends ProjectMethod>(361 method: M,362 args: ArgsOf<M>363) => Effect.Effect<SuccessOf<M>, ErrorOf<M>>;364365export const through =366 (shell: ProjectShell): Call =>367 (method, args) =>368 encodeCall(method, args).pipe(369 Effect.flatMap((request) => shell.call(request)),370 Effect.flatMap((reply) => decodeReply(method, reply))371 );372373export const opening = (call: Call) =>374 Effect.gen(function* () {375 yield* call("initProject", [alice, {}]);376377 const first = yield* Pusher.use((git) =>378 git.push(repo, Option.none(), start, "Start")379 );380381 const { landed } = yield* call("recordFirstPush", [alice, first]);382 const files = askFiles();383384 const { commit } = yield* Lander.use((lander) =>385 lander.compose({ files, main: landed, repo })386 ).pipe(Effect.orDie);387388 yield* CheckScript.use((scripted) =>389 scripted.script(CheckAt.cases.Commit.make({ commit }), redThenGreen, [390 "failed",391 "failed",392 ])393 );394395 return yield* call("openAsk", [alice, { ask: parseIso, files }]);396 });397398export const tipOf = (name: RepoName) =>399 Effect.gen(function* () {400 const refs = yield* (yield* RepoHost).refs(name).pipe(Effect.orDie);401402 return LandedSha.make(403 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))404 );405 });406407export const outcomeOf = <A, E, R>(effect: Effect.Effect<A, E, R>) =>408 Effect.map(409 Effect.exit(effect),410 Exit.match({411 onFailure: (cause) =>412 Option.match(Cause.findErrorOption(cause), {413 onNone: () => "died" as const,414 onSome: (refused) => ({ refused }),415 }),416 onSuccess: (value) => ({ value }),417 })418 );419420export const namespaceOf = inProcessNamespace((name) =>421 shellOver(":memory:", Option.some(name))422);