Files
Kelx/utils/auth-redis-deadline.js
2026-11-30 16:32:37 +00:00

112 lines
5.1 KiB
JavaScript

"use strict";
const { resolveClampedInt } = require("./clamped-int");
function boundAuthRedisClient(client, { timeoutMs = 5000, setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
if (typeof client?.sendCommand !== "function" || typeof client?.multi !== "function" ||
!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
throw new TypeError("A Redis client and positive command deadline are required");
}
let recovering = false;
let stopping = false;
let connectionVersion = 0;
const run = (operation, controller) => new Promise((resolve, reject) => {
let settled = false;
let timer;
const startedVersion = connectionVersion;
const finish = (error, result) => {
if (settled) return;
settled = true;
clearTimer(timer);
if (error) reject(error);
else resolve(result);
};
// adpanel:auth-redis-deadline - connected-but-stalled commands must
// release requests and their queue rather than accumulating indefinitely.
timer = setTimer(() => {
const error = Object.assign(new Error("Authentication storage command timed out"), { code: "AUTH_REDIS_TIMEOUT" });
finish(error);
controller?.abort();
if (stopping || recovering || startedVersion !== connectionVersion) return;
recovering = true;
connectionVersion += 1;
try {
if (typeof client.destroy === "function") client.destroy();
else client.disconnect();
} catch { }
Promise.resolve().then(() => { if (!stopping) return client.connect(); }).catch(() => { }).finally(() => { recovering = false; });
}, timeoutMs);
try {
Promise.resolve(operation()).then((result) => finish(null, result), (error) => finish(error));
} catch (error) {
finish(error);
}
});
const wrapTransaction = (transaction) => {
const executionMethods = new Set(["exec", "EXEC", "execAsPipeline", "execTyped"]);
const proxy = new Proxy(transaction, {
get(target, property) {
const value = Reflect.get(target, property, target);
if (typeof value !== "function") return value;
if (executionMethods.has(property)) return (...args) => run(() => value.apply(target, args));
return (...args) => {
const result = value.apply(target, args);
return result === target ? proxy : result;
};
},
});
return proxy;
};
const lifecycleMethods = new Set(["connect", "quit", "close", "destroy", "disconnect", "monitor"]);
const optionMethods = new Set(["withCommandOptions", "withAbortSignal", "withTypeMapping", "asap"]);
const wrapClient = (target, commandOptions = {}) => {
const proxy = new Proxy(target, {
get(receiver, property) {
const value = Reflect.get(receiver, property, receiver);
if (typeof value !== "function") return value;
if (property === "multi" || property === "MULTI") return (...args) => wrapTransaction(value.apply(receiver, args));
if (optionMethods.has(property)) return (...args) => {
const options = property === "withCommandOptions" ? (args[0] || {})
: property === "withAbortSignal" ? { ...commandOptions, abortSignal: args[0] } : commandOptions;
return wrapClient(value.apply(receiver, args), options);
};
if (value.constructor.name === "AsyncGeneratorFunction") return (...args) => value.apply(proxy, args);
const command = property === "sendCommand" || (
typeof property === "string" && !property.startsWith("_") &&
value.constructor.name === "AsyncFunction" && !lifecycleMethods.has(property)
);
if (command) return (...args) => {
const controller = new AbortController();
const suppliedSignal = property === "sendCommand" ? (args[1]?.abortSignal || commandOptions.abortSignal) : commandOptions.abortSignal;
const abort = () => controller.abort();
if (suppliedSignal?.aborted) abort();
else suppliedSignal?.addEventListener("abort", abort, { once: true });
return run(() => {
if (property === "sendCommand") {
return value.call(receiver, args[0], { ...args[1], abortSignal: controller.signal });
}
const scopedClient = typeof receiver.withAbortSignal === "function" ? receiver.withAbortSignal(controller.signal) : receiver;
return scopedClient[property](...args);
}, controller).finally(() => suppliedSignal?.removeEventListener("abort", abort));
};
return (...args) => {
if (["quit", "close", "destroy", "disconnect"].includes(property)) stopping = true;
else if (property === "connect") stopping = false;
const result = value.apply(receiver, args);
return result === receiver ? proxy : result;
};
},
});
return proxy;
};
return wrapClient(client, client.options?.commandOptions);
}
function authRedisDeadlineOptions(env = process.env) {
return {
timeoutMs: resolveClampedInt(env, "AUTH_REDIS_COMMAND_TIMEOUT_MS", { fallback: 5000, min: 1000, max: 15000 }),
};
}
module.exports = { boundAuthRedisClient, authRedisDeadlineOptions };