From cbac5a508824c094506e5a96f2cf657177bc8ce5 Mon Sep 17 00:00:00 2001 From: leejpsd Date: Tue, 24 Nov 2026 10:44:33 +0900 Subject: [PATCH 1/2] fix(incremental): read tag states with one MGET; per-key only on Cluster (#34) The ISR handler read each tag's state with its own GET: one round trip thanks to auto-pipelining, but one command per tag, and a page carries an implicit _N_T_ tag per layout segment. That is six to seven times the command count of other handlers under the same traffic, which is what per-command pricing and command-rate limits see. Per-key reads stay for Redis Cluster, where the un-namespaced tag keys never share a slot: from the start when the adapter is flagged isCluster (new on RedisClientLike) or hashTag is set, otherwise from the first CROSSSLOT reply on, retried in place. ioredis with auto-pipelining refuses client-side with a different message, which is recognised too. --- .changeset/isr-tag-read-mget.md | 5 + README.md | 8 +- docs/api.md | 2 +- docs/architecture.md | 15 +- scripts/bench-isr-tag-read.mjs | 86 +++++++++++ skills/nextjs-redis-cache/SKILL.md | 2 +- src/incremental/handler.ts | 81 +++++++++- src/shared/client/adapter-ioredis.ts | 1 + src/types.ts | 8 + tests/cluster/cluster.test.ts | 57 ++++++- tests/integration/isr-tag-read.test.ts | 119 ++++++++++++++ tests/unit/_mock-client.ts | 1 + tests/unit/isr-tag-read.test.ts | 206 +++++++++++++++++++++++++ 13 files changed, 577 insertions(+), 14 deletions(-) create mode 100644 .changeset/isr-tag-read-mget.md create mode 100644 scripts/bench-isr-tag-read.mjs create mode 100644 tests/integration/isr-tag-read.test.ts create mode 100644 tests/unit/isr-tag-read.test.ts diff --git a/.changeset/isr-tag-read-mget.md b/.changeset/isr-tag-read-mget.md new file mode 100644 index 0000000..f051b49 --- /dev/null +++ b/.changeset/isr-tag-read-mget.md @@ -0,0 +1,5 @@ +--- +"@leejpsd/nextjs-cache-handler": patch +--- + +ISR handler: read all of an entry's tag states with one `MGET` instead of one `GET` per tag (#34). A page with five `_N_T_` layout tags now costs two Redis commands per `get()` instead of six; round trips were already one thanks to auto-pipelining, so this matters for per-command pricing and command-rate limits. On Redis Cluster, where the un-namespaced tag keys never share a slot, the handler keeps reading key by key: from the start when the client is the Cluster adapter (new `isCluster` flag on `RedisClientLike`) or `hashTag: true` is set, otherwise from the first `CROSSSLOT` reply on, retrying that read in place and logging one warning. `tag.expiration.read` is now also emitted by the ISR handler with `meta.strategy` (`"mget"` or `"per-key"`). diff --git a/README.md b/README.md index 8ab7a33..597048d 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,13 @@ Full reference: [`docs/api.md`](./docs/api.md). Cluster support is validated by a dedicated e2e suite against a real 3-master cluster (`npm run test:cluster`, also in CI) — covering the multi-key Lua scripts, per-master SCAN propagation, and both handlers. - Not yet load-tested at production scale. + Not yet load-tested at production scale. The flag also tells the ISR + handler to read tag states key by key: on a single node it reads all of + a page's tags with one `MGET`, but ISR tag keys are deliberately + un-namespaced (so `revalidateTag` survives a deploy) and never share a + slot. Without the flag, a Cluster client still works: the first + `CROSSSLOT` reply switches that handler to per-key reads and logs one + warning. - [ ] **Redis `maxmemory-policy: allkeys-lru` or `noeviction`** — if you need bounded memory, choose `allkeys-lru`. Otherwise `noeviction` keeps tag indices intact. diff --git a/docs/api.md b/docs/api.md index b897ebc..454aeda 100644 --- a/docs/api.md +++ b/docs/api.md @@ -48,7 +48,7 @@ ctx contract are accepted (`ctx.cacheControl.revalidate` / `kind` and | `singleFlight` | `boolean` | `false` | opt-in refresh lock at the SWR boundary (leader/follower metrics; does not suppress refreshes) | | `singleFlightLockTtlSec` | `number` | `10` | lock TTL for `singleFlight` | | `isBuildPhase` | `() => boolean` | `NEXT_PHASE === "phase-production-build"` | build-phase gate override | -| `hashTag` | `boolean` | `false` | wrap namespace in `{}` — **required on Redis Cluster** (multi-key Lua) | +| `hashTag` | `boolean` | `false` | wrap namespace in `{}` — **required on Redis Cluster** (multi-key Lua). Also makes the ISR handler read tag states key by key instead of with one `MGET`, which Cluster refuses across slots; without it a Cluster client is detected on the first `CROSSSLOT` | | `tagPubSub` | `boolean` | `false` | push-based cross-instance tag propagation (plural handler; ~3ms); scan polling remains the safety net; unavailable on Cluster | | `tagReadMode` | `"scan" \| "on-demand"` | `"scan"` | plural handler only. `scan`: `refreshTags()` SCANs the namespace's tag markers once per request (cost grows with total keys in Redis, not with tags: ~20 ms at 20k keys, 65–170 ms at 100k on a local Redis). `on-demand`: no scan; `get()` and `getExpiration()` `MGET` exactly the tags they need (one extra round trip per `get()`). See [#31](https://github.com/leejpsd/nextjs-cache-handler/issues/31) | | `onMetric` | `(event: MetricEvent) => void` | — | telemetry hook; emitter errors are swallowed | diff --git a/docs/architecture.md b/docs/architecture.md index 9cba98c..15a7e75 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -117,8 +117,19 @@ For multi-instance deployments: With `tagReadMode: "on-demand"` (#31) step 2 is a no-op and steps 3 and 4 read the markers for exactly the tags they are given with one `MGET`, merging them into the local mirror, so Redis stays the source of truth and -no request pays for a scan. That is also how the singular handler has always -read tags. +no request pays for a scan. + +The singular (ISR) handler has always read tags on demand too. Since #34 it +reads all of an entry's tag states with one `MGET`, so a page carrying five +`_N_T_` layout tags costs two commands per `get()` (entry + markers), not +six. On Redis Cluster that `MGET` fails with `CROSSSLOT`, because ISR tag +keys are deliberately un-namespaced and so never share a slot; there the +handler reads key by key (one auto-pipelined round trip, one command per +tag). It knows it is on Cluster from the adapter's `isCluster` flag or +`hashTag: true`, and otherwise latches to per-key reads on the first +`CROSSSLOT` reply, retrying that read in place. `scripts/bench-isr-tag-read.mjs` +prints the command count per `get()` for both strategies against a local +Redis. The reference implementation in next-redis-cache-demo measured **6.4 ms** mean propagation across two ECS tasks under sustained load with this diff --git a/scripts/bench-isr-tag-read.mjs b/scripts/bench-isr-tag-read.mjs new file mode 100644 index 0000000..e561d98 --- /dev/null +++ b/scripts/bench-isr-tag-read.mjs @@ -0,0 +1,86 @@ +#!/usr/bin/env node +// #34: how many Redis commands one ISR get() costs, by tag count, for the +// two ways the handler can read tag states: one MGET (default on a single +// node) and one GET per tag (what Redis Cluster needs; also what every +// release before this one did on a single node). +// +// npm run build +// REDIS_URL=redis://127.0.0.1:6390 node scripts/bench-isr-tag-read.mjs [runs] +// +// The target database is FLUSHED. The script refuses to run against a +// non-empty database unless BENCH_FLUSH=1 is set. Needs a single-node Redis. + +import { createClient } from "redis"; + +import { createIncrementalCacheHandler } from "../dist/incremental/index.js"; + +const RUNS = Number(process.argv[2] ?? 200); +const url = process.env.REDIS_URL ?? "redis://127.0.0.1:6390"; + +if (!Number.isFinite(RUNS)) { + console.error("usage: bench-isr-tag-read.mjs [runs]"); + process.exit(1); +} + +const raw = createClient({ url }); +raw.on("error", () => {}); +await raw.connect(); +if ((await raw.dbSize()) > 0 && process.env.BENCH_FLUSH !== "1") { + console.error(`${url} is not empty; set BENCH_FLUSH=1 to flush it.`); + await raw.quit(); + process.exit(1); +} +await raw.flushAll(); + +// Total command count seen by the server, from INFO commandstats. +async function commands() { + const info = await raw.sendCommand(["INFO", "commandstats"]); + let total = 0; + for (const m of String(info).matchAll(/cmdstat_(\w+):calls=(\d+)/g)) { + if (m[1] !== "info") total += Number(m[2]); + } + return total; +} + +// The entry's own tags plus the implicit `_N_T_` tag Next adds for every +// layout segment on the way to the page. +function tagsFor(n) { + return Array.from({ length: n }, (_, i) => + i % 2 === 0 ? `tag-${i}` : `_N_T_/seg-${i}` + ).join(","); +} +const ctx = { kind: "APP_PAGE", cacheControl: { revalidate: 60 } }; +const body = Buffer.from("".padEnd(4096, ".")); + +const modes = [ + { label: "mget (default)", opts: {} }, + // hashTag only changes the entry key's shape; on a single node that is + // harmless, and it makes the handler read tag states key by key. + { label: "per-key (Cluster / <=1.1.0)", opts: { hashTag: true } }, +]; + +const rows = []; +for (const n of [1, 3, 5, 7, 10]) { + const row = { tags: n }; + for (const mode of modes) { + const Handler = createIncrementalCacheHandler({ + client: { type: "redis", url }, + buildNamespace: `bench-${n}-${mode.label.slice(0, 4)}`, + ...mode.opts, + }); + await new Handler().set(`/page-${n}`, { kind: "APP_PAGE", body, headers: { "x-next-cache-tags": tagsFor(n) } }, ctx); + await new Handler().get(`/page-${n}`, ctx); // warm-up (connects) + const before = await commands(); + for (let i = 0; i < RUNS; i++) { + await new Handler().get(`/page-${n}`, ctx); + } + row[mode.label] = ((await commands()) - before) / RUNS; + } + rows.push(row); +} + +console.log(`Redis commands per ISR get(), ${RUNS} reads each (entry GET included)`); +console.table(rows); +await raw.flushAll(); +await raw.quit(); +process.exit(0); diff --git a/skills/nextjs-redis-cache/SKILL.md b/skills/nextjs-redis-cache/SKILL.md index d2664f7..93c3931 100644 --- a/skills/nextjs-redis-cache/SKILL.md +++ b/skills/nextjs-redis-cache/SKILL.md @@ -116,7 +116,7 @@ Facts that prevent misdiagnosis: | `fallback: "auto"\|"always"\|"never"` | auto | `never` = strict (miss on Redis failure); `always` = no Redis (build/dev) | | `singleFlight: true` | off | To measure duplicate refresh work across instances at revalidate boundaries (leader/follower metrics; it does not suppress refreshes) | | `abortTimeoutMs` | 1500 | Per-op Redis deadline; timeouts degrade to miss | -| `hashTag: true` | off | REQUIRED on Redis Cluster | +| `hashTag: true` | off | REQUIRED on Redis Cluster (multi-key Lua; also switches ISR tag reads from one `MGET` to per-key GETs, which Cluster needs) | | `onMetric` | — | Wire `createOtelMetricEmitter()` from `@leejpsd/nextjs-cache-handler/otel` | | `tagPubSub: true` | off | 0.4+: push-based cross-instance invalidation (~3ms vs seconds); polling stays as safety net; not on Cluster | | `tagReadMode: "on-demand"` | `"scan"` | 1.1+: Redis holds many keys (tens of thousands) and `refreshTags()` shows up in request latency. Skips the per-request SCAN; `get()` MGETs only the entry's tags (one extra round trip) | diff --git a/src/incremental/handler.ts b/src/incremental/handler.ts index 6eaf36f..0f772ac 100644 --- a/src/incremental/handler.ts +++ b/src/incremental/handler.ts @@ -28,6 +28,7 @@ import type { IncrementalCacheData, Logger, MetricEmitter, + RedisClientLike, } from "../types.js"; import { @@ -92,6 +93,15 @@ interface HandlerState { /** Tag states, by bare tag (no namespace prefix — see tagMetaKey comment). */ memTagStates: Map; resolveNs: () => string; + /** + * How `readTagStates` fetches tag markers. `"mget"` (default) reads all of + * an entry's tags with one command. `"per-key"` sends one GET per tag; it is + * what Redis Cluster needs, because tag keys are deliberately un-namespaced + * (cross-deploy semantics) and so never share a hash slot. Starts as + * `"per-key"` when the options say Cluster (`hashTag: true`) and flips to it + * for good the first time an MGET fails with CROSSSLOT. + */ + tagReadStrategy: "mget" | "per-key"; } function gateRedis(state: HandlerState): boolean { @@ -125,6 +135,10 @@ function init(opts: CacheHandlerOptions): HandlerState { memEntries: new MemoryStore(opts.memoryMaxEntries), memTagStates: new Map(), resolveNs: () => resolveBuildNamespace(opts.buildNamespace), + // `hashTag` is only ever set for Cluster, so skip the MGET that would + // fail there. Everything else starts optimistic and may still latch to + // per-key on a CROSSSLOT reply (see readTagValues). + tagReadStrategy: opts.hashTag ? "per-key" : "mget", }; } @@ -253,14 +267,17 @@ async function readTagStates( async () => { const client = await state.conn.getOrConnect(); if (!client) return tags.map((t) => state.memTagStates.get(t) ?? null); - // Per-key GETs, not MGET: ISR tag keys are deliberately un-namespaced - // (cross-deploy semantics), so on Redis Cluster a multi-tag MGET is a - // guaranteed CROSSSLOT error — which the outer catch would silently - // swallow, disabling cross-instance revalidateTag for multi-tag - // entries. Auto-pipelining makes the fan-out one round trip anyway. - const values = await Promise.all( - tags.map((t) => client.get(tagMetaKey(state, t))) - ); + const keys = tags.map((t) => tagMetaKey(state, t)); + const values = await readTagValues(state, client, keys); + state.emit({ + type: "tag.expiration.read", + meta: { + source: "redis", + op: "incremental.get", + count: tags.length, + strategy: state.tagReadStrategy, + }, + }); return values.map((v) => { if (!v) return null; try { @@ -276,6 +293,54 @@ async function readTagStates( } } +/** + * Fetch the raw marker values for `keys`. + * + * One `MGET` on a single node: one command whatever the tag count, which is + * what per-command pricing (Upstash) and command-rate limits see (#34). On + * Redis Cluster the keys sit in different slots, so an `MGET` is refused + * with CROSSSLOT: a client flagged `isCluster` (or options with `hashTag`) + * goes key by key from the start, and an unflagged Cluster client is caught + * on its first CROSSSLOT reply, which latches the handler to per-key reads + * and is retried in place so that read loses nothing. Per-key GETs are + * auto-pipelined by both supported clients, so they still cost one round + * trip; only the command count differs. + */ +async function readTagValues( + state: HandlerState, + client: RedisClientLike, + keys: string[] +): Promise<(string | null)[]> { + if (keys.length === 1) return [await client.get(keys[0]!)]; + if (state.tagReadStrategy === "mget" && client.isCluster) { + state.tagReadStrategy = "per-key"; + } + if (state.tagReadStrategy === "mget") { + try { + return await client.mGet(keys); + } catch (err) { + if (!isCrossSlotError(err)) throw err; + state.tagReadStrategy = "per-key"; + state.logger.warn( + "MGET of tag states hit CROSSSLOT (Redis Cluster); reading tag states key by key from now on. Set hashTag: true to skip this probe." + ); + } + } + return Promise.all(keys.map((k) => client.get(k))); +} + +/** + * Two spellings of the same refusal: the server's `CROSSSLOT Keys in request + * don't hash to the same slot`, and ioredis's client-side check when + * auto-pipelining is on, `All the keys in a pipeline command should belong + * to the same slot`, which never reaches the server. + */ +function isCrossSlotError(err: unknown): boolean { + const message = + err instanceof Error ? err.message : typeof err === "string" ? err : ""; + return /CROSSSLOT|same slot/i.test(message); +} + // ─── Handler class ────────────────────────────────────────────────────────── export class IncrementalRedisCacheHandler { diff --git a/src/shared/client/adapter-ioredis.ts b/src/shared/client/adapter-ioredis.ts index 61aad87..6623789 100644 --- a/src/shared/client/adapter-ioredis.ts +++ b/src/shared/client/adapter-ioredis.ts @@ -16,6 +16,7 @@ type AnyRedis = Redis | Cluster; function adapt(client: AnyRedis, isClusterClient = false): RedisClientLike { return { + isCluster: isClusterClient, get isOpen() { // ioredis exposes a `status` string. Both single-node and cluster // report "ready" once connected. diff --git a/src/types.ts b/src/types.ts index 822179b..40426e5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -58,6 +58,14 @@ export interface RedisClientLike { * both of which are used as fallbacks when this is absent. */ dispose?(): void; + /** + * `true` when the client talks to a Redis Cluster, where a multi-key + * command fails with `CROSSSLOT` unless every key hashes to the same slot. + * The ISR handler then reads tag states key by key instead of with one + * `MGET`. Set by `adaptCluster`; a raw Cluster client passed through a + * factory without this flag is still detected on the first `CROSSSLOT`. + */ + isCluster?: boolean; } export type RedisClientFactory = () => diff --git a/tests/cluster/cluster.test.ts b/tests/cluster/cluster.test.ts index 9c4e024..e75211a 100644 --- a/tests/cluster/cluster.test.ts +++ b/tests/cluster/cluster.test.ts @@ -9,10 +9,14 @@ * - cross-"instance" (two handler objects) tag propagation on a cluster * - tagPubSub degrades gracefully (no subscribe on the cluster adapter) */ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { createCacheComponentsHandler } from "../../src/cache-components/index.js"; import { createIncrementalCacheHandler } from "../../src/incremental/index.js"; +import { + adaptCluster, + createIoredisCluster, +} from "../../src/shared/client/adapter-ioredis.js"; import { bufferToStream, readStreamFully, @@ -129,4 +133,55 @@ describe("Redis Cluster e2e — cacheHandler (ISR)", () => { h.resetRequestCache(); expect(await h.get("/page", { kind: "APP_PAGE" })).toBeNull(); }); + + const multiTagPage = { + kind: "APP_PAGE" as const, + body: Buffer.from("multi-tag"), + headers: { "x-next-cache-tags": "posts,authors,_N_T_/page" }, + }; + const ctx = { kind: "APP_PAGE", cacheControl: { revalidate: 300 } }; + + it("tag states are read key by key on a cluster adapter: no MGET, invalidation still seen (#34)", async () => { + const ns = `cl-${Math.floor(Math.random() * 1e9)}`; + const client = adaptCluster(createIoredisCluster({ type: "cluster", nodes: NODES })); + const Handler = createIncrementalCacheHandler({ + client: () => client, + hashTag: true, + abortTimeoutMs: 3000, + buildNamespace: ns, + }); + const mget = vi.spyOn(client, "mGet"); + + await new Handler().set("/multi", multiTagPage, ctx); + expect(await new Handler().get("/multi", ctx)).not.toBeNull(); + await new Handler().revalidateTag("authors"); // hard, one of three tags + expect(await new Handler().get("/multi", ctx)).toBeNull(); + expect(mget).not.toHaveBeenCalled(); + }); + + it("a cluster client without the isCluster flag or hashTag latches on the first CROSSSLOT and loses nothing", async () => { + const ns = `cl-${Math.floor(Math.random() * 1e9)}`; + const flagged = adaptCluster(createIoredisCluster({ type: "cluster", nodes: NODES })); + // Same adapter, flag hidden: what a raw Cluster client from a user factory looks like. + const client = Object.create(flagged, { isCluster: { value: undefined } }) as typeof flagged; + const warns: string[] = []; + const Handler = createIncrementalCacheHandler({ + client: () => client, + abortTimeoutMs: 3000, + buildNamespace: ns, + logger: { debug() {}, info() {}, warn: (m: string) => warns.push(m), error() {} }, + }); + const mget = vi.spyOn(client, "mGet"); + + await new Handler().set("/latch", multiTagPage, ctx); + await new Handler().revalidateTag("posts"); // hard, before the first read + // First read: MGET → CROSSSLOT → per-key retry in the same read. + expect(await new Handler().get("/latch", ctx)).toBeNull(); + expect(mget).toHaveBeenCalledTimes(1); + expect(warns.filter((w) => /CROSSSLOT/.test(w))).toHaveLength(1); + + await new Handler().set("/latch-2", multiTagPage, ctx); + expect(await new Handler().get("/latch-2", ctx)).not.toBeNull(); + expect(mget).toHaveBeenCalledTimes(1); // latched: no second probe + }); }); diff --git a/tests/integration/isr-tag-read.test.ts b/tests/integration/isr-tag-read.test.ts new file mode 100644 index 0000000..e1e9905 --- /dev/null +++ b/tests/integration/isr-tag-read.test.ts @@ -0,0 +1,119 @@ +/** + * ISR handler tag reads (#34) against a real Redis: a page's tag states come + * back with one MGET per get(), and a hard revalidateTag from a second + * instance is still seen through that path. Runs over both adapters. + */ + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; + +import { createIncrementalCacheHandler } from "../../src/incremental/index.js"; +import type { RedisClientLike } from "../../src/types.js"; +import { adaptRedisV5, createRedisV5Client } from "../../src/shared/client/adapter-redis.js"; +import { adaptIoredis, createIoredisClient } from "../../src/shared/client/adapter-ioredis.js"; + +import { flushAll, getRedisUrl, isRedisReachable } from "./_redis-helpers.js"; + +const NAMESPACE = "it-isr-tag-read"; + +let reachable = true; +let probed = false; + +beforeAll(async () => { + reachable = await isRedisReachable(); + probed = true; +}); + +const adapters = [ + { + name: "redis@5", + build: (): RedisClientLike => + adaptRedisV5(createRedisV5Client({ type: "redis", url: getRedisUrl() })), + }, + { + name: "ioredis", + build: (): RedisClientLike => + adaptIoredis(createIoredisClient({ type: "ioredis", url: getRedisUrl() })), + }, +]; + +const page = (tags: string) => ({ + kind: "APP_PAGE" as const, + body: Buffer.from("isr"), + headers: { "x-next-cache-tags": tags }, +}); +const ctx = { kind: "APP_PAGE", cacheControl: { revalidate: 60 } }; + +for (const adapter of adapters) { + describe(`integration: ISR tag reads over ${adapter.name}`, () => { + let client: RedisClientLike; + let Handler: ReturnType; + + beforeAll(async () => { + if (!probed) reachable = await isRedisReachable(); + if (!reachable) return; + client = adapter.build(); + if (!client.isOpen) await client.connect(); + Handler = createIncrementalCacheHandler({ + client: () => client, + keyPrefix: "next-incremental:", + buildNamespace: () => NAMESPACE, + abortTimeoutMs: 3000, + }); + }); + + beforeEach(async () => { + if (!reachable) return; + await flushAll(client); + }); + + afterAll(async () => { + if (!reachable || !client) return; + await flushAll(client); + }); + + it.skipIf(!reachable)("get() reads a page's tag states with one MGET", async () => { + await new Handler().set("/blog", page("posts,authors,_N_T_/blog"), ctx); + const mget = vi.spyOn(client, "mGet"); + const get = vi.spyOn(client, "get"); + + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + + expect(mget).toHaveBeenCalledTimes(1); + expect(mget.mock.calls[0]![0]).toHaveLength(3); + expect(get).toHaveBeenCalledTimes(1); + mget.mockRestore(); + get.mockRestore(); + }); + + it.skipIf(!reachable)( + "a hard revalidateTag on instance B is seen by A through the MGET path", + async () => { + const a = new Handler(); + const b = new Handler(); + await a.set("/post/1", page("posts,authors"), ctx); + expect(await a.get("/post/1", ctx)).not.toBeNull(); + + await b.revalidateTag("authors"); + a.resetRequestCache(); + expect(await a.get("/post/1", ctx)).toBeNull(); + } + ); + + it.skipIf(!reachable)( + "a soft revalidateTag on instance B backdates the entry read by A", + async () => { + const a = new Handler(); + const b = new Handler(); + await a.set("/post/2", page("posts,authors"), ctx); + const before = (await a.get("/post/2", ctx))!.lastModified; + + await new Promise((r) => setTimeout(r, 20)); + await b.revalidateTag("posts", { expire: 3600 }); + a.resetRequestCache(); + const got = await a.get("/post/2", ctx); + expect(got).not.toBeNull(); + expect(got!.lastModified).toBeLessThan(before); + } + ); + }); +} diff --git a/tests/unit/_mock-client.ts b/tests/unit/_mock-client.ts index 3e42248..b721e2e 100644 --- a/tests/unit/_mock-client.ts +++ b/tests/unit/_mock-client.ts @@ -20,6 +20,7 @@ interface MockOptions { export class MockRedisClient implements RedisClientLike { isOpen = false; + isCluster?: boolean; readonly kv = new Map(); readonly sets = new Map>(); readonly errorListeners: Array<(err: Error) => void> = []; diff --git a/tests/unit/isr-tag-read.test.ts b/tests/unit/isr-tag-read.test.ts new file mode 100644 index 0000000..ecc1b37 --- /dev/null +++ b/tests/unit/isr-tag-read.test.ts @@ -0,0 +1,206 @@ +/** + * How the ISR (singular) handler reads tag states on get() (#34). + * + * Default: one MGET for all of an entry's tags. Redis Cluster refuses a + * multi-key command whose keys sit in different slots (CROSSSLOT), and ISR + * tag keys are deliberately un-namespaced, so there the handler reads key + * by key: from the start when the client says `isCluster` or the options say + * `hashTag`, otherwise from the first CROSSSLOT reply on. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { createIncrementalCacheHandler } from "../../src/incremental/index.js"; +import type { CacheHandlerOptions, MetricEvent } from "../../src/types.js"; + +import { MockRedisClient } from "./_mock-client.js"; + +const T0 = 1_700_000_000_000; +const CROSSSLOT = "CROSSSLOT Keys in request don't hash to the same slot"; + +let originalPhase: string | undefined; +beforeEach(() => { + vi.useFakeTimers({ now: T0 }); + originalPhase = process.env.NEXT_PHASE; + delete process.env.NEXT_PHASE; +}); +afterEach(() => { + vi.useRealTimers(); + if (originalPhase === undefined) delete process.env.NEXT_PHASE; + else process.env.NEXT_PHASE = originalPhase; +}); + +function setup(extra: Partial = {}, client = new MockRedisClient()) { + client.isOpen = true; + const events: MetricEvent[] = []; + const warns: string[] = []; + const Handler = createIncrementalCacheHandler({ + client: () => client, + abortTimeoutMs: 100, + onMetric: (e) => events.push(e), + logger: { debug() {}, info() {}, warn: (m: string) => warns.push(m), error() {} }, + ...extra, + }); + return { Handler, client, events, warns }; +} + +const page = (tags: string) => ({ + kind: "APP_PAGE" as const, + body: Buffer.from("hello"), + headers: { "x-next-cache-tags": tags }, +}); +const ctx = { kind: "APP_PAGE", cacheControl: { revalidate: 60 } }; + +describe("ISR handler — tag state reads (#34)", () => { + it("reads all of an entry's tags with one MGET", async () => { + const { Handler, client, events } = setup(); + const h = new Handler(); + await h.set("/blog", page("posts,authors,_N_T_/blog"), ctx); + const mget = vi.spyOn(client, "mGet"); + const get = vi.spyOn(client, "get"); + + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + + expect(mget).toHaveBeenCalledTimes(1); + expect(mget.mock.calls[0]![0]).toHaveLength(3); + expect(get).toHaveBeenCalledTimes(1); // the entry itself + const read = events.find((e) => e.type === "tag.expiration.read"); + expect(read?.meta).toMatchObject({ + source: "redis", + op: "incremental.get", + count: 3, + strategy: "mget", + }); + }); + + it("an entry with no tags touches no tag keys", async () => { + const { Handler, client } = setup(); + await new Handler().set("/blog", page(""), ctx); + const mget = vi.spyOn(client, "mGet"); + const get = vi.spyOn(client, "get"); + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + expect(mget).not.toHaveBeenCalled(); + expect(get).toHaveBeenCalledTimes(1); + }); + + it("a single tag is a plain GET, not an MGET", async () => { + const { Handler, client } = setup(); + await new Handler().set("/blog", page("posts"), ctx); + const mget = vi.spyOn(client, "mGet"); + const get = vi.spyOn(client, "get"); + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + expect(mget).not.toHaveBeenCalled(); + expect(get).toHaveBeenCalledTimes(2); // entry + tag + }); + + it("the MGET path still honours a hard invalidation from another instance", async () => { + const { Handler } = setup(); + const a = new Handler(); + const b = new Handler(); + await a.set("/blog", page("posts,authors"), ctx); + vi.setSystemTime(new Date(T0 + 10)); + await b.revalidateTag("authors"); // hard + expect(await new Handler().get("/blog", ctx)).toBeNull(); + }); + + it("the MGET path still honours a soft invalidation from another instance", async () => { + const { Handler } = setup(); + const a = new Handler(); + const b = new Handler(); + await a.set("/blog", page("posts,authors"), ctx); + vi.setSystemTime(new Date(T0 + 10)); + await b.revalidateTag("posts", { expire: 3600 }); // soft + const got = await new Handler().get("/blog", ctx); + expect(got).not.toBeNull(); + // Served, but backdated past its revalidate window so Next refreshes it. + expect(got!.lastModified).toBeLessThan(T0); + }); + + it("hashTag: true reads key by key from the start (Cluster hint)", async () => { + const { Handler, client, events } = setup({ hashTag: true }); + await new Handler().set("/blog", page("posts,authors,_N_T_/blog"), ctx); + const mget = vi.spyOn(client, "mGet"); + const get = vi.spyOn(client, "get"); + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + expect(mget).not.toHaveBeenCalled(); + expect(get).toHaveBeenCalledTimes(4); // entry + 3 tags + expect(events.find((e) => e.type === "tag.expiration.read")?.meta?.strategy).toBe("per-key"); + }); + + it("a client flagged isCluster reads key by key from the start", async () => { + const client = new MockRedisClient(); + client.isCluster = true; + const { Handler } = setup({}, client); + await new Handler().set("/blog", page("posts,authors"), ctx); + const mget = vi.spyOn(client, "mGet"); + const get = vi.spyOn(client, "get"); + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + expect(mget).not.toHaveBeenCalled(); + expect(get).toHaveBeenCalledTimes(3); + }); + + it("a CROSSSLOT reply latches the handler to per-key reads without losing that read", async () => { + const { Handler, client, warns } = setup(); + const a = new Handler(); + const b = new Handler(); + await a.set("/blog", page("posts,authors,_N_T_/blog"), ctx); + vi.setSystemTime(new Date(T0 + 10)); + await b.revalidateTag("authors"); // hard: the read below must see it + + const mget = vi.spyOn(client, "mGet").mockRejectedValue(new Error(CROSSSLOT)); + const get = vi.spyOn(client, "get"); + + // First request: MGET fails, the same read retries key by key. + expect(await new Handler().get("/blog", ctx)).toBeNull(); + expect(mget).toHaveBeenCalledTimes(1); + expect(get).toHaveBeenCalledTimes(4); // entry + 3 tags + expect(warns.filter((w) => /CROSSSLOT/.test(w))).toHaveLength(1); + + // Later requests: no MGET probe any more. + await a.set("/other", page("x,y"), ctx); + expect(await new Handler().get("/other", ctx)).not.toBeNull(); + expect(mget).toHaveBeenCalledTimes(1); + expect(warns.filter((w) => /CROSSSLOT/.test(w))).toHaveLength(1); + }); + + it("ioredis's client-side same-slot check (auto-pipelining) latches too", async () => { + const { Handler, client, warns } = setup(); + await new Handler().set("/blog", page("posts,authors"), ctx); + const mget = vi + .spyOn(client, "mGet") + .mockRejectedValue( + new Error("All the keys in a pipeline command should belong to the same slot") + ); + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + expect(mget).toHaveBeenCalledTimes(1); + expect(warns.filter((w) => /CROSSSLOT/.test(w))).toHaveLength(1); + }); + + it("any other MGET error falls back to the local tag mirror and does not latch", async () => { + const { Handler, client, warns } = setup(); + await new Handler().set("/blog", page("posts,authors"), ctx); + const mget = vi.spyOn(client, "mGet").mockRejectedValueOnce(new Error("boom")); + + // Degrades like before: the entry is served from what the mirror knows. + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + expect(mget).toHaveBeenCalledTimes(1); + expect(warns.some((w) => /CROSSSLOT/.test(w))).toBe(false); + + // Next request tries MGET again. + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + expect(mget).toHaveBeenCalledTimes(2); + }); + + it("per-key reads after a latch still honour invalidations", async () => { + const { Handler, client } = setup(); + const a = new Handler(); + await a.set("/blog", page("posts,authors"), ctx); + vi.spyOn(client, "mGet").mockRejectedValueOnce(new Error(CROSSSLOT)); + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); // latches + + vi.setSystemTime(new Date(T0 + 10)); + await new Handler().revalidateTag("posts"); // hard + expect(await new Handler().get("/blog", ctx)).toBeNull(); + }); +}); From 3bf1f1f02d4df6438d0a27759563a863d13176bd Mon Sep 17 00:00:00 2001 From: leejpsd Date: Tue, 24 Nov 2026 10:54:19 +0900 Subject: [PATCH 2/2] fix(incremental): latch to per-key tag reads whenever MGET cannot work QA against a real Redis: with an ACL user that may GET but not MGET, every multi-tag read fell through to the local tag mirror, so a hard revalidateTag from a second handler was not seen. Releases up to 1.1.0 read key by key and were not affected. NOPERM, an unknown command, a client without mGet and a reply that is not one value per key now latch to per-key reads the same way CROSSSLOT does, retrying that read in place. Timeouts and dropped connections still fall back without latching. Concurrent first reads warn once. --- .changeset/isr-tag-read-mget.md | 2 +- README.md | 2 +- docs/architecture.md | 6 +- src/incremental/handler.ts | 67 +++++++++++++++++----- tests/integration/isr-tag-read.test.ts | 69 +++++++++++++++++++++++ tests/unit/isr-tag-read.test.ts | 77 ++++++++++++++++++++++++++ 6 files changed, 205 insertions(+), 18 deletions(-) diff --git a/.changeset/isr-tag-read-mget.md b/.changeset/isr-tag-read-mget.md index f051b49..53e6b67 100644 --- a/.changeset/isr-tag-read-mget.md +++ b/.changeset/isr-tag-read-mget.md @@ -2,4 +2,4 @@ "@leejpsd/nextjs-cache-handler": patch --- -ISR handler: read all of an entry's tag states with one `MGET` instead of one `GET` per tag (#34). A page with five `_N_T_` layout tags now costs two Redis commands per `get()` instead of six; round trips were already one thanks to auto-pipelining, so this matters for per-command pricing and command-rate limits. On Redis Cluster, where the un-namespaced tag keys never share a slot, the handler keeps reading key by key: from the start when the client is the Cluster adapter (new `isCluster` flag on `RedisClientLike`) or `hashTag: true` is set, otherwise from the first `CROSSSLOT` reply on, retrying that read in place and logging one warning. `tag.expiration.read` is now also emitted by the ISR handler with `meta.strategy` (`"mget"` or `"per-key"`). +ISR handler: read all of an entry's tag states with one `MGET` instead of one `GET` per tag (#34). A page with five `_N_T_` layout tags now costs two Redis commands per `get()` instead of six; round trips were already one thanks to auto-pipelining, so this matters for per-command pricing and command-rate limits. On Redis Cluster, where the un-namespaced tag keys never share a slot, the handler keeps reading key by key: from the start when the client is the Cluster adapter (new `isCluster` flag on `RedisClientLike`) or `hashTag: true` is set, otherwise from the first `CROSSSLOT` reply on, retrying that read in place and logging one warning. The same fallback applies when `MGET` can never work for another reason: an ACL that allows `GET` but not `MGET`, a server that does not know the command, or a custom client without a usable `mGet`. `tag.expiration.read` is now also emitted by the ISR handler with `meta.strategy` (`"mget"` or `"per-key"`). diff --git a/README.md b/README.md index 597048d..34d05e2 100644 --- a/README.md +++ b/README.md @@ -269,7 +269,7 @@ Full reference: [`docs/api.md`](./docs/api.md). un-namespaced (so `revalidateTag` survives a deploy) and never share a slot. Without the flag, a Cluster client still works: the first `CROSSSLOT` reply switches that handler to per-key reads and logs one - warning. + warning. A Redis user whose ACL denies `MGET` is handled the same way. - [ ] **Redis `maxmemory-policy: allkeys-lru` or `noeviction`** — if you need bounded memory, choose `allkeys-lru`. Otherwise `noeviction` keeps tag indices intact. diff --git a/docs/architecture.md b/docs/architecture.md index 15a7e75..6102a3e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -127,7 +127,11 @@ keys are deliberately un-namespaced and so never share a slot; there the handler reads key by key (one auto-pipelined round trip, one command per tag). It knows it is on Cluster from the adapter's `isCluster` flag or `hashTag: true`, and otherwise latches to per-key reads on the first -`CROSSSLOT` reply, retrying that read in place. `scripts/bench-isr-tag-read.mjs` +`CROSSSLOT` reply, retrying that read in place. The same latch covers the +other cases where `MGET` can never work: a Redis user whose ACL allows `GET` +but not `MGET`, a server or proxy that does not know the command, and a +custom client whose `mGet` is missing or malformed. Timeouts and dropped +connections do not latch. `scripts/bench-isr-tag-read.mjs` prints the command count per `get()` for both strategies against a local Redis. diff --git a/src/incremental/handler.ts b/src/incremental/handler.ts index 0f772ac..b4c2439 100644 --- a/src/incremental/handler.ts +++ b/src/incremental/handler.ts @@ -301,10 +301,19 @@ async function readTagStates( * Redis Cluster the keys sit in different slots, so an `MGET` is refused * with CROSSSLOT: a client flagged `isCluster` (or options with `hashTag`) * goes key by key from the start, and an unflagged Cluster client is caught - * on its first CROSSSLOT reply, which latches the handler to per-key reads - * and is retried in place so that read loses nothing. Per-key GETs are - * auto-pipelined by both supported clients, so they still cost one round - * trip; only the command count differs. + * on its first refusal. + * + * Any sign that `MGET` cannot be used here latches the handler to per-key + * reads for good and retries that read in place, so nothing is lost: a + * cross-slot refusal, a Redis user whose ACL allows GET but not MGET, a + * server or proxy that does not know the command, or a custom client whose + * `mGet` is missing or does not return one value per key. Without the + * latch those would fall through to the local tag mirror on every read and + * silently miss invalidations made by other instances. Transient failures + * (timeouts, dropped connections) are rethrown and do not latch. + * + * Per-key GETs are auto-pipelined by both supported clients, so they still + * cost one round trip; only the command count differs. */ async function readTagValues( state: HandlerState, @@ -312,33 +321,61 @@ async function readTagValues( keys: string[] ): Promise<(string | null)[]> { if (keys.length === 1) return [await client.get(keys[0]!)]; - if (state.tagReadStrategy === "mget" && client.isCluster) { - state.tagReadStrategy = "per-key"; + if (state.tagReadStrategy === "mget") { + if (client.isCluster) { + state.tagReadStrategy = "per-key"; + } else if (typeof client.mGet !== "function") { + latchPerKey(state, "the client has no mGet method"); + } } if (state.tagReadStrategy === "mget") { try { - return await client.mGet(keys); + const values: unknown = await client.mGet(keys); + if (Array.isArray(values) && values.length === keys.length) { + return values as (string | null)[]; + } + latchPerKey(state, "mGet did not return one value per key"); } catch (err) { - if (!isCrossSlotError(err)) throw err; - state.tagReadStrategy = "per-key"; - state.logger.warn( - "MGET of tag states hit CROSSSLOT (Redis Cluster); reading tag states key by key from now on. Set hashTag: true to skip this probe." - ); + const reason = mgetRefusal(err); + if (!reason) throw err; + latchPerKey(state, reason); } } return Promise.all(keys.map((k) => client.get(k))); } +/** Switch to per-key reads for the life of this handler; warn once. */ +function latchPerKey(state: HandlerState, reason: string): void { + // Concurrent first reads all see the same refusal; only the first warns. + if (state.tagReadStrategy === "per-key") return; + state.tagReadStrategy = "per-key"; + state.logger.warn( + `MGET of tag states is not usable here (${reason}); reading tag states key by key from now on.` + ); +} + /** - * Two spellings of the same refusal: the server's `CROSSSLOT Keys in request + * Why an `MGET` error means "this command will never work here", or `null` + * for anything that may be transient. + * + * Cross-slot comes in two spellings: the server's `CROSSSLOT Keys in request * don't hash to the same slot`, and ioredis's client-side check when * auto-pipelining is on, `All the keys in a pipeline command should belong * to the same slot`, which never reaches the server. */ -function isCrossSlotError(err: unknown): boolean { +function mgetRefusal(err: unknown): string | null { const message = err instanceof Error ? err.message : typeof err === "string" ? err : ""; - return /CROSSSLOT|same slot/i.test(message); + if (/CROSSSLOT|same slot/i.test(message)) { + return "CROSSSLOT: Redis Cluster keeps these keys in different slots; set hashTag: true to skip this probe"; + } + if (/NOPERM/i.test(message)) { + return "NOPERM: the Redis user may not run MGET"; + } + if (/unknown command/i.test(message)) { + return "the server does not know MGET"; + } + return null; } // ─── Handler class ────────────────────────────────────────────────────────── diff --git a/tests/integration/isr-tag-read.test.ts b/tests/integration/isr-tag-read.test.ts index e1e9905..288233c 100644 --- a/tests/integration/isr-tag-read.test.ts +++ b/tests/integration/isr-tag-read.test.ts @@ -117,3 +117,72 @@ for (const adapter of adapters) { ); }); } + +/** + * A Redis user whose ACL allows GET but not MGET. Without the per-key latch + * every multi-tag read would fall back to the local mirror and a second + * instance's invalidation would be missed (found in QA for #34). + */ +describe("integration: ISR tag reads with an ACL that denies MGET", () => { + const USER = "isr-no-mget"; + const PASS = "pw"; + let admin: import("redis").RedisClientType | undefined; + + function aclUrl(): string { + const u = new URL(getRedisUrl()); + u.username = USER; + u.password = PASS; + return u.toString(); + } + + beforeAll(async () => { + if (!probed) reachable = await isRedisReachable(); + if (!reachable) return; + const { createClient } = require("redis") as typeof import("redis"); + admin = createClient({ url: getRedisUrl() }) as import("redis").RedisClientType; + admin.on("error", () => {}); + await admin.connect(); + await admin.sendCommand([ + "ACL", + "SETUSER", + USER, + "on", + `>${PASS}`, + "~*", + "&*", + "+@all", + "-mget", + ]); + }); + + afterAll(async () => { + if (!admin) return; + await admin.sendCommand(["ACL", "DELUSER", USER]); + await admin.flushAll(); + await admin.quit(); + }); + + it.skipIf(!reachable)( + "a hard revalidateTag on another instance is still seen, and the handler stops trying MGET", + async () => { + const warns: string[] = []; + const make = () => + createIncrementalCacheHandler({ + client: { type: "redis", url: aclUrl() }, + keyPrefix: "next-incremental:", + buildNamespace: () => `${NAMESPACE}-acl`, + abortTimeoutMs: 3000, + logger: { debug() {}, info() {}, warn: (m: string) => warns.push(m), error() {} }, + }); + // Separate handler states stand in for two servers: no shared mirror. + const A = make(); + const B = make(); + + await new A().set("/acl", page("posts,authors"), ctx); + expect(await new A().get("/acl", ctx)).not.toBeNull(); // probe: NOPERM → per-key + await new B().revalidateTag("authors"); + expect(await new A().get("/acl", ctx)).toBeNull(); + expect(warns.filter((w) => /NOPERM/.test(w))).toHaveLength(1); // only A reads + } + ); +}); diff --git a/tests/unit/isr-tag-read.test.ts b/tests/unit/isr-tag-read.test.ts index ecc1b37..987bedb 100644 --- a/tests/unit/isr-tag-read.test.ts +++ b/tests/unit/isr-tag-read.test.ts @@ -203,4 +203,81 @@ describe("ISR handler — tag state reads (#34)", () => { await new Handler().revalidateTag("posts"); // hard expect(await new Handler().get("/blog", ctx)).toBeNull(); }); + + it("a Redis user without MGET permission (NOPERM) latches and still sees invalidations", async () => { + const { Handler, client, warns } = setup(); + const a = new Handler(); + await a.set("/blog", page("posts,authors"), ctx); + vi.setSystemTime(new Date(T0 + 10)); + await new Handler().revalidateTag("authors"); // hard + const mget = vi + .spyOn(client, "mGet") + .mockRejectedValue(new Error("NOPERM User app has no permissions to run the 'mget' command")); + + // Without the latch this read would fall back to the local mirror and + // serve the entry as if nothing had been invalidated. + expect(await new Handler().get("/blog", ctx)).toBeNull(); + await a.set("/other", page("x,y"), ctx); + expect(await new Handler().get("/other", ctx)).not.toBeNull(); + expect(mget).toHaveBeenCalledTimes(1); + expect(warns.filter((w) => /NOPERM/.test(w))).toHaveLength(1); + }); + + it("a server that does not know MGET latches", async () => { + const { Handler, client } = setup(); + await new Handler().set("/blog", page("posts,authors"), ctx); + const mget = vi + .spyOn(client, "mGet") + .mockRejectedValue(new Error("ERR unknown command 'mget'")); + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + expect(mget).toHaveBeenCalledTimes(1); + }); + + it("a custom client without mGet reads key by key", async () => { + const client = new MockRedisClient(); + (client as unknown as { mGet?: unknown }).mGet = undefined; + const { Handler, warns } = setup({}, client); + await new Handler().set("/blog", page("posts,authors"), ctx); + vi.setSystemTime(new Date(T0 + 10)); + await new Handler().revalidateTag("posts"); // hard + expect(await new Handler().get("/blog", ctx)).toBeNull(); + expect(warns.filter((w) => /no mGet method/.test(w))).toHaveLength(1); + }); + + it("an mGet that does not return one value per key is not trusted", async () => { + const { Handler, client, warns } = setup(); + await new Handler().set("/blog", page("posts,authors"), ctx); + vi.setSystemTime(new Date(T0 + 10)); + await new Handler().revalidateTag("posts"); // hard + const mget = vi.spyOn(client, "mGet").mockResolvedValue([null] as unknown as (string | null)[]); + expect(await new Handler().get("/blog", ctx)).toBeNull(); + expect(mget).toHaveBeenCalledTimes(1); + expect(warns.filter((w) => /one value per key/.test(w))).toHaveLength(1); + }); + + it("concurrent first reads that all hit the refusal warn once", async () => { + const { Handler, client, warns } = setup(); + await new Handler().set("/a", page("posts,authors"), ctx); + await new Handler().set("/b", page("x,y"), ctx); + await new Handler().set("/c", page("m,n"), ctx); + vi.spyOn(client, "mGet").mockRejectedValue(new Error(CROSSSLOT)); + + const got = await Promise.all(["/a", "/b", "/c"].map((k) => new Handler().get(k, ctx))); + expect(got.every((g) => g !== null)).toBe(true); + expect(warns.filter((w) => /MGET of tag states/.test(w))).toHaveLength(1); + }); + + it("a timeout on MGET does not latch", async () => { + const { Handler, client } = setup(); + await new Handler().set("/blog", page("posts,authors"), ctx); + const mget = vi.spyOn(client, "mGet").mockImplementationOnce( + () => new Promise(() => {}) // never settles → abortTimeoutMs fires + ); + const pending = new Handler().get("/blog", ctx); + await vi.advanceTimersByTimeAsync(150); + expect(await pending).not.toBeNull(); // degraded to the local mirror + expect(await new Handler().get("/blog", ctx)).not.toBeNull(); + expect(mget).toHaveBeenCalledTimes(2); // tried MGET again + }); });