Skip to content
Myr

landing.ts

This file

Path

packages/project/src/landing.ts

508 lines · 14.6 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

1import { AgentTrailer, Credit } from "@repo/protocol/domain/credit";2import type { CreditRole } from "@repo/protocol/domain/credit";3import type { Choice } from "@repo/protocol/domain/decision";4import { DecisionSubject } from "@repo/protocol/domain/decision";5import { AskKind } from "@repo/protocol/domain/kind";6import { LandingView } from "@repo/protocol/domain/landing";7import { Outcome } from "@repo/protocol/domain/outcome";8import {9  AskId,10  BlobSha,11  CommitSha,12  DecisionId,13  Handle,14  LandedSha,15  ProjectName,16  RepoName,17  RepoPath,18  RequestId,19  TreeSha,20} from "@repo/protocol/ids";21import {22  PostureChange,23  Refusal,24  StaleBase,25  Weakened,26} from "@repo/protocol/refusal";27import type { MovedBy } from "@repo/protocol/refusal";28import { Array, Data, DateTime, Duration, Match, Option, Schema } from "effect";2930import { ProjectEventInput } from "./events.ts";3132export const maxRemerges = 3;3334/** Structurally the gate's and git's `Change`, so either passes where the other is expected. */35export const Change = Schema.Struct({36  after: Schema.optionalKey(BlobSha),37  before: Schema.optionalKey(BlobSha),38  path: RepoPath,39  status: Schema.Literals(["added", "modified", "deleted"]),40});4142export type Change = typeof Change.Type;4344export const Request = Schema.Struct({45  answerer: Handle,46  /** Absent for a maintainer's own landing. */47  ask: Schema.OptionFromOptionalKey(AskId),48  assisted: Schema.Array(AgentTrailer),49  base: CommitSha,50  credits: Schema.Array(Credit),51  fork: RepoName,52  head: CommitSha,53  project: ProjectName,54  requestId: RequestId,55});5657export type Request = typeof Request.Type;5859export const AnswerDecision = Schema.Union([60  DecisionSubject.cases.PostureChange,61  DecisionSubject.cases.RaiseRatchet,62  DecisionSubject.cases.Waiver,63]).pipe(Schema.toTaggedUnion("_tag"));6465export type AnswerDecision = typeof AnswerDecision.Type;6667export const PendingDecision = Schema.Struct({68  id: DecisionId,69  subject: AnswerDecision,70});7172export type PendingDecision = typeof PendingDecision.Type;7374const Count = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));7576const underway = {77  attempt: Count,78  main: LandedSha,79  remerges: Count,80  request: Request,81};8283const checkedFields = { ...underway, tree: TreeSha };8485export const LandingState = Schema.TaggedUnion({86  AwaitingDecision: {87    ...checkedFields,88    decisions: Schema.NonEmptyArray(PendingDecision),89    finish: AskKind.fields.finish,90  },91  AwaitingFinish: checkedFields,92  Checking: { ...checkedFields, changes: Schema.Array(Change) },93  Landed: { request: Request, sha: LandedSha },94  Landing: checkedFields,95  Merging: underway,96  Queued: { request: Request },97  Refused: { refusals: Schema.NonEmptyArray(Refusal), request: Request },98  WaitingOnParent: { parent: AskId, request: Request },99});100101export type LandingState = typeof LandingState.Type;102103export type LandingCommand = Data.TaggedEnum<{104  Start: { readonly main: LandedSha };105  Wait: { readonly parent: AskId };106  Merged: {107    readonly changes: readonly Change[];108    readonly main: LandedSha;109    readonly tree: TreeSha;110  };111  MergeConflict: {112    readonly conflicts: readonly RepoPath[];113    readonly main: LandedSha;114    readonly movedBy?: Array.NonEmptyReadonlyArray<MovedBy>;115  };116  Checked: {117    readonly decisions: readonly PendingDecision[];118    readonly finish: AskKind["finish"];119    readonly refusals: readonly Refusal[];120    readonly tree: TreeSha;121  };122  Finished: { readonly by: Handle };123  Decided: {124    readonly by: Handle;125    readonly choice: Choice;126    readonly decision: DecisionId;127  };128  MainMoved: { readonly from: LandedSha; readonly main: LandedSha };129  LandedOk: { readonly sha: LandedSha };130  Busy: { readonly attempt: number };131  /** Retried with backoff, never counted against the answerer. */132  Blocked: { readonly attempt: number };133}>;134135export const LandingCommand = Data.taggedEnum<LandingCommand>();136137export type LandingEffect = Data.TaggedEnum<{138  Merge: {139    readonly base: CommitSha;140    readonly fork: RepoName;141    readonly head: CommitSha;142    readonly main: LandedSha;143  };144  RunChecks: { readonly tree: TreeSha };145  Land: { readonly main: LandedSha; readonly tree: TreeSha };146  Retry: { readonly at: DateTime.Utc };147  Emit: { readonly event: ProjectEventInput };148  Record: { readonly sha: LandedSha };149}>;150151export const LandingEffect = Data.taggedEnum<LandingEffect>();152153export interface Step {154  readonly effects: readonly LandingEffect[];155  readonly state: LandingState;156}157158const {159  AwaitingDecision,160  AwaitingFinish,161  Checking,162  Landed,163  Landing,164  Merging,165  Refused,166  WaitingOnParent,167} = LandingState.cases;168169type Underway = Pick<170  typeof Merging.Type,171  "attempt" | "main" | "remerges" | "request"172>;173174type Passed = Underway & { readonly tree: TreeSha };175176const passedOf = ({ attempt, main, remerges, request, tree }: Passed) => ({177  attempt,178  main,179  remerges,180  request,181  tree,182});183184export const backoff = (attempt: number): Duration.Duration =>185  Duration.millis(Math.min(1000 * 2 ** attempt, 5 * 60 * 1000));186187export const pendingEffects = (state: LandingState): readonly LandingEffect[] =>188  LandingState.matchOrElse<readonly LandingEffect[]>(189    state,190    {191      Checking: ({ tree }) => [LandingEffect.RunChecks({ tree })],192      Landing: ({ main, tree }) => [LandingEffect.Land({ main, tree })],193      Merging: ({ main, request }) => [194        LandingEffect.Merge({195          base: request.base,196          fork: request.fork,197          head: request.head,198          main,199        }),200      ],201    },202    () => []203  );204205const stay = (state: LandingState): Step => ({ effects: [], state });206207const enter = (state: LandingState): Step => ({208  effects: pendingEffects(state),209  state,210});211212const refuse = (213  request: Request,214  refusals: Array.NonEmptyReadonlyArray<Refusal>215): Step => stay(Refused.make({ refusals, request }));216217const start = (request: Request, main: LandedSha): Step =>218  enter(Merging.make({ attempt: 0, main, remerges: 0, request }));219220const retry = (221  state: typeof Checking.Type | typeof Landing.Type | typeof Merging.Type,222  attempt: number,223  now: DateTime.Utc224): Step =>225  attempt === state.attempt226    ? {227        effects: [228          LandingEffect.Retry({229            at: DateTime.addDuration(now, backoff(attempt)),230          }),231        ],232        state: { ...state, attempt: attempt + 1 },233      }234    : stay(state);235236const isFinished = (request: Request) =>237  request.credits.some(({ role }) => role === "Finished-by");238239const credit = (request: Request, role: CreditRole, handle: Handle): Request =>240  request.credits.some(241    (given) => given.role === role && given.handle === handle242  )243    ? request244    : { ...request, credits: [...request.credits, { handle, role }] };245246const human = (247  passed: Passed,248  decisions: readonly PendingDecision[],249  finish: AskKind["finish"]250): Step =>251  Array.match(decisions, {252    onEmpty: () =>253      finish === "required" && !isFinished(passed.request)254        ? stay(AwaitingFinish.make(passedOf(passed)))255        : enter(Landing.make(passedOf(passed))),256    onNonEmpty: (waiting) =>257      stay(258        AwaitingDecision.make({259          ...passedOf(passed),260          decisions: waiting,261          finish,262        })263      ),264  });265266const staleOn = (267  base: CommitSha,268  {269    conflicts,270    main,271    movedBy,272  }: Extract<LandingCommand, { readonly _tag: "MergeConflict" }>273) =>274  movedBy === undefined275    ? new StaleBase({ base, conflicts, main })276    : new StaleBase({ base, conflicts, main, movedBy });277278const declined = (subject: AnswerDecision): Refusal =>279  AnswerDecision.match(subject, {280    PostureChange: ({ from, to }) => new PostureChange({ from, to }),281    RaiseRatchet: ({ after, before, ratchet, territory }) =>282      new Weakened({ weakening: { after, before, ratchet, territory } }),283    Waiver: ({ at, marker, reason }) =>284      new Weakened({ at, weakening: { marker, reason } }),285  });286287const approves = {288  accept: true,289  adopt: true,290  decline: false,291  revert: false,292} as const satisfies Record<Choice, boolean>;293294const decide = (295  state: typeof AwaitingDecision.Type,296  { by, choice, decision }: Data.TaggedEnum.Value<LandingCommand, "Decided">297): Step =>298  Option.match(299    Array.findFirst(state.decisions, ({ id }) => id === decision),300    {301      onNone: () => stay(state),302      onSome: ({ subject }) =>303        approves[choice]304          ? human(305              { ...state, request: credit(state.request, "Decided-by", by) },306              state.decisions.filter(({ id }) => id !== decision),307              state.finish308            )309          : refuse(state.request, [declined(subject)]),310    }311  );312313const finished = (state: typeof AwaitingFinish.Type, by: Handle): Step =>314  enter(315    Landing.make({316      ...passedOf(state),317      request: credit(state.request, "Finished-by", by),318    })319  );320321const landed = (322  state: typeof Landing.Type,323  sha: LandedSha,324  now: DateTime.Utc325): Step => {326  const { request } = state;327328  const view = {329    assisted: request.assisted,330    author: request.answerer,331    credits: request.credits,332    landedAt: now,333    parent: state.main,334    project: request.project,335    requestId: request.requestId,336    sha,337  };338339  const landing = LandingView.make(340    Option.match(request.ask, {341      onNone: () => view,342      onSome: (ask) => ({ ...view, ask }),343    })344  );345346  return {347    effects: [348      LandingEffect.Emit({349        event: ProjectEventInput.Landed({ at: now, landing }),350      }),351      LandingEffect.Record({ sha }),352    ],353    state: Landed.make({ request, sha }),354  };355};356357const moved = (358  state: typeof Landing.Type,359  { from, main }: { readonly from: LandedSha; readonly main: LandedSha }360): Step => {361  if (from !== state.main || main === state.main) {362    return stay(state);363  }364365  return state.remerges >= maxRemerges366    ? refuse(state.request, [367        new StaleBase({ base: state.request.base, conflicts: [], main }),368      ])369    : enter(370        Merging.make({371          attempt: state.attempt,372          main,373          remerges: state.remerges + 1,374          request: state.request,375        })376      );377};378379/** A command that does not apply, or reports on another main, tree, attempt or decision, changes nothing: replays converge. */380export const transition = (381  state: LandingState,382  command: LandingCommand,383  now: DateTime.Utc384): Step =>385  LandingState.match(state, {386    AwaitingDecision: (waiting) =>387      Match.value(command).pipe(388        Match.tag("Decided", (decided) => decide(waiting, decided)),389        Match.orElse(() => stay(waiting))390      ),391    AwaitingFinish: (waiting) =>392      Match.value(command).pipe(393        Match.tag("Finished", ({ by }) => finished(waiting, by)),394        Match.orElse(() => stay(waiting))395      ),396    Checking: (checking) =>397      Match.value(command).pipe(398        Match.tag("Checked", ({ decisions, finish, refusals, tree }) =>399          tree === checking.tree400            ? Array.match(refusals, {401                onEmpty: () => human(checking, decisions, finish),402                onNonEmpty: (all) => refuse(checking.request, all),403              })404            : stay(checking)405        ),406        Match.tag("Blocked", ({ attempt }) => retry(checking, attempt, now)),407        Match.orElse(() => stay(checking))408      ),409    Landed: stay,410    Landing: (landing) =>411      Match.value(command).pipe(412        Match.tag("LandedOk", ({ sha }) => landed(landing, sha, now)),413        Match.tag("MainMoved", (report) => moved(landing, report)),414        Match.tag("Busy", "Blocked", ({ attempt }) =>415          retry(landing, attempt, now)416        ),417        Match.orElse(() => stay(landing))418      ),419    Merging: (merging) =>420      Match.value(command).pipe(421        Match.tag("Merged", ({ changes, main, tree }) =>422          main === merging.main423            ? enter(424                Checking.make({425                  attempt: merging.attempt,426                  changes,427                  main,428                  remerges: merging.remerges,429                  request: merging.request,430                  tree,431                })432              )433            : stay(merging)434        ),435        Match.tag("MergeConflict", (conflict) =>436          conflict.main === merging.main437            ? refuse(merging.request, [staleOn(merging.request.base, conflict)])438            : stay(merging)439        ),440        Match.tag("Blocked", ({ attempt }) => retry(merging, attempt, now)),441        Match.orElse(() => stay(merging))442      ),443    Queued: (queued) =>444      Match.value(command).pipe(445        Match.tag("Start", ({ main }) => start(queued.request, main)),446        Match.tag("Wait", ({ parent }) =>447          stay(WaitingOnParent.make({ parent, request: queued.request }))448        ),449        Match.orElse(() => stay(queued))450      ),451    Refused: stay,452    WaitingOnParent: (waiting) =>453      Match.value(command).pipe(454        Match.tag("Start", ({ main }) => start(waiting.request, main)),455        Match.orElse(() => stay(waiting))456      ),457  });458459export const outcomeOf = (state: LandingState): Outcome =>460  LandingState.match<Outcome>(state, {461    AwaitingDecision: ({ decisions }) =>462      Outcome.cases.AwaitingDecision.make({ decision: decisions[0].id }),463    AwaitingFinish: () => Outcome.cases.AwaitingFinish.make({}),464    Checking: () => Outcome.cases.Checking.make({ stage: "checks" }),465    Landed: ({ sha }) => Outcome.cases.Landed.make({ sha }),466    Landing: () => Outcome.cases.Checking.make({ stage: "human" }),467    Merging: () => Outcome.cases.Checking.make({ stage: "merge" }),468    Queued: () => Outcome.cases.Checking.make({ stage: "merge" }),469    Refused: ({ refusals }) => Outcome.cases.Refused.make({ refusals }),470    WaitingOnParent: ({ parent }) =>471      Outcome.cases.WaitingOnParent.make({ ask: parent }),472  });473474export const LandingQueue = Schema.Struct({475  active: Schema.OptionFromOptionalKey(RequestId),476  order: Schema.Array(RequestId),477});478479export type LandingQueue = typeof LandingQueue.Type;480481const isActive = (queue: LandingQueue, id: RequestId) =>482  Option.contains(queue.active, id);483484export const enqueue = (queue: LandingQueue, id: RequestId): LandingQueue =>485  isActive(queue, id) || queue.order.includes(id)486    ? queue487    : { ...queue, order: [...queue.order, id] };488489export const next = (490  queue: LandingQueue491): {492  readonly admit: Option.Option<RequestId>;493  readonly queue: LandingQueue;494} =>495  Option.isSome(queue.active)496    ? { admit: Option.none(), queue }497    : Array.match(queue.order, {498        onEmpty: () => ({ admit: Option.none(), queue }),499        onNonEmpty: ([front, ...rest]) => ({500          admit: Option.some(front),501          queue: { active: Option.some(front), order: rest },502        }),503      });504505export const settle = (queue: LandingQueue, id: RequestId): LandingQueue =>506  isActive(queue, id)507    ? { ...queue, active: Option.none() }508    : { ...queue, order: queue.order.filter((waiting) => waiting !== id) };