Open History to see the last commit
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, 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;
24}
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 }>;
43}
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;
70}
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;
79}
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 payload = buildDiscordReleaseAnnouncement({
205 target,
206 roleId,
207 releaseName,
208 version: releaseVersion,
209 tag,
210 releaseUrl,
211 timestamp: new Date().toISOString(),
212 });
213
214 yield* Effect.logInfo("discord release announcement payload built").pipe(
215 Effect.annotateLogs(summarizePayload(payload)),
216 );
217 yield* postDiscordWebhook(webhookUrl, payload);
218 yield* Effect.logInfo("discord release announcement completed");
219 }),
220).pipe(Command.withDescription("Post a T3 Code release announcement to Discord."));
221
222if (import.meta.main) {
223 Command.run(notifyDiscordReleaseCommand, { version: "0.0.0" }).pipe(
224 Effect.provide(
225 Layer.mergeAll(
226 Logger.layer([Logger.consolePretty()]),
227 NodeServices.layer,
228 FetchHttpClient.layer,
229 ),
230 ),
231 NodeRuntime.runMain,
232 );
233}