facts.ts
This file
Path
packages/project/src/facts.ts
278 lines · 8.2 KiB · TypeScript
Last changed by
Merge build/comments-project into mainoscabrielbefore adoption49efd2a
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 { ObjectId, RepoHost, Revision } from "@repo/artifacts/repo-host";2import type { RepoNotFound } from "@repo/artifacts/repo-host";3import { judgeInputs } from "@repo/checks/judge";4import { workspacesIn } from "@repo/checks/workspaces";5import { PushTarget } from "@repo/gate/facts";6import type { PushFacts } from "@repo/gate/facts";7import { addedLines, treeDiff } from "@repo/git/tree-diff";8import type { Change } from "@repo/git/tree-diff";9import type { Ask } from "@repo/protocol/domain/ask";10import type { ClaimView } from "@repo/protocol/domain/claim";11import { RefNameText } from "@repo/protocol/domain/common";12import type { Policy } from "@repo/protocol/domain/policy";Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 13why, one step back13import { AskId, Handle, keyOf, LayerName, TreeSha } from "@repo/protocol/ids";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–40why, one step back14import type {15 CommitSha,16 LandedSha,17 ProjectName,18 RepoName,19 RepoPath,20} from "@repo/protocol/ids";21import type { Principal } from "@repo/protocol/principal";22import type { EvaluationFacts } from "@repo/rules/rules-evaluator";23import { Array, Effect, Option, Schema } from "effect";24import type { DateTime } from "effect";2526export class MissingCommit extends Schema.TaggedError<MissingCommit>()(27 "MissingCommit",28 { sha: Schema.String }29) {}3031const asAsk = Schema.decodeUnknownOption(AskId);3233const asHandle = Schema.decodeUnknownOption(Handle);3435const asLayer = Schema.decodeUnknownOption(LayerName);3637export const targetOf = (repo: RepoName, project: ProjectName): PushTarget => {38 const [named, second, third, ...rest] = repo.split("--");39 const canonical = PushTarget.Canonical({ project });40Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 41why, one step back41 if (named !== keyOf(project) || rest.length > 0 || second === undefined) {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 42–217why, one step back42 return canonical;43 }4445 if (third === undefined) {46 return Option.match(asLayer(second), {47 onNone: () => canonical,48 onSome: (layer) => PushTarget.Layer({ layer, project }),49 });50 }5152 if (second === "me") {53 return Option.match(asHandle(third), {54 onNone: () => canonical,55 onSome: (owner) => PushTarget.WorkingFork({ owner, project }),56 });57 }5859 return Option.match(60 Option.all({ ask: asAsk(second), claimant: asHandle(third) }),61 {62 onNone: () => canonical,63 onSome: ({ ask, claimant }) =>64 PushTarget.ClaimFork({ ask, claimant, project }),65 }66 );67};6869const commitIn = (repo: RepoName, sha: CommitSha) =>70 RepoHost.use((host) => host.readCommit(repo, sha)).pipe(71 Effect.flatMap(72 Option.match({73 onNone: () => Effect.fail(new MissingCommit({ sha })),74 onSome: Effect.succeed,75 })76 )77 );7879const textOf = (bytes: Uint8Array) => new TextDecoder().decode(bytes);8081const ScriptsOf = Schema.fromJsonString(82 Schema.Struct({ scripts: Schema.optionalKey(Schema.Json) })83);8485const decodeScripts = Schema.decodeUnknownOption(ScriptsOf);8687const scriptsIn = (repo: RepoName, blob: string | undefined) =>88 blob === undefined89 ? Effect.succeed("")90 : RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(91 Effect.map((bytes) =>92 Option.flatMap(bytes, (read) => decodeScripts(textOf(read))).pipe(93 Option.map(({ scripts }) => JSON.stringify(scripts ?? null)),94 Option.getOrElse(() => "")95 )96 )97 );9899const scriptsChanged = (repo: RepoName, changes: readonly Change[]) =>100 Option.match(101 Array.findFirst(changes, (change) => change.path === "package.json"),102 {103 onNone: () => Effect.succeed(false),104 onSome: (change) =>105 Effect.map(106 Effect.all([107 scriptsIn(repo, change.before),108 scriptsIn(repo, change.after),109 ]),110 ([before, after]) => before !== after111 ),112 }113 );114115export interface PushInput {116 readonly ask: Option.Option<Ask>;117 readonly base: CommitSha;118 readonly claim: Option.Option<ClaimView>;119 readonly claimsHeld: number;120 readonly head: CommitSha;121 readonly landed: LandedSha;122 readonly policy: Policy;123 readonly project: ProjectName;124 readonly pusher: Principal;125 readonly ref: string;126 readonly repo: RepoName;127}128129export const pushFacts = (130 input: PushInput131): Effect.Effect<PushFacts, RepoNotFound | MissingCommit, RepoHost> =>132 Effect.gen(function* () {133 const base = yield* commitIn(input.repo, input.base);134 const head = yield* commitIn(input.repo, input.head);135136 const changes = yield* treeDiff(137 input.repo,138 TreeSha.make(base.tree),139 TreeSha.make(head.tree)140 );141142 return {143 addedLines: yield* addedLines(input.repo, changes),144 ask: input.ask,145 base: input.base,146 changes,147 claim: input.claim,148 claimsHeld: input.claimsHeld,149 head: input.head,150 landed: input.landed,151 layerPaths: new Set(),152 opensAsk: false,153 policy: input.policy,154 pusher: input.pusher,155 ref: Option.getOrElse(Schema.decodeOption(RefNameText)(input.ref), () =>156 RefNameText.make("refs/heads/main")157 ),158 scriptsChanged: yield* scriptsChanged(input.repo, changes),159 target: targetOf(input.repo, input.project),160 } satisfies PushFacts;161 });162163const READS_AT_ONCE = 16;164165interface Located {166 readonly path: string;167 readonly sha: ObjectId;168}169170const blobsUnder = (171 repo: RepoName,172 root: ObjectId173): Effect.Effect<readonly Located[], RepoNotFound, RepoHost> => {174 const level = (175 folders: readonly Located[],176 found: readonly Located[]177 ): Effect.Effect<readonly Located[], RepoNotFound, RepoHost> =>178 folders.length === 0179 ? Effect.succeed(found)180 : Effect.flatMap(181 Effect.forEach(182 folders,183 (folder) =>184 RepoHost.use((host) => host.readTree(repo, folder.sha)).pipe(185 Effect.map((entries) =>186 Option.getOrElse(entries, () => []).map((entry) => ({187 path:188 folder.path === ""189 ? entry.name190 : `${folder.path}/${entry.name}`,191 sha: entry.sha,192 type: entry.type,193 }))194 )195 ),196 { concurrency: READS_AT_ONCE }197 ),198 (children) => {199 const all = children.flat();200201 return level(202 all.filter(({ type }) => type === "tree"),203 [...found, ...all.filter(({ type }) => type === "blob")]204 );205 }206 );207208 return level([{ path: "", sha: root }], []);209};210211export interface FactsInput {212 readonly initializer: Handle;213 readonly now: DateTime.Utc;214 readonly project: ProjectName;215 readonly vouchFile: RepoPath;216}217Merge build/comments-project into mainoscabrielbefore adoption49efd2a
lines 218–219why, one step back218// The seed is the commit's first eight hex digits, so the same commit always219// sees the same randomness.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 220–278why, one step back220export const evaluationFacts = (221 repo: RepoName,222 at: CommitSha,223 input: FactsInput224): Effect.Effect<EvaluationFacts, never, RepoHost> => {225 const empty: EvaluationFacts = {226 ci: [],227 initializer: input.initializer,228 now: input.now,229 project: input.project,230 seed: Number.parseInt(at.slice(0, 8), 16),231 workspaces: [],232 };233234 return Effect.gen(function* () {235 const commit = yield* RepoHost.use((host) => host.readCommit(repo, at));236237 if (Option.isNone(commit)) {238 return empty;239 }240241 const blobs = yield* blobsUnder(repo, commit.value.tree);242 const ids = new Map(blobs.map(({ path, sha }) => [path, sha]));243244 const ci = yield* judgeInputs(blobs, (paths) =>245 Effect.forEach(246 paths,247 (path) =>248 Option.match(Option.fromUndefinedOr(ids.get(path)), {249 onNone: () => Effect.succeed([]),250 onSome: (sha) =>251 RepoHost.use((host) => host.readBlob(repo, sha)).pipe(252 Effect.map((bytes) =>253 Option.toArray(254 Option.map(bytes, (read) => ({ bytes: read, path }))255 )256 )257 ),258 }),259 { concurrency: READS_AT_ONCE }260 ).pipe(Effect.map((read) => read.flat()))261 );262263 const vouch = yield* RepoHost.use((host) =>264 host.readFile(repo, Revision.Commit({ sha: at }), input.vouchFile)265 );266267 const facts: EvaluationFacts = {268 ...empty,269 ci,270 workspaces: workspacesIn(ci),271 };272273 return Option.match(vouch, {274 onNone: () => facts,275 onSome: (bytes) => ({ ...facts, vouchFile: textOf(bytes) }),276 });277 }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeed(empty)));278};