Skip to content
Myr

Merge perf/cheap into main

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 670fbca, 6f579d1 · Browse files · 15 files+393 added−29 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+393 added−29 removed

  • tests:+183 added−1 removed
  • other:+210 added−28 removed

15 files+393 added−29 removed

modified:apps/cli/test/version.test.ts+2 added
modified:apps/cli/build.ts+4 added
38 unmodified lines
39 readonly version: string;40}) => [41 "build",42 "--compile",43 // Bytecode: the binary starts by loading its bundle, and a bytecode cache44 // skips the parse of the whole bundle each start. ESM is what bytecode takes.45 "--bytecode",46 "--format=esm",47 "--minify",48 ...Object.entries(versionDefine(input.version)).flatMap(([key, value]) => [49 "--define",50 `${key}=${value}`,
362 unmodified lines
added:apps/platform/src/adapters/background.ts+19 added
modified:apps/platform/src/handlers.ts+4 added-5 removed
10 unmodified lines
11 whyOf,12} from "@repo/project/code";13import type { CodeProject } from "@repo/project/code";14import { envSchemaMethod } from "@repo/project/deciders";15import { landedProjectOf, withDescriptions } from "@repo/project/description";15import { landedProjectOf } from "@repo/project/description";16import { FrontPage } from "@repo/project/front-page";17import { withProjectFacts } from "@repo/project/listing";18import { GatewayUrl } from "@repo/project/project";19import type { ProjectApi } from "@repo/project/project";20import { Projects } from "@repo/project/projects";20import { withStandingPosture } from "@repo/project/standing-posture";21import { Contracts, EnvSchemaOf } from "@repo/protocol/contracts";22import type { AnswerView } from "@repo/protocol/domain/answer";23import type { ClaimView } from "@repo/protocol/domain/claim";24import type { Decision, Today } from "@repo/protocol/domain/decision";
239 unmodified lines
264 listPaths: ({ at, project }) =>265 code(project, (of) => pathsOf(of, Option.fromUndefinedOr(at))),266 listProjects: () =>267 frontPage.projects().pipe(268 Effect.flatMap(withStandingPosture),269 Effect.provideService(Projects, projects),268 Effect.flatMap((listed) =>271 withDescriptions(listed, (project) =>269 withProjectFacts(listed, (project) =>270 Effect.map(projects.get(project), (api) =>271 landedProjectOf(api, project)272 )273 )274 ),275 Effect.provideService(Projects, projects),276 Effect.provideService(RepoHost, host),277 Effect.map((listed) => ({ projects: listed }))278 ),279 listRefs: ({ project }) => code(project, refsOf),
114 unmodified lines
modified:apps/platform/src/project-do.ts+14 added-1 removed
7 unmodified lines
89import { DoAlarms } from "./adapters/alarms.ts";10import type { AlarmStorage } from "./adapters/alarms.ts";11import { AnswerRunsWorkflow } from "./adapters/answer-runs-workflow.ts";12import { DoBackground } from "./adapters/background.ts";13import type { BackgroundHost } from "./adapters/background.ts";14import { decodeEnv } from "./platform.ts";15import type { InvalidEnv, PlatformConfig } from "./platform.ts";16import { telemetryOf, workerPorts } from "./ports.ts";17import type { CallRequest, ExitEncoded } from "./project-calls.ts";
14 unmodified lines
32);3334export const doPorts = (input: {35 readonly config: PlatformConfig;36 readonly host: BackgroundHost;37 readonly storage: AlarmStorage;38 readonly name: Option.Option<ProjectName>;39}) =>40 Layer.mergeAll(41 workerPorts(input.config),42 DoAlarms(input.storage),43 DoBackground(input.host),44 Option.match(input.name, {45 onNone: () => Nameless,46 onSome: (project) => AnswerRunsWorkflow(input.config.ANSWER, project),47 }),
12 unmodified lines
60 return Layer.effect(61 Shell,62 projectShell({63 name: Option.getOrUndefined(name),60 ports: doPorts({ config, name, storage: ctx.storage }),64 ports: doPorts({65 config,66 host: {67 waitUntil: (promise) => {68 ctx.waitUntil(promise);69 },70 },71 name,72 storage: ctx.storage,73 }),74 // The storage itself, not `storage.sql`: transactions run through it.75 sql: SqliteClient.layer({ storage: ctx.storage }),76 })77 ).pipe(Layer.provideMerge(telemetryOf(config)));
63 unmodified lines
modified:apps/platform/test/project-do.test.ts+92 added-1 removed
4 unmodified lines
5import { RequestId } from "@repo/protocol/ids";6import { UnknownProject } from "@repo/protocol/refusal";7import { advanceTo, at } from "@repo/testkit/clock";8import { untouchable } from "@repo/testkit/untouchable";9import { Context, DateTime, Effect, Layer, Option } from "effect";9import { Context, DateTime, Deferred, Effect, Layer, Option } from "effect";1011import { AnswerRunsWorkflow } from "../src/adapters/answer-runs-workflow.ts";12import type { AnswerWorkflow } from "../src/adapters/answer-runs-workflow.ts";13import { DoBackground } from "../src/adapters/background.ts";14import { decodeEnv } from "../src/platform.ts";15import { doPorts, Project } from "../src/project-do.ts";16import { generate } from "../src/workflows/generated.ts";17import { fakeEnv } from "./fake-env.ts";
109 unmodified lines
127 }).pipe(Effect.provide(world))128 );129130 it.effect(131 "answers a push before the Answer Workflow is admitted: the start's row stays until the start returns, an alarm meanwhile starts nothing, and the row is acked once",132 () =>133 Effect.gen(function* () {134 yield* advanceTo(noon);135136 const admitted = yield* Deferred.make<string>();137 const context = yield* Effect.context();138 const { instances, workflow } = answerWorkflow();139 const pending: Promise<unknown>[] = [];140141 // Admission takes as long as the test says, as a Workflow's does.142 const slow: AnswerWorkflow = {143 ...workflow,144 create: (input) =>145 Effect.runPromiseWith(context)(146 Effect.flatMap(Deferred.await(admitted), () =>147 Effect.promise(() => workflow.create(input))148 )149 ),150 };151152 const host = {153 waitUntil: (promise: Promise<unknown>) => {154 pending.push(promise);155 },156 };157158 const shell = yield* shellOver(":memory:").pipe(159 Effect.provide(160 Layer.mergeAll(161 AnswerRunsWorkflow(slow, project),162 Layer.succeed(Instances, instances),163 DoBackground(host)164 )165 )166 );167168 const call = through(shell);169 const { landed } = yield* opening(call);170171 yield* call("claim", [bob, parseIso]);172173 const head = yield* Pusher.use((git) =>174 git.push(forkOf(bob), Option.some(landed), fixedFiles)175 );176177 const requestId = RequestId.make("req-fix0002");178 const answer = { ask: parseIso, base: landed, head, requestId };179 const receipt = yield* call("submitAnswer", [bob, answer]);180181 // The push is answered while the Workflow's admission is still awaited.182 const answered = {183 outcome: receipt.outcome._tag,184 pending: pending.length,185 tries: yield* instances.tries,186 };187188 yield* shell.alarm();189190 const alarmed = yield* instances.tries;191192 yield* Deferred.succeed(admitted, "admitted");193 yield* Effect.promise(() => Promise.all(pending));194195 const made = yield* instances.made;196197 yield* shell.alarm();198199 const replay = yield* call("submitAnswer", [bob, answer]);200201 expect(answered).toStrictEqual({202 outcome: "Checking",203 pending: 1,204 tries: 0,205 });206 expect(alarmed).toBe(0);207 expect(made).toStrictEqual([208 { id: requestId, params: { project, requestId } },209 ]);210 expect(replay).toStrictEqual(receipt);211 expect({212 restarts: yield* instances.restarts,213 tries: yield* instances.tries,214 }).toStrictEqual({ restarts: [], tries: 1 });215 }).pipe(Effect.provide(world))216 );217218 it.effect(219 "takes a nameless DO's name from the project its storage holds, and dies with neither",220 () =>221 Effect.gen(function* () {222 yield* advanceTo(noon);
122 unmodified lines
345346 const ports = yield* Layer.build(347 doPorts({348 config,349 host: untouchable("host"),350 name: Option.some(project),351 storage: untouchable("storage"),352 })353 );
5 unmodified lines
modified:apps/web/src/dev/handlers.ts+4 added-5 removed
9 unmodified lines
10 treeOf,11 whyOf,12} from "@repo/project/code";13import type { CodeProject } from "@repo/project/code";14import { landedProjectOf, withDescriptions } from "@repo/project/description";14import { landedProjectOf } from "@repo/project/description";15import { FrontPage } from "@repo/project/front-page";16import { withProjectFacts } from "@repo/project/listing";17import type { ProjectApi } from "@repo/project/project";18import { Projects } from "@repo/project/projects";18import { withStandingPosture } from "@repo/project/standing-posture";19import { Contracts, EnvSchemaOf } from "@repo/protocol/contracts";20import type { AnswerView } from "@repo/protocol/domain/answer";21import type { ClaimView } from "@repo/protocol/domain/claim";22import type { Decision, Today } from "@repo/protocol/domain/decision";
212 unmodified lines
235 listPaths: ({ at, project }) =>236 code(project, (of) => pathsOf(of, Option.fromUndefinedOr(at))),237 listProjects: () =>238 frontPage.projects().pipe(239 Effect.flatMap(withStandingPosture),240 Effect.provideService(Projects, projects),239 Effect.flatMap((listed) =>242 withDescriptions(listed, (project) =>240 withProjectFacts(listed, (project) =>241 Effect.map(projects.get(project), (api) =>242 landedProjectOf(api, project)243 )244 )245 ),246 Effect.provideService(Projects, projects),247 Effect.provideService(RepoHost, host),248 Effect.map((listed) => ({ projects: listed }))249 ),250 listRefs: ({ project }) => code(project, refsOf),
113 unmodified lines
modified:apps/web/src/routes/$owner/$project/route.tsx+10 added
127 unmodified lines
128 </ProjectFrame>129 );130};131132/**133 * How long the header's facts stand before a move between the project's pages134 * reads them again: without it the router reads the six facts on every move.135 * A reader who enters at a page with no header of its own (a new proposal)136 * and moves to a tab within this time sees the frame without a header until137 * the next read.138 */139export const HEADER_STALE_MS = 60_000;140141// One header for every page of a project, and the page's side column (`staticData.column`) under it, so both142// stay mounted as the reader moves between the project's pages.143export const Route = createFileRoute("/$owner/$project")({144 staticData: { shell: "project" },145 params: projectParams,146 loader: headerLoader((project) => projectHeader({ data: project })),147 staleTime: HEADER_STALE_MS,148 component: ProjectLayout,149});
modified:apps/web/vite.config.ts+9 added-1 removed
93 unmodified lines
94 // The Worker's own code is minified like the browser's: about a third95 // of its bytes. Its source maps go up with each deploy96 // (`upload_source_maps` in wrangler.jsonc), so a stack trace in the97 // Worker's logs still names the source.98 environments: { ssr: { build: { minify: true, sourcemap: true } } },98 environments: {99 ssr: {100 build: { minify: true, sourcemap: true },101 // The first page waited on Vite transforming the Worker's modules on102 // demand (ten to twenty-five seconds, by the machine's load);103 // transformed as the dev server starts, it waits on a fraction.104 dev: { warmup: ["./src/server.ts", "./src/routes/**/*.tsx"] },105 },106 },107 };108});
added:packages/project/src/background.ts+18 added
1import { Context } from "effect";2import type { Effect } from "effect";34export interface BackgroundApi {5 /** Runs the work, which a call asked for, once the call can answer. */6 readonly run: (work: Effect.Effect<void>) => Effect.Effect<void>;7}89/**10 * The start of an answer run waits on a Workflow's admission, which a push's11 * reply need not: a host that lives on past a call (a Durable Object) runs it12 * in a fiber of its own. The default runs the work inline, so the start is13 * done when the call returns.14 */15export const Background = Context.Reference<BackgroundApi>(16 "project/Background",17 { defaultValue: () => ({ run: (work) => work }) }18);
added:packages/project/src/listing.ts+30 added
1import type { RepoHost } from "@repo/artifacts/repo-host";2import type { ProjectListing } from "@repo/protocol/domain/front-page";3import type { ProjectName } from "@repo/protocol/ids";4import { Array as Arr, Effect } from "effect";56import { withDescriptions } from "./description.ts";7import type { LandedProject } from "./description.ts";8import type { Projects } from "./projects.ts";9import { withStandingPosture } from "./standing-posture.ts";1011/**12 * A listing with each project's own posture and its description: two reads,13 * each of its own kept record and then of the projects it finds stale, made14 * at once, since neither waits on the other's answer.15 */16export const withProjectFacts = <E>(17 listed: readonly ProjectListing[],18 landedOf: (project: ProjectName) => Effect.Effect<LandedProject, E>19): Effect.Effect<readonly ProjectListing[], never, Projects | RepoHost> =>20 Effect.map(21 Effect.all(22 [withStandingPosture(listed), withDescriptions(listed, landedOf)],23 { concurrency: 2 }24 ),25 ([postured, described]) =>26 Arr.zipWith(described, postured, (listing, { posture }) => ({27 ...listing,28 posture,29 }))30 );
modified:packages/project/src/outbox.ts+7 added-1 removed
126 unmodified lines
127 readonly done: readonly string[];128 readonly retry: readonly OutboxRow[];129}130131/** The row tried again later, with the next backoff. */131const later = (row: OutboxRow, now: DateTime.Utc): OutboxRow => ({132export const later = (row: OutboxRow, now: DateTime.Utc): OutboxRow => ({133 ...row,134 attempts: row.attempts + 1,135 notBefore: DateTime.addDuration(now, backoff(row.attempts)),136});137138const START: OutboxBody["_tag"] = "StartAnswer";139140/** An answer's start, which runs once the call that wrote it can answer (see `Background`). */141export const isStart = (row: OutboxRow) => row.kind === START;142143interface Decoded {144 readonly body: OutboxBody;145 readonly row: OutboxRow;146}
148 unmodified lines
modified:packages/project/src/project.ts+89 added-15 removed
194 unmodified lines
195import { isStep } from "./answer-runs/steps.ts";196import { openDecision } from "./attention/decisions.ts";197import { recordOf } from "./attention/record.ts";198import { capFor, capped, mayClaim, standing } from "./attention/vouch.ts";199import { Background } from "./background.ts";200import {201 ClaimCommand,202 ClaimEffect,203 ClaimState,
66 unmodified lines
270 splitFamily,271} from "./migrate.ts";272import {273 isDue,274 isStart,275 later,276 measuredRow,277 outboxRow,278 OutboxBody,279 projectedRows,
1557 unmodified lines
1837 const visibility = yield* ProjectVisibility;1838 const envPort = yield* ProjectEnv;1839 const draftRuns = yield* DraftRuns;1840 const metrics = yield* Metrics;1841 const background = yield* Background;1842 const lock = yield* Semaphore.make(1);1843 const repo = RepoName.make(keyOf(name));18441845 const withPorts = <A, E>(effect: Effect.Effect<A, E, ProjectPorts>) =>
252 unmodified lines
20982099 return outbox;2100 });21012102 // An answer's start runs in the background (see `Background`): its row2103 // stays in the store until the start returns, so a settle meanwhile (the2104 // alarm's, or one the start itself makes) skips it, and a shell that lost2105 // the fiber runs the row again, which the run's id dedupes.2106 const starting = yield* Ref.make<ReadonlySet<string>>(new Set());21072108 const notStarting = (rows: readonly OutboxRow[]) =>2109 Effect.map(Ref.get(starting), (ids) =>2110 rows.filter((row) => !ids.has(row.id))2111 );21122113 const armAlarm = Effect.gen(function* () {2114 const h = yield* hydrate;2115 const outbox = yield* notStarting(h.outbox);21162117 const deadlines = [2118 ...h.claims.flatMap(({ state }) => Option.toArray(deadlineOf(state))),2119 ...deciderDeadlines(h),2104 ...h.outbox.map(({ notBefore }) => notBefore),2120 ...outbox.map(({ notBefore }) => notBefore),2121 ];21222123 if (Array.isReadonlyArrayNonEmpty(deadlines)) {2124 yield* alarms.set(Array.min(deadlines, DateTime.Order));2125 }2126 });21272128 const runRows = (2129 queue: AnswerQueue,2130 rows: Array.NonEmptyReadonlyArray<OutboxRow>,2131 now: DateTime.Utc2132 ) =>2133 Effect.gen(function* () {2134 const ran = yield* withPorts(2135 runOutbox(rows, queue, now, store.ackOutbox)2136 ).pipe(2137 Effect.provideService(DraftRuns, draftRuns),2138 Effect.provideService(Metrics, metrics)2139 );21402141 yield* store.ackOutbox(ran.done);21422143 if (Array.isReadonlyArrayNonEmpty(ran.retry)) {2144 yield* lock.withPermits(1)(store.commit({ outbox: ran.retry }));2145 }2146 });21472148 const startLater = (2149 queue: AnswerQueue,2150 row: OutboxRow,2151 now: DateTime.Utc2152 ) =>2153 runRows(queue, [row], now).pipe(2154 Effect.catchCause((cause) =>2155 Cause.hasInterruptsOnly(cause)2156 ? Effect.interrupt2157 : Effect.logWarning(2158 "the answer's start failed: it is tried again",2159 cause2160 ).pipe(2161 Effect.andThen(2162 lock.withPermits(1)(2163 store.commit({ outbox: [later(row, now)] })2164 )2165 )2166 )2167 ),2168 Effect.ensuring(2169 Ref.update(2170 starting,2171 (ids) => new Set([...ids].filter((id) => id !== row.id))2172 )2173 ),2174 Effect.andThen(armAlarm)2175 );21762177 const settle = (queue: AnswerQueue, rows: readonly OutboxRow[]) =>2178 Effect.gen(function* () {2179 const now = yield* DateTime.now;21802181 const due = yield* notStarting(2116 const due = Array.dedupeWith(2117 rows.filter((row) => isDue(row, now)),2118 (one, other) => one.id === other.id2182 Array.dedupeWith(2183 rows.filter((row) => isDue(row, now)),2184 (one, other) => one.id === other.id2185 )2186 );21872121 if (Array.isReadonlyArrayNonEmpty(due)) {2122 const ran = yield* withPorts(2123 runOutbox(due, queue, now, store.ackOutbox)2124 ).pipe(2125 Effect.provideService(DraftRuns, draftRuns),2126 Effect.provideService(Metrics, metrics)2127 );2188 const settled = due.filter((row) => !isStart(row));21892129 yield* store.ackOutbox(ran.done);2190 if (Array.isReadonlyArrayNonEmpty(settled)) {2191 yield* runRows(queue, settled, now);2192 }21932131 if (Array.isReadonlyArrayNonEmpty(ran.retry)) {2132 yield* lock.withPermits(1)(store.commit({ outbox: ran.retry }));2133 }2194 // Answer runs go last: they may run long, and settle their own rows.2195 const starts = due.filter(isStart);21962197 if (Array.isReadonlyArrayNonEmpty(starts)) {2198 yield* Ref.update(2199 starting,2200 (ids) => new Set([...ids, ...starts.map(({ id }) => id)])2201 );22022203 yield* Effect.forEach(2204 starts,2205 (row) => background.run(startLater(queue, row, now)),2206 { discard: true }2207 );2208 }22092210 yield* armAlarm;2211 });
3406 unmodified lines
added:packages/project/test/listing.test.ts+89 added
1import { describe, expect, it } from "@effect/vitest";2import { RepoHost } from "@repo/artifacts/repo-host";3import type { ProjectListing } from "@repo/protocol/domain/front-page";4import { ProjectName } from "@repo/protocol/ids";5import { untouchable } from "@repo/testkit/untouchable";6import {7 DateTime,8 Deferred,9 Duration,10 Effect,11 Fiber,12 Layer,13 Logger,14 Ref,15} from "effect";16import { TestClock } from "effect/testing";1718import type { LandedProject } from "../src/description.ts";19import { withProjectFacts } from "../src/listing.ts";20import type { ProjectApi } from "../src/project.ts";21import { Projects } from "../src/projects.ts";2223const datekit = ProjectName.make("alice/datekit");2425const landedAt = DateTime.makeUnsafe("2026-10-08T12:00:00Z");2627describe(withProjectFacts, () => {28 it.effect(29 "reads each project's posture and its description at once: neither read waits on the other's answer",30 () =>31 Effect.gen(function* () {32 const described = yield* Deferred.make<string>();33 const steps = yield* Ref.make<readonly string[]>([]);3435 const seen = (step: string) =>36 Ref.update(steps, (before) => [...before, step]);3738 // The posture's read ends only once the description's has begun: one39 // read after the other would wait forever.40 const api = untouchable<ProjectApi>("ProjectApi", {41 standing: () =>42 seen("posture").pipe(43 Effect.andThen(Deferred.await(described)),44 Effect.as({ posture: "open" as const, seen: 1 })45 ),46 });4748 const projects = Layer.succeed(49 Projects,50 Projects.of({51 create: () => Effect.die("a listing makes no project"),52 get: () => Effect.succeed(api),53 })54 );5556 const listed: readonly ProjectListing[] = [57 { landedAt, openAsks: 2, posture: "openCore", project: datekit },58 ];5960 const facts = withProjectFacts(61 listed,62 (): Effect.Effect<LandedProject, string> =>63 seen("description").pipe(64 Effect.andThen(Deferred.succeed(described, "described")),65 Effect.andThen(Effect.fail("the repo is not read here"))66 )67 ).pipe(68 Effect.timeout(Duration.seconds(5)),69 Effect.provide(projects),70 Effect.provideService(RepoHost, untouchable("RepoHost")),71 Effect.provide(Logger.layer([]))72 );7374 const fiber = yield* Effect.forkChild(facts);7576 yield* TestClock.adjust(Duration.seconds(10));7778 const result = yield* Fiber.join(fiber);7980 expect((yield* Ref.get(steps)).toSorted()).toStrictEqual([81 "description",82 "posture",83 ]);84 expect(result).toStrictEqual([85 { landedAt, openAsks: 2, posture: "open", project: datekit },86 ]);87 })88 );89});
modified:packages/project/package.json+2 added
3 unmodified lines
4 "type": "module",5 "exports": {6 "./claim": "./src/claim.ts",7 "./landing": "./src/landing.ts",8 "./listing": "./src/listing.ts",9 "./project-store": "./src/project-store.ts",10 "./project-store/rows": "./src/project-store/rows.ts",11 "./project-store/memory": "./src/project-store/memory.ts",12 "./project-store/sqlite": "./src/project-store/sqlite.ts",
5 unmodified lines
18 "./project": "./src/project.ts",19 "./alarms": "./src/alarms.ts",20 "./alarms/memory": "./src/alarms/memory.ts",21 "./answer-runs": "./src/answer-runs.ts",22 "./background": "./src/background.ts",23 "./answer-runs/inline": "./src/answer-runs/inline.ts",24 "./projection": "./src/projection.ts",25 "./projection/memory": "./src/projection/memory.ts",26 "./front-page": "./src/front-page.ts",
33 unmodified lines