import { BillingPools } from "@usine/core/agent/pool"; import { harvestedAttemptChanges, taskPullRequestState } from "../task-changes.ts"; import { boardRepositories } from "@usine/config/project"; import type { LoadedInstance } from "@usine/config/instance"; import { ItemKey, ItemNumber } from "@usine/core/item"; import { canonicalRepositoryName, RepositoryName } from "@usine/core/repository"; import { type Comment } from "@usine/core/step/result"; import { CycleBudgets } from "@usine/engine/cycle-budget"; import { ItemProjectionReader } from "@usine/engine/item-projection"; import { LoopControl } from "@usine/engine/loop-control"; import { RepositoryLabelProjectionReader } from "@usine/engine/repository-label-projection"; import { type RunSnapshot, RunReader } from "@usine/engine/run-reader"; import { Array as EffectArray, Context, DateTime, Effect, Layer, Option, Result } from "effect"; import { WorkerStatus } from "../../worker-status.ts"; import { quotaWaits } from "../machines.ts"; import { readBoardItems } from "../../board/selection.ts"; import { projectedItem } from "../../board/items.ts"; import { projectBoard } from "../../board/projection.ts"; import { BoardItemNotFoundError, BoardProjectNotFoundError } from "../board.ts"; import { readRunningEvents, runSummaryView, declaredWorkers } from "../projection.ts"; import { TaskCommentView, TaskItemView, TaskLaneView, type TaskReadDepth, type TaskReadError, TaskView, } from "./view.ts"; const isoOrNull = Option.match({ onNone: () => null, onSome: DateTime.formatIso }); /** * Returns the comments and reviews that a Run's Attempts posted, newest first and without * duplicates. */ const harvestedComments = (summary: RunSnapshot): ReadonlyArray => { const view = (comment: Comment, endedAt: Option.Option) => TaskCommentView.make({ runId: summary.run.id, kind: comment.kind, url: comment.url.toString(), postedAt: isoOrNull(comment.at), attemptEndedAt: isoOrNull(endedAt), }); const succeededEnd = EffectArray.findLast(summary.attempts, (attempt) => Option.exists(attempt.outcome, ({ _tag }) => _tag === "Succeeded"), ).pipe(Option.flatMap(({ endedAt }) => endedAt)); const delivered = Option.match(summary.step.result, { onNone: () => [], onSome: ({ facts }) => facts.flatMap((fact) => (fact._tag === "Comment" ? [view(fact, succeededEnd)] : [])), }); const unsuccessful = summary.attempts.flatMap((attempt) => attempt.comments.map((comment) => view(comment, attempt.endedAt)), ); const time = ({ postedAt, attemptEndedAt }: TaskCommentView) => postedAt ?? attemptEndedAt ?? ""; return EffectArray.dedupeWith( [...delivered, ...unsuccessful].sort((a, b) => time(b).localeCompare(time(a))), (a, b) => a.url === b.url, ); }; const makeTaskReader = Effect.gen(function* () { const reader = yield* RunReader; const workerStatus = yield* WorkerStatus; const controls = yield* LoopControl; const itemReader = yield* ItemProjectionReader; const repositoryLabels = yield* RepositoryLabelProjectionReader; const budgets = yield* CycleBudgets; const pools = yield* BillingPools; const read = Effect.fn("TaskReader.read")(function* ( instance: LoadedInstance, repository: RepositoryName, number: ItemNumber, depth: TaskReadDepth, ) { yield* Effect.annotateCurrentSpan({ repository, item: number, depth }); const managed = boardRepositories(instance.config).find( ({ name }) => canonicalRepositoryName(name) === canonicalRepositoryName(repository), ); if (managed === undefined) { yield* Effect.logInfo("Task read refused; the repository is not a registered Project", { repository, item: number, }); return yield* BoardProjectNotFoundError.make({ repository }); } const [stored, labelProjection, states, asks, provisioning] = yield* Effect.all( [ reader .list({ closedLimit: 0 }) .pipe(Effect.flatMap((runs) => readBoardItems(itemReader, managed.name, runs))), repositoryLabels.get(managed.name), controls.states, budgets.asks, workerStatus.provisioning, ] as const, { concurrency: "unbounded" }, ); const summaries = yield* reader.forItems(stored.map(({ itemKey }) => itemKey)); const runEvents = yield* readRunningEvents(reader, summaries); const paused = new Set(states.filter((state) => state.paused).map((state) => state.loop)); const runWorkers = declaredWorkers(instance.config.workers); const waits = quotaWaits(provisioning); const board = yield* projectBoard( managed, Option.match(labelProjection, { onNone: () => [], onSome: ({ labels }) => labels.map(({ name }) => name), }), stored, summaries.map((summary) => runSummaryView(summary, paused, runWorkers, waits)), pools, asks.map(({ itemKey }) => itemKey), new Map(), new Map(), runEvents, ); const placed = board.lanes .flatMap((lane) => lane.items.map((task) => ({ lane, task }))) .find(({ task }) => task.items.some((member) => member.number === number)); if (placed === undefined) { yield* Effect.logInfo("Task read found no task in the selected board items", { repository: managed.name, item: number, selectedItems: stored.length, }); return yield* BoardItemNotFoundError.make({ repository: managed.name, item: number }); } const { lane, task } = placed; const memberKeys = new Set(task.items.map(({ itemKey }) => itemKey)); const projected = yield* Effect.forEach( stored.filter(({ itemKey }) => memberKeys.has(itemKey)), (item) => projectedItem(item).pipe(Effect.result), ); const details = new Map(); const storedByKey = new Map(stored.map((item) => [item.itemKey, item])); for (const result of projected) { if (Result.isFailure(result)) { yield* Effect.logError("Task Item could not be projected; the other Items are shown", { repository: managed.name, itemKey: result.failure.itemKey, message: result.failure.message, }); continue; } const { itemKey, kind, number: itemNumber, title, url, state, labels, conflicting, } = result.success; const storedItem = storedByKey.get(itemKey); const pullRequest = kind === "pr" && storedItem !== undefined ? taskPullRequestState(storedItem.payload) : Option.none(); if (kind === "pr" && Option.isNone(pullRequest)) yield* Effect.logDebug( "Pull request changes unavailable without a valid projected base and head", { repository: managed.name, itemKey }, ); details.set( itemKey, TaskItemView.make({ itemKey, kind, number: itemNumber, title, url, state, labels, conflicting, pullRequest: Option.getOrNull(pullRequest), }), ); } const [first, ...rest] = task.items.flatMap(({ itemKey }) => { const detail = details.get(itemKey); return detail === undefined ? [] : [detail]; }); if (first === undefined) { return yield* BoardItemNotFoundError.make({ repository: managed.name, item: number }); } const memberRuns = summaries .filter(({ itemKey }) => memberKeys.has(itemKey)) .sort( (a, b) => DateTime.toEpochMillis(b.run.openedAt) - DateTime.toEpochMillis(a.run.openedAt) || b.run.id.localeCompare(a.run.id), ); const runs = memberRuns.map((summary) => runSummaryView(summary, paused, runWorkers, waits)); const summary = TaskView.make({ repository: managed.name, number: first.number, title: task.title, current: task.itemKey, lane: TaskLaneView.make({ id: lane.id, name: lane.name }), needsYou: task.needsYou, items: [first, ...rest], runs, runsTotal: runs.length, }); const fields = { repository: managed.name, item: number, depth, origin: summary.number, lane: lane.name, items: summary.items.length, runs: runs.length, }; if (depth === "summary") { yield* Effect.logDebug("Read a Task", fields); return summary; } const inspected = yield* Effect.forEach(memberRuns, ({ run }) => reader.inspect(run.id), { concurrency: 4, }); const comments = inspected.flatMap(harvestedComments); yield* Effect.logDebug("Read a Task", { ...fields, comments: comments.length }); return TaskView.make({ ...summary, comments, attemptChanges: inspected.flatMap(harvestedAttemptChanges), }); }); return { read } as const; }); /** * Reads one task from the board projection over recent items and items with open runs. */ export class TaskReader extends Context.Service< TaskReader, { /** * Returns the Task that contains Item `item` of `repository`, read to `depth`. Fails if the * repository isn't a Project or the item isn't in the board selection. */ readonly read: ( instance: LoadedInstance, repository: RepositoryName, item: ItemNumber, depth: TaskReadDepth, ) => Effect.Effect; } >()("@usine/orchestrator/operator/task/task/TaskReader") { static readonly layer = Layer.effect(TaskReader, makeTaskReader); }