Review fixes for 1202
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- watch.ts: following from the replay's last number dropped the read that covers the gap between a page's first read and the stream. A page its loader seeded on the server (answer, ledger, env, people, a proposal), or whose list was read beside the replay, missed whatever was judged or landed before the replay was read. Once the replay is in, the keys its events change are now invalidated once; the stream still follows from the replay's last number. - keys.events(project): the replay's own key, so that one read does not replay every event again. Each event the stream brings and each poll invalidate it; a mutation's keys no longer do (its event does). - Tests: watch.test.ts reads the page once more after the replay and never the replay itself; the replay is read again on each streamed event and on each poll (both red by assertion first); the gap-event test counts the re-read and the event, once each.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+148 added−30 removed
- tests:+94 added−3 removed
- other:+54 added−27 removed
Provenance
- Commit
512af5a- Tree
f87efbd- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
38e5215
4 files changed+148 added−30 removed
modified:apps/web/src/client/events.ts+7 added-4 removed
4 unmodified lines5 * No contract of its own: the fold reads only what `watch` already sends.6 *7 * - `projectEventsAtom(project)` holds the replay. Over JSON the platform8 * replays the kept events in one response and ends (only the framed9- * `/rpc` keeps the stream open), and the project's key reads it again,10- * so the page's live view (`watch.ts`) keeps it current.9+ * `/rpc` keeps the stream open), and the page's live view (`watch.ts`)10+ * reads it again on each event, so it stays current.11 * - The derivations beside it are pure: `askStates` (per ask), `whoseMove`,12 * `familyMarks`, `stampsFrom` (when a landing that happened while the page13 * was open earns its stamp) and `recentLandings`.14 */64 unmodified lines79 80 /** Who acts next on an ask. */81 export type Move = "answerer" | "decider" | "family" | "none" | "platform";82 83-/** The project's events, replayed from the first; read again whenever the project's key is invalidated. */83+/**84+ * The project's events, replayed from the first; read again on each event85+ * the page's live view hears, and on each of its polls (`keys.events`).86+ */87 export const projectEventsAtom = Atom.family((project: ProjectName) =>88 Atom.withServerValueInitial(86- ContractsClient.runtime.factory.withReactivity(keys.project(project))(89+ ContractsClient.runtime.factory.withReactivity(keys.events(project))(90 ContractsClient.runtime.atom(91 Effect.gen(function* () {92 const client = yield* ContractsClient;93 217 unmodified linesmodified:apps/web/src/client/keys.ts+6 added
14 unmodified lines15161718192021222324252627288 unmodified lines14 unmodified lines `project:${project}`, ], /** The project's code reads (refs, trees, files, log, commits, why): a landing changes them. */ code: (project: ProjectName): readonly string[] => [`code:${project}`], /** * The project's replayed events (`events.ts`): every event changes them. * Not the project's key, so a page's reads can be read again without * replaying every event once more. */ events: (project: ProjectName): readonly string[] => [`events:${project}`], front: (): readonly string[] => ["front"], ledger: (project: ProjectName): readonly string[] => [`ledger:${project}`], /** The project's evaluated policy (the people page): a landing may change it. */ policy: (project: ProjectName): readonly string[] => [`policy:${project}`],8 unmodified linesmodified:apps/web/src/client/watch.ts+41 added-23 removed
12 unmodified lines131415161718192021222324171819202122232425262728293031323334353637383940414255 unmodified lines9899100101979810210310410510610710810911011111211311411510211611711811912012112212312412512612712812913013113213311111211313413513613713813914014110 unmodified lines1521531541551321561571581591602 unmodified lines16316416516614314414514614714814915016716816917017117212 unmodified lines * polling: every `POLL_MS` the project's keys are invalidated, and since * an ask's keys include its project's (`keys.ts`), the answer page's * verdict fetches again too. * * The project and answer pages mount it (`useAtomMount`), so it runs only * in the browser, from the page's mount to its unmount. It follows from the * last number of the project's replay (`projectEventsAtom`, which the page * reads anyway), not from the first event, so a new watcher hears none of * the kept events again and makes the page read nothing twice; whatever * happened between that replay and the stream's start comes first on the * stream, so it is heard once. A replay that cannot be read starts the * follow from the first event, as before. * Every page that shows a project live mounts it (`useAtomMount`), so it * runs only in the browser, from the page's mount to its unmount. It follows from the * last number of the project's replay (`projectEventsAtom`), not from the * first event, so a new watcher hears none of the kept events again and * never replays them twice. The page's own reads may be older than that * replay (a loader read them on the server, or they were read beside it), * so once the replay is in, the keys its events change are invalidated * once: whatever happened between the page's first read and the replay is * read then, and whatever happened after comes first on the stream. The * replay has a key of its own (`keys.events`), so that read leaves it be; * each event the stream brings, and each poll, reads it again. A replay * that cannot be read starts the follow from the first event, as before. */import { ProjectEvent } from "@repo/protocol/domain/event";import type { ProjectName } from "@repo/protocol/ids";import { Array, Context, Effect, Exit, Layer, Option, Ref, Schedule, Stream,} from "effect";55 unmodified lines Released: () => keys.project(project), Warned: ({ ask }) => keys.ask(project, ask), });
/** `project` followed from `since` for as long as it runs: the stream while it works, then the poll. */const followed = (project: ProjectName, since: Effect.Effect<number>) =>/** The keys any of `events` changes, each once. */const keysOfAll = (project: ProjectName) => (events: readonly ProjectEvent[]): readonly string[] => Array.dedupe(events.flatMap((event) => keysOf(project, event)));
/** `project` followed from the end of its `replay` for as long as it runs: the stream while it works, then the poll. */const followed = <E>( project: ProjectName, replay: Effect.Effect<readonly ProjectEvent[], E>) => Effect.gen(function* () { const watch = yield* ProjectWatch; const reactivity = yield* Reactivity.Reactivity; const last = yield* Ref.make(yield* since); const kept = yield* Effect.option(replay);
const last = yield* Ref.make( Option.match(kept, { onNone: () => 0, onSome: lastSeq }) );
// The page's reads, once, for what came between them and the replay. yield* reactivity.invalidate( Option.match(kept, { onNone: () => [], onSome: keysOfAll(project) }) );
/** One stream from the last number heard, to its end: whether it failed before it heard anything. */ const once = Effect.gen(function* () { const heard = yield* Ref.make(false);
const ended = yield* watch.follow(project, yield* Ref.get(last)).pipe( Stream.runForEachArray((events) => Effect.gen(function* () { yield* reactivity.invalidate( Array.dedupe(events.flatMap((event) => keysOf(project, event))) ); yield* reactivity.invalidate([ ...keysOfAll(project)(events), ...keys.events(project), ]); yield* Ref.set(last, Array.lastNonEmpty(events).seq); yield* Ref.set(heard, true); }) ),10 unmodified lines }) );
return yield* reactivity .invalidate(keys.project(project)) .invalidate([...keys.project(project), ...keys.events(project)]) .pipe(Effect.delay(POLL_MS), Effect.forever); });
/**2 unmodified lines */export const watchAtom = Atom.family((project: ProjectName) => Atom.map( watchRuntime.atom((get) => followed( project, // Read once, not followed: a new replay must not start the stream over. get.resultOnce(projectEventsAtom(project)).pipe( Effect.map(lastSeq), Effect.orElseSucceed(() => 0) ) ) // Read once, not followed: a new replay must not start the stream over. followed(project, get.resultOnce(projectEventsAtom(project))) ), constVoid ));modified:apps/web/test/watch.test.ts+94 added-3 removed
1 /**2 * The page's live view: `watchAtom(project)`, mounted by the3 * project and answer pages, follows the project's events from the last4 * number of the replay the page read and invalidates the keys each one5- * changes, so the page's reads fetch again; a stream that fails before it6- * hears anything turns into a poll every `POLL_MS`. Each test runs the atom5+ * changes, so the page's reads fetch again (and, once the replay is in,6+ * the keys its events change, for what came before the stream); a stream7+ * that fails before it hears anything turns into a poll every `POLL_MS`. Each test runs the atom8 * in a registry of its own, over a stub stream, a replay given as the9 * project's events and the test's own `Reactivity`, on the TestClock.10 */11 import { describe, expect, it } from "@effect/vitest";363 unmodified lines375 reactivity,376 AsyncResult.success(kept.slice(0, 7))377 );378 379+ // Once for the page's read after the replay, once for the event.380+ yield* runUntil(() => fired.length > 1);381+ yield* runUntil(() => fired.length > 2);382+383+ expect(fired).toStrictEqual([projectKey, projectKey]);384+ })385+ );386+387+ // A page's own reads may be older than the replay (a loader read them on388+ // the server; the replay is read in the browser later): what happened in389+ // between is in the replay but not on the page, and the stream starts390+ // after it.391+ it.effect(392+ "reads the page once more after the replay, for what came between the page's read and the replay, and never the replay itself",393+ () =>394+ Effect.gen(function* () {395+ const { fired, reactivity } = yield* invalidations;396+ const [events] = keys.events(datekit);397+398+ reactivity.registerUnsafe([events ?? ""], () => {399+ fired.push("events");400+ });401+402+ yield* tab(403+ () => Stream.never,404+ reactivity,405+ AsyncResult.success([406+ ProjectEvent.cases.Claimed.make({407+ ask: parseIso,408+ at,409+ claimant: Handle.make("alice"),410+ seq: 1,411+ }),412+ ProjectEvent.cases.Judged.make({413+ ask: parseIso,414+ at,415+ head,416+ outcome: Outcome.cases.Checking.make({ stage: "merge" }),417+ seq: 2,418+ }),419+ ])420+ );421+422 const heard = yield* firedNow(fired);423 424 yield* runUntil(() => fired.length > 0);425 426 expect({ after: [...fired], heard }).toStrictEqual({427 after: [],384- heard: [projectKey],428+ heard: [askKey, projectKey],429 });430 })431 );432 433 it.effect(434+ "reads the replay again on each event the stream brings, and on each poll",435+ () =>436+ Effect.gen(function* () {437+ const reactivity = yield* Reactivity.make;438+ const fired: string[] = [];439+ const [events] = keys.events(datekit);440+441+ reactivity.registerUnsafe([events ?? ""], () => {442+ fired.push("events");443+ });444+445+ const heard = yield* Queue.unbounded<ProjectEvent>();446+ const connects = yield* Ref.make(0);447+448+ yield* tab(449+ () =>450+ Stream.unwrap(451+ Effect.map(452+ Ref.getAndUpdate(connects, (count) => count + 1),453+ (count) =>454+ count === 0455+ ? Stream.fromQueue(heard).pipe(Stream.take(1))456+ : Stream.fail("no framed /rpc here")457+ )458+ ),459+ reactivity460+ );461+462+ yield* Queue.offer(463+ heard,464+ ProjectEvent.cases.Warned.make({ ask: parseIso, at, seq: 1 })465+ );466+467+ const onEvent = yield* firedNow(fired);468+469+ yield* TestClock.adjust(POLL_MS);470+ yield* runUntil(() => Ref.getUnsafe(connects) > 1);471+ yield* TestClock.adjust(POLL_MS);472+473+ expect({ onEvent, onPoll: yield* firedNow(fired) }).toStrictEqual({474+ onEvent: ["events"],475+ onPoll: ["events"],476+ });477+ })478+ );479+480+ it.effect(481 "follows from the first event when the replay could not be read",482 () =>483 Effect.gen(function* () {484 const { reactivity } = yield* invalidations;20 unmodified lines