Open History to see the last commit
1import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils";
2import * as Clock from "effect/Clock";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Random from "effect/Random";
7import * as Redacted from "effect/Redacted";
8import * as Schema from "effect/Schema";
9import * as Stream from "effect/Stream";
10import * as Sse from "effect/encoding/Sse";
11import { HttpClient, HttpClientRequest } from "effect/http";
12
13import * as GitHubRest from "./GitHubRest.ts";
14
15/** Readers fetch the pull request on every event, so check suites' conclusions go unused. */
16const EVENT_TYPES = [
17 "com.github.pull_request.review.submitted.v1",
18 "com.github.pull_request.head.changed.v1",
19 "com.github.pull_request.state.changed.v1",
20 "com.github.pull_request.merge_conflict.v1",
21 "com.github.pull_request.check_suite.status.changed.v1",
22];
23const API_ORIGIN = "https://api.github.com";
24/** GitHub sends a keep-alive at least every 15 seconds while a stream is idle. */
25const SILENCE_LIMIT = Duration.seconds(45);
26/** A connection open this long was healthy, however it ended. */
27const HEALTHY_AFTER = Duration.minutes(2);
28/** GitHub enables event streams per account, so a refusal holds for a while. */
29const REFUSED_PAUSE = Duration.hours(1);
30/** Another watch ending may free a slot under the per-account subscription limit. */
31const LIMIT_PAUSE = Duration.minutes(10);
32const MAX_FAILURES = 6;
33const MAX_BACKOFF_MS = 60_000;
34
35const Subscription = Schema.Struct({
36 id: Schema.Union([Schema.String, Schema.Number]),
37 events_url: Schema.String,
38});
39const decodeSubscription = Schema.decodeUnknownOption(Schema.fromJsonString(Subscription));
40
41const decodeStreamEnd = Schema.decodeUnknownOption(
42 Schema.fromJsonString(Schema.Struct({ outcome: Schema.String })),
43);
44
45/**
46 * How a connection ended. `renew` means the subscription expired or lost access, and `personal`
47 * that the app's token was refused where the user's own may still read.
48 */
49type Ending = "reconnect" | "renew" | "personal" | "stop";
50
51const endingOf = (data: string): Ending =>
52 Option.match(decodeStreamEnd(data), {
53 onNone: () => "reconnect",
54 onSome: ({ outcome }) => (outcome === "subscription_ended" ? "renew" : "reconnect"),
55 });
56
57export interface PullRequestEventsInput {
58 readonly host: string;
59 readonly repository: string;
60 readonly number: number;
61}
62
63/**
64 * Emits when a connection opens, so a reader catches up on what it missed, then once per change
65 * GitHub reports. Ends quietly when GitHub refuses the subscription; the caller polls meanwhile.
66 */
67export const make = Effect.gen(function* () {
68 const rest = yield* GitHubRest.GitHubRest;
69 const httpClient = yield* HttpClient.HttpClient;
70 /** Keyed by host for account-wide refusals, and by pull request for one it cannot read. */
71 const pausedUntil = new Map<string, number>();
72
73 const subscribe = Effect.fn("GitHubPullRequestEvents.subscribe")(function* (
74 input: PullRequestEventsInput,
75 ) {
76 const resourceUrl = `https://${input.host}/${input.repository}/pull/${input.number}`;
77 const now = yield* Clock.currentTimeMillis;
78 if (Math.max(pausedUntil.get(input.host) ?? 0, pausedUntil.get(resourceUrl) ?? 0) > now) {
79 return Option.none();
80 }
81 const pause = (key: string, duration: Duration.Duration) =>
82 Effect.sync(() => pausedUntil.set(key, now + Duration.toMillis(duration)));
83 const response = yield* rest
84 .rest({
85 host: input.host,
86 operation: "subscribePullRequestEvents",
87 method: "POST",
88 path: "event-subscriptions",
89 body: { resource_url: resourceUrl, event_types: EVENT_TYPES },
90 })
91 .pipe(
92 Effect.asSome,
93 Effect.catchTags({
94 GitHubApiNotFoundError: () =>
95 pause(resourceUrl, REFUSED_PAUSE).pipe(Effect.as(Option.none())),
96 GitHubApiResponseError: (error) =>
97 (error.status === 403
98 ? pause(input.host, REFUSED_PAUSE)
99 : error.status === 422
100 ? pause(input.host, LIMIT_PAUSE)
101 : Effect.void
102 ).pipe(Effect.as(Option.none())),
103 }),
104 Effect.catch((error) =>
105 Effect.logDebug("pull request event subscription failed", { error }).pipe(
106 Effect.as(Option.none()),
107 ),
108 ),
109 );
110 if (Option.isNone(response)) return Option.none();
111 // The stream request carries the token, so its URL must stay on GitHub's API.
112 return decodeSubscription(response.value.body).pipe(
113 Option.filter(({ events_url }) => URL.parse(events_url)?.origin === API_ORIGIN),
114 );
115 });
116
117 const unsubscribe = Effect.fn("GitHubPullRequestEvents.unsubscribe")(function* (
118 host: string,
119 id: string | number,
120 ) {
121 yield* rest
122 .rest({
123 host,
124 operation: "unsubscribePullRequestEvents",
125 method: "DELETE",
126 path: `event-subscriptions/${encodeURIComponent(String(id))}`,
127 })
128 .pipe(Effect.ignore);
129 });
130
131 /** One SSE connection: "changed" when it opens and per event, and last, how it ended. */
132 const connection = (
133 host: string,
134 eventsUrl: string,
135 personal: boolean,
136 ): Stream.Stream<"changed" | Ending> =>
137 Stream.unwrap(
138 Effect.gen(function* () {
139 const held = yield* rest.credential(host, { personal });
140 const response = yield* (
141 httpClient
142 .execute(
143 HttpClientRequest.get(eventsUrl).pipe(
144 HttpClientRequest.setHeaders({
145 accept: "text/event-stream",
146 "x-github-api-version": "2022-11-28",
147 "user-agent": "t3code",
148 authorization: `Bearer ${Redacted.value(held.token)}`,
149 }),
150 ),
151 )
152 // Client spans would carry the subscription URL.
153 .pipe(Effect.provideService(HttpClient.TracerDisabledWhen, () => true))
154 );
155 if (response.status === 403 || response.status === 404) {
156 return Stream.succeed<Ending>(held.source === "app" ? "personal" : "stop");
157 }
158 if (response.status !== 200) return Stream.succeed<Ending>("reconnect");
159 return response.stream.pipe(
160 Stream.timeoutOrElse({ duration: SILENCE_LIMIT, orElse: () => Stream.fail("silent") }),
161 Stream.decodeText,
162 Stream.pipeThroughChannel(Sse.decode()),
163 Stream.map((frame): "changed" | Ending =>
164 frame.event === "github.stream.end" ? endingOf(frame.data) : "changed",
165 ),
166 Stream.prepend(["changed" as const]),
167 // A close without GitHub's end frame is reconnected like one with it.
168 Stream.concat(Stream.succeed<Ending>("reconnect")),
169 Stream.takeUntil((element) => element !== "changed"),
170 );
171 }),
172 ).pipe(
173 Stream.catchCause((cause) =>
174 Stream.fromEffect(
175 Effect.logDebug("pull request event stream failed", { cause }).pipe(
176 Effect.as<Ending>("reconnect"),
177 ),
178 ),
179 ),
180 );
181
182 const backoff = Effect.fn("GitHubPullRequestEvents.backoff")(function* (failures: number) {
183 const jitter = yield* Random.next;
184 yield* Effect.sleep(
185 Duration.millis(Math.min(MAX_BACKOFF_MS, 1_000 * 2 ** failures) * (0.5 + jitter / 2)),
186 );
187 });
188
189 return (input: PullRequestEventsInput): Stream.Stream<void> => {
190 const target = { ...input, host: normalizeHost(input.host) };
191 if (target.host !== "github.com") return Stream.empty;
192
193 /** Follows one subscription; sets `session.renew` when it needs replacing. */
194 const follow = (
195 session: { renew: boolean },
196 eventsUrl: string,
197 personal: boolean,
198 failuresSoFar: number,
199 ): Stream.Stream<void> =>
200 Stream.unwrap(
201 Clock.currentTimeMillis.pipe(
202 Effect.map((openedAt) => {
203 let ending: Ending = "reconnect";
204 let changes = 0;
205 return connection(target.host, eventsUrl, personal).pipe(
206 Stream.flatMap((element) => {
207 if (element === "changed") {
208 changes += 1;
209 return Stream.succeed(undefined);
210 }
211 ending = element;
212 return Stream.empty;
213 }),
214 Stream.concat(
215 Stream.unwrap(
216 Clock.currentTimeMillis.pipe(
217 Effect.map((closedAt) => {
218 // The first change is the opening; an event or a long life proves it worked.
219 const healthy =
220 changes > 1 || closedAt - openedAt >= Duration.toMillis(HEALTHY_AFTER);
221 const failures = healthy ? 0 : failuresSoFar + 1;
222 switch (ending) {
223 case "stop":
224 return Stream.empty;
225 case "renew":
226 session.renew = true;
227 return Stream.empty;
228 case "personal":
229 return personal
230 ? Stream.empty
231 : follow(session, eventsUrl, true, failuresSoFar);
232 case "reconnect":
233 return failures > MAX_FAILURES
234 ? Stream.empty
235 : Stream.fromEffectDrain(backoff(failures)).pipe(
236 Stream.concat(follow(session, eventsUrl, personal, failures)),
237 );
238 }
239 }),
240 ),
241 ),
242 ),
243 );
244 }),
245 ),
246 );
247
248 /** One subscription, deleted once its stream has closed. */
249 const subscription = (session: { renew: boolean }): Stream.Stream<void> =>
250 Stream.unwrap(
251 Effect.acquireRelease(subscribe(target), (held) =>
252 Option.isSome(held) ? unsubscribe(target.host, held.value.id) : Effect.void,
253 ).pipe(
254 Effect.map(
255 Option.match({
256 onNone: () => Stream.empty,
257 onSome: ({ events_url }) => follow(session, events_url, false, 0),
258 }),
259 ),
260 ),
261 );
262
263 const subscribed = (): Stream.Stream<void> =>
264 Stream.suspend(() => {
265 const session = { renew: false };
266 return subscription(session).pipe(
267 Stream.concat(
268 Stream.suspend(() =>
269 session.renew
270 ? Stream.fromEffectDrain(backoff(0)).pipe(Stream.concat(subscribed()))
271 : Stream.empty,
272 ),
273 ),
274 );
275 });
276
277 // Event streams are a GitHub preview, so only the app sign-in, itself opt-in, uses them.
278 return Stream.unwrap(
279 rest.appCredential(target.host).pipe(
280 Effect.map((app) => (Option.isSome(app) ? subscribed() : Stream.empty)),
281 Effect.orElseSucceed(() => Stream.empty),
282 ),
283 );
284 };
285});