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

tanStackSourceEvents.ts

170 lines6.8 KB

1import * as Clock from "effect/Clock";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Random from "effect/Random";
5import * as Redacted from "effect/Redacted";
6import * as Stream from "effect/Stream";
7import * as FetchHttpClient from "effect/http/FetchHttpClient";
8import * as HttpClient from "effect/http/HttpClient";
9import * as HttpClientRequest from "effect/http/HttpClientRequest";
10​
11import * as Credentials from "./TanStackSourceCredentials.ts";
12import * as Hosts from "./tanStackSourceHosts.ts";
13​
14/** Source sends `: ok` every 15 seconds and ends each stream after 60. */
15const SILENCE_LIMIT = Duration.seconds(45);
16/** A stream that stayed open this long was healthy however it ended; Source closes at 60s. */
17const HEALTHY_AFTER = Duration.seconds(30);
18const MAX_FAILURES = 6;
19const MAX_BACKOFF_MS = 60_000;
20const NO_REDIRECT: RequestInit = { redirect: "manual" };
21​
22export interface PullRequestEventsInput {
23 readonly host: string;
24 readonly repository: string;
25 readonly number: number;
27​
28/**
29 * Reads Source's stream a line at a time; true where a frame that reports a change ends. Source
30 * also sends frames with an id alone, which only move the cursor, and `: ok` keep-alives; a
31 * generic SSE decoder drops the former without recording their id.
32 */
33export function frameReader(cursor: { lastEventId: string | undefined }) {
34 let reports = false;
35 return (line: string): boolean => {
36 if (line === "") {
37 const ended = reports;
38 reports = false;
39 return ended;
40 }
41 if (line.startsWith(":")) return false;
42 const colon = line.indexOf(":");
43 const field = colon < 0 ? line : line.slice(0, colon);
44 const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /u, "");
45 if (field === "id") cursor.lastEventId = value;
46 else if (field === "event" || field === "data") reports = true;
47 return false;
48 };
50​
51/** How one connection ended: Source closes every stream after a minute, which is `reconnect`. */
52type Ending = { readonly _tag: "reconnect"; readonly healthy: boolean } | { readonly _tag: "stop" };
53​
54/**
55 * Follows the pull request's live event stream: once when it first connects, so a reader catches
56 * up, then once per change Source reports. Reconnects resume from the last event, so nothing in
57 * between is lost. Ends quietly when Source refuses it; readers then poll.
58 */
59export const make = Effect.gen(function* () {
60 const httpClient = yield* HttpClient.HttpClient;
61 const credentials = yield* Credentials.TanStackSourceCredentials;
62​
63 const connection = (
64 input: PullRequestEventsInput,
65 cursor: { lastEventId: string | undefined },
66 ): Stream.Stream<"changed" | Ending> =>
67 Stream.unwrap(
68 Effect.gen(function* () {
69 const credential = yield* credentials.get(input.host);
70 const query = new URLSearchParams({ scope: "pr", number: String(input.number) });
71 const response = yield* httpClient
72 .execute(
73 HttpClientRequest.get(
74 `https://${input.host}/api/v1/repos/${input.repository}/events?${query}`,
75 ).pipe(
76 HttpClientRequest.setHeaders({
77 accept: "text/event-stream",
78 "user-agent": "t3code",
79 authorization: `Bearer ${Redacted.value(credential.token)}`,
80 ...(cursor.lastEventId === undefined
81 ? {}
82 : { "last-event-id": cursor.lastEventId }),
83 }),
84 ),
85 )
86 .pipe(
87 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
88 Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT),
89 );
90 if (response.status === 401 || response.status === 403 || response.status === 404)
91 return Stream.succeed<Ending>({ _tag: "stop" });
92 if (response.status !== 200)
93 return Stream.succeed<Ending>({ _tag: "reconnect", healthy: false });
94 const openedAt = yield* Clock.currentTimeMillis;
95 // A stream with nothing to resume from is a catch-up point; one sent `Last-Event-ID`
96 // resumes where the last left off, so it misses nothing and needs no refresh of its own.
97 const opening = cursor.lastEventId === undefined ? (["changed"] as const) : [];
98 const readLine = frameReader(cursor);
99 let events = 0;
100 return response.stream.pipe(
101 Stream.timeoutOrElse({ duration: SILENCE_LIMIT, orElse: () => Stream.fail("silent") }),
102 Stream.decodeText,
103 Stream.splitLines,
104 Stream.filter(readLine),
105 Stream.map((): "changed" => {
106 events += 1;
107 return "changed";
108 }),
109 Stream.prepend(opening),
110 Stream.concat(
111 Stream.fromEffect(
112 Clock.currentTimeMillis.pipe(
113 Effect.map((closedAt): Ending => ({
114 _tag: "reconnect",
115 // An event, or a stream that ran most of its minute, proves it worked.
116 healthy: events > 0 || closedAt - openedAt >= Duration.toMillis(HEALTHY_AFTER),
117 })),
118 ),
119 ),
120 ),
121 );
122 }),
123 ).pipe(
124 Stream.catchCause((cause) =>
125 Stream.fromEffect(
126 Effect.logDebug("TanStack Source event stream failed", { cause }).pipe(
127 Effect.as<Ending>({ _tag: "reconnect", healthy: false }),
128 ),
129 ),
130 ),
131 );
132​
133 const backoff = Effect.fn("TanStackSourceEvents.backoff")(function* (failures: number) {
134 const jitter = yield* Random.next;
135 yield* Effect.sleep(
136 Duration.millis(Math.min(MAX_BACKOFF_MS, 1_000 * 2 ** failures) * (0.5 + jitter / 2)),
137 );
138 });
139​
140 return (input: PullRequestEventsInput): Stream.Stream<void> => {
141 const host = Hosts.tanStackSourceHost(input.host);
142 const repository = Hosts.tanStackSourceRepositoryPath(input.repository);
143 if (host === null || repository === null) return Stream.empty;
144 const target = { host, repository, number: input.number };
145 const cursor = { lastEventId: undefined as string | undefined };
146​
147 const follow = (failures: number): Stream.Stream<void> => {
148 let ending: Ending = { _tag: "stop" };
149 return connection(target, cursor).pipe(
150 Stream.flatMap((element) => {
151 if (element === "changed") return Stream.succeed(undefined);
152 ending = element;
153 return Stream.empty;
154 }),
155 Stream.concat(
156 Stream.suspend(() => {
157 if (ending._tag === "stop") return Stream.empty;
158 const next = ending.healthy ? 0 : failures + 1;
159 if (next > MAX_FAILURES) return Stream.empty;
160 return next === 0
161 ? follow(0)
162 : Stream.fromEffectDrain(backoff(next)).pipe(Stream.concat(follow(next)));
163 }),
164 ),
165 );
166 };
167​
168 return follow(0);
169 };
170});