outbox.ts
This file
Path
packages/project/src/outbox.ts
288 lines · 8.3 KiB · TypeScript
Last changed by
Merge observability into mainoscabrielbefore adoption1985111
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–12why, one step back1import { RefName, RepoHost } from "@repo/artifacts/repo-host";2import { Verdict } from "@repo/protocol/domain/answer";3import type { ProjectEvent } from "@repo/protocol/domain/event";4import {5 CommitSha,6 Handle,7 LandedSha,8 RepoName,9 RequestId,10 TreeSha,11} from "@repo/protocol/ids";12import type { ProjectName } from "@repo/protocol/ids";Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 13why, one step back13import { Array, DateTime, Effect, Option, Order, Schema, Struct } from "effect";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 14–16why, one step back1415import { AnswerRuns } from "./answer-runs.ts";16import type { AnswerQueue } from "./answer-runs.ts";Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 17why, one step back17import { DraftParams, DraftRuns } from "./draft-runs.ts";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 18–19why, one step back18import { Lander, Rebuild } from "./lander.ts";19import { backoff } from "./landing.ts";Merge observability into mainoscabrielbefore adoption1985111
line 20why, one step back20import { MetricPoint, Metrics } from "./metrics.ts";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 21–47why, one step back21import type { OutboxRow } from "./project-store/rows.ts";22import { Projection, ProjectedEvent } from "./projection.ts";23import { ProjectVisibility, VisibilityEffect } from "./visibility-port.ts";2425const mainRef = RefName.make("refs/heads/main");2627export const LandAgain = Schema.Struct({28 author: Handle,29 base: CommitSha,30 fork: RepoName,31 head: CommitSha,32 main: LandedSha,33 message: Schema.String,34 repo: RepoName,35 requestId: RequestId,36 tree: TreeSha,37 verdict: Schema.optionalKey(Verdict),38});3940export type LandAgain = typeof LandAgain.Type;4142export const OutboxBody = Schema.Union([43 ProjectedEvent,44 Schema.TaggedStruct("MakeFork", { from: RepoName, name: RepoName }),45 Schema.TaggedStruct("StartAnswer", { requestId: RequestId }),46 Schema.TaggedStruct("Bookkeeping", { job: LandAgain }),47 Schema.TaggedStruct("Visibility", { effect: VisibilityEffect }),Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 48why, one step back48 Schema.TaggedStruct("StartDraft", DraftParams.fields),Merge observability into mainoscabrielbefore adoption1985111
lines 49–51why, one step back49 Schema.TaggedStruct("Measured", {50 points: Schema.NonEmptyArray(MetricPoint),51 }),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 52–94why, one step back52]).pipe(Schema.toTaggedUnion("_tag"));5354export type OutboxBody = typeof OutboxBody.Type;5556const BodyJson = Schema.toCodecJson(OutboxBody);5758const encodeBody = Schema.encodeEffect(BodyJson);5960const decodeBody = Schema.decodeUnknownEffect(BodyJson);6162export const outboxRow = (63 id: string,64 body: OutboxBody,65 notBefore: DateTime.Utc66): Effect.Effect<OutboxRow> =>67 Effect.map(Effect.orDie(encodeBody(body)), (encoded) => ({68 attempts: 0,69 body: encoded,70 id,71 kind: body._tag,72 notBefore,73 }));7475export const projectedRows = (76 project: ProjectName,77 events: readonly ProjectEvent[],78 now: DateTime.Utc79): Effect.Effect<readonly OutboxRow[]> =>80 Effect.forEach(events, (event) =>81 outboxRow(82 `projected:${event.seq}`,83 ProjectedEvent.make({ event, project }),84 now85 )86 );8788export const startRow = (requestId: RequestId, at: DateTime.Utc) =>89 outboxRow(90 `start:${requestId}:${DateTime.toEpochMillis(at)}`,91 OutboxBody.cases.StartAnswer.make({ requestId }),92 at93 );94Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
lines 95–101why, one step back95export const draftRow = (params: DraftParams, at: DateTime.Utc) =>96 outboxRow(97 `draft:${params.proposal}:r${params.round}`,98 OutboxBody.cases.StartDraft.make(params),99 at100 );101Merge observability into mainoscabrielbefore adoption1985111
lines 102–122why, one step back102/**103 * Written in the commit that holds the fact, under an id the fact alone104 * names, so a replay that changes nothing writes no row and the same fact105 * kept twice is one row.106 */107export const measuredRow = (108 fact: string,109 points: readonly MetricPoint[],110 at: DateTime.Utc111): Effect.Effect<readonly OutboxRow[]> =>112 Array.isReadonlyArrayNonEmpty(points)113 ? Effect.map(114 outboxRow(115 `measured:${fact}`,116 OutboxBody.cases.Measured.make({ points }),117 at118 ),119 Array.of120 )121 : Effect.succeed([]);122Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 123–149why, one step back123export const isDue = (row: OutboxRow, now: DateTime.Utc) =>124 DateTime.isLessThanOrEqualTo(row.notBefore, now);125126export interface OutboxRun {127 readonly done: readonly string[];128 readonly retry: readonly OutboxRow[];129}130131const later = (row: OutboxRow, now: DateTime.Utc): OutboxRow => ({132 ...row,133 attempts: row.attempts + 1,134 notBefore: DateTime.addDuration(now, backoff(row.attempts)),135});136137interface Decoded {138 readonly body: OutboxBody;139 readonly row: OutboxRow;140}141142const ran = (row: OutboxRow, ok: boolean, now: DateTime.Utc): OutboxRun =>143 ok ? { done: [row.id], retry: [] } : { done: [], retry: [later(row, now)] };144145const all = (runs: readonly OutboxRun[]): OutboxRun => ({146 done: runs.flatMap(({ done }) => done),147 retry: runs.flatMap(({ retry }) => retry),148});149Merge build/comments-project into mainoscabrielbefore adoption49efd2a
lines 150–151why, one step back150// Artifacts may answer a fork that worked with an error: a fork that exists151// and has `main` is made.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 152–190why, one step back152const fork = (from: RepoName, name: RepoName) =>153 RepoHost.use((host) =>154 host.fork(from, name).pipe(155 Effect.as(true),156 Effect.catchTag("RepoExists", () =>157 host.refs(name).pipe(158 Effect.map((refs) => refs.has(mainRef)),159 Effect.orElseSucceed(() => false)160 )161 ),162 Effect.orElseSucceed(() => false)163 )164 );165166const landAgain = (job: LandAgain) =>167 Lander.use((lander) =>168 lander.land({169 author: job.author,170 main: job.main,171 message: job.message,172 rebuild: Rebuild.Merge({173 base: job.base,174 fork: job.fork,175 head: job.head,176 }),177 repo: job.repo,178 requestId: job.requestId,179 tree: job.tree,180 verdict: Option.fromUndefinedOr(job.verdict),181 })182 ).pipe(183 Effect.map(({ pending }) => pending.length === 0),184 Effect.orElseSucceed(() => false)185 );186187const bySeq = Order.mapInput(Order.Number, ({ body }: Decoded) =>188 OutboxBody.guards.Projected(body) ? body.event.seq : 0189);190Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 191why, one step back191// Answer runs go last: they may run long, and settle their own rows.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 192–194why, one step back192export const runOutbox = (193 rows: readonly OutboxRow[],194 queue: AnswerQueue,Merge observability into mainoscabrielbefore adoption1985111
lines 195–197why, one step back195 now: DateTime.Utc,196 // Takes rows out of the store before they run, naming those it still held.197 claim: (ids: readonly string[]) => Effect.Effect<readonly string[]>Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 198–246why, one step back198): Effect.Effect<199 OutboxRun,200 never,201 AnswerRuns | Lander | Projection | RepoHost202> =>203 Effect.gen(function* () {204 const decoded = yield* Effect.forEach(rows, (row) =>205 Effect.map(Effect.orDie(decodeBody(row.body)), (body) => ({ body, row }))206 );207208 const of = <Tag extends OutboxBody["_tag"]>(tag: Tag) =>209 decoded.filter(210 (211 each212 ): each is Decoded & {213 readonly body: Extract<OutboxBody, { readonly _tag: Tag }>;214 } => OutboxBody.guards[tag](each.body)215 );216217 const projected = Array.sort(of("Projected"), bySeq);218219 const delivered = Array.isReadonlyArrayNonEmpty(projected)220 ? yield* Projection.use((projection) =>221 projection.apply(projected.map(({ row }) => row))222 ).pipe(223 Effect.as(true),224 Effect.catchTag("ProjectionFailed", (failed) =>225 Effect.as(226 Effect.logWarning("the projection refused rows", failed),227 false228 )229 )230 )231 : true;232233 const forks = yield* Effect.forEach(of("MakeFork"), ({ body, row }) =>234 Effect.map(fork(body.from, body.name), (ok) => ran(row, ok, now))235 );236237 const kept = yield* Effect.forEach(of("Bookkeeping"), ({ body, row }) =>238 Effect.map(landAgain(body.job), (ok) => ran(row, ok, now))239 );240241 const visibility = yield* ProjectVisibility;242243 const planned = yield* Effect.forEach(of("Visibility"), ({ body, row }) =>244 Effect.map(visibility.settle(body.effect), (ok) => ran(row, ok, now))245 );246Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
lines 247–255why, one step back247 const draftRuns = yield* DraftRuns;248249 const drafts = yield* Effect.forEach(of("StartDraft"), ({ body, row }) =>250 Effect.as(251 draftRuns.start(Struct.omit(body, ["_tag"])),252 ran(row, true, now)253 )254 );255Merge observability into mainoscabrielbefore adoption1985111
lines 256–271why, one step back256 const metrics = yield* Metrics;257258 // A point is written at most once, and never retried: the dataset adds259 // every point it takes. Its row leaves the store first, so of a call's260 // settle and the alarm's, both holding it, only the one that took it261 // writes its points.262 const taken = new Set(263 yield* claim(of("Measured").map(({ row }) => row.id))264 );265266 const measured = yield* Effect.forEach(267 of("Measured").filter(({ row }) => taken.has(row.id)),268 ({ body, row }) =>269 Effect.as(metrics.write(body.points), ran(row, true, now))270 );271Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 272–283why, one step back272 const runs = yield* Effect.forEach(of("StartAnswer"), ({ body, row }) =>273 Effect.as(274 AnswerRuns.use((answers) => answers.start(body.requestId, queue)),275 ran(row, true, now)276 )277 );278279 return all([280 ...projected.map(({ row }) => ran(row, delivered, now)),281 ...forks,282 ...kept,283 ...planned,Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 284why, one step back284 ...drafts,Merge observability into mainoscabrielbefore adoption1985111
line 285why, one step back285 ...measured,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 286–288why, one step back286 ...runs,287 ]);288 });