|
| 1 | +import express, {NextFunction, Request, Response} from "express"; |
| 2 | +import {Webhook, WebhookUnbrandedRequiredHeaders, WebhookVerificationError} from "standardwebhooks" |
| 3 | +import {RenderEvent, RenderService, WebhookPayload} from "./render"; |
| 4 | +import { |
| 5 | + ActionRowBuilder, |
| 6 | + ButtonBuilder, |
| 7 | + ButtonStyle, |
| 8 | + Client, |
| 9 | + EmbedBuilder, |
| 10 | + Events, |
| 11 | + GatewayIntentBits, |
| 12 | + MessageActionRowComponentBuilder |
| 13 | +} from "discord.js"; |
| 14 | + |
| 15 | +const app = express(); |
| 16 | +const port = process.env.PORT || 3001; |
| 17 | +const renderWebhookSecret = process.env.RENDER_WEBHOOK_SECRET || ''; |
| 18 | + |
| 19 | +const renderAPIURL = process.env.RENDER_API_URL || "https://api.render.com/v1" |
| 20 | + |
| 21 | +// To create a Render API token, follow instructions here: https://render.com/docs/api#1-create-an-api-key |
| 22 | +const renderAPIToken = process.env.RENDER_API_TOKEN || ''; |
| 23 | + |
| 24 | +const discordToken = process.env.DISCORD_TOKEN || ''; |
| 25 | +const discordChannelID = process.env.DISCORD_CHANNEL_ID || ''; |
| 26 | + |
| 27 | +// Create a new client instance |
| 28 | +const client = new Client({ intents: [GatewayIntentBits.Guilds] }); |
| 29 | + |
| 30 | +// When the client is ready, run this code (only once). |
| 31 | +// The distinction between `client: Client<boolean>` and `readyClient: Client<true>` is important for TypeScript developers. |
| 32 | +// It makes some properties non-nullable. |
| 33 | +client.once(Events.ClientReady, readyClient => { |
| 34 | + console.log(`Discord client setup! Logged in as ${readyClient.user.tag}`); |
| 35 | +}); |
| 36 | + |
| 37 | +// Log in to Discord with your client's token |
| 38 | +client.login(discordToken).catch(err => { |
| 39 | + console.error(`unable to connect to Discord: ${err}`); |
| 40 | +}); |
| 41 | + |
| 42 | +app.post("/webhook", express.raw({type: 'application/json'}), (req: Request, res: Response, next: NextFunction) => { |
| 43 | + try { |
| 44 | + validateWebhook(req); |
| 45 | + } catch (error) { |
| 46 | + return next(error) |
| 47 | + } |
| 48 | + |
| 49 | + const payload: WebhookPayload = JSON.parse(req.body) |
| 50 | + |
| 51 | + res.status(200).send({}).end() |
| 52 | + |
| 53 | + // handle the webhook async so we don't timeout the request |
| 54 | + handleWebhook(payload) |
| 55 | +}); |
| 56 | + |
| 57 | +app.use((err: any, req: Request, res: Response, next: NextFunction) => { |
| 58 | + console.error(err); |
| 59 | + if (err instanceof WebhookVerificationError) { |
| 60 | + res.status(400).send({}).end() |
| 61 | + } else { |
| 62 | + res.status(500).send({}).end() |
| 63 | + } |
| 64 | +}); |
| 65 | + |
| 66 | +const server = app.listen(port, () => console.log(`Example app listening on port ${port}!`)); |
| 67 | + |
| 68 | +function validateWebhook(req: Request) { |
| 69 | + const headers: WebhookUnbrandedRequiredHeaders = { |
| 70 | + "webhook-id": req.header("webhook-id") || "", |
| 71 | + "webhook-timestamp": req.header("webhook-timestamp") || "", |
| 72 | + "webhook-signature": req.header("webhook-signature") || "" |
| 73 | + } |
| 74 | + |
| 75 | + const wh = new Webhook(renderWebhookSecret); |
| 76 | + wh.verify(req.body, headers); |
| 77 | +} |
| 78 | + |
| 79 | +async function handleWebhook(payload: WebhookPayload) { |
| 80 | + try { |
| 81 | + switch (payload.type) { |
| 82 | + case "server_failed": |
| 83 | + const service = await fetchServiceInfo(payload) |
| 84 | + const event = await fetchEventInfo(payload) |
| 85 | + |
| 86 | + console.log(`sending discord message for ${service.name}`) |
| 87 | + await sendServerFailedMessage(service, event.details.reason) |
| 88 | + return |
| 89 | + default: |
| 90 | + console.log(`unhandled webhook type ${payload.type} for service ${payload.data.serviceId}`) |
| 91 | + } |
| 92 | + } catch (error) { |
| 93 | + console.error(error) |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +async function sendServerFailedMessage(service: RenderService, failureReason: any) { |
| 98 | + const channel = await client.channels.fetch(discordChannelID); |
| 99 | + if (!channel ){ |
| 100 | + throw new Error(`unable to find specified Discord channel ${discordChannelID}`); |
| 101 | + } |
| 102 | + |
| 103 | + const isSendable = channel.isSendable() |
| 104 | + if (!isSendable) { |
| 105 | + throw new Error(`specified Discord channel ${discordChannelID} is not sendable`); |
| 106 | + } |
| 107 | + |
| 108 | + let description = "Failed for unknown reason" |
| 109 | + if (failureReason.nonZeroExit) { |
| 110 | + description = `Exited with status ${failureReason.nonZeroExit}` |
| 111 | + } else if (failureReason.oomKilled) { |
| 112 | + description = `Out of Memory` |
| 113 | + } else if (failureReason.timedOutSeconds) { |
| 114 | + description = `Timed out ` + failureReason.timedOutReason |
| 115 | + } else if (failureReason.unhealthy) { |
| 116 | + description = failureReason.unhealthy |
| 117 | + } |
| 118 | + |
| 119 | + const embed = new EmbedBuilder() |
| 120 | + .setColor(`#FF5C88`) |
| 121 | + .setTitle(`${service.name} Failed`) |
| 122 | + .setDescription(description) |
| 123 | + .setURL(service.dashboardUrl) |
| 124 | + |
| 125 | + const logs = new ButtonBuilder() |
| 126 | + .setLabel("View Logs") |
| 127 | + .setURL(`${service.dashboardUrl}/logs`) |
| 128 | + .setStyle(ButtonStyle.Link); |
| 129 | + const row = new ActionRowBuilder<MessageActionRowComponentBuilder>() |
| 130 | + .addComponents(logs); |
| 131 | + |
| 132 | + channel.send({embeds: [embed], components: [row]}) |
| 133 | +} |
| 134 | + |
| 135 | +// fetchEventInfo fetches the event that triggered the webhook |
| 136 | +// some events have additional information that isn't in the webhook payload |
| 137 | +// for example, deploy events have the deploy id |
| 138 | +async function fetchEventInfo(payload: WebhookPayload): Promise<RenderEvent> { |
| 139 | + const res = await fetch( |
| 140 | + `${renderAPIURL}/events/${payload.data.id}`, |
| 141 | + { |
| 142 | + method: "get", |
| 143 | + headers: { |
| 144 | + "Content-Type": "application/json", |
| 145 | + Accept: "application/json", |
| 146 | + Authorization: `Bearer ${renderAPIToken}`, |
| 147 | + }, |
| 148 | + }, |
| 149 | + ) |
| 150 | + if (res.ok) { |
| 151 | + return res.json() |
| 152 | + } else { |
| 153 | + throw new Error(`unable to fetch event info; received code :${res.status.toString()}`) |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +async function fetchServiceInfo(payload: WebhookPayload): Promise<RenderService> { |
| 158 | + const res = await fetch( |
| 159 | + `${renderAPIURL}/services/${payload.data.serviceId}`, |
| 160 | + { |
| 161 | + method: "get", |
| 162 | + headers: { |
| 163 | + "Content-Type": "application/json", |
| 164 | + Accept: "application/json", |
| 165 | + Authorization: `Bearer ${renderAPIToken}`, |
| 166 | + }, |
| 167 | + }, |
| 168 | + ) |
| 169 | + if (res.ok) { |
| 170 | + return res.json() |
| 171 | + } else { |
| 172 | + throw new Error(`unable to fetch service info; received code :${res.status.toString()}`) |
| 173 | + } |
| 174 | +} |
| 175 | + |
| 176 | +process.on('SIGTERM', () => { |
| 177 | + console.debug('SIGTERM signal received: closing HTTP server') |
| 178 | + server.close(() => { |
| 179 | + console.debug('HTTP server closed') |
| 180 | + }) |
| 181 | +}) |
0 commit comments