Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

guestTurnItemSource.ts

102 lines4.0 KB

1import {
2 applyCommandOutputFrame,
3 EMPTY_COMMAND_OUTPUT,
4} from "@t3tools/client-runtime/state/command-output";
5import {
6 GUEST_COMMAND_OUTPUT_ROUTE,
7 GUEST_ITEM_ROUTE,
8 GUEST_SHARE_PARAM,
9 OrchestrationV2CommandOutputFrame,
10 OrchestrationV2GetTurnItemResult,
11} from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import * as Data from "effect/Data";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import * as Queue from "effect/Queue";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19import { Atom } from "effect/reactivity";
20​
21import type { TurnItemSource } from "../chat/timelineRowContext";
22​
23/** What an expanded guest row says when it cannot read the item. */
24class GuestItemReadError extends Data.TaggedError("GuestItemReadError")<{
25 readonly message: string;
26}> {}
27​
28const decodeDetail = Schema.decodeUnknownSync(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));
29const decodeFrame = Schema.decodeUnknownOption(
30 Schema.fromJsonString(OrchestrationV2CommandOutputFrame),
31);
32​
33const itemUrl = (route: string, shareId: string, itemId: string) =>
34 `${route}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&item=${encodeURIComponent(itemId)}`;
35​
36/** `item` is null when the thread no longer has the item, or the share ended. */
37async function fetchGuestItemDetail(
38 shareId: string,
39 itemId: string,
40): Promise<OrchestrationV2GetTurnItemResult> {
41 const response = await fetch(itemUrl(GUEST_ITEM_ROUTE, shareId, itemId));
42 if (response.status === 403) return { item: null };
43 if (!response.ok) throw new Error(`Guest item request failed with ${response.status}.`);
44 return decodeDetail(await response.json());
46​
47// Keys are JSON so a share id or item id can never run into the next part.
48const guestItemDetailAtom = Atom.family((key: string) => {
49 const [shareId, itemId] = JSON.parse(key) as [string, string, string];
50 return Atom.make(
51 Effect.tryPromise({
52 try: () => fetchGuestItemDetail(shareId, itemId),
53 catch: () => new GuestItemReadError({ message: "Could not load this item." }),
54 }),
55 );
56});
57​
58/** Ends after the frame of a settled command, so the browser does not reconnect to it. */
59const guestCommandOutputAtom = Atom.family((key: string) => {
60 const [shareId, itemId] = JSON.parse(key) as [string, string];
61 const frames = Stream.callback<OrchestrationV2CommandOutputFrame, GuestItemReadError>((queue) =>
62 Effect.acquireRelease(
63 Effect.sync(() => {
64 const source = new EventSource(itemUrl(GUEST_COMMAND_OUTPUT_ROUTE, shareId, itemId));
65 source.addEventListener("message", (message) => {
66 const frame = decodeFrame(message.data);
67 if (Option.isNone(frame)) return;
68 Queue.offerUnsafe(queue, frame.value);
69 if (!frame.value.running) {
70 source.close();
71 Queue.endUnsafe(queue);
72 }
73 });
74 // A non-200 response closes the source for good: the share ended or the item is gone.
75 source.addEventListener("error", () => {
76 if (source.readyState === EventSource.CLOSED) {
77 Queue.failCauseUnsafe(
78 queue,
79 Cause.fail(new GuestItemReadError({ message: "Output is no longer available." })),
80 );
81 }
82 });
83 return source;
84 }),
85 (source) => Effect.sync(() => source.close()),
86 ),
87 );
88 // `scan` emits its seed first; skipping it keeps the row "loading" until the first frame.
89 return Atom.make(
90 frames.pipe(
91 Stream.scan(() => EMPTY_COMMAND_OUTPUT, applyCommandOutputFrame),
92 Stream.filter((view) => view !== EMPTY_COMMAND_OUTPUT),
93 ),
94 );
95});
96​
97/** Expanded rows on the guest page read through the guest routes, with the page's share cookie. */
98export const guestTurnItemSource = (shareId: string): TurnItemSource => ({
99 detail: ({ itemId, revision }) =>
100 guestItemDetailAtom(JSON.stringify([shareId, itemId, revision])),
101 commandOutput: ({ itemId }) => guestCommandOutputAtom(JSON.stringify([shareId, itemId])),
102});