Add validation for cache capacity and TTL in LRUCache (#6187)
* fix: lru cache validation * chore: increased ttl to 30 mins * fix: tests
This commit is contained in:
@@ -31,6 +31,16 @@ describe('Http', (): void => {
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('should throw error on negative cache capacity or TTL', () => {
|
||||
expect(() =>
|
||||
new HttpProvider(TEST_HTTP_URL, {}, -5, 30000)
|
||||
).toThrow(/'capacity' must be a non-negative integer/);
|
||||
|
||||
expect(() =>
|
||||
new HttpProvider(TEST_HTTP_URL, {}, 1024, -1000)
|
||||
).toThrow(/'ttl' must be between 0 and 1800000 ms or null to disable/);
|
||||
});
|
||||
|
||||
it('allow clone', (): void => {
|
||||
const clone = http.clone();
|
||||
/* eslint-disable */
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
// for Kusama/Polkadot/Substrate falls between 600-750K, 2x for estimate)
|
||||
|
||||
export const DEFAULT_CAPACITY = 1024;
|
||||
export const DEFAULT_TTL = 30000;
|
||||
export const DEFAULT_TTL = 30000; // 30 seconds
|
||||
const MAX_TTL = 1800_000; // 30 minutes
|
||||
|
||||
// If the user decides to disable the TTL we set the value
|
||||
// to a very high number (A year = 365 * 24 * 60 * 60 * 1000).
|
||||
@@ -52,6 +53,16 @@ export class LRUCache {
|
||||
readonly #ttl: number;
|
||||
|
||||
constructor (capacity = DEFAULT_CAPACITY, ttl: number | null = DEFAULT_TTL) {
|
||||
// Validate capacity
|
||||
if (!Number.isInteger(capacity) || capacity < 0) {
|
||||
throw new Error(`LRUCache initialization error: 'capacity' must be a non-negative integer. Received: ${capacity}`);
|
||||
}
|
||||
|
||||
// Validate ttl
|
||||
if (ttl !== null && (!Number.isFinite(ttl) || ttl < 0 || ttl > MAX_TTL)) {
|
||||
throw new Error(`LRUCache initialization error: 'ttl' must be between 0 and ${MAX_TTL} ms or null to disable. Received: ${ttl}`);
|
||||
}
|
||||
|
||||
this.capacity = capacity;
|
||||
ttl ? this.#ttl = ttl : this.#ttl = DISABLED_TTL;
|
||||
this.#head = this.#tail = new LRUNode('<empty>', this.#ttl);
|
||||
|
||||
@@ -60,6 +60,11 @@ describe('Endpoint Parsing', (): void => {
|
||||
new WsProvider(TEST_WS_URL, 0);
|
||||
});
|
||||
|
||||
it('should throw error on negative cache capacity or TTL', () => {
|
||||
expect(() => new WsProvider(TEST_WS_URL, false, {}, undefined, -5, 30000)).toThrow(/'capacity' must be a non-negative integer/);
|
||||
expect(() => new WsProvider(TEST_WS_URL, false, {}, undefined, 1024, -1000)).toThrow(/'ttl' must be between 0 and 1800000 ms or null to disable/);
|
||||
});
|
||||
|
||||
it('Throws when WsProvider endpoint is an invalid string', () => {
|
||||
expect(
|
||||
() => new WsProvider('http://127.0.0.1:9955', 0)
|
||||
|
||||
Reference in New Issue
Block a user