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

gitHubPullRequestEvents.test.ts

195 lines7.5 KB

1import { assert, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as Option from "effect/Option";
5import * as Redacted from "effect/Redacted";
6import * as Stream from "effect/Stream";
7import * as TestClock from "effect/testing/TestClock";
8import { HttpClient, HttpClientResponse } from "effect/http";
9​
10import * as GitHubPullRequestEvents from "./gitHubPullRequestEvents.ts";
11import { GitHubApiNotFoundError, GitHubApiResponseError } from "./GitHubRequestPolicy.ts";
12import * as GitHubRest from "./GitHubRest.ts";
13​
14const target = { host: "github.com", repository: "pingdotgg/t3code", number: 15 };
15​
16const sse = (...frames: ReadonlyArray<readonly [string, string]>) =>
17 frames.map(([event, data]) => `event: ${event}\ndata: ${data}\n\n`).join("");
18​
19function fakeRest(
20 subscribe: (
21 count: number,
22 ) => Effect.Effect<string, GitHubApiResponseError | GitHubApiNotFoundError>,
23 signedIn = true,
24) {
25 const posts: Array<unknown> = [];
26 const deletes: Array<string> = [];
27 const rest = GitHubRest.GitHubRest.of({
28 rest: (input) =>
29 input.method === "DELETE"
30 ? Effect.sync(() => {
31 deletes.push(input.path);
32 return { status: 204, headers: {}, body: "", truncated: false, invalidUtf8: false };
33 })
34 : Effect.suspend(() => {
35 posts.push(input.body);
36 return subscribe(posts.length);
37 }).pipe(
38 Effect.map((body) => ({
39 status: 201,
40 headers: {},
41 body,
42 truncated: false,
43 invalidUtf8: false,
44 })),
45 ),
46 credential: (_host, options) =>
47 Effect.succeed(
48 options?.personal === true
49 ? { token: Redacted.make("user-token"), fingerprint: "user", source: "gh" as const }
50 : { token: Redacted.make("app-token"), fingerprint: "app", source: "app" as const },
51 ),
52 appCredential: () =>
53 Effect.succeed(
54 signedIn
55 ? Option.some({
56 token: Redacted.make("app-token"),
57 fingerprint: "app",
58 source: "app" as const,
59 })
60 : Option.none(),
61 ),
62 });
63 return { rest, posts, deletes };
65​
66const eventsOf = (rest: GitHubRest.GitHubRest["Service"], httpClient: HttpClient.HttpClient) =>
67 GitHubPullRequestEvents.make.pipe(
68 Effect.provideService(GitHubRest.GitHubRest, rest),
69 Effect.provideService(HttpClient.HttpClient, httpClient),
70 );
71​
72const subscription = (id: number) =>
73 Effect.succeed(
74 JSON.stringify({ id, events_url: `https://api.github.com/event-subscriptions/${id}/events` }),
75 );
76​
77it.effect("follows a pull request across a refused app token, reconnects, and renewals", () =>
78 Effect.gen(function* () {
79 const { rest, posts, deletes } = fakeRest(subscription);
80 const connections: Array<string> = [];
81 const answers = [
82 // The app is not installed on this repository; the user's own token reads it.
83 () => new Response(null, { status: 404 }),
84 () =>
85 new Response(
86 sse(
87 ["com.github.pull_request.head.changed.v1", "{}"],
88 ["github.stream.end", '{"outcome":"reconnect","reason":"shutdown"}'],
89 ),
90 ),
91 () =>
92 new Response(
93 sse(["github.stream.end", '{"outcome":"subscription_ended","reason":"expired"}']),
94 ),
95 () => new Response(": heartbeat\n\n"),
96 ];
97 const httpClient = HttpClient.make((request) =>
98 Effect.sync(() => {
99 connections.push(`${request.url} ${request.headers.authorization}`);
100 return HttpClientResponse.fromWeb(request, answers[connections.length - 1]!());
101 }),
102 );
103​
104 const events = yield* eventsOf(rest, httpClient);
105 const fiber = yield* events(target).pipe(Stream.take(4), Stream.runCount, Effect.forkChild);
106 yield* TestClock.adjust("5 minutes");
107 // An open per connection plus the head change.
108 assert.equal(yield* Fiber.join(fiber), 4);
109​
110 assert.deepEqual(connections, [
111 "https://api.github.com/event-subscriptions/1/events Bearer app-token",
112 "https://api.github.com/event-subscriptions/1/events Bearer user-token",
113 "https://api.github.com/event-subscriptions/1/events Bearer user-token",
114 "https://api.github.com/event-subscriptions/2/events Bearer app-token",
115 ]);
116 assert.deepEqual(posts[0], {
117 resource_url: "https://github.com/pingdotgg/t3code/pull/15",
118 event_types: [
119 "com.github.pull_request.review.submitted.v1",
120 "com.github.pull_request.head.changed.v1",
121 "com.github.pull_request.state.changed.v1",
122 "com.github.pull_request.merge_conflict.v1",
123 ],
124 });
125 assert.deepEqual(deletes, ["event-subscriptions/1", "event-subscriptions/2"]);
126 }),
127);
128​
129it.effect("gives up on a silent stream and deletes its subscription", () =>
130 Effect.gen(function* () {
131 const { rest, posts, deletes } = fakeRest(subscription);
132 let connections = 0;
133 // Answers, then never sends a byte, not even a keep-alive.
134 const httpClient = HttpClient.make((request) =>
135 Effect.sync(() => {
136 connections += 1;
137 return HttpClientResponse.fromWeb(request, new Response(new ReadableStream()));
138 }),
139 );
140 const events = yield* eventsOf(rest, httpClient);
141 const fiber = yield* events(target).pipe(Stream.runCount, Effect.forkChild);
142 yield* TestClock.adjust("15 minutes");
143​
144 assert.equal(yield* Fiber.join(fiber), 7, "one catch-up read per connection");
145 assert.equal(connections, 7);
146 assert.equal(posts.length, 1);
147 assert.deepEqual(deletes, ["event-subscriptions/1"]);
148 }),
149);
150​
151it.effect("leaves users without the app sign-in, other hosts, and refusals to polling", () =>
152 Effect.gen(function* () {
153 const httpClient = HttpClient.make(() => Effect.die("no stream without a subscription"));
154 const signedOut = fakeRest(subscription, false);
155 assert.equal(yield* Stream.runCount((yield* eventsOf(signedOut.rest, httpClient))(target)), 0);
156 assert.equal(signedOut.posts.length, 0);
157​
158 const signedIn = fakeRest(subscription);
159 const enterprise = { ...target, host: "ghe.example.com" };
160 assert.equal(
161 yield* Stream.runCount((yield* eventsOf(signedIn.rest, httpClient))(enterprise)),
162 0,
163 );
164 assert.equal(signedIn.posts.length, 0);
165​
166 const refused = fakeRest(() =>
167 Effect.fail(
168 new GitHubApiResponseError({
169 host: "github.com",
170 operation: "subscribePullRequestEvents",
171 status: 403,
172 }),
173 ),
174 );
175 const events = yield* eventsOf(refused.rest, httpClient);
176 assert.equal(yield* Stream.runCount(events(target)), 0);
177 assert.equal(yield* Stream.runCount(events({ ...target, number: 16 })), 0);
178 assert.equal(refused.posts.length, 1, "a refused account is not asked again for an hour");
179 yield* TestClock.adjust("61 minutes");
180 assert.equal(yield* Stream.runCount(events(target)), 0);
181 assert.equal(refused.posts.length, 2);
182​
183 const missing = fakeRest(() =>
184 Effect.fail(
185 new GitHubApiNotFoundError({ host: "github.com", operation: "subscribePullRequestEvents" }),
186 ),
187 );
188 const missingEvents = yield* eventsOf(missing.rest, httpClient);
189 assert.equal(yield* Stream.runCount(missingEvents(target)), 0);
190 assert.equal(yield* Stream.runCount(missingEvents(target)), 0);
191 assert.equal(missing.posts.length, 1, "a pull request it cannot see is not asked again");
192 assert.equal(yield* Stream.runCount(missingEvents({ ...target, number: 16 })), 0);
193 assert.equal(missing.posts.length, 2, "other pull requests on the host still subscribe");
194 }),
195);