266 lines
7.9 KiB
TypeScript
266 lines
7.9 KiB
TypeScript
import { EventEmitter } from "node:events";
|
|
import type { SharedStoreAdapter, SharedStoreScanOptions, SharedStoreSetOptions } from "./adapter.js";
|
|
|
|
interface KvEntry {
|
|
value: string;
|
|
expiresAt: number | null;
|
|
}
|
|
|
|
interface SortedSetMember {
|
|
score: number;
|
|
member: string;
|
|
}
|
|
|
|
/**
|
|
* Registry for `eval` scripts. The memory adapter cannot run real Lua,
|
|
* so it matches the script body against a TypeScript equivalent that
|
|
* mirrors the Redis behavior. New helpers register their script via
|
|
* `MemoryAdapter.registerScript` so the same script string can be sent
|
|
* through `eval` against either backend.
|
|
*/
|
|
export type MemoryScriptHandler = (
|
|
adapter: MemoryAdapter,
|
|
keys: string[],
|
|
args: string[],
|
|
) => Promise<unknown> | unknown;
|
|
|
|
const scriptRegistry = new Map<string, MemoryScriptHandler>();
|
|
|
|
/**
|
|
* In-process implementation of `SharedStoreAdapter` for dev, tests, and
|
|
* single-instance deployments. TTLs are evaluated lazily on read; no
|
|
* background timers are used so tests can exit cleanly.
|
|
*/
|
|
export class MemoryAdapter implements SharedStoreAdapter {
|
|
private readonly kv = new Map<string, KvEntry>();
|
|
private readonly sortedSets = new Map<string, SortedSetMember[]>();
|
|
private readonly emitter = new EventEmitter();
|
|
private readonly clock: () => number;
|
|
private closed = false;
|
|
|
|
constructor(options: { now?: () => number } = {}) {
|
|
this.clock = options.now ?? (() => Date.now());
|
|
this.emitter.setMaxListeners(0);
|
|
}
|
|
|
|
/**
|
|
* Register a TypeScript equivalent of a Redis Lua script so that the
|
|
* same `eval(script, keys, args)` call works against both adapters.
|
|
*/
|
|
static registerScript(script: string, handler: MemoryScriptHandler): void {
|
|
scriptRegistry.set(script, handler);
|
|
}
|
|
|
|
static hasRegisteredScript(script: string): boolean {
|
|
return scriptRegistry.has(script);
|
|
}
|
|
|
|
async get(key: string): Promise<string | null> {
|
|
this.assertOpen();
|
|
const entry = this.kv.get(key);
|
|
if (!entry) {
|
|
return null;
|
|
}
|
|
if (this.isExpired(entry)) {
|
|
this.kv.delete(key);
|
|
return null;
|
|
}
|
|
return entry.value;
|
|
}
|
|
|
|
async set(key: string, value: string, opts: SharedStoreSetOptions = {}): Promise<boolean> {
|
|
this.assertOpen();
|
|
if (opts.nx) {
|
|
const existing = this.kv.get(key);
|
|
if (existing && !this.isExpired(existing)) {
|
|
return false;
|
|
}
|
|
}
|
|
const expiresAt =
|
|
typeof opts.ttlSeconds === "number" && opts.ttlSeconds > 0 ? this.clock() + opts.ttlSeconds * 1000 : null;
|
|
this.kv.set(key, { value, expiresAt });
|
|
return true;
|
|
}
|
|
|
|
async del(key: string): Promise<number> {
|
|
this.assertOpen();
|
|
const existed = this.kv.delete(key);
|
|
const setExisted = this.sortedSets.delete(key);
|
|
return existed || setExisted ? 1 : 0;
|
|
}
|
|
|
|
async incr(key: string, by = 1): Promise<number> {
|
|
this.assertOpen();
|
|
const entry = this.kv.get(key);
|
|
let current = 0;
|
|
let expiresAt: number | null = null;
|
|
if (entry && !this.isExpired(entry)) {
|
|
const parsed = Number.parseInt(entry.value, 10);
|
|
if (Number.isNaN(parsed)) {
|
|
throw new Error(`incr called on non-numeric key: ${key}`);
|
|
}
|
|
current = parsed;
|
|
expiresAt = entry.expiresAt;
|
|
}
|
|
const next = current + by;
|
|
this.kv.set(key, { value: String(next), expiresAt });
|
|
return next;
|
|
}
|
|
|
|
async expire(key: string, ttlSeconds: number): Promise<boolean> {
|
|
this.assertOpen();
|
|
const entry = this.kv.get(key);
|
|
if (!entry || this.isExpired(entry)) {
|
|
if (entry) this.kv.delete(key);
|
|
return false;
|
|
}
|
|
entry.expiresAt = ttlSeconds > 0 ? this.clock() + ttlSeconds * 1000 : null;
|
|
return true;
|
|
}
|
|
|
|
async mget(keys: string[]): Promise<(string | null)[]> {
|
|
this.assertOpen();
|
|
return Promise.all(keys.map((key) => this.get(key)));
|
|
}
|
|
|
|
scan(pattern: string, opts: SharedStoreScanOptions = {}): AsyncIterable<string> {
|
|
this.assertOpen();
|
|
const regex = patternToRegExp(pattern);
|
|
const snapshot: string[] = [];
|
|
for (const [key, entry] of this.kv.entries()) {
|
|
if (!this.isExpired(entry) && regex.test(key)) {
|
|
snapshot.push(key);
|
|
}
|
|
}
|
|
const batchSize = Math.max(1, opts.count ?? 100);
|
|
let index = 0;
|
|
return {
|
|
[Symbol.asyncIterator]: () => ({
|
|
async next() {
|
|
if (index >= snapshot.length) {
|
|
return { value: undefined as unknown as string, done: true };
|
|
}
|
|
const value = snapshot[index];
|
|
index += 1;
|
|
// batchSize is honored implicitly by sequential iteration; the
|
|
// counter exists so callers can reason about it in logs.
|
|
void batchSize;
|
|
return { value, done: false };
|
|
},
|
|
}),
|
|
};
|
|
}
|
|
|
|
async publish(channel: string, message: string): Promise<number> {
|
|
this.assertOpen();
|
|
const listeners = this.emitter.listenerCount(channel);
|
|
this.emitter.emit(channel, message);
|
|
return listeners;
|
|
}
|
|
|
|
async subscribe(channel: string, handler: (message: string) => void | Promise<void>): Promise<() => Promise<void>> {
|
|
this.assertOpen();
|
|
const wrapped = (message: string) => {
|
|
// Defer handler errors to the next tick so other subscribers still run.
|
|
Promise.resolve()
|
|
.then(() => handler(message))
|
|
.catch(() => {
|
|
/* swallowed; consumers handle their own errors */
|
|
});
|
|
};
|
|
this.emitter.on(channel, wrapped);
|
|
return async () => {
|
|
this.emitter.off(channel, wrapped);
|
|
};
|
|
}
|
|
|
|
async zAdd(key: string, score: number, member: string): Promise<number> {
|
|
this.assertOpen();
|
|
const set = this.sortedSets.get(key) ?? [];
|
|
const existingIndex = set.findIndex((entry) => entry.member === member);
|
|
if (existingIndex >= 0) {
|
|
set[existingIndex].score = score;
|
|
this.sortedSets.set(key, set);
|
|
return 0;
|
|
}
|
|
set.push({ score, member });
|
|
this.sortedSets.set(key, set);
|
|
return 1;
|
|
}
|
|
|
|
async zRemRangeByScore(key: string, min: number, max: number): Promise<number> {
|
|
this.assertOpen();
|
|
const set = this.sortedSets.get(key);
|
|
if (!set) return 0;
|
|
const before = set.length;
|
|
const remaining = set.filter((entry) => entry.score < min || entry.score > max);
|
|
if (remaining.length === 0) {
|
|
this.sortedSets.delete(key);
|
|
} else {
|
|
this.sortedSets.set(key, remaining);
|
|
}
|
|
return before - remaining.length;
|
|
}
|
|
|
|
async zCard(key: string): Promise<number> {
|
|
this.assertOpen();
|
|
return this.sortedSets.get(key)?.length ?? 0;
|
|
}
|
|
|
|
async eval(script: string, keys: string[], args: string[]): Promise<unknown> {
|
|
this.assertOpen();
|
|
const handler = scriptRegistry.get(script);
|
|
if (!handler) {
|
|
throw new Error("shared-store memory adapter: unknown eval script (use MemoryAdapter.registerScript)");
|
|
}
|
|
return handler(this, keys, args);
|
|
}
|
|
|
|
onReconnect(_handler: () => void | Promise<void>): () => void {
|
|
// The in-process memory adapter has no connection that can drop, so
|
|
// there is nothing to wire. Returning a noop disposer keeps callers
|
|
// adapter-agnostic.
|
|
void _handler;
|
|
return () => {
|
|
/* no-op */
|
|
};
|
|
}
|
|
|
|
async close(): Promise<void> {
|
|
this.closed = true;
|
|
this.kv.clear();
|
|
this.sortedSets.clear();
|
|
this.emitter.removeAllListeners();
|
|
}
|
|
|
|
private assertOpen(): void {
|
|
if (this.closed) {
|
|
throw new Error("shared-store memory adapter is closed");
|
|
}
|
|
}
|
|
|
|
private isExpired(entry: KvEntry): boolean {
|
|
return entry.expiresAt !== null && entry.expiresAt <= this.clock();
|
|
}
|
|
}
|
|
|
|
function patternToRegExp(pattern: string): RegExp {
|
|
// Translate a tiny subset of glob (`*`, `?`) into a regex, escaping
|
|
// everything else. This mirrors how Redis SCAN MATCH works for the
|
|
// patterns used in this codebase.
|
|
let regex = "^";
|
|
for (const ch of pattern) {
|
|
if (ch === "*") {
|
|
regex += ".*";
|
|
} else if (ch === "?") {
|
|
regex += ".";
|
|
} else if (/[\\^$.+()|[\]{}]/.test(ch)) {
|
|
regex += `\\${ch}`;
|
|
} else {
|
|
regex += ch;
|
|
}
|
|
}
|
|
regex += "$";
|
|
return new RegExp(regex);
|
|
}
|