/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/queue/sharded/redis * * Small helpers over Bun's native Redis client for the sharded frontier: * connection factory, cached Lua scripts (`EVALSHA` with `EVAL` fallback) and * key naming. All keys of one frontier share the `{name}` hash tag so the * multi-key Lua scripts also work on Redis Cluster (one slot per frontier). */ import { RedisClient } from "bun"; /** Default Redis endpoint. */ export const DEFAULT_REDIS_URL = "redis://127.0.0.1:6379"; /** Resolve the Redis URL: explicit value, `BXC_REDIS_URL`, `REDIS_URL`, default. */ export function resolveRedisUrl(url?: string): string { return url || Bun.env.BXC_REDIS_URL || Bun.env.REDIS_URL || DEFAULT_REDIS_URL; } /** Open a client (lazy connection; commands queue until connected). */ export function openRedis(url?: string): RedisClient { return new RedisClient(resolveRedisUrl(url), { connectionTimeout: 5_000, autoReconnect: true, enableAutoPipelining: true, }); } /** `true` when a `PING` succeeds within `timeoutMs`. */ export async function isRedisReachable(url?: string, timeoutMs = 1_000): Promise { const client = new RedisClient(resolveRedisUrl(url), { connectionTimeout: timeoutMs, autoReconnect: false, maxRetries: 0, }); try { const pong = await Promise.race([ client.send("PING", []), Bun.sleep(timeoutMs).then(() => null), ]); return pong === "PONG"; } catch { return false; } finally { client.close(); } } /** Key prefix of a frontier: `bxc:{name}` (`{name}` is a Redis Cluster hash tag). */ export function frontierPrefix(name: string): string { if (!/^[A-Za-z0-9._:-]{1,128}$/.test(name)) { throw new Error(`Invalid frontier name "${name}": use 1-128 characters from [A-Za-z0-9._:-]`); } return `bxc:{${name}}`; } /** A Lua script executed by SHA with transparent (re)loading. */ export class RedisScript { readonly source: string; readonly sha: string; constructor(source: string) { this.source = source; this.sha = new Bun.CryptoHasher("sha1").update(source).digest("hex"); } async run(client: RedisClient, keys: readonly string[], args: ReadonlyArray): Promise { const argv = [String(keys.length), ...keys, ...args.map(String)]; try { return await client.send("EVALSHA", [this.sha, ...argv]); } catch (err) { if (!String((err as Error)?.message ?? err).includes("NOSCRIPT")) throw err; return client.send("EVAL", [this.source, ...argv]); } } } /** `true` when a Redis error is `BUSYGROUP` (consumer group already exists). */ export function isBusyGroupError(err: unknown): boolean { return String((err as Error)?.message ?? err).includes("BUSYGROUP"); } /** Numeric reply (Redis integers may arrive as numbers or strings). */ export function toInt(value: unknown, fallback = 0): number { const n = typeof value === "number" ? value : Number.parseInt(String(value ?? ""), 10); return Number.isFinite(n) ? n : fallback; }