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

notify-discord-release.test.ts

491 lines19.9 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Cause from "effect/Cause";
4import * as ConfigProvider from "effect/ConfigProvider";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Logger from "effect/Logger";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import { Command } from "effect/cli";
12import { HttpClient, HttpClientError, HttpClientResponse, UrlParams } from "effect/http";
13import { ChildProcess, ChildProcessSpawner } from "effect/process";
14​
15import {
16 buildDiscordReleaseAnnouncement,
17 notifyDiscordReleaseCommand,
18 postDiscordWebhook,
19} from "./notify-discord-release.ts";
20​
21const latestAnnouncement = {
22 target: "latest",
23 roleId: "222222222222222222",
24 releaseName: "T3 Code v1.2.3",
25 version: "1.2.3",
26 tag: "v1.2.3",
27 releaseUrl: new URL("https://github.com/pingdotgg/t3code/releases/tag/v1.2.3"),
28 timestamp: "2026-05-01T01:41:00.000Z",
29} as const;
30const nightlyAnnouncement = { ...latestAnnouncement, target: "prerelease" } as const;
31const webhookUrl = new URL("https://discord.com/api/webhooks/123456/test-secret-token");
32const intro = "A new T3 Code prerelease is available for nightly testers.";
33const notes = `## What's Changed\n* Fix remote reconnection by @contributor in https://github.com/pingdotgg/t3code/pull/10\n* Improve thread search in https://github.com/pingdotgg/t3code/pull/11\n\n**Full Changelog**: https://github.com/pingdotgg/t3code/compare/v1.2.2...v1.2.3`;
34const formattedNotes = `## What's Changed\n* [Fix remote reconnection](https://github.com/pingdotgg/t3code/pull/10) by [@contributor](https://github.com/contributor)\n* [Improve thread search](https://github.com/pingdotgg/t3code/pull/11)\n\n[Full Changelog](https://github.com/pingdotgg/t3code/compare/v1.2.2...v1.2.3)`;
35const runCli = Command.runWith(notifyDiscordReleaseCommand, { version: "0.0.0" });
36const cliArgs = (target: "latest" | "prerelease") => [
37 target,
38 "--role-id",
39 latestAnnouncement.roleId,
40 "--release-name",
41 latestAnnouncement.releaseName,
42 "--release-version",
43 latestAnnouncement.version,
44 "--tag",
45 latestAnnouncement.tag,
46 "--release-url",
47 latestAnnouncement.releaseUrl.href,
48];
49const configLayer = ConfigProvider.layer(
50 ConfigProvider.fromEnv({ env: { DISCORD_WEBHOOK_URL: webhookUrl.href } }),
51);
52const PayloadSchema = Schema.fromJsonString(
53 Schema.Struct({
54 content: Schema.String,
55 allowed_mentions: Schema.Struct({
56 parse: Schema.Array(Schema.String),
57 roles: Schema.Array(Schema.String),
58 }),
59 embeds: Schema.Array(
60 Schema.Struct({ title: Schema.String, description: Schema.String, url: Schema.String }),
61 ),
62 }),
63);
64const decodePayload = Schema.decodeUnknownSync(PayloadSchema);
65const payloadDescription = (payloads: ReturnType<typeof buildDiscordReleaseAnnouncement>) =>
66 payloads.flatMap((payload) => payload.embeds.map((embed) => embed.description)).join("");
67const captureClient = (requests: string[], status = 204) =>
68 Layer.succeed(
69 HttpClient.HttpClient,
70 HttpClient.make((request) => {
71 assert.deepStrictEqual(UrlParams.getAll(request.urlParams, "wait"), ["true"]);
72 assert.equal(request.body._tag, "Uint8Array");
73 if (request.body._tag !== "Uint8Array") return Effect.die("Expected JSON request body");
74 requests.push(new TextDecoder().decode(request.body.body));
75 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status })));
76 }),
77 );
78​
79function assertDiscordLimits(payloads: ReturnType<typeof buildDiscordReleaseAnnouncement>) {
80 for (const payload of payloads) {
81 assert.ok(payload.content.length <= 2000);
82 assert.equal(payload.embeds.length, 1);
83 let total = 0;
84 for (const embed of payload.embeds) {
85 assert.ok(embed.title.length <= 256);
86 assert.ok(embed.description.length <= 4096);
87 assert.ok(embed.footer.text.length <= 2048);
88 total += embed.title.length + embed.description.length + embed.footer.text.length;
89 }
90 assert.ok(total <= 6000);
91 }
93​
94it("keeps stable announcements short even when a long changelog is provided", () => {
95 assert.deepStrictEqual(
96 buildDiscordReleaseAnnouncement({ ...latestAnnouncement, releaseNotes: notes.repeat(200) }),
97 [
98 {
99 content: "-# <@&222222222222222222>",
100 allowed_mentions: { parse: [], roles: [latestAnnouncement.roleId] },
101 embeds: [
102 {
103 title: latestAnnouncement.releaseName,
104 url: latestAnnouncement.releaseUrl.href,
105 description: `[View full release notes on GitHub](${latestAnnouncement.releaseUrl.href})`,
106 color: 0x2ecc71,
107 footer: { text: "v1.2.3" },
108 timestamp: latestAnnouncement.timestamp,
109 },
110 ],
111 },
112 ],
113 );
114});
115​
116it("links contributor profiles and escapes brackets in change titles and bot handles", () => {
117 const releaseNotes =
118 "* Fix [web] links by @octo-user in https://github.com/pingdotgg/t3code/pull/12\n* Bump dependencies by @dependabot[bot] in https://github.com/pingdotgg/t3code/pull/13";
119 const payloads = buildDiscordReleaseAnnouncement({ ...nightlyAnnouncement, releaseNotes });
120 assert.equal(
121 payloadDescription(payloads),
122 `${intro}\n\n* [Fix \\[web\\] links](https://github.com/pingdotgg/t3code/pull/12) by [@octo-user](https://github.com/octo-user)\n* [Bump dependencies](https://github.com/pingdotgg/t3code/pull/13) by [@dependabot\\[bot\\]](https://github.com/apps/dependabot)`,
123 );
124});
125​
126it("preserves custom notes and links outside generated GitHub pull request entries", () => {
127 const releaseNotes =
128 "## Migration\n* Written by @someone in the docs\n* Commit https://github.com/pingdotgg/t3code/commit/abc123\n[Guide](https://example.com/guide)";
129 assert.equal(
130 payloadDescription(buildDiscordReleaseAnnouncement({ ...nightlyAnnouncement, releaseNotes })),
131 `${intro}\n\n${releaseNotes}`,
132 );
133});
134​
135it("falls back when notes are missing, empty, or whitespace", () => {
136 const fallback = buildDiscordReleaseAnnouncement(nightlyAnnouncement);
137 assert.equal(payloadDescription(fallback), intro);
138 assert.deepStrictEqual(
139 buildDiscordReleaseAnnouncement({ ...nightlyAnnouncement, releaseNotes: "" }),
140 fallback,
141 );
142 assert.deepStrictEqual(
143 buildDiscordReleaseAnnouncement({ ...nightlyAnnouncement, releaseNotes: " \r\n\t" }),
144 fallback,
145 );
146});
147​
148it("splits long notes at line boundaries without dropping changes or the comparison link", () => {
149 const longNotes =
150 Array.from(
151 { length: 150 },
152 (_, i) => `* Change ${i} in https://github.com/pingdotgg/t3code/pull/${i}\n`,
153 ).join("") + notes;
154 const payloads = buildDiscordReleaseAnnouncement({
155 ...nightlyAnnouncement,
156 releaseNotes: longNotes,
157 });
158 assert.ok(payloads.length > 2);
159 const formattedChanges = Array.from(
160 { length: 150 },
161 (_, i) => `* [Change ${i}](https://github.com/pingdotgg/t3code/pull/${i})\n`,
162 ).join("");
163 assert.equal(payloadDescription(payloads), `${intro}\n\n${formattedChanges}${formattedNotes}`);
164 assertDiscordLimits(payloads);
165 for (const [index, payload] of payloads.entries()) {
166 assert.deepStrictEqual(payload.allowed_mentions, {
167 parse: [],
168 roles: index === 0 ? [latestAnnouncement.roleId] : [],
169 });
170 if (index > 0) {
171 assert.equal(payload.content, "");
172 assert.equal(
173 payload.embeds[0]?.title,
174 `Changelog continued (${index + 1}/${payloads.length})`,
175 );
176 }
177 if (index < payloads.length - 1) assert.ok(payload.embeds[0]?.description.endsWith("\n"));
178 assert.equal(payload.embeds[0]?.url, nightlyAnnouncement.releaseUrl.href);
179 }
180});
181​
182it("handles oversized lines, words, and Unicode without losing or breaking characters", () => {
183 const longNotes =
184 "a".repeat(9000) + "\n" + "πŸ¦‹".repeat(4500) + "\n" + "word ".repeat(2000).trim();
185 const payloads = buildDiscordReleaseAnnouncement({
186 ...nightlyAnnouncement,
187 releaseNotes: longNotes,
188 });
189 assertDiscordLimits(payloads);
190 assert.equal(payloadDescription(payloads), `${intro}\n\n${longNotes}`);
191 for (const payload of payloads) assert.ok(payload.embeds[0]?.description.isWellFormed());
192});
193​
194it("accepts exactly 4096 description characters and splits the next character", () => {
195 const releaseNotes = "x".repeat(4096 - intro.length - 2);
196 assert.equal(buildDiscordReleaseAnnouncement({ ...nightlyAnnouncement, releaseNotes }).length, 1);
197 const longer = buildDiscordReleaseAnnouncement({
198 ...nightlyAnnouncement,
199 releaseNotes: releaseNotes + "x",
200 });
201 assert.equal(longer.length, 2);
202 assert.equal(payloadDescription(longer), `${intro}\n\n${releaseNotes}x`);
203 assertDiscordLimits(longer);
204});
205​
206it("suppresses everyone, here, user, and role mentions on every message", () => {
207 const mentions = `@everyone @here <@123> <@!123> <@&456> <@&${nightlyAnnouncement.roleId}>`;
208 const inert = mentions.replaceAll("@", "@\u200b");
209 const payloads = buildDiscordReleaseAnnouncement({
210 ...nightlyAnnouncement,
211 releaseName: mentions,
212 releaseNotes: `${mentions}\n`.repeat(100) + notes,
213 });
214 assert.ok(payloads.length > 1);
215 assert.equal(
216 payloadDescription(payloads),
217 `${intro}\n\n${`${inert}\n`.repeat(100)}${formattedNotes}`,
218 );
219 for (const [index, payload] of payloads.entries()) {
220 assert.deepStrictEqual(payload.allowed_mentions, {
221 parse: [],
222 roles: index === 0 ? [latestAnnouncement.roleId] : [],
223 });
224 if (index === 0) assert.equal(payload.embeds[0]?.title, inert);
225 assert.ok(!payload.content.includes("@everyone"));
226 assert.ok(!payload.content.includes("@here"));
227 assert.equal(payload.content.match(/<@&\d+>/g)?.length ?? 0, index === 0 ? 1 : 0);
228 }
229});
230​
231it("rejects invalid metadata before sending", () => {
232 assert.throws(
233 () => buildDiscordReleaseAnnouncement({ ...nightlyAnnouncement, releaseName: "x".repeat(257) }),
234 /title exceeds/,
235 );
236 assert.throws(
237 () => buildDiscordReleaseAnnouncement({ ...nightlyAnnouncement, version: "x".repeat(2048) }),
238 /footer exceeds/,
239 );
240 assert.throws(
241 () => buildDiscordReleaseAnnouncement({ ...nightlyAnnouncement, roleId: "123> @everyone" }),
242 /Invalid Discord release role/,
243 );
244});
245​
246it.effect("retains safe request context without leaking the webhook URL or nested cause", () =>
247 Effect.gen(function* () {
248 const payload = buildDiscordReleaseAnnouncement(latestAnnouncement)[0]!;
249 const logs: string[] = [];
250 const client = Layer.succeed(
251 HttpClient.HttpClient,
252 HttpClient.make((request) =>
253 Effect.fail(
254 new HttpClientError.HttpClientError({
255 reason: new HttpClientError.EncodeError({
256 request,
257 cause: new Error(`Encoder failed for ${webhookUrl.href}`),
258 }),
259 }),
260 ),
261 ),
262 );
263 const error = yield* postDiscordWebhook(webhookUrl, payload, latestAnnouncement).pipe(
264 Effect.tapCause(Effect.logError),
265 Effect.provide([
266 client,
267 Logger.layer([
268 Logger.make((options) => {
269 logs.push(Logger.formatJson.log(options));
270 }),
271 ]),
272 ]),
273 Effect.flip,
274 );
275 if (error._tag !== "DiscordReleaseWebhookRequestError")
276 assert.fail(`Unexpected error: ${error._tag}`);
277 assert.equal(error.reason, "EncodeError");
278 assert.equal(error.target, "latest");
279 assert.equal(error.tag, latestAnnouncement.tag);
280 assert.equal(error.webhookOrigin, webhookUrl.origin);
281 assert.equal(error.webhookPathnameSegmentCount, 4);
282 assert.equal(error.contentLength, payload.content.length);
283 assert.equal(error.allowedRoleMentionCount, 1);
284 assert.ok(!Cause.pretty(Cause.fail(error)).includes("test-secret-token"));
285 assert.ok(!logs.join("\n").includes("test-secret-token"));
286 }),
287);
288​
289it.effect(
290 "retains response status without retaining the secret-bearing request or response body",
291 () =>
292 Effect.gen(function* () {
293 const client = Layer.succeed(
294 HttpClient.HttpClient,
295 HttpClient.make((request) =>
296 Effect.succeed(
297 HttpClientResponse.fromWeb(request, new Response(webhookUrl.href, { status: 400 })),
298 ),
299 ),
300 );
301 const error = yield* postDiscordWebhook(
302 webhookUrl,
303 buildDiscordReleaseAnnouncement(latestAnnouncement)[0]!,
304 latestAnnouncement,
305 ).pipe(Effect.provide(client), Effect.flip);
306 if (error._tag !== "DiscordReleaseWebhookResponseError")
307 assert.fail(`Unexpected error: ${error._tag}`);
308 assert.equal(error.status, 400);
309 assert.equal(error.tag, latestAnnouncement.tag);
310 assert.ok(!Cause.pretty(Cause.fail(error)).includes("test-secret-token"));
311 }),
312);
313​
314function workflowRun(workflow: string, stepName: string) {
315 const step = workflow.split(` - name: ${stepName}\n`)[1]?.split("\n - name:")[0];
316 assert.ok(step, `Missing workflow step: ${stepName}`);
317 const run = step.split(" run: |\n")[1];
318 assert.ok(run, `Missing run block: ${stepName}`);
319 return run
320 .split("\n")
321 .map((line) => line.replace(/^ /, ""))
322 .join("\n");
324​
325it.layer(NodeServices.layer)("Discord release CLI and workflow", (it) => {
326 it.effect("passes the published nightly body from the workflow to ordered sends", () =>
327 Effect.gen(function* () {
328 const fs = yield* FileSystem.FileSystem;
329 const path = yield* Path.Path;
330 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
331 const temp = yield* fs.makeTempDirectoryScoped({ prefix: "discord release " });
332 const workflow = yield* fs.readFileString(
333 yield* path.fromFileUrl(new URL("../.github/workflows/release.yml", import.meta.url)),
334 );
335 const publishedNotes =
336 Array.from({ length: 50 }, () => notes).join("\n\n") +
337 '\n* Literal $(touch "$RUNNER_TEMP/executed") and `touch "$RUNNER_TEMP/executed"`';
338 const read = workflowRun(workflow, "Read published release notes");
339 const shellEnv = {
340 RUNNER_TEMP: temp,
341 RELEASE_TAG: nightlyAnnouncement.tag,
342 RELEASE_CHANNEL: "nightly",
343 FIXTURE_NOTES: publishedNotes,
344 };
345 const readStatus = yield* spawner.exitCode(
346 ChildProcess.make(
347 "bash",
348 [
349 "-e",
350 "-c",
351 `gh() { [ "$*" = 'release view v1.2.3 --json body --jq .body // ""' ] || return 1; printf '%s' "$FIXTURE_NOTES"; }\n${read}`,
352 ],
353 { env: shellEnv },
354 ),
355 );
356 assert.equal(readStatus, 0);
357 assert.equal(yield* fs.readFileString(`${temp}/discord-release-notes.md`), publishedNotes);
358 const replacements: Record<string, string> = {
359 "needs.preflight.outputs.release_name": latestAnnouncement.releaseName,
360 "needs.preflight.outputs.version": latestAnnouncement.version,
361 "needs.preflight.outputs.tag": latestAnnouncement.tag,
362 "github.repository": "pingdotgg/t3code",
363 };
364 const announce = workflowRun(workflow, "Announce prerelease on Discord").replace(
365 /\$\{\{ (.*?) \}\}/g,
366 (_, key: string) => {
367 assert.ok(replacements[key], `Unexpected expression: ${key}`);
368 return replacements[key]!;
369 },
370 );
371 const announceStatus = yield* spawner.exitCode(
372 ChildProcess.make(
373 "bash",
374 ["-e", "-c", `node() { printf '%s\\0' "$@" > "$RUNNER_TEMP/args"; }\n${announce}`],
375 { env: { RUNNER_TEMP: temp, DISCORD_MENTION_ROLE_ID: latestAnnouncement.roleId } },
376 ),
377 );
378 assert.equal(announceStatus, 0);
379 const args = (yield* fs.readFileString(`${temp}/args`)).split("\0").slice(1, -1);
380 const requests: string[] = [];
381 yield* runCli(args).pipe(Effect.provide([configLayer, captureClient(requests)]));
382 const payloads = requests.map((request) => decodePayload(request));
383 assert.ok(payloads.length > 2);
384 assert.equal(
385 payloads.flatMap((payload) => payload.embeds.map((embed) => embed.description)).join(""),
386 `${intro}\n\n${Array.from({ length: 50 }, () => formattedNotes).join("\n\n")}\n* Literal $(touch "$RUNNER_TEMP/executed") and \`touch "$RUNNER_TEMP/executed"\``,
387 );
388 for (const [index, payload] of payloads.entries())
389 assert.deepStrictEqual(payload.allowed_mentions, {
390 parse: [],
391 roles: index === 0 ? [latestAnnouncement.roleId] : [],
392 });
393 assert.equal(yield* fs.exists(`${temp}/executed`), false);
394 assert.equal(
395 yield* spawner.exitCode(
396 ChildProcess.make("bash", ["-e", "-c", `gh() { return 99; }\n${read}`], {
397 env: { ...shellEnv, RELEASE_CHANNEL: "stable" },
398 }),
399 ),
400 0,
401 );
402 assert.equal(yield* fs.readFileString(`${temp}/discord-release-notes.md`), "");
403 assert.equal(
404 yield* spawner.exitCode(
405 ChildProcess.make(
406 "bash",
407 ["-e", "-c", `gh() { printf '%s' 'partial changelog'; return 42; }\n${read}`],
408 { env: shellEnv },
409 ),
410 ),
411 0,
412 );
413 assert.equal(yield* fs.readFileString(`${temp}/discord-release-notes.md`), "");
414 const fallbackRequests: string[] = [];
415 yield* runCli(args).pipe(Effect.provide([configLayer, captureClient(fallbackRequests)]));
416 assert.equal(fallbackRequests.length, 1);
417 const fallback = decodePayload(fallbackRequests[0]!);
418 assert.equal(fallback.embeds[0]?.description, intro);
419 assert.equal(fallback.content, `-# <@&${latestAnnouncement.roleId}>`);
420 assert.deepStrictEqual(fallback.allowed_mentions, {
421 parse: [],
422 roles: [latestAnnouncement.roleId],
423 });
424 assert.ok(
425 workflow
426 .split(" - name: Announce prerelease on Discord\n")[1]
427 ?.startsWith(" if: needs.preflight.outputs.is_prerelease == 'true'\n"),
428 );
429 assert.ok(workflow.includes("GH_REPO: ${{ github.repository }}"));
430 assert.ok(workflow.includes("RELEASE_TAG: ${{ needs.preflight.outputs.tag }}"));
431 assert.ok(
432 !workflowRun(workflow, "Announce latest release on Discord").includes(
433 "--release-notes-file",
434 ),
435 );
436 assert.ok(
437 workflow
438 .slice(workflow.indexOf(" announce_discord:"))
439 .includes("needs.preflight.outputs.release_channel != 'preview'"),
440 );
441 }),
442 );
443​
444 it.effect("fails before sending when the requested nightly notes file cannot be read", () =>
445 Effect.gen(function* () {
446 const requests: string[] = [];
447 const result = yield* runCli([
448 ...cliArgs("prerelease"),
449 "--release-notes-file",
450 "/missing-nightly-notes.md",
451 ]).pipe(Effect.provide([configLayer, captureClient(requests)]), Effect.result);
452 assert.equal(result._tag, "Failure");
453 assert.deepStrictEqual(requests, []);
454 }),
455 );
456​
457 it.effect("stops on a failed send rather than posting later continuations", () =>
458 Effect.gen(function* () {
459 const fs = yield* FileSystem.FileSystem;
460 const temp = yield* fs.makeTempDirectoryScoped();
461 const file = `${temp}/notes.md`;
462 yield* fs.writeFileString(file, notes.repeat(100));
463 const requests: string[] = [];
464 const result = yield* runCli([...cliArgs("prerelease"), "--release-notes-file", file]).pipe(
465 Effect.provide([configLayer, captureClient(requests, 400)]),
466 Effect.result,
467 );
468 assert.equal(result._tag, "Failure");
469 assert.equal(requests.length, 1);
470 }),
471 );
472​
473 it.effect("does not expose an invalid webhook secret in configuration errors", () =>
474 Effect.gen(function* () {
475 const requests: string[] = [];
476 const result = yield* runCli(cliArgs("latest")).pipe(
477 Effect.provide([
478 ConfigProvider.layer(
479 ConfigProvider.fromEnv({ env: { DISCORD_WEBHOOK_URL: "invalid-test-secret-token" } }),
480 ),
481 captureClient(requests),
482 ]),
483 Effect.result,
484 );
485 assert.equal(result._tag, "Failure");
486 if (result._tag === "Failure")
487 assert.ok(!Cause.pretty(Cause.fail(result.failure)).includes("test-secret-token"));
488 assert.deepStrictEqual(requests, []);
489 }),
490 );
491});