Skip to content
Myr

fixtures.ts

This file

Path

apps/web/src/dev/fixtures.ts

435 lines · 13.2 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1// The switch is a `VITE_` variable because the dev world runs in the Worker's runtime,2// which sees no other variable of the shell that started Vite.3import { RepoHost } from "@repo/artifacts/repo-host";4import { envSchemaMethod } from "@repo/project/deciders";5import type { ProjectApi } from "@repo/project/project";6import { ProjectedEvent } from "@repo/project/projection";7import { Projects } from "@repo/project/projects";8import type { Ask } from "@repo/protocol/domain/ask";9import type { ProjectName } from "@repo/protocol/ids";10import { sameHandle } from "@repo/protocol/ids";11import { Principal } from "@repo/protocol/principal";12import type { Person } from "@repo/protocol/principal";13import {14  NotDecider,15  UnknownAsk,16  UnknownCommit,17  UnknownProject,18  UnknownProposal,19} from "@repo/protocol/refusal";20import {21  Clock,22  Context,23  DateTime,24  Duration,25  Effect,26  Layer,27  Option,28  Ref,29  Schema,30  Semaphore,31} from "effect";3233import { DevClock, devStart } from "./clock.ts";34import { seedFillers } from "./fixtures/fillers.ts";35import {36  creditsIn,37  decisionTaken,38  decodeRecord,39  landingIn,40  lastSeqOf,41  listedOf,42  statusIn,43  todayIn,44  verdictIn,45} from "./fixtures/record.ts";46import type { FixtureRecord } from "./fixtures/record.ts";47import type { Story } from "./fixtures/story.ts";48import {49  decisionsPerDay,50  fixturesNow,51  landLintChild,52  tellVellum,53  vellum,54  vellumFiles,55  vellumInitializer,56  vellumStart,57} from "./fixtures/vellum.ts";58import { DevProjected } from "./projection.ts";59import { seedDev, startedAt } from "./seed.ts";60import { devWorldWith } from "./world.ts";6162export type FixtureMode = "off" | "on" | "live";6364const Switch = Schema.Literals(["1", "on", "live"]);6566export const fixturesMode: FixtureMode = Option.match(67  Schema.decodeUnknownOption(Switch)(import.meta.env.VITE_DEV_FIXTURES),68  {69    onNone: (): FixtureMode => "off",70    onSome: (on): FixtureMode => (on === "live" ? "live" : "on"),71  }72);7374export const fixturesOn = fixturesMode !== "off";7576export const LIVE_AFTER = Duration.seconds(20);7778interface Told {79  readonly record: FixtureRecord;80  readonly story: Story;81  readonly told: () => FixtureRecord;82}8384export class Fixtures extends Context.Service<85  Fixtures,86  {87    readonly told: Ref.Ref<Option.Option<Told>>;88    readonly liveAfter: Option.Option<Duration.Duration>;89    readonly armedAt: Ref.Ref<Option.Option<bigint>>;90    readonly landed: Ref.Ref<boolean>;91    readonly lock: Semaphore.Semaphore;92  }93>()("web/dev/Fixtures") {}9495const fixturesLayer = (liveAfter: Option.Option<Duration.Duration>) =>96  Layer.effect(97    Fixtures,98    Effect.gen(function* () {99      return Fixtures.of({100        armedAt: yield* Ref.make(Option.none<bigint>()),101        landed: yield* Ref.make(false),102        liveAfter,103        lock: yield* Semaphore.make(1),104        told: yield* Ref.make(Option.none<Told>()),105      });106    })107  );108109const callerOf = (principal: Principal) =>110  Principal.match(principal, {111    Anonymous: () => Option.none<Person>(),112    Person: (person) => Option.some(person),113  });114115const isFixture = (project: ProjectName) => project === vellum;116117const briefOf = (ask: Ask): string =>118  [119    `# ${ask.brief.want}`,120    "",121    `Ask \`${ask.id}\` in ${ask.project}, a \`${ask.kind}\` ask from ${ask.askedBy}.`,122    "",123    "## Territory",124    "",125    ask.territory.module === "."126      ? `The paths ${ask.territory.paths.map((path) => `\`${path}\``).join(", ")}.`127      : `The module \`${ask.territory.module}\`: ${ask.territory.paths.map((path) => `\`${path}\``).join(", ")}.`,128    ...(ask.brief.current === undefined129      ? []130      : ["", "## Current", "", ask.brief.current]),131    "",132  ].join("\n");133134const overlay: Layer.Layer<135  Projects | DevProjected,136  never,137  Projects | DevProjected | Fixtures | RepoHost | DevClock138> = Layer.effectContext(139  Effect.gen(function* () {140    const projects = yield* Projects;141    const projected = yield* DevProjected;142    const fixtures = yield* Fixtures;143    const host = yield* RepoHost;144    const devClock = yield* DevClock;145    const clock = yield* Clock.Clock;146147    const now = Effect.sync(() =>148      DateTime.toUtc(DateTime.makeUnsafe(clock.currentTimeMillisUnsafe()))149    );150151    const provided = <A, E>(effect: Effect.Effect<A, E, RepoHost | DevClock>) =>152      effect.pipe(153        Effect.provideService(RepoHost, host),154        Effect.provideService(DevClock, devClock)155      );156157    const current = Effect.flatMap(Ref.get(fixtures.told), (told) =>158      Option.match(told, {159        onNone: () => Effect.die("vellum's story is not told yet"),160        onSome: ({ record }) => Effect.succeed(record),161      })162    );163164    const write = <A, E>(165      step: (story: Story) => Effect.Effect<A, E, RepoHost | DevClock>166    ) =>167      fixtures.lock.withPermits(1)(168        Effect.gen(function* () {169          const told = yield* Effect.flatMap(170            Ref.get(fixtures.told),171            Effect.fromOption172          ).pipe(Effect.orDie);173174          const out = yield* provided(step(told.story));175          const record = yield* decodeRecord(told.told());176177          yield* Ref.set(fixtures.told, Option.some({ ...told, record }));178179          return out;180        })181      );182183    // Only a read's start counts, so a later page of the same replay never lands it mid-replay.184    const heard = (since: number) =>185      Option.match(fixtures.liveAfter, {186        onNone: () => Effect.void,187        onSome: (after) =>188          Effect.gen(function* () {189            const record = yield* current;190191            if (since !== 0 && since < lastSeqOf(record)) {192              return;193            }194195            const at = yield* Clock.monotonicTimeNanos;196197            const armed = yield* Ref.modify(198              fixtures.armedAt,199              (was): readonly [Option.Option<bigint>, Option.Option<bigint>] =>200                Option.isSome(was)201                  ? [was, was]202                  : [Option.none(), Option.some(at)]203            );204205            if (Option.isNone(armed)) {206              return;207            }208209            const waited = Duration.nanos(at - armed.value);210211            // Taken in one step, so two reads at once land it only once.212            if (213              Duration.isLessThan(waited, after) ||214              (yield* Ref.getAndSet(fixtures.landed, true))215            ) {216              return;217            }218219            yield* write((story) =>220              Effect.flatMap(devClock.step, (landedAt) =>221                landLintChild(story, landedAt)222              )223            );224          }).pipe(Effect.provideService(Clock.Clock, clock)),225      });226227    const overlaid = (api: ProjectApi): ProjectApi => ({228      ...api,229      credits: (_caller, handle) =>230        Effect.map(current, (record) => ({231          credits: creditsIn(record, handle),232        })),233      decide: (caller, input) =>234        write((story) =>235          Effect.gen(function* () {236            const decision = yield* decisionTaken(yield* current, {237              ...input,238              now: yield* now,239              who: caller.handle,240            });241242            if (decision.decided !== undefined) {243              story.decide(decision.id, decision.decided);244            }245246            return { decision };247          })248        ),249      [envSchemaMethod]: () => Effect.map(current, ({ env }) => env),250      events: (since, limit) =>251        Effect.andThen(252          heard(since),253          Effect.map(current, ({ events }) =>254            events255              .filter(({ seq }) => seq > since)256              .slice(0, limit)257              .map((event) => ({ event, seq: event.seq }))258          )259        ),260      // Anyone but a maintainer or the log's claimant hears `NotDecider` whether or not a log is kept,261      // so the reply tells no one which logs exist.262      evidence: (caller, ref) =>263        Effect.gen(function* () {264          const record = yield* current;265          const log = Option.fromUndefinedOr(record.logs.get(ref));266267          const allowed = Option.exists(268            callerOf(caller),269            ({ handle }) =>270              record.decisions.some(({ deciders }) =>271                deciders.some((each) => sameHandle(each, handle))272              ) ||273              Option.exists(log, ({ claimant }) => sameHandle(claimant, handle))274          );275276          if (!allowed) {277            return yield* new NotDecider({});278          }279280          if (Option.isNone(log)) {281            return yield* new UnknownProject({ project: vellum });282          }283284          return {285            lane: log.value.lane,286            text: log.value.text,287            truncated: false,288          };289        }),290      // A claim's fork is made when the forks are first read, not when the291      // world is built: each copies the repo, and most worlds read no code.292      forks: () =>293        fixtures.lock294          .withPermits(1)(295            Effect.flatMap(296              Effect.flatMap(Ref.get(fixtures.told), Effect.fromOption),297              ({ story }) => provided(story.forkClaims())298            ).pipe(Effect.orDie, Effect.andThen(current))299          )300          .pipe(Effect.map(({ forks }) => forks)),301      head: () => Effect.map(current, ({ head }) => ({ landed: head })),302      landing: (_caller, sha) =>303        Effect.flatMap(current, (record) =>304          Option.match(landingIn(record, sha), {305            onNone: () => Effect.fail(new UnknownCommit({ sha })),306            onSome: (landing) => Effect.succeed({ landing }),307          })308        ),309      landingCount: () =>310        Effect.map(current, ({ landings }) => landings.length),311      landings: (shas) =>312        Effect.map(current, ({ landings }) =>313          shas.flatMap((sha) =>314            landings.filter((landing) => landing.sha === sha).slice(0, 1)315          )316        ),317      ledger: () => Effect.map(current, ({ ledger }) => ledger),318      listAsks: () =>319        Effect.map(current, (record) => ({ asks: listedOf(record) })),320      policy: () =>321        Effect.flatMap(current, ({ head }) =>322          Effect.map(api.policy(), (status) =>323            status.policy === undefined324              ? status325              : { ...status, policy: { ...status.policy, at: head } }326          )327        ),328      showAsk: (_caller, id) =>329        Effect.flatMap(current, ({ asks }) =>330          Effect.fromOption(Option.fromUndefinedOr(asks.get(id))).pipe(331            Effect.mapError(() => new UnknownAsk({ ask: id })),332            Effect.map((ask) => ({ ask, brief: briefOf(ask) }))333          )334        ),335      showProposal: (_caller, id) =>336        Effect.flatMap(current, ({ proposals }) =>337          Effect.fromOption(Option.fromUndefinedOr(proposals.get(id))).pipe(338            Effect.mapError(() => new UnknownProposal({ proposal: id }))339          )340        ),341      standing: () =>342        Effect.map(current, (record) => ({343          posture: record.ledger.posture,344          seen: lastSeqOf(record),345        })),346      status: (caller) =>347        Effect.map(current, (record) => statusIn(record, caller.handle)),348      today: (caller) =>349        Effect.flatMap(Effect.zip(current, now), ([record, at]) =>350          Effect.fromOption(351            todayIn(record, caller.handle, at, decisionsPerDay)352          ).pipe(Effect.mapError(() => new NotDecider({})))353        ),354      verdict: (_caller, input) =>355        Effect.flatMap(current, (record) =>356          record.asks.has(input.ask)357            ? Effect.succeed(358                Option.match(verdictIn(record, input.ask, input.head), {359                  onNone: () => ({}),360                  onSome: (verdict) => ({ verdict }),361                })362              )363            : Effect.fail(new UnknownAsk({ ask: input.ask }))364        ),365    });366367    return Context.make(368      Projects,369      Projects.of({370        create: projects.create,371        get: (project) =>372          isFixture(project)373            ? Effect.map(projects.get(project), overlaid)374            : projects.get(project),375      })376    ).pipe(377      Context.add(DevProjected, {378        events: Effect.gen(function* () {379          const all = yield* projected.events;380          const told = yield* Ref.get(fixtures.told);381382          return [383            ...all.filter(({ project }) => !isFixture(project)),384            ...Option.match(told, {385              onNone: () => [],386              onSome: ({ record }) =>387                record.events.map((event) =>388                  ProjectedEvent.make({ event, project: vellum })389                ),390            }),391          ];392        }),393      })394    );395  })396);397398const seedFixtures = Effect.gen(function* () {399  const fixtures = yield* Fixtures;400401  yield* seedFillers(30);402403  const { landed } = yield* startedAt(404    vellum,405    vellumInitializer,406    vellumFiles,407    vellumStart408  );409410  const { story, told } = yield* tellVellum(landed);411  const record = yield* decodeRecord(told());412413  yield* Ref.set(fixtures.told, Option.some({ record, story, told }));414  yield* (yield* DevClock).set(fixturesNow);415}).pipe(Effect.orDie);416417export const withFixtures = (418  mode: "on" | "live",419  liveAfter: Duration.Duration = LIVE_AFTER,420  start: DateTime.Utc = devStart421) =>422  Layer.effectDiscard(Effect.andThen(seedDev, seedFixtures)).pipe(423    Layer.provideMerge(424      devWorldWith(425        overlay.pipe(426          Layer.provideMerge(427            fixturesLayer(428              mode === "live" ? Option.some(liveAfter) : Option.none()429            )430          )431        ),432        start433      )434    )435  );