-
Notifications
You must be signed in to change notification settings - Fork 1
imp(): move rate limiting to grouper #576
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
e11sy
wants to merge
6
commits into
master
Choose a base branch
from
imp/mv-rate-limits-to-grouper
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.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f383184
imp(): move rate limiting to grouper
7f670e2
tests(): fix redis initialization in tests
2f14cb3
chore(): eslint fix
c7905d2
chore(): restore redis testcontainers
ea8c5e8
chore(): yarn lock restoe
f53a5e2
chore(): readme minor improvements
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
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 |
|---|---|---|
| @@ -1,2 +1,8 @@ | ||
| # Url for connecting to Redis | ||
| REDIS_URL=redis://redis:6379 | ||
|
|
||
| # How often to refresh project rate limits from MongoDB (seconds) | ||
| PROJECTS_LIMITS_UPDATE_PERIOD=3600 | ||
|
|
||
| # Redis hash key for per-project rate limit counters | ||
| REDIS_RATE_LIMITS_KEY=rate_limits |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,10 +22,12 @@ import { MS_IN_SEC } from '../../../lib/utils/consts'; | |
| import TimeMs from '../../../lib/utils/time'; | ||
| import DataFilter from './data-filter'; | ||
| import RedisHelper from './redisHelper'; | ||
| import ProjectLimitsCache from './projectLimitsCache'; | ||
| import { computeDelta } from './utils/repetitionDiff'; | ||
| import { bucketTimestampMs } from './utils/bucketTimestamp'; | ||
| import { rightTrim } from '../../../lib/utils/string'; | ||
| import { hasValue } from '../../../lib/utils/hasValue'; | ||
| import { positiveIntEnv } from '../../../lib/utils/positiveIntEnv'; | ||
| import GrouperMetrics from './metrics/grouperMetrics'; | ||
| import GrouperMemoryMonitor from './metrics/memoryMonitor'; | ||
| import SlowHandleDiagnostics, { SlowHandleSession } from './metrics/slowHandleDiagnostics'; | ||
|
|
@@ -63,6 +65,11 @@ const DAILY_METRICS_RETENTION_DAYS = 90; | |
| */ | ||
| const MAX_CODE_LINE_LENGTH = 140; | ||
|
|
||
| /** | ||
| * Default interval for refreshing project limits cache (in seconds) | ||
| */ | ||
| const DEFAULT_PROJECTS_LIMITS_UPDATE_PERIOD_SECONDS = 3600; | ||
|
|
||
| /** | ||
| * Worker for handling Javascript events | ||
| */ | ||
|
|
@@ -92,6 +99,16 @@ export default class GrouperWorker extends Worker { | |
| */ | ||
| private redis = new RedisHelper(); | ||
|
|
||
| /** | ||
| * Cached project rate limits loaded from accounts MongoDB | ||
| */ | ||
| private projectLimitsCache: ProjectLimitsCache; | ||
|
|
||
| /** | ||
| * Interval for periodic project limits cache refresh | ||
| */ | ||
| private projectLimitsRefreshInterval: NodeJS.Timeout | null = null; | ||
|
|
||
| /** | ||
| * Prometheus metrics facade. | ||
| */ | ||
|
|
@@ -117,6 +134,14 @@ export default class GrouperWorker extends Worker { | |
| */ | ||
| private handledTasksCount = 0; | ||
|
|
||
| /** | ||
| * Create grouper worker instance | ||
| */ | ||
| constructor() { | ||
| super(); | ||
| this.projectLimitsCache = new ProjectLimitsCache(this.accountsDb); | ||
| } | ||
|
|
||
| /** | ||
| * Start consuming messages | ||
| */ | ||
|
|
@@ -131,6 +156,21 @@ export default class GrouperWorker extends Worker { | |
| await this.redis.initialize(); | ||
| console.log('redis initialized'); | ||
|
|
||
| await this.projectLimitsCache.refresh(); | ||
|
|
||
| const limitsUpdatePeriodSeconds = positiveIntEnv( | ||
| process.env.PROJECTS_LIMITS_UPDATE_PERIOD, | ||
| DEFAULT_PROJECTS_LIMITS_UPDATE_PERIOD_SECONDS, | ||
| ); | ||
|
|
||
| this.projectLimitsRefreshInterval = setInterval(() => { | ||
| /* eslint-disable-next-line no-void */ | ||
| void this.projectLimitsCache.refresh() | ||
| .catch((error) => { | ||
| this.logger.error('Failed to refresh project limits cache', error); | ||
| }); | ||
| }, limitsUpdatePeriodSeconds * MS_IN_SEC); | ||
|
Comment on lines
+166
to
+172
|
||
|
|
||
| /** | ||
| * Start periodic cache cleanup to prevent memory leaks from unbounded cache growth | ||
| * Runs every 30 seconds to clear old cache entries | ||
|
|
@@ -155,6 +195,11 @@ export default class GrouperWorker extends Worker { | |
| this.cacheCleanupInterval = null; | ||
| } | ||
|
|
||
| if (this.projectLimitsRefreshInterval) { | ||
| clearInterval(this.projectLimitsRefreshInterval); | ||
| this.projectLimitsRefreshInterval = null; | ||
| } | ||
|
|
||
| this.memoryMonitor.logShutdown(this.handledTasksCount); | ||
| await super.finish(); | ||
| this.prepareCache(); | ||
|
|
@@ -170,6 +215,16 @@ export default class GrouperWorker extends Worker { | |
| */ | ||
| public async handle(task: GroupWorkerTask<ErrorsCatcherType>): Promise<void> { | ||
| try { | ||
| const withinLimit = await this.checkRateLimit(task.projectId); | ||
|
|
||
| if (!withinLimit) { | ||
| this.grouperMetrics.incrementRateLimitedTotal(); | ||
| await this.recordProjectMetrics(task.projectId, 'events-rate-limited'); | ||
| this.logger.info(`[rate-limit] project=${task.projectId} title="${task.payload?.title}" dropped`); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| await this.grouperMetrics.observeHandleDuration(async () => { | ||
| await this.handleInternal(task); | ||
| }); | ||
|
|
@@ -180,6 +235,30 @@ export default class GrouperWorker extends Worker { | |
| } | ||
| } | ||
|
|
||
| /** | ||
| * Check and update per-project rate limit in Redis. | ||
| * | ||
| * @param projectId - project id | ||
| */ | ||
| private async checkRateLimit(projectId: string): Promise<boolean> { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I’m not fond of the constant addition of new methods to the grouper index file. Let’s adhere to the principle of separation of concerns and create a separate ReteLimitter file that will encapsulate all the necessary logic. |
||
| const limits = this.projectLimitsCache.getProjectLimits(projectId); | ||
|
|
||
| if (!limits) { | ||
| this.logger.warn(`Project ${projectId} is not in the projects limits cache`); | ||
| } | ||
|
|
||
| const eventsLimit = limits?.eventsLimit ?? 0; | ||
| const eventsPeriod = limits?.eventsPeriod ?? 0; | ||
|
|
||
| try { | ||
| return await this.redis.updateRateLimit(projectId, eventsLimit, eventsPeriod); | ||
| } catch (error) { | ||
| this.logger.error(`Failed to update rate limit for project ${projectId}`, error); | ||
|
|
||
| return false; | ||
| } | ||
|
Comment on lines
+255
to
+259
|
||
| } | ||
|
|
||
| /** | ||
| * Internal task handling function | ||
| * | ||
|
|
@@ -301,7 +380,7 @@ export default class GrouperWorker extends Worker { | |
| this.grouperMetrics.incrementDuplicateRetriesTotal(); | ||
| this.logger.info(`[saveEvent] project=${task.projectId} title="${task.payload.title}" duplicate key, retrying as repetition`); | ||
|
|
||
| await this.handle(task); | ||
| await this.handleInternal(task); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
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.
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.
we already have 2 cache mechanics:
Let's use one of them and do not implement another one.