Skip to content

Commit e46ce31

Browse files
committed
Add workflow dispatch throttling
1 parent 48e0f49 commit e46ce31

File tree

1 file changed

+31
-17
lines changed

1 file changed

+31
-17
lines changed

workspaces/functions/api/deploy-webhook.ts

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ const HYGRAPH_SECRET = process.env.HYGRAPH_SECRET!
55
const GITHUB_WORKFLOW_URL = process.env.GITHUB_WORKFLOW_URL!
66
const GITHUB_TOKEN = process.env.GITHUB_TOKEN!
77

8+
// Global timer to accumulate webhook requests
9+
let timer: NodeJS.Timeout | null = null
10+
const TIMEOUT = 30000
811

912
export default async function handler(req: VercelRequest, res: VercelResponse) {
1013
if (req.method !== 'POST') {
@@ -31,23 +34,34 @@ export default async function handler(req: VercelRequest, res: VercelResponse) {
3134
return res.status(403).json({ message: 'Invalid signature' })
3235
}
3336

34-
try {
35-
const response = await fetch(GITHUB_WORKFLOW_URL, {
36-
method: 'POST',
37-
headers: {
38-
Authorization: `Bearer ${GITHUB_TOKEN}`,
39-
Accept: 'application/vnd.github+json',
40-
'X-GitHub-Api-Version': '2022-11-28',
41-
},
42-
body: JSON.stringify({ ref: 'main' }),
43-
})
44-
45-
if (!response.ok) {
46-
throw new Error(`Failed to trigger workflow: ${response.statusText}`)
37+
if (timer) {
38+
return res.status(200).json({ message: 'Deployment already scheduled' })
39+
}
40+
41+
timer = setTimeout(async () => {
42+
try {
43+
const response = await fetch(GITHUB_WORKFLOW_URL, {
44+
method: 'POST',
45+
headers: {
46+
Authorization: `Bearer ${GITHUB_TOKEN}`,
47+
Accept: 'application/vnd.github+json',
48+
'X-GitHub-Api-Version': '2022-11-28',
49+
},
50+
body: JSON.stringify({ ref: 'main' }),
51+
})
52+
53+
if (!response.ok) {
54+
console.error(`Failed to trigger workflow: ${response.statusText}`)
55+
} else {
56+
console.log('Deployment triggered')
57+
}
58+
} catch (error) {
59+
console.error('Error triggering deployment:', error)
60+
} finally {
61+
// Reset the timer so that future requests can schedule a new dispatch.
62+
timer = null
4763
}
64+
}, TIMEOUT)
4865

49-
return res.status(200).json({ message: 'Deployment triggered' })
50-
} catch (error) {
51-
return res.status(500).json({ error: (error as unknown as Error).message })
52-
}
66+
return res.status(200).json({ message: 'Deployment scheduled' })
5367
}

0 commit comments

Comments
 (0)