Skip to content
Myr

counter.ts

This file

Path

scripts/lib/swarm/views/counter.ts

265 lines · 7.5 KiB · TypeScript

Last changed by

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

History of this file

Take it

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

lines 1–3why, one step back
1// The scripts reach the network only through processes (their allow-list grants
2// `effect/process`), so `curl` carries the call. A held stream does end (Bun's3// `fetch` at 361 s), so the counter follows again from the last event it heard.

Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8

lines 4–47why, one step back
4import { ProjectEvent } from "@repo/protocol/domain/event";
5import type { ProjectName } from "@repo/protocol/ids";6import {7 Array,8 DateTime,9 Duration,10 Effect,11 FileSystem,12 Option,13 Ref,14 Schedule,15 Schema,16 Stream,17} from "effect";18import { ChildProcess, ChildProcessSpawner } from "effect/process";1920import { run, SwarmFailed } from "../workspace.ts";2122const counted = (event: ProjectEvent) =>23 ProjectEvent.guards.Claimed(event) ||24 ProjectEvent.guards.Pushed(event) ||25 ProjectEvent.guards.Landed(event);2627export const counterLine = (events: readonly ProjectEvent[]): string => {28 const claims = events.filter(ProjectEvent.guards.Claimed).length;29 const pushes = events.filter(ProjectEvent.guards.Pushed).length;30 const landings = events.filter(ProjectEvent.guards.Landed).length;3132 return `claims ${claims} · pushes ${pushes} · landed ${landings}`;33};3435const short = (sha: string) => sha.slice(0, 7);3637const happening = (event: ProjectEvent) =>38 ProjectEvent.match(event, {39 AskClosed: () => "",40 AskOpened: () => "",41 Claimed: ({ ask, claimant }) => `${claimant} claimed ${ask}`,42 Decided: () => "",43 Judged: () => "",44 Landed: ({ landing }) =>45 `${landing.ask ?? "main"} landed as ${short(landing.sha)}`,46 Lapsed: () => "",47 LedgerAppended: () => "",

Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d

line 48why, one step back
48 ProposalDrafted: () => "",

Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8

lines 49–134why, one step back
49 ProposalOpened: () => "",
50 Pushed: ({ ask, head }) => `${ask} pushed ${short(head)}`,51 Released: () => "",52 Warned: () => "",53 });5455export const counterEntry = (56 events: readonly ProjectEvent[],57 event: ProjectEvent58) =>59 `${DateTime.formatIso(event.at).slice(11, 19)} ${counterLine(events)} ${happening(event)}`;6061const WatchCall = Schema.TaggedStruct("Request", {62 headers: Schema.Array(Schema.Tuple([Schema.String, Schema.String])),63 id: Schema.String,64 payload: Schema.Struct({65 project: Schema.String,66 since: Schema.optionalKey(Schema.Int),67 }),68 tag: Schema.Literal("watch"),69});7071const encodeCall = Schema.encodeSync(Schema.fromJsonString(WatchCall));7273const watchRequest = (project: ProjectName, since: Option.Option<number>) =>74 encodeCall(75 WatchCall.make({76 headers: [],77 id: "1",78 payload: Option.match(since, {79 onNone: () => ({ project }),80 onSome: (after) => ({ project, since: after }),81 }),82 tag: "watch",83 })84 );8586const ChunkOf = <S extends Schema.Top>(value: S) =>87 Schema.TaggedStruct("Chunk", { values: Schema.Array(value) });8889const Held = ChunkOf(Schema.Struct({ seq: Schema.Int }));9091const isHeld = Schema.is(Held);9293const decodeReplay = Schema.decodeUnknownOption(94 Schema.fromJsonString(95 Schema.Array(Schema.Union([Held, Schema.Struct({ _tag: Schema.String })]))96 )97);9899const decodeLine = Schema.decodeUnknownOption(100 Schema.fromJsonString(ChunkOf(Schema.Unknown))101);102103const eventOf = Schema.decodeUnknownOption(ProjectEvent);104105export const eventsIn = (line: string): readonly ProjectEvent[] =>106 Option.match(decodeLine(line), {107 onNone: () => [],108 onSome: ({ values }) =>109 Array.getSomes(values.map((value) => eventOf(value))),110 });111112const curlArgs = (input: {113 readonly origin: string;114 readonly contentType: string;115 readonly body: string;116}) => [117 "--silent",118 "--show-error",119 "--fail",120 "--no-buffer",121 "--request",122 "POST",123 "--header",124 `content-type: ${input.contentType}`,125 "--data-binary",126 input.body,127 `${input.origin}/rpc`,128];129130const unread = (project: ProjectName, said: string) =>131 new SwarmFailed({132 reason: `the counter couldn't read ${project}'s events: ${said.trim().slice(0, 300)}`,133 });134

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

lines 135–136why, one step back
135// A read that fails is the run's failure, not 0: a counter that started from 0
136// would count the project's whole history as the run's.

Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8

lines 137–171why, one step back
137export const lastHeld = (origin: string, project: ProjectName) =>
138 Effect.gen(function* () {139 const ran = yield* run({140 args: curlArgs({141 body: `[${watchRequest(project, Option.none())}]`,142 contentType: "application/json",143 origin,144 }),145 command: "curl",146 env: {},147 }).pipe(Effect.mapError(({ reason }) => unread(project, reason)));148149 if (ran.code !== 0) {150 return yield* unread(project, `curl exited ${ran.code}: ${ran.stderr}`);151 }152153 const frames = yield* Effect.fromOption(decodeReplay(ran.stdout)).pipe(154 Effect.mapError(() => unread(project, ran.stdout))155 );156157 return Math.max(158 0,159 ...frames.flatMap((frame) =>160 isHeld(frame) ? frame.values.map(({ seq }) => seq) : []161 )162 );163 });164165interface Tally {166 readonly last: number;167 readonly events: readonly ProjectEvent[];168}169170const FOLLOW_AGAIN = Duration.seconds(2);171

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

line 172why, one step back
172// Never ends on its own: interrupt it when the run is over.

Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8

lines 173–265why, one step back
173export const followCounter = (input: {
174 readonly origin: string;175 readonly project: ProjectName;176 readonly file: string;177 readonly from: number;178}) =>179 Effect.gen(function* () {180 const fs = yield* FileSystem.FileSystem;181 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;182 const tally = yield* Ref.make<Tally>({ events: [], last: input.from });183 const said = yield* Ref.make(false);184185 const append = (line: string) =>186 fs.writeFileString(input.file, `${line}\n`, { flag: "a" });187188 const hear = (event: ProjectEvent) =>189 Effect.gen(function* () {190 const before = yield* Ref.get(tally);191192 if (event.seq <= before.last) {193 return;194 }195196 const events = counted(event)197 ? [...before.events, event]198 : before.events;199200 yield* Ref.set(tally, { events, last: event.seq });201202 if (counted(event)) {203 yield* append(counterEntry(events, event));204 }205 });206207 const followOnce = Effect.scoped(208 Effect.gen(function* () {209 const { last } = yield* Ref.get(tally);210211 const child = yield* spawner.spawn(212 ChildProcess.make(213 "curl",214 curlArgs({215 body: `${watchRequest(input.project, Option.some(last))}\n`,216 contentType: "application/ndjson",217 origin: input.origin,218 }),219 { stdin: "ignore" }220 )221 );222223 // curl's exit says whether the stream ended or the call failed.224 const [stderr, code] = yield* Effect.all(225 [226 child.stderr.pipe(Stream.decodeText(), Stream.mkString),227 child.exitCode,228 child.stdout.pipe(229 Stream.decodeText(),230 Stream.splitLines,231 Stream.flatMap((line) => Stream.fromIterable(eventsIn(line))),232 Stream.runForEach(hear)233 ),234 ],235 { concurrency: "unbounded" }236 );237238 yield* Effect.when(239 Effect.fail(240 new SwarmFailed({ reason: `curl exited ${code}: ${stderr.trim()}` })241 ),242 Effect.succeed(code !== 0)243 );244 })245 ).pipe(246 // Said once, so a counter that cannot follow says why; it keeps trying.247 Effect.tapError(({ message }) =>248 Effect.gen(function* () {249 if (!(yield* Ref.getAndSet(said, true))) {250 yield* append(`counter: watch didn't run: ${message}`);251 }252 })253 ),254 Effect.ignore255 );256257 yield* append(258 `${counterLine([])} (${input.project}, after event ${input.from})`259 );260261 return yield* followOnce.pipe(262 Effect.repeat(Schedule.spaced(FOLLOW_AGAIN)),263 Effect.andThen(Effect.never)264 );265 });