Skip to content
Myr

read.ts

This file

Path

apps/web/src/features/inbox/read.ts

344 lines · 9.5 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 1–344why, one step back
1import { Client } from "@repo/protocol/contracts";
2import { AnswerView } from "@repo/protocol/domain/answer";3import { ClaimView } from "@repo/protocol/domain/claim";4import { Today } from "@repo/protocol/domain/decision";5import { FrontPageEntry } from "@repo/protocol/domain/front-page";6import { Outcome, StageName } from "@repo/protocol/domain/outcome";7import { Handle } from "@repo/protocol/ids";8import type { ProjectName } from "@repo/protocol/ids";9import { NotDecider, Refusal } from "@repo/protocol/refusal";10import {11 Array as Arr,12 Cause,13 DateTime,14 Effect,15 Exit,16 Option,17 Order,18 Schema,19} from "effect";2021import { isSignedOut } from "./decisions.ts";2223const ASKS_SHOWN = 8;2425export const WORK_SHOWN = 10;2627const AT_ONCE = 4;2829export const Work = Schema.Struct({30 answer: Schema.optionalKey(AnswerView),31 claim: ClaimView,32 /** The gate stage the answer reached, from its verdict; absent while it has none. */33 stage: Schema.optionalKey(StageName),34 want: Schema.optionalKey(Schema.NonEmptyString),35});3637export type Work = typeof Work.Type;3839export const Decisions = Schema.TaggedUnion({40 Decides: { today: Today },41 NotDecider: {},42 Unreachable: {},43});4445export type Decisions = typeof Decisions.Type;4647export const Takeable = Schema.TaggedUnion({48 Listed: { asks: Schema.Array(FrontPageEntry) },49 Unreachable: {},50});5152export type Takeable = typeof Takeable.Type;5354export const InboxRead = Schema.TaggedUnion({55 Read: {56 asks: Takeable,57 decisions: Decisions,58 handle: Handle,59 held: Schema.Int,60 running: Schema.Int,61 work: Schema.Array(Work),62 },63 Refused: { refusal: Refusal },64 SignedOut: {},65 Unreachable: {},66});6768export type InboxRead = typeof InboxRead.Type;6970export const InboxPageData = Schema.Struct({71 now: Schema.DateTimeUtcFromString,72 read: InboxRead,73});7475export type InboxPageData = typeof InboxPageData.Type;7677/** The decisions the read carries, when the reader decides somewhere and they came. */78export const todayOf = (read: InboxRead): Option.Option<Today> =>79 InboxRead.match(read, {80 Read: ({ decisions }) =>81 Decisions.match(decisions, {82 Decides: ({ today }) => Option.some(today),83 NotDecider: () => Option.none(),84 Unreachable: () => Option.none(),85 }),86 Refused: () => Option.none(),87 SignedOut: () => Option.none(),88 Unreachable: () => Option.none(),89 });9091/** The decisions read again after a choice take the loaded ones' place; the rest stays as it was read. */92export const withToday = (read: InboxRead, today: Today): InboxRead =>93 InboxRead.match(read, {94 Read: (signed) =>95 Option.isSome(todayOf(read))96 ? { ...signed, decisions: Decisions.cases.Decides.make({ today }) }97 : read,98 Refused: () => read,99 SignedOut: () => read,100 Unreachable: () => read,101 });102103export const isRunning = (claim: ClaimView) =>104 claim.state === "live" || claim.state === "warned";105106const openedOrder = Order.mapInput(107 DateTime.Order,108 (claim: ClaimView) => claim.openedAt109);110111const workOrder: Order.Order<ClaimView> = Order.combine(112 Order.mapInput(Order.Boolean, (claim: ClaimView) => !isRunning(claim)),113 Order.flip(openedOrder)114);115116const answerOrder = Order.mapInput(117 DateTime.Order,118 (answer: AnswerView) => answer.at119);120121const isNotDecider = Schema.is(NotDecider);122123const isRefusal = Schema.is(Refusal);124125export const askKey = ({ ask, project }: ClaimView) => `${project}/${ask}`;126127const sharedAsks = (claims: readonly ClaimView[]) =>128 new Set(129 Object.entries(Arr.groupBy(claims, ({ ask }) => ask)).flatMap(130 ([ask, holding]) =>131 new Set(holding.map(({ project }) => project)).size > 1 ? [ask] : []132 )133 );134135const answersIn = (projects: readonly ProjectName[]) =>136 Effect.gen(function* () {137 const client = yield* Client;138139 return new Map(140 yield* Effect.forEach(141 projects,142 (project) =>143 client.status({ project }).pipe(144 Effect.map(({ answers }) => [project, answers] as const),145 Effect.orElseSucceed(() => [project, []] as const)146 ),147 { concurrency: AT_ONCE }148 )149 );150 });151152const wantsOf = (claims: readonly ClaimView[]) =>153 Effect.gen(function* () {154 const client = yield* Client;155 const asks = Arr.dedupeWith(claims, (a, b) => askKey(a) === askKey(b));156157 return new Map(158 yield* Effect.forEach(159 asks,160 (claim) =>161 client.showAsk({ ask: claim.ask, project: claim.project }).pipe(162 Effect.map(({ ask }) => [[askKey(claim), ask.brief.want] as const]),163 Effect.orElseSucceed(() => [])164 ),165 { concurrency: AT_ONCE }166 ).pipe(Effect.map((found) => found.flat()))167 );168 });169170const shownOf = (claims: readonly ClaimView[]) =>171 Arr.sort(claims, workOrder).slice(0, WORK_SHOWN);172173export const pairWork = ({174 again,175 answers,176 claims,177 wants,178}: {179 readonly claims: readonly ClaimView[];180 readonly answers: readonly AnswerView[];181 readonly again: ReadonlyMap<ProjectName, readonly AnswerView[]>;182 readonly wants: ReadonlyMap<string, string>;183}): readonly Work[] => {184 const shared = sharedAsks(claims);185186 const newest = new Map(187 Arr.sort(claims, openedOrder).map(188 (claim) => [askKey(claim), claim] as const189 )190 );191192 const answerOf = (claim: ClaimView) => {193 if (newest.get(askKey(claim)) !== claim) {194 return Option.none();195 }196197 const [latest] = Arr.sort(198 (shared.has(claim.ask)199 ? (again.get(claim.project) ?? [])200 : answers201 ).filter(({ ask }) => ask === claim.ask),202 Order.flip(answerOrder)203 );204205 return Option.fromUndefinedOr(latest);206 };207208 return shownOf(claims).map((claim): Work => ({209 claim,210 ...Option.match(answerOf(claim), {211 onNone: () => ({}),212 onSome: (answer) => ({ answer }),213 }),214 ...Option.match(Option.fromUndefinedOr(wants.get(askKey(claim))), {215 onNone: () => ({}),216 onSome: (want) => ({ want }),217 }),218 }));219};220221// A verdict names the stage an answer reached; a check still running names it in its outcome.222const stageOf = (work: Work) =>223 Effect.gen(function* () {224 const client = yield* Client;225 const { answer, claim } = work;226227 if (answer === undefined) {228 return work;229 }230231 const { verdict } = yield* client232 .verdict({ ask: claim.ask, head: answer.head, project: claim.project })233 .pipe(Effect.orElseSucceed(() => ({ verdict: undefined })));234235 const stage = Option.firstSomeOf([236 Option.map(Option.fromUndefinedOr(verdict), ({ stage: at }) => at),237 Outcome.isAnyOf(["Checking"])(answer.outcome)238 ? Option.some(answer.outcome.stage)239 : Option.none(),240 ]);241242 return Option.match(stage, {243 onNone: () => work,244 onSome: (at): Work => ({ ...work, stage: at }),245 });246 });247248const workOf = (claims: readonly ClaimView[], answers: readonly AnswerView[]) =>249 Effect.gen(function* () {250 const shown = shownOf(claims);251 const shared = sharedAsks(claims);252253 const [again, wants] = yield* Effect.all(254 [255 answersIn(256 Arr.dedupe(257 shown.flatMap(({ ask, project }) =>258 shared.has(ask) ? [project] : []259 )260 )261 ),262 wantsOf(shown),263 ],264 { concurrency: "unbounded" }265 );266267 return yield* Effect.forEach(268 pairWork({ again, answers, claims, wants }),269 stageOf,270 { concurrency: AT_ONCE }271 );272 });273274const failedRead = (cause: Cause.Cause<unknown>): InboxRead => {275 const error = Cause.findErrorOption(cause);276277 if (Option.isSome(error) && isRefusal(error.value)) {278 return InboxRead.cases.Refused.make({ refusal: error.value });279 }280281 return isSignedOut(cause)282 ? InboxRead.cases.SignedOut.make({})283 : InboxRead.cases.Unreachable.make({});284};285286/** `project` narrows the inbox to one project: its decisions, the reader's claims in it and its asks. */287export const readInbox = ({ project }: { readonly project?: ProjectName }) =>288 Effect.gen(function* () {289 const client = yield* Client;290 const scope = project === undefined ? {} : { project };291292 const [status, today, front] = yield* Effect.all(293 [294 Effect.exit(client.status(scope)),295 Effect.exit(client.today(scope)),296 Effect.option(client.frontPage({})),297 ],298 { concurrency: "unbounded" }299 );300301 const decisions = Exit.match(today, {302 onFailure: (cause) =>303 Option.exists(Cause.findErrorOption(cause), isNotDecider)304 ? Decisions.cases.NotDecider.make({})305 : Decisions.cases.Unreachable.make({}),306 onSuccess: (read) => Decisions.cases.Decides.make({ today: read }),307 });308309 const asks = Option.match(front, {310 onNone: () => Takeable.cases.Unreachable.make({}),311 onSome: ({ entries }) =>312 Takeable.cases.Listed.make({313 asks: entries314 .filter(315 (entry) =>316 entry.takeable &&317 (project === undefined || entry.project === project)318 )319 .slice(0, ASKS_SHOWN),320 }),321 });322323 const read = yield* Exit.match(status, {324 onFailure: (cause) => Effect.succeed(failedRead(cause)),325 onSuccess: ({ answers, claims, handle }) =>326 workOf(claims, answers).pipe(327 Effect.map((work) =>328 InboxRead.cases.Read.make({329 asks,330 decisions,331 handle,332 held: claims.length,333 running: claims.filter(isRunning).length,334 work,335 })336 )337 ),338 });339340 return yield* Schema.encodeEffect(InboxPageData)({341 now: yield* DateTime.now,342 read,343 });344 });