-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
198 lines (176 loc) · 6.55 KB
/
app.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import express, {NextFunction, Request, Response} from "express";
import {Webhook, WebhookUnbrandedRequiredHeaders, WebhookVerificationError} from "standardwebhooks"
import {RenderDeploy, RenderEvent, RenderKeyValue, RenderPostgres, RenderService, WebhookPayload} from "./render";
const app = express();
const port = process.env.PORT || 3001;
const renderWebhookSecret = process.env.RENDER_WEBHOOK_SECRET || '';
if (!renderWebhookSecret ) {
console.error("Error: RENDER_WEBHOOK_SECRET is not set.");
process.exit(1);
}
const renderAPIURL = process.env.RENDER_API_URL || "https://api.render.com/v1"
// To create a Render API token, follow instructions here: https://render.com/docs/api#1-create-an-api-key
const renderAPIKey = process.env.RENDER_API_KEY || '';
if (!renderAPIKey ) {
console.error("Error: RENDER_API_KEY is not set.");
process.exit(1);
}
app.get('/', (req: Request, res: Response) => {
res.send('Render Webhook Receiver is listening!')
})
app.post("/webhook", express.raw({type: 'application/json'}), (req: Request, res: Response, next: NextFunction) => {
try {
validateWebhook(req);
} catch (error) {
return next(error)
}
const payload: WebhookPayload = JSON.parse(req.body)
res.status(200).send({}).end()
// handle the webhook async so we don't timeout the request
handleWebhook(payload)
});
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
console.error(err);
if (err instanceof WebhookVerificationError) {
res.status(400).send({}).end()
} else {
res.status(500).send({}).end()
}
});
const server = app.listen(port, () => console.log(`Example app listening on port ${port}!`));
function validateWebhook(req: Request) {
const headers: WebhookUnbrandedRequiredHeaders = {
"webhook-id": req.header("webhook-id") || "",
"webhook-timestamp": req.header("webhook-timestamp") || "",
"webhook-signature": req.header("webhook-signature") || ""
}
const wh = new Webhook(renderWebhookSecret);
wh.verify(req.body, headers);
}
async function handleWebhook(payload: WebhookPayload) {
try {
switch (payload.type) {
case "deploy_started":
const event = await fetchEventInfo(payload)
const deploy = await fetchDeployInfo(payload.data.serviceId, event.details.deployId)
const service = await fetchServiceInfo(payload)
if (deploy.commit) {
console.log(`deploy started for service ${service.name} with commit "${deploy.commit.message}"`)
} else if (deploy.image) {
console.log(`deploy started for service ${service.name} with image sha "${deploy.image.sha}"`)
}
return
case "database_available":
const postgres = await fetchPostgresInfo(payload)
console.log(`${payload.type} for postgres ${postgres.name}`)
return
case "key_value_available":
const keyValue = await fetchKeyValueInfo(payload)
console.log(`${payload.type} for key value ${keyValue.name}`)
return
default:
console.log(`unhandled webhook type ${payload.type} for service ${payload.data.serviceId}`)
}
} catch (error) {
console.error(error)
}
}
// fetchEventInfo fetches the event that triggered the webhook
// some events have additional information that isn't in the webhook payload
// for example, deploy events have the deploy id
async function fetchEventInfo(payload: WebhookPayload): Promise<RenderEvent> {
const res = await fetch(
`${renderAPIURL}/events/${payload.data.id}`,
{
method: "get",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${renderAPIKey}`,
},
},
)
if (res.ok) {
return res.json()
} else {
throw new Error(`unable to fetch event info; received code :${res.status.toString()}`)
}
}
async function fetchDeployInfo(serviceId: string, deployId: string): Promise<RenderDeploy> {
const res = await fetch(
`${renderAPIURL}/services/${serviceId}/deploys/${deployId}`,
{
method: "get",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${renderAPIKey}`,
},
},
)
if (res.ok) {
return res.json()
} else {
throw new Error(`unable to fetch deploy info; received code :${res.status.toString()}`)
}
}
async function fetchServiceInfo(payload: WebhookPayload): Promise<RenderService> {
const res = await fetch(
`${renderAPIURL}/services/${payload.data.serviceId}`,
{
method: "get",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${renderAPIKey}`,
},
},
)
if (res.ok) {
return res.json()
} else {
throw new Error(`unable to fetch service info; received code :${res.status.toString()}`)
}
}
async function fetchPostgresInfo(payload: WebhookPayload): Promise<RenderPostgres> {
const res = await fetch(
`${renderAPIURL}/postgres/${payload.data.serviceId}`,
{
method: "get",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${renderAPIKey}`,
},
},
)
if (res.ok) {
return res.json()
} else {
throw new Error(`unable to fetch postgres info; received code :${res.status.toString()}`)
}
}
async function fetchKeyValueInfo(payload: WebhookPayload): Promise<RenderKeyValue> {
const res = await fetch(
`${renderAPIURL}/key-value/${payload.data.serviceId}`,
{
method: "get",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${renderAPIKey}`,
},
},
)
if (res.ok) {
return res.json()
} else {
throw new Error(`unable to fetch key value info; received code :${res.status.toString()}`)
}
}
process.on('SIGTERM', () => {
console.debug('SIGTERM signal received: closing HTTP server')
server.close(() => {
console.debug('HTTP server closed')
})
})