This repository has been archived by the owner on Sep 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 38
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Rate limiter Architecture To Ocular (#62)
* Add Rate Limiting Architecture * Add Rate Limiter Architecture To Ocular * Remove Extra File
- Loading branch information
1 parent
fd1ffef
commit 88eb98f
Showing
8 changed files
with
130 additions
and
5 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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 |
---|---|---|
@@ -1,4 +1,5 @@ | ||
env.local | ||
.env.dev | ||
.env.local | ||
.env | ||
.env | ||
*.DS_Store |
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
File renamed without changes.
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,58 @@ | ||
import { after } from 'node:test'; | ||
import RateLimiterService from '../rate-limiter' | ||
import Redis from 'ioredis'; | ||
|
||
describe('queueService', () => { | ||
let rateLimiterService: RateLimiterService; | ||
let redis: Redis; | ||
beforeAll(async () => { | ||
try{ | ||
redis = new Redis("redis://localhost:6379", { | ||
// Lazy connect to properly handle connection errors | ||
lazyConnect: true, | ||
maxRetriesPerRequest: null, // Add this line | ||
}) | ||
|
||
try { | ||
await redis.connect() | ||
} catch (err) { | ||
console.log(`An error occurred while connecting to Redis:${err}`) | ||
} | ||
|
||
|
||
const moduleDeps = { | ||
redisClient: redis, | ||
} | ||
rateLimiterService = new RateLimiterService(moduleDeps); | ||
} catch (error) { | ||
console.log('Error Instantiating The Rate Limiter Service', error) | ||
} | ||
}); | ||
|
||
afterAll(async () => { | ||
await redis.disconnect(); | ||
}) | ||
|
||
it('it should rate limit an api', async () => { | ||
// Register a rate limiter for an ocular api to allow 5 requests per second | ||
await rateLimiterService.register("ocular", 5, 1); | ||
const requestQueue = await rateLimiterService.getRequestQueue("ocular"); | ||
expect(requestQueue).toBeDefined(); | ||
|
||
// Consume 14 tokens from the rate limiter queue at a rate of 5 tokens per second | ||
const promises: Promise<void>[] = []; | ||
for (let i = 0; i < 14; i++) { | ||
const promise = requestQueue.removeTokens(1,"ocular") | ||
.then((rateLimiterRes) => { | ||
console.log('Rate Limit Remaining', rateLimiterRes) | ||
}).catch((error) => { | ||
console.log('Error Consuming Rate Limit', error) | ||
}); | ||
promises.push(promise); | ||
} | ||
|
||
// Wait for all promises to complete | ||
await Promise.all(promises) | ||
}); | ||
} | ||
) |
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,52 @@ | ||
import Redis from "ioredis" | ||
import { RateLimiterRedis, RateLimiterQueue } from "rate-limiter-flexible" | ||
import { RateLimiterOpts } from "../types" | ||
import { TransactionBaseService } from "@ocular/types" | ||
import { AutoflowAiError } from "@ocular/utils" | ||
|
||
type RateLimiterServiceProps = { | ||
redisClient: Redis | ||
} | ||
|
||
/** | ||
* Stores Rate Limiters For Apps In Ocular | ||
*/ | ||
class RateLimiterService extends TransactionBaseService { | ||
protected apiToRateLimiterMap_: Map <string, RateLimiterQueue> = new Map() | ||
protected redisClient_: Redis | ||
|
||
constructor({ redisClient }: RateLimiterServiceProps) { | ||
super(arguments[0]) | ||
this.redisClient_ = redisClient | ||
} | ||
|
||
protected storeRateLimiterQueues({ | ||
apiName, | ||
limiterQueue, | ||
}: { | ||
apiName: string | ||
limiterQueue: RateLimiterQueue | ||
}) { | ||
this.apiToRateLimiterMap_.set(apiName, limiterQueue) | ||
} | ||
|
||
|
||
async register(apiName:string , points: number, duration: number): Promise<void> { | ||
try { | ||
const rateLimiter = new RateLimiterRedis({storeClient: this.redisClient_, keyPrefix: apiName, points: points, duration: duration}) | ||
const limiterQueue = new RateLimiterQueue(rateLimiter); | ||
this.storeRateLimiterQueues({apiName, limiterQueue}) | ||
} catch(e) { | ||
throw new AutoflowAiError ( | ||
AutoflowAiError.Types.INVALID_DATA, | ||
`Failed to rate limiter for ${apiName} with ${e}` | ||
) | ||
} | ||
} | ||
|
||
async getRequestQueue(apiName: string): Promise<RateLimiterQueue> { | ||
return this.apiToRateLimiterMap_.get(apiName) | ||
} | ||
} | ||
|
||
export default RateLimiterService |
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,4 @@ | ||
export interface RateLimiterOpts{ | ||
points: number // Number of points | ||
duration: number, // Per second(s) | ||
} |