Skip to content
Myr

standing-posture.test.ts

This file

Path

packages/project/test/standing-posture.test.ts

436 lines · 12.6 KiB · TypeScript

Last changed by

Merge build/comments-project into mainoscabrielbefore adoption49efd2a

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { ProjectEvent } from "@repo/protocol/domain/event";3import type { ProjectListing } from "@repo/protocol/domain/front-page";4import { LedgerEntry } from "@repo/protocol/domain/visibility";5import { DecisionId, Handle, LandedSha, ProjectName } from "@repo/protocol/ids";6import type { Posture } from "@repo/protocol/posture";7import { UnknownProject } from "@repo/protocol/refusal";8import { untouchable } from "@repo/testkit/untouchable";9import {10  Array,11  DateTime,12  Duration,13  Effect,14  Layer,15  Logger,16  Option,17  Ref,18} from "effect";19import { TestClock } from "effect/testing";2021import { projectedRows } from "../src/outbox.ts";22import type { ProjectApi } from "../src/project.ts";23import { StandingPosturesD1 } from "../src/projection-d1/postures.ts";24import { ProjectionD1 } from "../src/projection-d1/projection.ts";25import { Projection } from "../src/projection.ts";26import { Projects } from "../src/projects.ts";27import {28  StandingPostures,29  withStandingPosture,30} from "../src/standing-posture.ts";31import { StandingPosturesMemory } from "../src/standing-posture/memory.ts";32import {33  frontPageMigration,34  migrated,35  posturesMigration,36  projectsMigration,37} from "./projection-d1.fixtures.ts";3839const datekit = ProjectName.make("alice/datekit");4041const ghost = ProjectName.make("alice/ghost");4243const broken = ProjectName.make("alice/broken");4445const burrow = ProjectName.make("alice/burrow");4647const landedAt = DateTime.makeUnsafe("2026-10-08T12:00:00Z");4849const standingAt = (50  project: ProjectName,51  posture: Posture,52  before: Effect.Effect<void> = Effect.void,53  until: Option.Option<DateTime.Utc> = Option.none()54) =>55  untouchable<ProjectApi>("ProjectApi", {56    standing: () =>57      Effect.as(58        before,59        Option.match(until, {60          onNone: () => ({ posture, seen: 7 }),61          onSome: (at) => ({ posture, seen: 7, until: at }),62        })63      ),64  });6566const platform = Layer.succeed(67  Projects,68  Projects.of({69    create: () => Effect.die("a listing makes no project"),70    get: (project) => {71      switch (project) {72        case datekit: {73          return Effect.succeed(standingAt(datekit, "openWithSealedEvidence"));74        }7576        case burrow: {77          return Effect.succeed(standingAt(burrow, "open"));78        }7980        case broken: {81          return Effect.succeed(82            untouchable<ProjectApi>("ProjectApi", {83              standing: () => Effect.die("the project's storage is down"),84            })85          );86        }8788        default: {89          return Effect.fail(new UnknownProject({ project }));90        }91      }92    },93  })94);9596const listed: readonly ProjectListing[] = [97  { landedAt, openAsks: 3, posture: "open", project: datekit },98  { openAsks: 1, posture: "openCore", project: ghost },99  { openAsks: 0, posture: "sourceAvailable", project: broken },100  { landedAt, openAsks: 2, posture: "openOnSchedule", project: burrow },101];102103const standingListed = [104  {105    landedAt,106    openAsks: 3,107    posture: "openWithSealedEvidence",108    project: datekit,109  },110  { openAsks: 1, posture: "openCore", project: ghost },111  { openAsks: 0, posture: "sourceAvailable", project: broken },112  { landedAt, openAsks: 2, posture: "open", project: burrow },113] satisfies readonly ProjectListing[];114115const inAnHour = DateTime.makeUnsafe(Duration.toMillis(Duration.hours(1)));116117const counted = (118  reads: Ref.Ref<readonly ProjectName[]>,119  datekitUntil: Option.Option<DateTime.Utc> = Option.none()120) =>121  Layer.succeed(122    Projects,123    Projects.of({124      create: () => Effect.die("a listing makes no project"),125      get: (project) => {126        const read = Ref.update(reads, (all) => [...all, project]);127128        switch (project) {129          case datekit: {130            return Effect.succeed(131              standingAt(datekit, "openWithSealedEvidence", read, datekitUntil)132            );133          }134135          case burrow: {136            return Effect.succeed(standingAt(burrow, "open", read));137          }138139          case broken: {140            return Effect.succeed(141              untouchable<ProjectApi>("ProjectApi", {142                standing: () =>143                  Effect.andThen(read, Effect.die("the storage is down")),144              })145            );146          }147148          default: {149            return Effect.fail(new UnknownProject({ project }));150          }151        }152      },153    })154  );155156const brokenStore = Layer.succeed(StandingPostures, {157  get: () => Effect.die("D1 is down"),158  put: () => Effect.die("D1 is down"),159});160161describe("a listing's standing posture", () => {162  it.effect("reads each project's posture from its own ledger", () =>163    Effect.gen(function* () {164      const standing = yield* withStandingPosture(listed);165166      expect(standing).toStrictEqual([167        {168          landedAt,169          openAsks: 3,170          posture: "openWithSealedEvidence",171          project: datekit,172        },173        { openAsks: 1, posture: "openCore", project: ghost },174        { openAsks: 0, posture: "sourceAvailable", project: broken },175        { landedAt, openAsks: 2, posture: "open", project: burrow },176      ]);177    }).pipe(Effect.provide(platform))178  );179180  it.effect(181    "warns once for each project whose posture stays the projection's",182    () =>183      Effect.gen(function* () {184        const warned: string[] = [];185186        const keeper = Logger.make(({ logLevel, message }) => {187          warned.push(`${logLevel}: ${String(message)}`);188        });189190        yield* withStandingPosture(listed).pipe(191          Effect.provide(Logger.layer([keeper]))192        );193194        expect(warned.toSorted()).toStrictEqual([195          "Warn: alice/broken's posture is the projection's: its ledger was not read",196          "Warn: alice/ghost's posture is the projection's: its ledger was not read",197        ]);198      }).pipe(Effect.provide(platform))199  );200201  it.effect("lists nothing for an empty list, and asks no project", () =>202    Effect.gen(function* () {203      expect(yield* withStandingPosture([])).toStrictEqual([]);204    }).pipe(205      Effect.provide(206        Layer.succeed(Projects, untouchable<Projects["Service"]>("Projects"))207      )208    )209  );210211  it.live("reads at most 8 projects at once", () =>212    Effect.gen(function* () {213      const under = yield* Ref.make(0);214      const peak = yield* Ref.make(0);215216      const timed = Effect.acquireUseRelease(217        Ref.updateAndGet(under, (count) => count + 1).pipe(218          Effect.tap((count) =>219            Ref.update(peak, (most) => Math.max(most, count))220          )221        ),222        () => Effect.sleep(Duration.millis(10)),223        () => Ref.update(under, (count) => count - 1)224      );225226      const many = Array.makeBy(20, (at): ProjectListing => ({227        openAsks: at,228        posture: "open",229        project: ProjectName.make(`alice/p${at}`),230      }));231232      const standing = yield* withStandingPosture(many).pipe(233        Effect.provide(234          Layer.succeed(235            Projects,236            Projects.of({237              create: () => Effect.die("a listing makes no project"),238              get: (project) =>239                Effect.succeed(standingAt(project, "openCore", timed)),240            })241          )242        )243      );244245      expect(standing).toStrictEqual(246        many.map((listing) => ({ ...listing, posture: "openCore" }))247      );248      expect(yield* Ref.get(peak)).toBe(8);249    })250  );251});252253describe("a listing's kept standing posture", () => {254  it.effect("is read once: a second list reads no project", () =>255    Effect.gen(function* () {256      const reads = yield* Ref.make<readonly ProjectName[]>([]);257258      const twice = yield* Effect.all([259        withStandingPosture(listed),260        withStandingPosture(listed),261      ]).pipe(262        Effect.provide(Layer.merge(counted(reads), StandingPosturesMemory))263      );264265      expect(twice).toStrictEqual([standingListed, standingListed]);266      // ghost was never made and broken's read fails: neither is kept, so267      // each is asked again; datekit and burrow were kept.268      expect((yield* Ref.get(reads)).toSorted()).toStrictEqual([269        broken,270        broken,271        burrow,272        datekit,273      ]);274    })275  );276277  it.effect(278    "keeps what it read, with the instant it moves and the event it saw",279    () =>280      Effect.gen(function* () {281        const reads = yield* Ref.make<readonly ProjectName[]>([]);282283        const kept = yield* Effect.gen(function* () {284          yield* withStandingPosture(listed);285286          const store = yield* StandingPostures;287288          return yield* store.get([datekit, ghost, broken, burrow]);289        }).pipe(290          Effect.provide(291            Layer.merge(292              counted(reads, Option.some(inAnHour)),293              StandingPosturesMemory294            )295          )296        );297298        expect(kept).toStrictEqual(299          new Map([300            [301              datekit,302              { posture: "openWithSealedEvidence", seen: 7, until: inAnHour },303            ],304            [burrow, { posture: "open", seen: 7 }],305          ])306        );307      })308  );309310  it.effect(311    "is read again once the instant it moves by the clock has come",312    () =>313      Effect.gen(function* () {314        const reads = yield* Ref.make<readonly ProjectName[]>([]);315316        yield* Effect.gen(function* () {317          yield* withStandingPosture(listed);318          yield* TestClock.adjust(Duration.minutes(59));319          yield* withStandingPosture(listed);320321          // The first list read both; the second, inside the hour, neither.322          expect(323            (yield* Ref.get(reads)).filter((at) => at !== broken).toSorted()324          ).toStrictEqual([burrow, datekit]);325326          yield* TestClock.adjust(Duration.minutes(1));327          yield* Ref.set(reads, []);328          yield* withStandingPosture(listed);329        }).pipe(330          Effect.provide(331            Layer.merge(332              counted(reads, Option.some(inAnHour)),333              StandingPosturesMemory334            )335          )336        );337338        expect(339          (yield* Ref.get(reads)).filter((at) => at !== broken)340        ).toStrictEqual([datekit]);341      })342  );343344  it.effect(345    "lists every project with its standing when the store cannot be read or written",346    () =>347      Effect.gen(function* () {348        const reads = yield* Ref.make<readonly ProjectName[]>([]);349350        const standing = yield* withStandingPosture(listed).pipe(351          Effect.provide(Layer.merge(counted(reads), brokenStore))352        );353354        expect(standing).toStrictEqual(standingListed);355      })356  );357});358359const d1 = Layer.mergeAll(StandingPosturesD1, ProjectionD1).pipe(360  Layer.provideMerge(361    migrated([frontPageMigration, projectsMigration, posturesMigration])362  )363);364365const projected = (project: ProjectName, event: ProjectEvent) =>366  Effect.flatMap(projectedRows(project, [event], landedAt), (rows) =>367    Projection.use((projection) => projection.apply(rows))368  );369370describe("a listing's standing posture kept in D1 beside the projection", () => {371  it.effect(372    "is read again only for the project whose event the projection applied",373    () =>374      Effect.gen(function* () {375        const reads = yield* Ref.make<readonly ProjectName[]>([]);376377        yield* Effect.gen(function* () {378          const list = Effect.gen(function* () {379            yield* Ref.set(reads, []);380381            expect(yield* withStandingPosture(listed)).toStrictEqual(382              standingListed383            );384385            return (yield* Ref.get(reads))386              .filter((at) => at !== broken)387              .toSorted();388          });389390          const first = yield* list;391          const warm = yield* list;392393          yield* projected(394            datekit,395            ProjectEvent.cases.Landed.make({396              at: landedAt,397              landing: {398                assisted: [],399                author: Handle.make("bram"),400                credits: [],401                landedAt,402                parent: LandedSha.make("b".repeat(40)),403                project: datekit,404                sha: LandedSha.make("a".repeat(40)),405              },406              seq: 1,407            })408          );409410          const afterLanding = yield* list;411412          yield* projected(413            burrow,414            ProjectEvent.cases.LedgerAppended.make({415              at: landedAt,416              entry: LedgerEntry.cases.PostureChanged.make({417                at: landedAt,418                decision: DecisionId.make("dec-000001"),419                from: "openCore",420                seq: 1,421                to: "open",422              }),423              seq: 1,424            })425          );426427          expect([first, warm, afterLanding, yield* list]).toStrictEqual([428            [burrow, datekit],429            [],430            [datekit],431            [burrow],432          ]);433        }).pipe(Effect.provide(Layer.merge(counted(reads), d1)));434      })435  );436});