-
Notifications
You must be signed in to change notification settings - Fork 1.2k
feat(metering): cron to monitor billing-events S3 DLQ bucket #6668
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
Open
pfreixes
wants to merge
3
commits into
master
Choose a base branch
from
pfreixes/nan-5734-listen-dlq-events
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+114
−0
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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 hidden or 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
101 changes: 101 additions & 0 deletions
101
packages/metering/lib/crons/billingEventsS3DLQMonitor.ts
This file contains hidden or 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,101 @@ | ||
| import { ListObjectsV2Command, S3Client } from '@aws-sdk/client-s3'; | ||
| import tracer from 'dd-trace'; | ||
| import * as cron from 'node-cron'; | ||
|
|
||
| import { getLocking } from '@nangohq/kvstore'; | ||
| import { getLogger, metrics } from '@nangohq/utils'; | ||
|
|
||
| import { envs } from '../env.js'; | ||
|
|
||
| import type { Lock } from '@nangohq/kvstore'; | ||
|
|
||
| const logger = getLogger('cron.billingEventsS3DLQMonitor'); | ||
| const cronMinute = envs.CRON_BILLING_EVENTS_S3_DLQ_MONITOR_MINUTE; | ||
| const bucket = envs.BILLING_EVENTS_S3_DLQ_BUCKET; | ||
| const region = envs.BILLING_EVENTS_S3_REGION; | ||
|
|
||
| const LOCK_KEY = 'lock:cron:billingEventsS3DLQMonitor'; | ||
| // Cron fires hourly; lock should expire well before the next tick. | ||
| const lockTtlMs = 30 * 60 * 1000; | ||
|
|
||
| const s3 = new S3Client({ region }); | ||
|
|
||
| export function billingEventsS3DLQMonitorCron(): void { | ||
| if (cronMinute < 0) { | ||
| logger.info(`Skipping (CRON_BILLING_EVENTS_S3_DLQ_MONITOR_MINUTE=${cronMinute})`); | ||
| return; | ||
| } | ||
| if (!bucket) { | ||
| logger.warning(`Skipping (BILLING_EVENTS_S3_DLQ_BUCKET not set)`); | ||
| return; | ||
| } | ||
| cron.schedule(`${cronMinute} * * * *`, () => { | ||
| exec().catch((err: unknown) => { | ||
| logger.error('Cron tick failed unexpectedly', err); | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| export async function exec(): Promise<void> { | ||
| await tracer.trace<Promise<void>>('nango.cron.billingEventsS3DLQMonitor', async () => { | ||
| logger.info(`Starting`); | ||
| await withLock(async () => { | ||
| let success = false; | ||
| try { | ||
| const fileCount = await countObjects(); | ||
| metrics.gauge(metrics.Types.BILLING_EVENTS_S3_DLQ_FILES, fileCount); | ||
| if (fileCount > 0) { | ||
| logger.warning(`DLQ bucket s3://${bucket!} has ${fileCount} file(s); alert should fire.`); | ||
| } else { | ||
| logger.info(`DLQ bucket s3://${bucket!} is empty.`); | ||
| } | ||
| success = true; | ||
| } catch (err) { | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| logger.error(`Failed to inspect DLQ bucket s3://${bucket!}`, err); | ||
| } finally { | ||
| metrics.increment(metrics.Types.BILLING_EVENTS_S3_DLQ_MONITOR_RUN_RESULT, 1, { success: success ? 'true' : 'false' }); | ||
| } | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| // We're already broken past 100 files; no need to paginate further. | ||
| const MAX_FILES_TO_COUNT = 100; | ||
|
|
||
| async function countObjects(): Promise<number> { | ||
| let count = 0; | ||
| let continuationToken: string | undefined; | ||
| do { | ||
| const res = await s3.send( | ||
| new ListObjectsV2Command({ | ||
| Bucket: bucket, | ||
| ContinuationToken: continuationToken | ||
| }) | ||
| ); | ||
| count += res.KeyCount ?? 0; | ||
| if (count >= MAX_FILES_TO_COUNT) return MAX_FILES_TO_COUNT; | ||
| continuationToken = res.IsTruncated ? res.NextContinuationToken : undefined; | ||
| } while (continuationToken); | ||
| return count; | ||
| } | ||
|
|
||
| async function withLock(fn: () => Promise<void>): Promise<void> { | ||
| const locking = await getLocking(); | ||
| let lock: Lock; | ||
| try { | ||
| lock = await locking.acquire(LOCK_KEY, lockTtlMs); | ||
| } catch { | ||
| logger.info(`Could not acquire lock, skipping`); | ||
| return; | ||
| } | ||
| logger.info(`Lock acquired`); | ||
| try { | ||
| await fn(); | ||
| } finally { | ||
| try { | ||
| await locking.release(lock); | ||
| } catch (err) { | ||
| logger.error('Error releasing lock', { lock: lock.key, error: err }); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or 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 hidden or 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.
Why is it hourly? If this is detecting things being broken, wouldn't it be worth knowing faster? I might be wrong, but it doesn't look like it's an expensive operation.
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.
We upload files once a day, so knowing it - worst case - after one hour is ok. From there we have "plenty" of time to fix the issue and reexport the data. Until we do not fix the issue we would be just alerted that there are files in the DLQ that require our attention, once fixed the issue we must remove manually the files from the DLQ
Im planning to provide a full demo of all of this