172 lines
7.2 KiB
TypeScript
172 lines
7.2 KiB
TypeScript
import type { SharedStoreAdapter, SharedStoreScanOptions, SharedStoreSetOptions } from "./adapters/adapter.js";
|
|
import { MemoryAdapter } from "./adapters/memory.js";
|
|
import { RedisAdapter, type RedisAdapterOptions } from "./adapters/redis.js";
|
|
|
|
/**
|
|
* Minimal logger shape consumed by the factory. Matches the pino-based
|
|
* `HiveGridLogger` shape so `@hivegrid/logger` can be passed directly,
|
|
* without forcing this package to depend on it at runtime.
|
|
*/
|
|
export interface SharedStoreLogger {
|
|
warn(obj: Record<string, unknown> | string, msg?: string): void;
|
|
info?(obj: Record<string, unknown> | string, msg?: string): void;
|
|
}
|
|
|
|
export interface CreateSharedStoreOptions {
|
|
/**
|
|
* Namespace prefix. Every key passes through `shared-store:<namespace>:<key>`
|
|
* so different consumers cannot collide. Required.
|
|
*/
|
|
namespace: string;
|
|
/** Default TTL in seconds applied to `set` calls that omit `ttlSeconds`. */
|
|
ttlDefault?: number;
|
|
/**
|
|
* Redis connection URL. When omitted, the factory checks
|
|
* `process.env.REDIS_URL`. If still undefined, the in-memory adapter
|
|
* is used and a warning is emitted.
|
|
*/
|
|
redisUrl?: string;
|
|
/** Override the Redis logical DB index (default 1). */
|
|
redisDbIndex?: number;
|
|
/** Optional logger; defaults to a no-op so the package stays leaf-free. */
|
|
logger?: SharedStoreLogger;
|
|
/** Test seam: inject a pre-built adapter, bypassing auto-selection. */
|
|
adapter?: SharedStoreAdapter;
|
|
/** Advanced ioredis-options forwarded to the RedisAdapter. */
|
|
redisAdapterOptions?: Omit<RedisAdapterOptions, "redisUrl" | "db">;
|
|
}
|
|
|
|
/**
|
|
* Bound, namespaced facade over a `SharedStoreAdapter`. Helpers receive a
|
|
* `SharedStore` (not the raw adapter) so prefix-rules are enforced in one
|
|
* place and key-injection via `*` / `:` is rejected up front.
|
|
*/
|
|
export interface SharedStore {
|
|
readonly namespace: string;
|
|
readonly ttlDefault: number | undefined;
|
|
readonly adapter: SharedStoreAdapter;
|
|
key(suffix: string): string;
|
|
get(suffix: string): Promise<string | null>;
|
|
set(suffix: string, value: string, opts?: SharedStoreSetOptions): Promise<boolean>;
|
|
del(suffix: string): Promise<number>;
|
|
incr(suffix: string, by?: number): Promise<number>;
|
|
expire(suffix: string, ttlSeconds: number): Promise<boolean>;
|
|
mget(suffixes: string[]): Promise<(string | null)[]>;
|
|
scan(pattern: string, opts?: SharedStoreScanOptions): AsyncIterable<string>;
|
|
publish(channel: string, message: string): Promise<number>;
|
|
subscribe(channel: string, handler: (message: string) => void | Promise<void>): Promise<() => Promise<void>>;
|
|
zAdd(suffix: string, score: number, member: string): Promise<number>;
|
|
zRemRangeByScore(suffix: string, min: number, max: number): Promise<number>;
|
|
zCard(suffix: string): Promise<number>;
|
|
eval(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
/**
|
|
* Register a handler that fires after the backing store reconnects.
|
|
* No-op on the in-process memory adapter. See
|
|
* `SharedStoreAdapter.onReconnect` for semantics.
|
|
*/
|
|
onReconnect(handler: () => void | Promise<void>): () => void;
|
|
close(): Promise<void>;
|
|
}
|
|
|
|
const NAMESPACE_PREFIX = "shared-store";
|
|
const INVALID_KEY_CHARS = /[*?[\]]/;
|
|
let memoryWarningEmitted = false;
|
|
|
|
/**
|
|
* Build a `SharedStore` instance. Picks the adapter automatically based
|
|
* on `REDIS_URL` unless `adapter` is supplied (used by tests). Emits a
|
|
* single warning (per process) when running in memory mode so the
|
|
* runtime is auditable.
|
|
*/
|
|
export function createSharedStore(options: CreateSharedStoreOptions): SharedStore {
|
|
validateNamespace(options.namespace);
|
|
if (options.ttlDefault !== undefined && options.ttlDefault <= 0) {
|
|
throw new Error("createSharedStore: ttlDefault must be a positive number of seconds");
|
|
}
|
|
const adapter = options.adapter ?? buildAdapter(options);
|
|
const prefix = `${NAMESPACE_PREFIX}:${options.namespace}:`;
|
|
const channelPrefix = `${NAMESPACE_PREFIX}:${options.namespace}:ch:`;
|
|
|
|
const ensureSuffix = (suffix: string): string => {
|
|
if (suffix.length === 0) {
|
|
throw new Error("shared-store key suffix must not be empty");
|
|
}
|
|
if (INVALID_KEY_CHARS.test(suffix)) {
|
|
throw new Error(`shared-store key suffix contains forbidden pattern characters: ${suffix}`);
|
|
}
|
|
return `${prefix}${suffix}`;
|
|
};
|
|
|
|
const ensureChannel = (channel: string): string => {
|
|
if (channel.length === 0) {
|
|
throw new Error("shared-store channel must not be empty");
|
|
}
|
|
if (INVALID_KEY_CHARS.test(channel)) {
|
|
throw new Error(`shared-store channel contains forbidden characters: ${channel}`);
|
|
}
|
|
return `${channelPrefix}${channel}`;
|
|
};
|
|
|
|
const applyDefaultTtl = (opts: SharedStoreSetOptions | undefined): SharedStoreSetOptions | undefined => {
|
|
if (options.ttlDefault === undefined) return opts;
|
|
if (!opts) return { ttlSeconds: options.ttlDefault };
|
|
if (typeof opts.ttlSeconds === "number") return opts;
|
|
return { ...opts, ttlSeconds: options.ttlDefault };
|
|
};
|
|
|
|
return {
|
|
namespace: options.namespace,
|
|
ttlDefault: options.ttlDefault,
|
|
adapter,
|
|
key: ensureSuffix,
|
|
get: async (suffix) => adapter.get(ensureSuffix(suffix)),
|
|
set: async (suffix, value, opts) => adapter.set(ensureSuffix(suffix), value, applyDefaultTtl(opts)),
|
|
del: async (suffix) => adapter.del(ensureSuffix(suffix)),
|
|
incr: async (suffix, by) => adapter.incr(ensureSuffix(suffix), by),
|
|
expire: async (suffix, ttlSeconds) => adapter.expire(ensureSuffix(suffix), ttlSeconds),
|
|
mget: async (suffixes) => adapter.mget(suffixes.map(ensureSuffix)),
|
|
scan: (pattern, scanOpts) => adapter.scan(`${prefix}${pattern}`, scanOpts),
|
|
publish: async (channel, message) => adapter.publish(ensureChannel(channel), message),
|
|
subscribe: async (channel, handler) => adapter.subscribe(ensureChannel(channel), handler),
|
|
zAdd: async (suffix, score, member) => adapter.zAdd(ensureSuffix(suffix), score, member),
|
|
zRemRangeByScore: async (suffix, min, max) => adapter.zRemRangeByScore(ensureSuffix(suffix), min, max),
|
|
zCard: async (suffix) => adapter.zCard(ensureSuffix(suffix)),
|
|
eval: async (script, keys, args) => adapter.eval(script, keys.map(ensureSuffix), args),
|
|
onReconnect: (handler) => adapter.onReconnect(handler),
|
|
close: async () => adapter.close(),
|
|
};
|
|
}
|
|
|
|
function validateNamespace(namespace: string): void {
|
|
if (!namespace || namespace.length === 0) {
|
|
throw new Error("createSharedStore: namespace is required");
|
|
}
|
|
if (!/^[a-z0-9][a-z0-9_-]*$/i.test(namespace)) {
|
|
throw new Error(`createSharedStore: namespace must match /^[a-z0-9][a-z0-9_-]*$/i, got "${namespace}"`);
|
|
}
|
|
}
|
|
|
|
function buildAdapter(options: CreateSharedStoreOptions): SharedStoreAdapter {
|
|
const redisUrl = options.redisUrl ?? process.env.REDIS_URL;
|
|
if (redisUrl) {
|
|
return new RedisAdapter({
|
|
...options.redisAdapterOptions,
|
|
redisUrl,
|
|
db: options.redisDbIndex ?? 1,
|
|
});
|
|
}
|
|
if (!memoryWarningEmitted) {
|
|
memoryWarningEmitted = true;
|
|
options.logger?.warn?.(
|
|
{ component: "shared-store", namespace: options.namespace },
|
|
"shared-store: running in memory mode, multi-replica unsafe",
|
|
);
|
|
}
|
|
return new MemoryAdapter();
|
|
}
|
|
|
|
/** Test-only hook: reset the one-shot warning latch. */
|
|
export function __resetMemoryWarningForTests(): void {
|
|
memoryWarningEmitted = false;
|
|
}
|