-
-
Notifications
You must be signed in to change notification settings - Fork 9
fix: use in-memory cache in price service #427
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 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
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,69 +1,182 @@ | ||
| import { assert } from '@metamask/utils'; | ||
|
|
||
| import type { Serializable } from '../serialization/types'; | ||
| import type { ILogger } from '../utils/logger'; | ||
| import type { ICache } from './ICache'; | ||
| import type { CacheEntry } from './types'; | ||
|
|
||
| /** | ||
| * A simple in-memory cache implementation, primarily used for testing purposes. | ||
| * A simple in-memory cache implementation supporting TTL (Time To Live) functionality. | ||
| * | ||
| * WARNINGS: | ||
| * - This cache is not persistent and will be lost when the process is restarted. | ||
| * - It does not support TTL. | ||
| */ | ||
| export class InMemoryCache implements ICache<Serializable> { | ||
| #cache: Map<string, Serializable> = new Map(); | ||
| #cache: Map<string, CacheEntry> = new Map(); | ||
|
|
||
| public readonly logger: ILogger; | ||
|
|
||
| constructor(logger: ILogger) { | ||
| this.logger = logger; | ||
| } | ||
|
|
||
| #validateTtlOrThrow(ttlMilliseconds?: number): void { | ||
| if (ttlMilliseconds === undefined) { | ||
| return; | ||
| } | ||
|
|
||
| if (typeof ttlMilliseconds !== 'number') { | ||
| throw new Error('TTL must be a number'); | ||
| } | ||
|
|
||
| if (ttlMilliseconds < 0) { | ||
| throw new Error('TTL must be positive'); | ||
| } | ||
|
|
||
| if (ttlMilliseconds > Number.MAX_SAFE_INTEGER) { | ||
| throw new Error('TTL must be less than 2^53 - 1'); | ||
| } | ||
| } | ||
|
|
||
| #isExpired(cacheEntry: CacheEntry): boolean { | ||
| return cacheEntry.expiresAt < Date.now(); | ||
| } | ||
|
|
||
| async #cleanupExpiredEntries(): Promise<void> { | ||
| const expiredKeys: string[] = []; | ||
| for (const [key, entry] of this.#cache.entries()) { | ||
| if (this.#isExpired(entry)) { | ||
| expiredKeys.push(key); | ||
| } | ||
| } | ||
| await this.mdelete(expiredKeys); | ||
| } | ||
|
|
||
| async get(key: string): Promise<Serializable | undefined> { | ||
| return this.#cache.get(key); | ||
| const result = await this.mget([key]); | ||
| return result[key]; | ||
| } | ||
|
|
||
| async set( | ||
| key: string, | ||
| value: Serializable, | ||
| _ttlMilliseconds?: number, | ||
| ttlMilliseconds = Number.MAX_SAFE_INTEGER, | ||
| ): Promise<void> { | ||
| this.#cache.set(key, value); | ||
| this.#validateTtlOrThrow(ttlMilliseconds); | ||
|
|
||
| this.#cache.set(key, { | ||
| value, | ||
| expiresAt: Math.min( | ||
| Date.now() + (ttlMilliseconds ?? Number.MAX_SAFE_INTEGER), | ||
| Number.MAX_SAFE_INTEGER, | ||
| ), | ||
| }); | ||
| } | ||
|
|
||
| async delete(key: string): Promise<boolean> { | ||
| return this.#cache.delete(key); | ||
| const result = await this.mdelete([key]); | ||
| return result[key] ?? false; | ||
| } | ||
|
|
||
| async clear(): Promise<void> { | ||
| this.#cache.clear(); | ||
| } | ||
|
|
||
| async has(key: string): Promise<boolean> { | ||
| return this.#cache.has(key); | ||
| const cacheEntry = this.#cache.get(key); | ||
| if (!cacheEntry) { | ||
| return false; | ||
| } | ||
|
|
||
| if (this.#isExpired(cacheEntry)) { | ||
| this.#cache.delete(key); | ||
| return false; | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| async keys(): Promise<string[]> { | ||
| await this.#cleanupExpiredEntries(); | ||
| return Array.from(this.#cache.keys()); | ||
| } | ||
|
|
||
| async size(): Promise<number> { | ||
| await this.#cleanupExpiredEntries(); | ||
| return this.#cache.size; | ||
| } | ||
|
|
||
| async peek(key: string): Promise<Serializable | undefined> { | ||
| return this.#cache.get(key); | ||
| const cacheEntry = this.#cache.get(key); | ||
| if (!cacheEntry) { | ||
| return undefined; | ||
| } | ||
|
|
||
| if (this.#isExpired(cacheEntry)) { | ||
| this.#cache.delete(key); | ||
| return undefined; | ||
| } | ||
|
|
||
| return cacheEntry.value; | ||
| } | ||
|
|
||
| async mget(keys: string[]): Promise<Record<string, Serializable>> { | ||
| return Object.fromEntries( | ||
| keys.map((key) => [key, this.#cache.get(key)]), | ||
| ) as Record<string, Serializable>; | ||
| async mget( | ||
| keys: string[], | ||
| ): Promise<Record<string, Serializable | undefined>> { | ||
| await this.#cleanupExpiredEntries(); | ||
|
|
||
| const result: Record<string, Serializable | undefined> = {}; | ||
|
|
||
| for (const key of keys) { | ||
| const cacheEntry = this.#cache.get(key); | ||
| if (!cacheEntry) { | ||
| this.logger.info(`[InMemoryCache] ❌ Cache miss for key "${key}"`); | ||
| result[key] = undefined; | ||
| continue; | ||
| } | ||
|
|
||
| this.logger.info(`[InMemoryCache] 🎉 Cache hit for key "${key}"`); | ||
| result[key] = cacheEntry.value; | ||
| } | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| async mset( | ||
| entries: { key: string; value: Serializable; _ttlMilliseconds?: number }[], | ||
| entries: { key: string; value: Serializable; ttlMilliseconds?: number }[], | ||
| ): Promise<void> { | ||
| entries.forEach(({ key, value }) => { | ||
| this.#cache.set(key, value); | ||
| if (entries.length === 0) { | ||
| return; | ||
| } | ||
|
|
||
| if (entries.length === 1) { | ||
| assert(entries[0]); // Enforce type narrowing as TS cannot infer that entries[0] is defined | ||
| const { key, value, ttlMilliseconds } = entries[0]; | ||
| await this.set(key, value, ttlMilliseconds); | ||
| return; | ||
| } | ||
|
|
||
| entries.forEach(({ ttlMilliseconds }) => { | ||
| this.#validateTtlOrThrow(ttlMilliseconds); | ||
| }); | ||
|
|
||
| entries.forEach(({ key, value, ttlMilliseconds }) => { | ||
| if (value === undefined) { | ||
| return; | ||
| } | ||
| this.#cache.set(key, { | ||
| value, | ||
| expiresAt: Math.min( | ||
| Date.now() + (ttlMilliseconds ?? Number.MAX_SAFE_INTEGER), | ||
| Number.MAX_SAFE_INTEGER, | ||
| ), | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| async mdelete(keys: string[]): Promise<Record<string, boolean>> { | ||
| return Object.fromEntries( | ||
| keys.map((key) => [key, this.#cache.delete(key)]), | ||
| ) as Record<string, boolean>; | ||
| ); | ||
| } | ||
| } |
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 |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| import type { Serializable } from '../serialization/types'; | ||
|
|
||
| export type TimestampMilliseconds = number; | ||
|
|
||
| /** | ||
| * A single cache entry. | ||
| */ | ||
| export type CacheEntry = { | ||
| value: Serializable; | ||
| expiresAt: TimestampMilliseconds; | ||
| }; |
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
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.
Uh oh!
There was an error while loading. Please reload this page.