WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

Commit d300555

Browse files
committed
Use redis in webhook instead of timeout
1 parent a946873 commit d300555

File tree

3 files changed

+55
-34
lines changed

3 files changed

+55
-34
lines changed
Lines changed: 37 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import type { VercelRequest, VercelResponse } from '@vercel/node'
2+
import { Redis } from '@upstash/redis'
23
import crypto from 'crypto'
34

45
const HYGRAPH_SECRET = process.env.HYGRAPH_SECRET!
56
const GITHUB_WORKFLOW_URL = process.env.GITHUB_WORKFLOW_URL!
67
const GITHUB_TOKEN = process.env.GITHUB_TOKEN!
78

8-
// Global timer to accumulate webhook requests
9-
let timer: NodeJS.Timeout | null = null
10-
const TIMEOUT = 30000
9+
const COOLDOWN_PERIOD = 30000 // seconds
10+
const DEPLOY_KEY = 'last_deploy_timestamp'
11+
12+
const redis = Redis.fromEnv();
1113

1214
export default async function handler(req: VercelRequest, res: VercelResponse) {
1315
if (req.method !== 'POST') {
@@ -34,38 +36,39 @@ export default async function handler(req: VercelRequest, res: VercelResponse) {
3436
return res.status(403).json({ message: 'Invalid signature' })
3537
}
3638

37-
if (timer) {
38-
return res.status(200).json({ message: 'Deployment already scheduled' })
39-
}
39+
try {
40+
const lastDeployTime = (await redis.get<number>(DEPLOY_KEY)) || 0
41+
const now = Date.now()
42+
const timeSinceLastDeploy = now - lastDeployTime
4043

41-
await new Promise<void>((resolve, reject) => {
42-
timer = setTimeout(async () => {
43-
try {
44-
const response = await fetch(GITHUB_WORKFLOW_URL, {
45-
method: 'POST',
46-
headers: {
47-
Authorization: `Bearer ${GITHUB_TOKEN}`,
48-
Accept: 'application/vnd.github+json',
49-
'X-GitHub-Api-Version': '2022-11-28',
50-
},
51-
body: JSON.stringify({ ref: 'main' }),
52-
})
44+
if (timeSinceLastDeploy < COOLDOWN_PERIOD) {
45+
return res.status(429).json({
46+
message: `Deployment already scheduled. Please wait ${Math.round((COOLDOWN_PERIOD - timeSinceLastDeploy) / 1000)} seconds.`,
47+
})
48+
}
5349

54-
if (!response.ok) {
55-
console.error(`Failed to trigger workflow: ${response.statusText}`)
56-
} else {
57-
console.log('Deployment triggered')
58-
}
59-
resolve()
60-
} catch (error) {
61-
console.error('Error triggering deployment:', error)
62-
reject(error)
63-
} finally {
64-
// Reset the timer so that future requests can schedule a new dispatch.
65-
timer = null
66-
}
67-
}, TIMEOUT)
68-
})
50+
await redis.set(DEPLOY_KEY, now)
6951

70-
return res.status(200).json({ message: 'Deployment scheduled' })
52+
const response = await fetch(GITHUB_WORKFLOW_URL, {
53+
method: 'POST',
54+
headers: {
55+
Authorization: `Bearer ${GITHUB_TOKEN}`,
56+
Accept: 'application/vnd.github+json',
57+
'X-GitHub-Api-Version': '2022-11-28',
58+
},
59+
body: JSON.stringify({ ref: 'main' }),
60+
})
61+
62+
if (!response.ok) {
63+
throw new Error(
64+
`Failed to trigger workflow: ${response.statusText} ${await response.text()}`,
65+
)
66+
}
67+
68+
console.log('Deployment triggered')
69+
return res.status(200).json({ message: 'Deployment triggered' })
70+
} catch (error) {
71+
console.error('Error:', error)
72+
return res.status(500).json({ message: 'Internal server error' })
73+
}
7174
}

workspaces/functions/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"author": "Teimur Gasanov",
77
"dependencies": {
88
"@types/node": "^20",
9+
"@upstash/redis": "^1.35.0",
910
"@vercel/node": "^5.1.10",
1011
"typescript": "^5.7.3"
1112
},

yarn.lock

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5709,6 +5709,7 @@ __metadata:
57095709
resolution: "@teimurjan/functions@workspace:workspaces/functions"
57105710
dependencies:
57115711
"@types/node": "npm:^20"
5712+
"@upstash/redis": "npm:^1.35.0"
57125713
"@vercel/node": "npm:^5.1.10"
57135714
typescript: "npm:^5.7.3"
57145715
languageName: unknown
@@ -6452,6 +6453,15 @@ __metadata:
64526453
languageName: node
64536454
linkType: hard
64546455

6456+
"@upstash/redis@npm:^1.35.0":
6457+
version: 1.35.0
6458+
resolution: "@upstash/redis@npm:1.35.0"
6459+
dependencies:
6460+
uncrypto: "npm:^0.1.3"
6461+
checksum: 10c0/9276bd1b093c17c5acb235537f1cb1eccfce7be77d5a9fbb4caaf4dcfb85eda8c9e3dcea93a0bf14d4dc1c5e39d201620eb0ffc4249476a6c19dbcd83be207a2
6462+
languageName: node
6463+
linkType: hard
6464+
64556465
"@use-gesture/core@npm:10.3.1":
64566466
version: 10.3.1
64576467
resolution: "@use-gesture/core@npm:10.3.1"
@@ -18019,6 +18029,13 @@ __metadata:
1801918029
languageName: node
1802018030
linkType: hard
1802118031

18032+
"uncrypto@npm:^0.1.3":
18033+
version: 0.1.3
18034+
resolution: "uncrypto@npm:0.1.3"
18035+
checksum: 10c0/74a29afefd76d5b77bedc983559ceb33f5bbc8dada84ff33755d1e3355da55a4e03a10e7ce717918c436b4dfafde1782e799ebaf2aadd775612b49f7b5b2998e
18036+
languageName: node
18037+
linkType: hard
18038+
1802218039
"undici-types@npm:~5.26.4":
1802318040
version: 5.26.5
1802418041
resolution: "undici-types@npm:5.26.5"

0 commit comments

Comments
 (0)