-
Notifications
You must be signed in to change notification settings - Fork 0
LVT-227 Scope Redis cache resets to Lovat keys #2
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
benstein
wants to merge
2
commits into
main
Choose a base branch
from
codex/lvt-227-remove-unsafe-redis-flushing
base: main
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
2 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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import { config } from "dotenv"; | ||
|
|
||
| export const loadEnvironmentFile = (path?: string): void => { | ||
| const result = config({ path, quiet: true }); | ||
|
|
||
| if ( | ||
| result.error && | ||
| (result.error as NodeJS.ErrnoException).code !== "ENOENT" | ||
| ) { | ||
| throw result.error; | ||
| } | ||
| }; |
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,92 @@ | ||
| const RESET_BATCH_SIZE = 100; | ||
|
|
||
| type RedisInteger = `${number}` | number; | ||
| type RedisKey = Buffer | string; | ||
|
|
||
| export type RedisKeyValueClient = { | ||
| set(key: string, data: string, options?: { EX: number }): Promise<unknown>; | ||
| get(key: string): Promise<Buffer | string | null>; | ||
| del(keys: RedisKey[] | RedisKey): Promise<RedisInteger>; | ||
| incr(key: string): Promise<RedisInteger>; | ||
| expire(key: string, seconds: number): Promise<unknown>; | ||
| scanIterator(options: { | ||
| MATCH: string; | ||
| COUNT: number; | ||
| }): AsyncIterable<RedisKey[]>; | ||
| }; | ||
|
|
||
| export type NamespacedKv = { | ||
| set(key: string, data: string): Promise<unknown>; | ||
| get(key: string): Promise<Buffer | string | null>; | ||
| del(keys: string[] | string): Promise<number>; | ||
| incr(key: string): Promise<number>; | ||
| exp(key: string, seconds: number): Promise<unknown>; | ||
| setEx(key: string, data: string, seconds: number): Promise<unknown>; | ||
| reset(): Promise<number>; | ||
| }; | ||
|
|
||
| export const createNamespacedKv = ( | ||
| redis: RedisKeyValueClient, | ||
| keyPrefix: string, | ||
| ): NamespacedKv => { | ||
| if (["*", "?", "[", "]", "\\"].some((char) => keyPrefix.includes(char))) { | ||
| throw new Error("Redis key prefix cannot contain Redis glob characters"); | ||
| } | ||
|
|
||
| const namespacedKey = (key: string): string => `${keyPrefix}${key}`; | ||
|
|
||
| const set = async (key: string, data: string): Promise<unknown> => { | ||
| return await redis.set(namespacedKey(key), data); | ||
| }; | ||
|
|
||
| const get = async (key: string): Promise<Buffer | string | null> => { | ||
| return await redis.get(namespacedKey(key)); | ||
| }; | ||
|
|
||
| const del = async (keys: string[] | string): Promise<number> => { | ||
| const namespacedKeys = Array.isArray(keys) | ||
| ? keys.map(namespacedKey) | ||
| : namespacedKey(keys); | ||
|
|
||
| return Number(await redis.del(namespacedKeys)); | ||
| }; | ||
|
|
||
| const incr = async (key: string): Promise<number> => { | ||
| return Number(await redis.incr(namespacedKey(key))); | ||
| }; | ||
|
|
||
| const exp = async (key: string, seconds: number): Promise<unknown> => { | ||
| return await redis.expire(namespacedKey(key), seconds); | ||
| }; | ||
|
|
||
| const setEx = async ( | ||
| key: string, | ||
| data: string, | ||
| seconds: number, | ||
| ): Promise<unknown> => { | ||
| return await redis.set(namespacedKey(key), data, { EX: seconds }); | ||
| }; | ||
|
|
||
| const reset = async (): Promise<number> => { | ||
| let deleted = 0; | ||
|
|
||
| for await (const keys of redis.scanIterator({ | ||
| MATCH: `${keyPrefix}*`, | ||
| COUNT: RESET_BATCH_SIZE, | ||
| })) { | ||
| if (keys.length > 0) deleted += Number(await redis.del(keys)); | ||
| } | ||
|
|
||
| return deleted; | ||
| }; | ||
|
|
||
| return { | ||
| set, | ||
| get, | ||
| del, | ||
| incr, | ||
| exp, | ||
| setEx, | ||
| reset, | ||
| }; | ||
| }; |
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,15 @@ | ||
| export type CacheResetDependencies = { | ||
| resetRedis(): Promise<number>; | ||
| deleteMetadata(): Promise<void>; | ||
| }; | ||
|
|
||
| export const resetCacheState = async ({ | ||
| resetRedis, | ||
| deleteMetadata, | ||
| }: CacheResetDependencies): Promise<number> => { | ||
| let deletedRedisKeys = await resetRedis(); | ||
| await deleteMetadata(); | ||
| deletedRedisKeys += await resetRedis(); | ||
|
|
||
| return deletedRedisKeys; | ||
| }; | ||
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,15 @@ | ||
| export type ServerStartupDependencies = { | ||
| initializeCache(): Promise<void>; | ||
| scheduleJobs(): Promise<void>; | ||
| listen(): void; | ||
| }; | ||
|
|
||
| export const startServer = async ({ | ||
| initializeCache, | ||
| scheduleJobs, | ||
| listen, | ||
| }: ServerStartupDependencies): Promise<void> => { | ||
| await initializeCache(); | ||
| await scheduleJobs(); | ||
| listen(); | ||
| }; |
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,55 +1,23 @@ | ||
| import { createClient } from "redis"; | ||
| import { createNamespacedKv } from "./lib/namespacedKv.js"; | ||
|
|
||
| const redis = createClient({ url: process.env.REDIS_URL }) | ||
| .on("error", (err) => console.log("Redis Client Error", err)) | ||
| .connect(); | ||
| const DEFAULT_KEY_PREFIX = "lovat:"; | ||
|
|
||
| const set = async ( | ||
| key: string, | ||
| data: string, | ||
| ): ReturnType<Awaited<typeof redis>["set"]> => { | ||
| return await (await redis).set(key, data); | ||
| const getKeyPrefix = (): string => { | ||
| return process.env.REDIS_KEY_PREFIX?.trim() || DEFAULT_KEY_PREFIX; | ||
| }; | ||
|
|
||
| const get = async (key: string): ReturnType<Awaited<typeof redis>["get"]> => { | ||
| return await (await redis).get(key); | ||
| }; | ||
|
|
||
| const del = async ( | ||
| key: string[] | string, | ||
| ): ReturnType<Awaited<typeof redis>["del"]> => { | ||
| return await (await redis).del(key); | ||
| }; | ||
|
|
||
| const flush = async (): ReturnType<Awaited<typeof redis>["flushDb"]> => { | ||
| return await (await redis).flushDb(); | ||
| }; | ||
|
|
||
| const incr = async (key: string): ReturnType<Awaited<typeof redis>["incr"]> => { | ||
| return await (await redis).incr(key); | ||
| }; | ||
| const redisClient = createClient({ url: process.env.REDIS_URL }).on( | ||
| "error", | ||
| (err) => console.log("Redis Client Error", err), | ||
| ); | ||
|
|
||
| const exp = async ( | ||
| key: string, | ||
| exp: number, | ||
| ): ReturnType<Awaited<typeof redis>["expire"]> => { | ||
| return await (await redis).expire(key, exp); | ||
| }; | ||
| export const kv = createNamespacedKv(redisClient, getKeyPrefix()); | ||
|
|
||
| const setEx = async ( | ||
| key: string, | ||
| data: string, | ||
| seconds: number, | ||
| ): ReturnType<Awaited<typeof redis>["set"]> => { | ||
| return await (await redis).set(key, data, { EX: seconds }); | ||
| export const connectRedis = async (): Promise<void> => { | ||
| if (!redisClient.isOpen) await redisClient.connect(); | ||
| }; | ||
|
|
||
| export const kv = { | ||
| set, | ||
| get, | ||
| del, | ||
| flush, | ||
| incr, | ||
| exp, | ||
| setEx, | ||
| export const closeRedis = async (): Promise<void> => { | ||
| if (redisClient.isOpen) await redisClient.close(); | ||
| }; |
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,24 @@ | ||
| import { loadEnvironmentFile } from "./lib/loadEnvironmentFile.js"; | ||
|
|
||
| loadEnvironmentFile(); | ||
|
|
||
| const [ | ||
| { resetCache }, | ||
| { default: prismaClient }, | ||
| { closeRedis, connectRedis }, | ||
| ] = await Promise.all([ | ||
| import("./lib/clearCache.js"), | ||
| import("./prismaClient.js"), | ||
| import("./redisClient.js"), | ||
| ]); | ||
|
|
||
| try { | ||
| await connectRedis(); | ||
| await resetCache(); | ||
| } finally { | ||
| try { | ||
| await prismaClient.$disconnect(); | ||
| } finally { | ||
| await closeRedis(); | ||
| } | ||
| } |
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,12 +1,16 @@ | ||
| import { app } from "./app.js"; | ||
| import { startServer } from "./lib/startServer.js"; | ||
| import scheduleJobs from "./lib/scheduleJobs.js"; | ||
| import { clearCache } from "./lib/clearCache.js"; | ||
| import { connectRedis } from "./redisClient.js"; | ||
|
|
||
| const port = process.env.PORT || 3000; | ||
|
|
||
| await scheduleJobs(); | ||
| await clearCache(); | ||
|
|
||
| app.listen(port, () => { | ||
| console.log(`Server running on :${port}`); | ||
| await startServer({ | ||
| initializeCache: connectRedis, | ||
| scheduleJobs, | ||
| listen: () => { | ||
| app.listen(port, () => { | ||
| console.log(`Server running on :${port}`); | ||
| }); | ||
| }, | ||
| }); |
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.
When
cache:resetruns while requests are still in flight, this final scan does not cover writes that occur after its SCAN cursor reaches zero. For example, a request already executing the schema-mismatch recovery path inanalysisFunction.ts:113-121can finish its calculation after both scans and rewrite the Redis value without recreating theCachedAnalysisrow thatdeleteMetadataremoved; subsequent data changes then cannot discover and invalidate that stale key. The reset can therefore report success while leaving an untracked cache entry unless writes are blocked or the server is guaranteed to be stopped.Useful? React with 👍 / 👎.