Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+83
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { MemoryAdapter } from "./memory.js";
|
||||
|
||||
describe("MemoryAdapter — onReconnect noop disposer", () => {
|
||||
test("returns a callable noop disposer that never invokes the handler", async () => {
|
||||
const adapter = new MemoryAdapter();
|
||||
let called = 0;
|
||||
const dispose = adapter.onReconnect(() => {
|
||||
called += 1;
|
||||
});
|
||||
// The memory adapter has no connection, so the handler must never fire,
|
||||
// and invoking the disposer must be a safe noop.
|
||||
expect(typeof dispose).toBe("function");
|
||||
expect(() => dispose()).not.toThrow();
|
||||
expect(called).toBe(0);
|
||||
await adapter.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("MemoryAdapter — expire edge cases", () => {
|
||||
test("expire on a lazily-expired key returns false and evicts it", async () => {
|
||||
let now = 0;
|
||||
const adapter = new MemoryAdapter({ now: () => now });
|
||||
await adapter.set("k", "v", { ttlSeconds: 1 });
|
||||
now = 2_000; // the key is past its TTL but not yet read (lazy expiry)
|
||||
// The entry still exists in the map but is expired → expire() must report
|
||||
// false and clean up rather than re-arming a dead key.
|
||||
expect(await adapter.expire("k", 60)).toBe(false);
|
||||
expect(await adapter.get("k")).toBeNull();
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
test("expire with a non-positive ttl clears the expiry so the key persists", async () => {
|
||||
let now = 0;
|
||||
const adapter = new MemoryAdapter({ now: () => now });
|
||||
await adapter.set("k", "v", { ttlSeconds: 1 });
|
||||
// ttlSeconds <= 0 removes the expiry (mirrors PERSIST-like behaviour).
|
||||
expect(await adapter.expire("k", 0)).toBe(true);
|
||||
now = 10_000; // would have expired under the original 1s TTL
|
||||
expect(await adapter.get("k")).toBe("v");
|
||||
await adapter.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("MemoryAdapter — scan glob translation", () => {
|
||||
test("'?' matches exactly one character", async () => {
|
||||
const adapter = new MemoryAdapter();
|
||||
await adapter.set("user:1", "a");
|
||||
await adapter.set("user:2", "b");
|
||||
await adapter.set("user:42", "c"); // two chars after the colon — must not match "user:?"
|
||||
const collected: string[] = [];
|
||||
for await (const key of adapter.scan("user:?")) {
|
||||
collected.push(key);
|
||||
}
|
||||
expect(collected.sort()).toEqual(["user:1", "user:2"]);
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
test("regex-special characters in the pattern are matched literally", async () => {
|
||||
const adapter = new MemoryAdapter();
|
||||
await adapter.set("a.b", "match");
|
||||
await adapter.set("axb", "no-match"); // would match if '.' were a wildcard
|
||||
const collected: string[] = [];
|
||||
for await (const key of adapter.scan("a.b")) {
|
||||
collected.push(key);
|
||||
}
|
||||
expect(collected).toEqual(["a.b"]);
|
||||
await adapter.close();
|
||||
});
|
||||
|
||||
test("a pattern combining a wildcard and an escaped char stays anchored", async () => {
|
||||
const adapter = new MemoryAdapter();
|
||||
await adapter.set("evt(1)", "a");
|
||||
await adapter.set("evt(2)", "b");
|
||||
await adapter.set("evtX1Y", "c"); // parens are literal, so this must not match
|
||||
const collected: string[] = [];
|
||||
for await (const key of adapter.scan("evt(*)")) {
|
||||
collected.push(key);
|
||||
}
|
||||
expect(collected.sort()).toEqual(["evt(1)", "evt(2)"]);
|
||||
await adapter.close();
|
||||
});
|
||||
});
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import RedisMock from "ioredis-mock";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { RedisAdapter } from "./redis.js";
|
||||
|
||||
type RedisClient = import("ioredis").Redis;
|
||||
|
||||
const adapters: RedisAdapter[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (adapters.length > 0) {
|
||||
const adapter = adapters.pop();
|
||||
if (adapter) {
|
||||
await adapter.close().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Client double whose `quit()` rejects, forcing `safeQuit` to take the
|
||||
* `disconnect()` fallback branch. Records whether disconnect ran.
|
||||
*/
|
||||
class QuitFailingClientDouble extends EventEmitter {
|
||||
status = "ready";
|
||||
quitCalled = false;
|
||||
disconnectCalled = false;
|
||||
|
||||
async quit(): Promise<never> {
|
||||
this.quitCalled = true;
|
||||
throw new Error("quit failed: connection already gone");
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
this.disconnectCalled = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Client double that supports SCRIPT LOAD / EVALSHA / EVAL so the
|
||||
* adapter's SHA-cache and NOSCRIPT-recovery branches can be exercised
|
||||
* (ioredis-mock rejects SCRIPT LOAD and so never reaches EVALSHA).
|
||||
*/
|
||||
class EvalClientDouble extends EventEmitter {
|
||||
status = "ready";
|
||||
loadCount = 0;
|
||||
evalshaCount = 0;
|
||||
evalCount = 0;
|
||||
|
||||
constructor(private readonly behaviour: { noscriptOnce?: boolean; evalshaError?: string } = {}) {
|
||||
super();
|
||||
}
|
||||
|
||||
async script(_subcommand: string, body: string): Promise<string> {
|
||||
this.loadCount += 1;
|
||||
return `sha:${body.length}`;
|
||||
}
|
||||
|
||||
// Called positionally by the adapter (sha, numKeys, ...keys, ...args); the
|
||||
// double ignores the arguments and is reached via the `RedisClient` cast.
|
||||
async evalsha(): Promise<string> {
|
||||
this.evalshaCount += 1;
|
||||
if (this.behaviour.evalshaError) {
|
||||
throw new Error(this.behaviour.evalshaError);
|
||||
}
|
||||
if (this.behaviour.noscriptOnce && this.evalshaCount === 1) {
|
||||
throw new Error("NOSCRIPT No matching script. Please use EVAL.");
|
||||
}
|
||||
return "via-evalsha";
|
||||
}
|
||||
|
||||
async eval(): Promise<string> {
|
||||
this.evalCount += 1;
|
||||
return "via-eval";
|
||||
}
|
||||
|
||||
async quit(): Promise<"OK"> {
|
||||
return "OK";
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
/* noop */
|
||||
}
|
||||
}
|
||||
|
||||
function buildEvalAdapter(primary: EvalClientDouble): RedisAdapter {
|
||||
const adapter = new RedisAdapter({
|
||||
clientFactory: (role) => (role === "primary" ? primary : new EvalClientDouble()) as unknown as RedisClient,
|
||||
});
|
||||
adapters.push(adapter);
|
||||
return adapter;
|
||||
}
|
||||
|
||||
async function waitForFanout(): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
describe("RedisAdapter — default client construction (no url)", () => {
|
||||
test("builds three lazy clients without a url and closes cleanly", async () => {
|
||||
// No clientFactory, no redisUrl and no db exercises buildClient's
|
||||
// `new Redis(baseOptions)` plus the default db/timeout branches.
|
||||
// lazyConnect keeps it from dialing out, so close() is fast and clean.
|
||||
const adapter = new RedisAdapter();
|
||||
adapters.push(adapter);
|
||||
await expect(adapter.close()).resolves.toBeUndefined();
|
||||
// Closing twice is idempotent.
|
||||
await expect(adapter.close()).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("RedisAdapter — scan default COUNT", () => {
|
||||
test("iterates matching keys when no count hint is supplied", async () => {
|
||||
const adapter = new RedisAdapter({
|
||||
clientFactory: () => new RedisMock() as unknown as RedisClient,
|
||||
});
|
||||
adapters.push(adapter);
|
||||
await adapter.set("u:1", "a");
|
||||
await adapter.set("u:2", "b");
|
||||
await adapter.set("other:1", "c");
|
||||
|
||||
const seen: string[] = [];
|
||||
// No opts → buildClient's `opts.count ?? 100` default branch.
|
||||
for await (const key of adapter.scan("u:*")) {
|
||||
seen.push(key);
|
||||
}
|
||||
expect(seen.sort()).toEqual(["u:1", "u:2"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("RedisAdapter — subscribe disposer idempotency", () => {
|
||||
test("calling the unsubscribe disposer twice is a safe noop", async () => {
|
||||
const adapter = new RedisAdapter({
|
||||
clientFactory: () => new RedisMock() as unknown as RedisClient,
|
||||
});
|
||||
adapters.push(adapter);
|
||||
|
||||
const dispose = await adapter.subscribe("ch", () => undefined);
|
||||
await dispose();
|
||||
// Second dispose finds no handler set for the channel and returns early.
|
||||
await expect(dispose()).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("RedisAdapter — eval SHA caching", () => {
|
||||
test("loads the script once, then reuses the cached SHA via EVALSHA", async () => {
|
||||
const primary = new EvalClientDouble();
|
||||
const adapter = buildEvalAdapter(primary);
|
||||
|
||||
expect(await adapter.eval("return 1", ["k"], ["a"])).toBe("via-evalsha");
|
||||
expect(await adapter.eval("return 1", ["k"], ["b"])).toBe("via-evalsha");
|
||||
|
||||
// SCRIPT LOAD ran once; the second call hit the SHA cache.
|
||||
expect(primary.loadCount).toBe(1);
|
||||
expect(primary.evalshaCount).toBe(2);
|
||||
expect(primary.evalCount).toBe(0);
|
||||
});
|
||||
|
||||
test("recovers from NOSCRIPT by dropping the cache and falling back to EVAL", async () => {
|
||||
const primary = new EvalClientDouble({ noscriptOnce: true });
|
||||
const adapter = buildEvalAdapter(primary);
|
||||
|
||||
// First call: SCRIPT LOAD ok, EVALSHA throws NOSCRIPT → cache cleared, raw EVAL.
|
||||
expect(await adapter.eval("return 2", ["k"], [])).toBe("via-eval");
|
||||
expect(primary.evalshaCount).toBe(1);
|
||||
expect(primary.evalCount).toBe(1);
|
||||
|
||||
// Cache was cleared, so the next call must reload the script.
|
||||
expect(await adapter.eval("return 2", ["k"], [])).toBe("via-evalsha");
|
||||
expect(primary.loadCount).toBe(2);
|
||||
});
|
||||
|
||||
test("rethrows non-NOSCRIPT errors from EVALSHA", async () => {
|
||||
const primary = new EvalClientDouble({ evalshaError: "ERR something unexpected" });
|
||||
const adapter = buildEvalAdapter(primary);
|
||||
|
||||
await expect(adapter.eval("return 3", [], [])).rejects.toThrow(/something unexpected/);
|
||||
expect(primary.evalCount).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("RedisAdapter — onReconnect disposer", () => {
|
||||
test("the returned disposer unregisters only its own handler", async () => {
|
||||
const primary = new EvalClientDouble();
|
||||
const adapter = buildEvalAdapter(primary);
|
||||
|
||||
let removed = 0;
|
||||
let kept = 0;
|
||||
const off = adapter.onReconnect(() => {
|
||||
removed += 1;
|
||||
});
|
||||
adapter.onReconnect(() => {
|
||||
kept += 1;
|
||||
});
|
||||
off();
|
||||
|
||||
// The client is already "ready", so the next emitted "ready" fans out.
|
||||
primary.emit("ready");
|
||||
await waitForFanout();
|
||||
|
||||
expect(removed).toBe(0);
|
||||
expect(kept).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("RedisAdapter — safeQuit fallback", () => {
|
||||
test("falls back to disconnect() when quit() rejects on every client", async () => {
|
||||
const doubles: QuitFailingClientDouble[] = [];
|
||||
const adapter = new RedisAdapter({
|
||||
clientFactory: () => {
|
||||
const client = new QuitFailingClientDouble();
|
||||
doubles.push(client);
|
||||
return client as unknown as RedisClient;
|
||||
},
|
||||
});
|
||||
|
||||
await adapter.close();
|
||||
|
||||
// One client per role: primary, subscriber, publisher.
|
||||
expect(doubles).toHaveLength(3);
|
||||
for (const client of doubles) {
|
||||
expect(client.quitCalled).toBe(true);
|
||||
expect(client.disconnectCalled).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { RedisAdapter } from "./adapters/redis.js";
|
||||
import { MemoryAdapter } from "./adapters/memory.js";
|
||||
import { __resetMemoryWarningForTests, createSharedStore } from "./factory.js";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
__resetMemoryWarningForTests();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("createSharedStore — channel validation edge cases", () => {
|
||||
test("rejects an empty channel on publish", async () => {
|
||||
const store = createSharedStore({ namespace: "demo", adapter: new MemoryAdapter() });
|
||||
await expect(store.publish("", "x")).rejects.toThrow(/channel must not be empty/);
|
||||
await store.close();
|
||||
});
|
||||
|
||||
test("rejects an empty channel on subscribe", async () => {
|
||||
const store = createSharedStore({ namespace: "demo", adapter: new MemoryAdapter() });
|
||||
await expect(store.subscribe("", () => undefined)).rejects.toThrow(/channel must not be empty/);
|
||||
await store.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("createSharedStore — ttlDefault merge semantics", () => {
|
||||
test("merges the default ttl into an options object that omits ttlSeconds", async () => {
|
||||
let now = 0;
|
||||
const adapter = new MemoryAdapter({ now: () => now });
|
||||
const store = createSharedStore({ namespace: "demo", adapter, ttlDefault: 5 });
|
||||
// opts present (nx) but without ttlSeconds → default ttl must be merged in,
|
||||
// while the nx flag is preserved.
|
||||
expect(await store.set("k", "v", { nx: true })).toBe(true);
|
||||
// nx still blocks a second write because the key is live.
|
||||
expect(await store.set("k", "v2", { nx: true })).toBe(false);
|
||||
// The merged default ttl is honoured: the key expires after 5s.
|
||||
now = 6_000;
|
||||
expect(await store.get("k")).toBeNull();
|
||||
await store.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("createSharedStore — auto adapter selection builds a RedisAdapter", () => {
|
||||
test("uses RedisAdapter when redisUrl is supplied (no real connection on lazyConnect)", async () => {
|
||||
const store = createSharedStore({
|
||||
namespace: "demo",
|
||||
redisUrl: "redis://127.0.0.1:6390",
|
||||
redisDbIndex: 2,
|
||||
});
|
||||
expect(store.adapter).toBeInstanceOf(RedisAdapter);
|
||||
await store.close();
|
||||
});
|
||||
|
||||
test("reads redisUrl from process.env.REDIS_URL when not passed explicitly", async () => {
|
||||
vi.stubEnv("REDIS_URL", "redis://127.0.0.1:6391");
|
||||
const store = createSharedStore({ namespace: "demo" });
|
||||
expect(store.adapter).toBeInstanceOf(RedisAdapter);
|
||||
await store.close();
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { RedisAdapter, type RedisAdapterOptions } from "./adapters/redis.js";
|
||||
|
||||
/**
|
||||
* Minimal logger shape consumed by the factory. Matches the pino-based
|
||||
* `ToolctrlLogger` shape so `@toolctrl/logger` can be passed directly,
|
||||
* `HiveGridLogger` shape so `@hivegrid/logger` can be passed directly,
|
||||
* without forcing this package to depend on it at runtime.
|
||||
*/
|
||||
export interface SharedStoreLogger {
|
||||
|
||||
@@ -42,7 +42,7 @@ const defaultJsonSerializer = <T>(): CacheSerializer<T> => ({
|
||||
/**
|
||||
* JSON-cached values keyed under `cache:<prefix>:<key>`. The cache is
|
||||
* paired with a pub/sub channel so peer replicas can be notified when
|
||||
* an entry must be invalidated (e.g. after a Stripe webhook or admin
|
||||
* an entry must be invalidated (e.g. after a Mollie webhook or admin
|
||||
* edit). Cache misses cost one Redis round-trip; invalidation is a
|
||||
* single PUBLISH.
|
||||
*/
|
||||
|
||||
+4
-4
@@ -6,7 +6,7 @@ import { createIdempotencyStore } from "./idempotency.js";
|
||||
function build(opts: { ttlSeconds?: number; now?: () => number } = {}) {
|
||||
const adapter = new MemoryAdapter({ now: opts.now });
|
||||
const store = createSharedStore({ namespace: "idemp", adapter });
|
||||
const idempotency = createIdempotencyStore({ store, prefix: "stripe", ttlSeconds: opts.ttlSeconds ?? 60 });
|
||||
const idempotency = createIdempotencyStore({ store, prefix: "mollie", ttlSeconds: opts.ttlSeconds ?? 60 });
|
||||
return { store, idempotency };
|
||||
}
|
||||
|
||||
@@ -65,10 +65,10 @@ describe("createIdempotencyStore", () => {
|
||||
test("corrupt completed payload is evicted on read", async () => {
|
||||
const adapter = new MemoryAdapter();
|
||||
const store = createSharedStore({ namespace: "idemp", adapter });
|
||||
const idempotency = createIdempotencyStore({ store, prefix: "stripe", ttlSeconds: 60 });
|
||||
await store.set("idempotency:stripe:k", "not-json");
|
||||
const idempotency = createIdempotencyStore({ store, prefix: "mollie", ttlSeconds: 60 });
|
||||
await store.set("idempotency:mollie:k", "not-json");
|
||||
expect(await idempotency.get("k")).toBeNull();
|
||||
expect(await store.get("idempotency:stripe:k")).toBeNull();
|
||||
expect(await store.get("idempotency:mollie:k")).toBeNull();
|
||||
await store.close();
|
||||
});
|
||||
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { MemoryAdapter } from "../adapters/memory.js";
|
||||
import { createSharedStore, type SharedStore } from "../factory.js";
|
||||
import { createFixedWindowRateLimiter } from "./rate-limit-fixed.js";
|
||||
|
||||
/**
|
||||
* Build a SharedStore whose `adapter.eval` is replaced with a stub that
|
||||
* returns a fixed value, so the consume() result-parsing branches can be
|
||||
* driven directly (undefined result, zero TTL, etc.).
|
||||
*/
|
||||
function buildStoreWithEval(evalResult: unknown): SharedStore {
|
||||
const memoryAdapter = new MemoryAdapter();
|
||||
const proxyAdapter = new Proxy(memoryAdapter, {
|
||||
get(target, prop, receiver) {
|
||||
if (prop === "eval") {
|
||||
return async () => evalResult;
|
||||
}
|
||||
const value = Reflect.get(target, prop, receiver);
|
||||
return typeof value === "function" ? value.bind(target) : value;
|
||||
},
|
||||
});
|
||||
return createSharedStore({ namespace: "rl-fixed-edge", adapter: proxyAdapter });
|
||||
}
|
||||
|
||||
describe("createFixedWindowRateLimiter — result parsing edge cases", () => {
|
||||
test("treats an undefined eval result as a fresh window (current 0)", async () => {
|
||||
const store = buildStoreWithEval(undefined);
|
||||
const limiter = createFixedWindowRateLimiter({ store, prefix: "ip", windowSeconds: 30, max: 5 });
|
||||
const decision = await limiter.consume("k");
|
||||
expect(decision.allowed).toBe(true);
|
||||
// current defaults to 0 → all 5 actions remain.
|
||||
expect(decision.remaining).toBe(5);
|
||||
// ttl defaults to windowSeconds when the eval result is missing.
|
||||
const delta = decision.resetAt.getTime() - Date.now();
|
||||
expect(delta).toBeGreaterThan(20_000);
|
||||
expect(delta).toBeLessThanOrEqual(30_000);
|
||||
await store.close();
|
||||
});
|
||||
|
||||
test("falls back to windowSeconds when the reported ttl is non-positive", async () => {
|
||||
// Redis returns a TTL of -1/-2 for keys without an expiry or that vanished
|
||||
// between INCR and TTL; the helper must not produce a resetAt in the past.
|
||||
const store = buildStoreWithEval([3, 0]);
|
||||
const limiter = createFixedWindowRateLimiter({ store, prefix: "ip", windowSeconds: 30, max: 5 });
|
||||
const decision = await limiter.consume("k");
|
||||
expect(decision.allowed).toBe(true);
|
||||
expect(decision.remaining).toBe(2);
|
||||
const delta = decision.resetAt.getTime() - Date.now();
|
||||
expect(delta).toBeGreaterThan(20_000);
|
||||
expect(delta).toBeLessThanOrEqual(30_000);
|
||||
await store.close();
|
||||
});
|
||||
|
||||
test("uses a positive reported ttl verbatim and blocks once over the cap", async () => {
|
||||
const store = buildStoreWithEval([6, 10]);
|
||||
const limiter = createFixedWindowRateLimiter({ store, prefix: "ip", windowSeconds: 30, max: 5 });
|
||||
const decision = await limiter.consume("k");
|
||||
expect(decision.allowed).toBe(false);
|
||||
expect(decision.remaining).toBe(0);
|
||||
const delta = decision.resetAt.getTime() - Date.now();
|
||||
// ttl of 10s is honoured instead of the 30s window.
|
||||
expect(delta).toBeGreaterThan(5_000);
|
||||
expect(delta).toBeLessThanOrEqual(10_000);
|
||||
await store.close();
|
||||
});
|
||||
});
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { MemoryAdapter } from "../adapters/memory.js";
|
||||
import { createSharedStore, type SharedStore } from "../factory.js";
|
||||
import { createSlidingWindowRateLimiter } from "./rate-limit-sliding.js";
|
||||
|
||||
/**
|
||||
* Build a SharedStore whose `adapter.eval` returns a fixed value so the
|
||||
* oldest-entry parsing branches in consume() can be exercised directly.
|
||||
* The real Redis script surfaces the oldest score as a string; the memory
|
||||
* adapter returns "" and falls back to `now`.
|
||||
*/
|
||||
function buildStoreWithEval(evalResult: unknown): SharedStore {
|
||||
const memoryAdapter = new MemoryAdapter();
|
||||
const proxyAdapter = new Proxy(memoryAdapter, {
|
||||
get(target, prop, receiver) {
|
||||
if (prop === "eval") {
|
||||
return async () => evalResult;
|
||||
}
|
||||
const value = Reflect.get(target, prop, receiver);
|
||||
return typeof value === "function" ? value.bind(target) : value;
|
||||
},
|
||||
});
|
||||
return createSharedStore({ namespace: "rl-sliding-edge", adapter: proxyAdapter });
|
||||
}
|
||||
|
||||
describe("createSlidingWindowRateLimiter — oldest-entry parsing", () => {
|
||||
test("parses a finite oldest score into a Date", async () => {
|
||||
const store = buildStoreWithEval([2, "1500"]);
|
||||
const limiter = createSlidingWindowRateLimiter({
|
||||
store,
|
||||
prefix: "ip",
|
||||
windowSeconds: 60,
|
||||
max: 5,
|
||||
now: () => 9_000,
|
||||
});
|
||||
const decision = await limiter.consume("k");
|
||||
expect(decision.allowed).toBe(true);
|
||||
expect(decision.remaining).toBe(3);
|
||||
expect(decision.oldestAt).toEqual(new Date(1500));
|
||||
await store.close();
|
||||
});
|
||||
|
||||
test("falls back to the current timestamp when the oldest score is non-numeric", async () => {
|
||||
const store = buildStoreWithEval([2, "not-a-timestamp"]);
|
||||
const limiter = createSlidingWindowRateLimiter({
|
||||
store,
|
||||
prefix: "ip",
|
||||
windowSeconds: 60,
|
||||
max: 5,
|
||||
now: () => 9_000,
|
||||
});
|
||||
const decision = await limiter.consume("k");
|
||||
// Number("not-a-timestamp") is NaN → not finite → conservative fallback to now.
|
||||
expect(decision.oldestAt).toEqual(new Date(9_000));
|
||||
await store.close();
|
||||
});
|
||||
|
||||
test("treats an undefined eval result as an empty window", async () => {
|
||||
const store = buildStoreWithEval(undefined);
|
||||
const limiter = createSlidingWindowRateLimiter({
|
||||
store,
|
||||
prefix: "ip",
|
||||
windowSeconds: 60,
|
||||
max: 5,
|
||||
now: () => 7_000,
|
||||
});
|
||||
const decision = await limiter.consume("k");
|
||||
expect(decision.allowed).toBe(true);
|
||||
// count defaults to 0 → full quota remains.
|
||||
expect(decision.remaining).toBe(5);
|
||||
// oldestRaw defaults to "" (falsy) → conservative fallback to now.
|
||||
expect(decision.oldestAt).toEqual(new Date(7_000));
|
||||
await store.close();
|
||||
});
|
||||
|
||||
test("blocks once the count exceeds the cap", async () => {
|
||||
const store = buildStoreWithEval([6, "1000"]);
|
||||
const limiter = createSlidingWindowRateLimiter({
|
||||
store,
|
||||
prefix: "ip",
|
||||
windowSeconds: 60,
|
||||
max: 5,
|
||||
now: () => 9_000,
|
||||
});
|
||||
const decision = await limiter.consume("k");
|
||||
expect(decision.allowed).toBe(false);
|
||||
expect(decision.remaining).toBe(0);
|
||||
expect(decision.oldestAt).toEqual(new Date(1000));
|
||||
await store.close();
|
||||
});
|
||||
});
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import { MemoryAdapter } from "../adapters/memory.js";
|
||||
import { createSharedStore } from "../factory.js";
|
||||
import { createTwoTierCache, type TwoTierL1Cache } from "./two-tier-cache.js";
|
||||
|
||||
interface Value {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
async function flushPubSubMicrotasks() {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
describe("createTwoTierCache — subscriber handler error path", () => {
|
||||
test("logs (and swallows) errors thrown by the extra handler", async () => {
|
||||
const adapter = new MemoryAdapter();
|
||||
const storeA = createSharedStore({ namespace: "ns", adapter });
|
||||
const storeB = createSharedStore({ namespace: "ns", adapter });
|
||||
const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn() };
|
||||
|
||||
const a = createTwoTierCache<Value>({ store: storeA, namespace: "subscription", ttlSeconds: 60 });
|
||||
const b = createTwoTierCache<Value>({ store: storeB, namespace: "subscription", ttlSeconds: 60, logger });
|
||||
|
||||
await b.set("t1", { id: "t1", name: "x" });
|
||||
await b.subscribe(() => {
|
||||
throw new Error("extra handler boom");
|
||||
});
|
||||
|
||||
// Peer publishes an invalidation → b's subscriber runs, extra handler throws.
|
||||
await a.invalidate("t1");
|
||||
await flushPubSubMicrotasks();
|
||||
|
||||
// Local L1 of b still purged despite the handler throwing.
|
||||
expect(b.l1.get("t1")).toBeUndefined();
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ component: "two-tier-cache", namespace: "subscription" }),
|
||||
expect.stringMatching(/subscriber handler threw/),
|
||||
);
|
||||
await storeA.close();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Build a SharedStore whose adapter `publish` and/or `del` throw, to drive
|
||||
* the L2 invalidate/delete failure branches in two-tier-cache.
|
||||
*/
|
||||
function buildStoreWithFailingOps(overrides: { publish?: boolean; del?: boolean }) {
|
||||
const memoryAdapter = new MemoryAdapter();
|
||||
const proxyAdapter = new Proxy(memoryAdapter, {
|
||||
get(target, prop, receiver) {
|
||||
if (prop === "publish" && overrides.publish) {
|
||||
return async () => {
|
||||
throw new Error("publish failed");
|
||||
};
|
||||
}
|
||||
if (prop === "del" && overrides.del) {
|
||||
return async () => {
|
||||
throw new Error("del failed");
|
||||
};
|
||||
}
|
||||
const value = Reflect.get(target, prop, receiver);
|
||||
return typeof value === "function" ? value.bind(target) : value;
|
||||
},
|
||||
});
|
||||
return createSharedStore({ namespace: "ns", adapter: proxyAdapter });
|
||||
}
|
||||
|
||||
describe("createTwoTierCache — L2 failure paths", () => {
|
||||
test("logs when the L2 invalidate (publish) throws", async () => {
|
||||
const store = buildStoreWithFailingOps({ publish: true });
|
||||
const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn() };
|
||||
const cache = createTwoTierCache<Value>({ store, namespace: "subscription", ttlSeconds: 60, logger });
|
||||
|
||||
// pubsubEnabled (default) + not localOnly → goes through l2.invalidate, which publishes.
|
||||
await cache.invalidate("t1");
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ component: "two-tier-cache", namespace: "subscription" }),
|
||||
expect.stringMatching(/l2 invalidate failed/),
|
||||
);
|
||||
await store.close();
|
||||
});
|
||||
|
||||
test("logs when the best-effort L2 delete throws on a localOnly invalidate", async () => {
|
||||
const store = buildStoreWithFailingOps({ del: true });
|
||||
const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn() };
|
||||
const cache = createTwoTierCache<Value>({ store, namespace: "subscription", ttlSeconds: 60, logger });
|
||||
|
||||
await cache.invalidate("t1", { localOnly: true });
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ component: "two-tier-cache", namespace: "subscription" }),
|
||||
expect.stringMatching(/l2 delete failed/),
|
||||
);
|
||||
await store.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("createTwoTierCache — pubsub disabled with logger", () => {
|
||||
test("warns that the subscriber is not started and returns a noop disposer", async () => {
|
||||
const adapter = new MemoryAdapter();
|
||||
const store = createSharedStore({ namespace: "ns", adapter });
|
||||
const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn() };
|
||||
const cache = createTwoTierCache<Value>({
|
||||
store,
|
||||
namespace: "subscription",
|
||||
ttlSeconds: 60,
|
||||
pubsubEnabled: false,
|
||||
logger,
|
||||
});
|
||||
|
||||
const dispose = await cache.subscribe();
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ component: "two-tier-cache", namespace: "subscription" }),
|
||||
expect.stringMatching(/pubsub disabled/),
|
||||
);
|
||||
await expect(dispose()).resolves.toBeUndefined();
|
||||
await store.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("createTwoTierCache — reconnect-flush success logging", () => {
|
||||
test("flushes L1 and logs an info line on a successful reconnect", async () => {
|
||||
const memoryAdapter = new MemoryAdapter();
|
||||
const reconnectHandlers = new Set<() => void | Promise<void>>();
|
||||
const proxyAdapter = new Proxy(memoryAdapter, {
|
||||
get(target, prop, receiver) {
|
||||
if (prop === "onReconnect") {
|
||||
return (handler: () => void | Promise<void>) => {
|
||||
reconnectHandlers.add(handler);
|
||||
return () => {
|
||||
reconnectHandlers.delete(handler);
|
||||
};
|
||||
};
|
||||
}
|
||||
const value = Reflect.get(target, prop, receiver);
|
||||
return typeof value === "function" ? value.bind(target) : value;
|
||||
},
|
||||
});
|
||||
const store = createSharedStore({ namespace: "ns", adapter: proxyAdapter });
|
||||
const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn() };
|
||||
const cache = createTwoTierCache<Value>({ store, namespace: "subscription", ttlSeconds: 60, logger });
|
||||
|
||||
const dispose = await cache.subscribe();
|
||||
await cache.set("t1", { id: "t1", name: "x" });
|
||||
expect(cache.l1.get("t1")).toEqual({ id: "t1", name: "x" });
|
||||
|
||||
for (const handler of reconnectHandlers) await handler();
|
||||
|
||||
expect(cache.l1.get("t1")).toBeUndefined();
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ component: "two-tier-cache", namespace: "subscription" }),
|
||||
expect.stringMatching(/redis reconnected, L1 flushed/),
|
||||
);
|
||||
expect(logger.error).not.toHaveBeenCalled();
|
||||
|
||||
await dispose();
|
||||
await store.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("createTwoTierCache — reconnect-flush error path", () => {
|
||||
test("logs (and swallows) errors thrown while flushing L1 on reconnect", async () => {
|
||||
const memoryAdapter = new MemoryAdapter();
|
||||
const reconnectHandlers = new Set<() => void | Promise<void>>();
|
||||
const proxyAdapter = new Proxy(memoryAdapter, {
|
||||
get(target, prop, receiver) {
|
||||
if (prop === "onReconnect") {
|
||||
return (handler: () => void | Promise<void>) => {
|
||||
reconnectHandlers.add(handler);
|
||||
return () => {
|
||||
reconnectHandlers.delete(handler);
|
||||
};
|
||||
};
|
||||
}
|
||||
const value = Reflect.get(target, prop, receiver);
|
||||
return typeof value === "function" ? value.bind(target) : value;
|
||||
},
|
||||
});
|
||||
const store = createSharedStore({ namespace: "ns", adapter: proxyAdapter });
|
||||
|
||||
const empty = new Map<string, Value>();
|
||||
const throwingL1: TwoTierL1Cache<Value> = {
|
||||
get: () => undefined,
|
||||
set: () => undefined,
|
||||
delete: () => false,
|
||||
clear: () => {
|
||||
throw new Error("l1 clear boom");
|
||||
},
|
||||
keys: () => empty.keys(),
|
||||
};
|
||||
|
||||
const logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn() };
|
||||
const cache = createTwoTierCache<Value>({
|
||||
store,
|
||||
namespace: "subscription",
|
||||
ttlSeconds: 60,
|
||||
l1Cache: throwingL1,
|
||||
logger,
|
||||
});
|
||||
const dispose = await cache.subscribe();
|
||||
|
||||
// Fire the reconnect event → debounced flush → l1.clear() throws → logged.
|
||||
for (const handler of reconnectHandlers) await handler();
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ component: "two-tier-cache", namespace: "subscription" }),
|
||||
expect.stringMatching(/reconnect-flush handler threw/),
|
||||
);
|
||||
|
||||
await dispose();
|
||||
expect(reconnectHandlers.size).toBe(0);
|
||||
await store.close();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user