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

notify-discord-release.ts

234 lines6.8 KB

1#!/usr/bin/env node
2​
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { Config, Data, DateTime, Effect, Layer, Logger, Schema } from "effect";
6import { Argument, Command, Flag } from "effect/unstable/cli";
7import {
8 FetchHttpClient,
9 HttpClient,
10 HttpClientRequest,
11 HttpClientResponse,
12} from "effect/unstable/http";
13​
14export type DiscordReleaseTarget = "prerelease" | "latest";
15​
16interface DiscordReleaseAnnouncementOptions {
17 readonly target: DiscordReleaseTarget;
18 readonly roleId: string;
19 readonly releaseName: string;
20 readonly version: string;
21 readonly tag: string;
22 readonly releaseUrl: URL;
23 readonly timestamp: string;
25​
26interface DiscordWebhookPayload {
27 readonly content: string;
28 readonly allowed_mentions: {
29 readonly roles: ReadonlyArray<string>;
30 };
31 readonly embeds: ReadonlyArray<{
32 readonly title: string;
33 readonly url: string;
34 readonly description: string;
35 readonly color: number;
36 readonly fields: ReadonlyArray<{
37 readonly name: string;
38 readonly value: string;
39 readonly inline: boolean;
40 }>;
41 readonly timestamp: string;
42 }>;
44​
45const DISCORD_RELEASE_TARGETS = ["prerelease", "latest"] as const;
46const DiscordRoleIdSchema = Schema.String.check(Schema.isPattern(/^\d+$/));
47const DiscordWebhookUrl = Config.url("DISCORD_WEBHOOK_URL");
48​
49class DiscordReleaseAnnouncementError extends Data.TaggedError("DiscordReleaseAnnouncementError")<{
50 readonly message: string;
51 readonly cause?: unknown;
52}> {}
53​
54const targetLabels = {
55 prerelease: "Prerelease",
56 latest: "Latest",
57} as const satisfies Record<DiscordReleaseTarget, string>;
58​
59const targetColors = {
60 prerelease: 0x5865f2,
61 latest: 0x2ecc71,
62} as const satisfies Record<DiscordReleaseTarget, number>;
63​
64function describeWebhookUrl(webhookUrl: URL) {
65 return {
66 configured: true,
67 origin: webhookUrl.origin,
68 pathnameSegmentCount: webhookUrl.pathname.split("/").filter(Boolean).length,
69 } as const;
71​
72function summarizePayload(payload: DiscordWebhookPayload) {
73 return {
74 contentLength: payload.content.length,
75 embedCount: payload.embeds.length,
76 allowedRoleMentionCount: payload.allowed_mentions.roles.length,
77 hasRoleMentionSyntax: payload.content.includes("<@&"),
78 } as const;
80​
81export const buildDiscordReleaseAnnouncement = (
82 options: DiscordReleaseAnnouncementOptions,
83): DiscordWebhookPayload => ({
84 content: `<@&${options.roleId}> ${targetLabels[options.target]} published: ${options.releaseName}`,
85 allowed_mentions: {
86 roles: [options.roleId],
87 },
88 embeds: [
89 {
90 title: options.releaseName,
91 url: options.releaseUrl.href,
92 description:
93 options.target === "prerelease"
94 ? "A new T3 Code prerelease is available for nightly testers."
95 : "A new T3 Code latest release is available.",
96 color: targetColors[options.target],
97 fields: [
98 {
99 name: "Version",
100 value: options.version,
101 inline: true,
102 },
103 {
104 name: "Tag",
105 value: options.tag,
106 inline: true,
107 },
108 ],
109 timestamp: options.timestamp,
110 },
111 ],
112});
113​
114const postDiscordWebhook = Effect.fn("postDiscordWebhook")(function* (
115 webhookUrl: URL,
116 payload: DiscordWebhookPayload,
117) {
118 const httpClient = (yield* HttpClient.HttpClient).pipe(
119 HttpClient.retryTransient({
120 retryOn: "errors-and-responses",
121 times: 3,
122 }),
123 );
124​
125 yield* Effect.logInfo("discord webhook request dispatching").pipe(
126 Effect.annotateLogs({
127 ...describeWebhookUrl(webhookUrl),
128 ...summarizePayload(payload),
129 }),
130 );
131​
132 const response = yield* HttpClientRequest.post(webhookUrl).pipe(
133 HttpClientRequest.bodyJson(payload),
134 Effect.flatMap(httpClient.execute),
135 Effect.mapError(
136 (cause) =>
137 new DiscordReleaseAnnouncementError({
138 message: "Failed to post Discord release announcement.",
139 cause,
140 }),
141 ),
142 );
143​
144 yield* Effect.logInfo("discord webhook response received").pipe(
145 Effect.annotateLogs({
146 status: response.status,
147 ok: response.status >= 200 && response.status < 300,
148 }),
149 );
150​
151 yield* HttpClientResponse.filterStatusOk(response).pipe(
152 Effect.mapError(
153 (cause) =>
154 new DiscordReleaseAnnouncementError({
155 message: `Discord webhook returned status ${response.status}.`,
156 cause,
157 }),
158 ),
159 );
160});
161​
162export const notifyDiscordReleaseCommand = Command.make(
163 "notify-discord-release",
164 {
165 target: Argument.choice("target", DISCORD_RELEASE_TARGETS).pipe(
166 Argument.withDescription("Discord announcement target: prerelease or latest."),
167 ),
168 roleId: Flag.string("role-id").pipe(
169 Flag.withSchema(DiscordRoleIdSchema),
170 Flag.withDescription("Discord role ID to mention in the release announcement."),
171 ),
172 releaseName: Flag.string("release-name").pipe(
173 Flag.withSchema(Schema.NonEmptyString),
174 Flag.withDescription("Human-readable release name."),
175 ),
176 releaseVersion: Flag.string("release-version").pipe(
177 Flag.withSchema(Schema.NonEmptyString),
178 Flag.withDescription("Release version."),
179 ),
180 tag: Flag.string("tag").pipe(
181 Flag.withSchema(Schema.NonEmptyString),
182 Flag.withDescription("Git tag for the release."),
183 ),
184 releaseUrl: Flag.string("release-url").pipe(
185 Flag.withSchema(Schema.URLFromString),
186 Flag.withDescription("Public GitHub release URL."),
187 ),
188 },
189 ({ target, roleId, releaseName, releaseVersion, tag, releaseUrl }) =>
190 Effect.gen(function* () {
191 yield* Effect.logInfo("discord release announcement starting").pipe(
192 Effect.annotateLogs({
193 target,
194 roleIdProvided: roleId.length > 0,
195 roleIdLength: roleId.length,
196 releaseName,
197 version: releaseVersion,
198 tag,
199 releaseUrl,
200 }),
201 );
202​
203 const webhookUrl = yield* DiscordWebhookUrl;
204 const timestamp = DateTime.formatIso(yield* DateTime.now);
205 const payload = buildDiscordReleaseAnnouncement({
206 target,
207 roleId,
208 releaseName,
209 version: releaseVersion,
210 tag,
211 releaseUrl,
212 timestamp,
213 });
214​
215 yield* Effect.logInfo("discord release announcement payload built").pipe(
216 Effect.annotateLogs(summarizePayload(payload)),
217 );
218 yield* postDiscordWebhook(webhookUrl, payload);
219 yield* Effect.logInfo("discord release announcement completed");
220 }),
221).pipe(Command.withDescription("Post a T3 Code release announcement to Discord."));
222​
223if (import.meta.main) {
224 Command.run(notifyDiscordReleaseCommand, { version: "0.0.0" }).pipe(
225 Effect.provide(
226 Layer.mergeAll(
227 Logger.layer([Logger.consolePretty()]),
228 NodeServices.layer,
229 FetchHttpClient.layer,
230 ),
231 ),
232 NodeRuntime.runMain,
233 );