Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

fix(api/redis): better connection handling

Gergő Móriczebe547801af3
diff --git a/apps/api/src/services/worker/redis.ts b/apps/api/src/services/worker/redis.ts
index 0c4f58d67..4b9d300db 100644
--- a/apps/api/src/services/worker/redis.ts
+++ b/apps/api/src/services/worker/redis.ts
@@ -69,8 +69,44 @@ let initPromise: Promise<void> | null = null;
export const ensureRedis = async () => {
if (initPromise) return initPromise;
+
+ // If Redis is already connected/ready, just load scripts if needed
+ if (redis.status === "ready") {
+ initPromise = (async () => {
+ for (const [k, v] of Object.entries(luaScripts)) {
+ if (!scripts[k]) scripts[k] = {};
+ for (const [k2, v2] of Object.entries(v)) {
+ if (!scripts[k][k2]) {
+ const h = await redis.script("LOAD", v2);
+ scripts[k][k2] = h as string;
+ }
+ }
+ }
+ })();
+ return initPromise;
+ }
+
initPromise = (async () => {
- await redis.connect();
+ // Only call connect if in 'wait' state (not yet connected)
+ if (redis.status === "wait") {
+ await redis.connect();
+ } else if (redis.status === "connecting") {
+ // Already connecting, wait for it to complete
+ await new Promise<void>((resolve, reject) => {
+ const onReady = () => {
+ redis.off("error", onError);
+ resolve();
+ };
+ const onError = (err: Error) => {
+ redis.off("ready", onReady);
+ reject(err);
+ };
+ redis.once("ready", onReady);
+ redis.once("error", onError);
+ });
+ } else if (redis.status !== "ready") {
+ throw new Error(`Redis in unexpected state: ${redis.status}`);
+ }
for (const [k, v] of Object.entries(luaScripts)) {
scripts[k] = {};