-
-
Notifications
You must be signed in to change notification settings - Fork 460
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(webhook): Implement webhook functionality for bookmark events #852
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
5ce291b
feat(webhook): Implement webhook functionality for bookmark events
hanguofeng c4d5482
feat(webhook): Update webhook handling and configuration
hanguofeng c2b1518
Merge branch 'hoarder-app:main' into feat-webhook
hanguofeng e68821a
Merge branch 'main' into feat-webhook
MohamedBassem 05970fb
minor modifications
MohamedBassem File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
import { eq } from "drizzle-orm"; | ||
import { DequeuedJob, Runner } from "liteque"; | ||
import fetch from "node-fetch"; | ||
|
||
import { db } from "@hoarder/db"; | ||
import { bookmarks } from "@hoarder/db/schema"; | ||
import serverConfig from "@hoarder/shared/config"; | ||
import logger from "@hoarder/shared/logger"; | ||
import { | ||
WebhookQueue, | ||
ZWebhookRequest, | ||
zWebhookRequestSchema, | ||
} from "@hoarder/shared/queues"; | ||
|
||
export class WebhookWorker { | ||
static build() { | ||
logger.info("Starting webhook worker ..."); | ||
const worker = new Runner<ZWebhookRequest>( | ||
WebhookQueue, | ||
{ | ||
run: runWebhook, | ||
onComplete: async (job) => { | ||
const jobId = job.id; | ||
logger.info(`[webhook][${jobId}] Completed successfully`); | ||
return Promise.resolve(); | ||
}, | ||
onError: async (job) => { | ||
const jobId = job.id; | ||
logger.error( | ||
`[webhook][${jobId}] webhook job failed: ${job.error}\n${job.error.stack}`, | ||
); | ||
return Promise.resolve(); | ||
}, | ||
}, | ||
{ | ||
concurrency: 1, | ||
pollIntervalMs: 1000, | ||
timeoutSecs: | ||
serverConfig.webhook.timeoutSec * | ||
(serverConfig.webhook.retryTimes + 1) + | ||
1, //consider retry times, and timeout and add 1 second for other stuff | ||
validator: zWebhookRequestSchema, | ||
}, | ||
); | ||
|
||
return worker; | ||
} | ||
} | ||
|
||
async function fetchBookmark(linkId: string) { | ||
return await db.query.bookmarks.findFirst({ | ||
where: eq(bookmarks.id, linkId), | ||
with: { | ||
link: true, | ||
text: true, | ||
asset: true, | ||
}, | ||
}); | ||
} | ||
|
||
async function runWebhook(job: DequeuedJob<ZWebhookRequest>) { | ||
const jobId = job.id; | ||
const webhookUrls = serverConfig.webhook.urls; | ||
if (!webhookUrls) { | ||
logger.info( | ||
`[webhook][${jobId}] No webhook urls configured. Skipping webhook job.`, | ||
); | ||
return; | ||
} | ||
const webhookToken = serverConfig.webhook.token; | ||
const webhookTimeoutSec = serverConfig.webhook.timeoutSec; | ||
|
||
const { bookmarkId } = job.data; | ||
const bookmark = await fetchBookmark(bookmarkId); | ||
if (!bookmark) { | ||
throw new Error( | ||
`[webhook][${jobId}] bookmark with id ${bookmarkId} was not found`, | ||
); | ||
} | ||
|
||
logger.info( | ||
`[webhook][${jobId}] Starting a webhook job for bookmark with id "${bookmark.id}"`, | ||
); | ||
|
||
await Promise.allSettled( | ||
webhookUrls.map(async (url) => { | ||
const maxRetries = serverConfig.webhook.retryTimes; | ||
let attempt = 0; | ||
let success = false; | ||
|
||
while (attempt < maxRetries && !success) { | ||
try { | ||
const response = await fetch(url, { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json", | ||
...(webhookToken | ||
? { | ||
Authorization: `Bearer ${webhookToken}`, | ||
} | ||
: {}), | ||
}, | ||
body: JSON.stringify({ | ||
jobId, | ||
bookmarkId, | ||
userId: bookmark.userId, | ||
url: bookmark.link ? bookmark.link.url : undefined, | ||
type: bookmark.type, | ||
operation: job.data.operation, | ||
}), | ||
signal: AbortSignal.timeout(webhookTimeoutSec * 1000), | ||
}); | ||
|
||
if (!response.ok) { | ||
logger.error( | ||
`Webhook call to ${url} failed with status: ${response.status}`, | ||
); | ||
} else { | ||
logger.info(`[webhook][${jobId}] Webhook to ${url} call succeeded`); | ||
success = true; | ||
} | ||
} catch (error) { | ||
logger.error( | ||
`[webhook][${jobId}] Webhook to ${url} call failed: ${error}`, | ||
); | ||
} | ||
attempt++; | ||
if (!success && attempt < maxRetries) { | ||
logger.info( | ||
`[webhook][${jobId}] Retrying webhook call to ${url}, attempt ${attempt + 1}`, | ||
); | ||
} | ||
} | ||
}), | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What should we do if the webhook response is a non success status code? In that case, do we want to retry or not? I think we probably should?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I added a retry logic and also a config
WEBHOOK_RETRY_TIMES