release: WRNexusJS 0.8.0
This commit is contained in:
+121
-39
@@ -32,6 +32,15 @@ interface ParsedUrl {
|
||||
tls: boolean;
|
||||
}
|
||||
|
||||
export interface RedisDriverOptions {
|
||||
/** Maximum writes buffered while Redis is unavailable. Default 1000. */
|
||||
maxPending?: number;
|
||||
/** Initial reconnect delay. Doubles up to reconnectMaxDelayMs. Default 100. */
|
||||
reconnectDelayMs?: number;
|
||||
/** Maximum reconnect delay. Default 5000. */
|
||||
reconnectMaxDelayMs?: number;
|
||||
}
|
||||
|
||||
function parseUrl(url: string): ParsedUrl {
|
||||
const u = new URL(url);
|
||||
if (u.protocol !== "redis:" && u.protocol !== "rediss:") {
|
||||
@@ -59,58 +68,101 @@ const isPattern = (p: string): boolean => p.includes("*");
|
||||
* Open a Redis TCP connection. `onReply` receives every parsed top-level reply
|
||||
* (used by the subscriber connection to dispatch message/pmessage pushes).
|
||||
*/
|
||||
function connect(cfg: ParsedUrl, onReply?: (value: RespValue) => void): RedisConn {
|
||||
function connect(
|
||||
cfg: ParsedUrl,
|
||||
options: Required<RedisDriverOptions>,
|
||||
onReply?: (value: RespValue) => void,
|
||||
onReconnect?: () => void,
|
||||
): RedisConn {
|
||||
let socket: { write(data: Uint8Array): void; end(): void } | null = null;
|
||||
const pending: Uint8Array[] = [];
|
||||
const maxPending = 1000;
|
||||
let buf: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
|
||||
let closed = false;
|
||||
let connecting = false;
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let reconnectAttempt = 0;
|
||||
let openedOnce = false;
|
||||
|
||||
// Bun.connect is available in the Bun runtime.
|
||||
const Bun = (globalThis as { Bun?: { connect: (opts: unknown) => Promise<unknown> } }).Bun;
|
||||
if (!Bun?.connect) throw new Error("redisDriver requires the Bun runtime (Bun.connect).");
|
||||
|
||||
void Bun.connect({
|
||||
hostname: cfg.host,
|
||||
port: cfg.port,
|
||||
tls: cfg.tls,
|
||||
socket: {
|
||||
open(s: { write(data: Uint8Array): void; end(): void }) {
|
||||
socket = s;
|
||||
if (cfg.password) s.write(encodeCommand(["AUTH", cfg.password]));
|
||||
if (cfg.db) s.write(encodeCommand(["SELECT", String(cfg.db)]));
|
||||
for (const p of pending) s.write(p);
|
||||
pending.length = 0;
|
||||
const scheduleReconnect = () => {
|
||||
if (closed || reconnectTimer) return;
|
||||
const delay = Math.min(
|
||||
options.reconnectMaxDelayMs,
|
||||
options.reconnectDelayMs * 2 ** reconnectAttempt++,
|
||||
);
|
||||
reconnectTimer = setTimeout(() => {
|
||||
reconnectTimer = null;
|
||||
start();
|
||||
}, delay);
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
if (closed || connecting) return;
|
||||
connecting = true;
|
||||
void Bun.connect({
|
||||
hostname: cfg.host,
|
||||
port: cfg.port,
|
||||
tls: cfg.tls,
|
||||
socket: {
|
||||
open(s: { write(data: Uint8Array): void; end(): void }) {
|
||||
connecting = false;
|
||||
socket = s;
|
||||
reconnectAttempt = 0;
|
||||
if (cfg.password) s.write(encodeCommand(["AUTH", cfg.password]));
|
||||
if (cfg.db) s.write(encodeCommand(["SELECT", String(cfg.db)]));
|
||||
if (openedOnce) onReconnect?.();
|
||||
openedOnce = true;
|
||||
for (const p of pending) s.write(p);
|
||||
pending.length = 0;
|
||||
},
|
||||
data(_s: unknown, chunk: Uint8Array) {
|
||||
buf = buf.length ? concat([buf, chunk]) : chunk;
|
||||
for (;;) {
|
||||
const r = parseReply(buf);
|
||||
if (!r) break;
|
||||
buf = buf.slice(r.next);
|
||||
onReply?.(r.value);
|
||||
}
|
||||
},
|
||||
error() {
|
||||
socket = null;
|
||||
connecting = false;
|
||||
scheduleReconnect();
|
||||
},
|
||||
close() {
|
||||
socket = null;
|
||||
connecting = false;
|
||||
scheduleReconnect();
|
||||
},
|
||||
},
|
||||
data(_s: unknown, chunk: Uint8Array) {
|
||||
buf = buf.length ? concat([buf, chunk]) : chunk;
|
||||
for (;;) {
|
||||
const r = parseReply(buf);
|
||||
if (!r) break;
|
||||
buf = buf.slice(r.next);
|
||||
onReply?.(r.value);
|
||||
}
|
||||
},
|
||||
error() {
|
||||
/* connection error — writes silently no-op until reconnect */
|
||||
},
|
||||
close() {
|
||||
socket = null;
|
||||
},
|
||||
},
|
||||
});
|
||||
}).catch(() => {
|
||||
connecting = false;
|
||||
scheduleReconnect();
|
||||
});
|
||||
};
|
||||
start();
|
||||
|
||||
return {
|
||||
send(bytes) {
|
||||
if (socket) socket.write(bytes);
|
||||
else {
|
||||
if (pending.length >= maxPending) {
|
||||
if (closed) throw new Error("Redis pubsub connection is closed");
|
||||
if (pending.length >= options.maxPending) {
|
||||
throw new Error("Redis connection is unavailable and its pending write queue is full");
|
||||
}
|
||||
pending.push(bytes);
|
||||
}
|
||||
},
|
||||
close() {
|
||||
closed = true;
|
||||
if (reconnectTimer) clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
pending.length = 0;
|
||||
socket?.end();
|
||||
socket = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -119,8 +171,22 @@ function connect(cfg: ParsedUrl, onReply?: (value: RespValue) => void): RedisCon
|
||||
* A cross-process pub/sub driver backed by Redis. `url` defaults to
|
||||
* `$REDIS_URL` or `redis://localhost:6379`.
|
||||
*/
|
||||
export function redisDriver(url?: string): PubSubDriver & { close(): void } {
|
||||
export function redisDriver(
|
||||
url?: string,
|
||||
options: RedisDriverOptions = {},
|
||||
): PubSubDriver & { close(): void } {
|
||||
const cfg = parseUrl(url ?? getEnv("REDIS_URL") ?? "redis://localhost:6379");
|
||||
const resolved = {
|
||||
maxPending: positiveInteger(options.maxPending ?? 1000, "Redis maxPending"),
|
||||
reconnectDelayMs: positiveInteger(options.reconnectDelayMs ?? 100, "Redis reconnectDelayMs"),
|
||||
reconnectMaxDelayMs: positiveInteger(
|
||||
options.reconnectMaxDelayMs ?? 5000,
|
||||
"Redis reconnectMaxDelayMs",
|
||||
),
|
||||
};
|
||||
if (resolved.reconnectMaxDelayMs < resolved.reconnectDelayMs) {
|
||||
throw new RangeError("Redis reconnectMaxDelayMs must be >= reconnectDelayMs");
|
||||
}
|
||||
const subs = new Map<string, Set<Handler>>();
|
||||
const redisSubscribed = new Set<string>();
|
||||
|
||||
@@ -136,13 +202,22 @@ export function redisDriver(url?: string): PubSubDriver & { close(): void } {
|
||||
for (const handler of handlers) void handler(message, topic);
|
||||
};
|
||||
|
||||
const subConn = connect(cfg, (value) => {
|
||||
if (!Array.isArray(value)) return;
|
||||
const kind = value[0];
|
||||
if (kind === "message") dispatch(String(value[1]), String(value[1]), String(value[2]));
|
||||
else if (kind === "pmessage") dispatch(String(value[1]), String(value[2]), String(value[3]));
|
||||
});
|
||||
const pubConn = connect(cfg);
|
||||
const subConn = connect(
|
||||
cfg,
|
||||
resolved,
|
||||
(value) => {
|
||||
if (!Array.isArray(value)) return;
|
||||
const kind = value[0];
|
||||
if (kind === "message") dispatch(String(value[1]), String(value[1]), String(value[2]));
|
||||
else if (kind === "pmessage") dispatch(String(value[1]), String(value[2]), String(value[3]));
|
||||
},
|
||||
() => {
|
||||
for (const pattern of redisSubscribed) {
|
||||
subConn.send(encodeCommand([isPattern(pattern) ? "PSUBSCRIBE" : "SUBSCRIBE", pattern]));
|
||||
}
|
||||
},
|
||||
);
|
||||
const pubConn = connect(cfg, resolved);
|
||||
|
||||
return {
|
||||
publish(topic, message) {
|
||||
@@ -175,6 +250,13 @@ export function redisDriver(url?: string): PubSubDriver & { close(): void } {
|
||||
};
|
||||
}
|
||||
|
||||
function positiveInteger(value: number, label: string): number {
|
||||
if (!Number.isInteger(value) || value < 1) {
|
||||
throw new RangeError(`${label} must be a positive integer`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function getEnv(key: string): string | undefined {
|
||||
return (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.[
|
||||
key
|
||||
|
||||
Reference in New Issue
Block a user