From 98a09c6101c1ab66138232509eed847a2dcfb0ac Mon Sep 17 00:00:00 2001 From: leejpsd Date: Fri, 13 Nov 2026 15:58:17 +0900 Subject: [PATCH] fix(incremental): reject revalidateTag when the tag state could not be written With no Redis connection (failed initialization, or the reconnect cooldown) getOrConnect() returns null. revalidateTag returned from its callback, fell through to the success path and emitted a tag.invalidate metric with backend "redis", so the caller could not tell an unwritten invalidation from a confirmed one while other instances kept serving the old entry. Throw in that case. The existing catch already decides what propagates: an invalidation with a deadline rejects, exactly as it does when the write fails or times out. The local stamp is applied before the remote write, so the calling process is invalidated either way. Memory-only modes are untouched. Closes #13 --- .../revalidate-tag-unconfirmed-write.md | 5 + docs/api.md | 2 +- src/incremental/handler.ts | 14 ++- tests/unit/incremental.test.ts | 92 +++++++++++++++++++ 4 files changed, 110 insertions(+), 3 deletions(-) create mode 100644 .changeset/revalidate-tag-unconfirmed-write.md diff --git a/.changeset/revalidate-tag-unconfirmed-write.md b/.changeset/revalidate-tag-unconfirmed-write.md new file mode 100644 index 0000000..b2ef898 --- /dev/null +++ b/.changeset/revalidate-tag-unconfirmed-write.md @@ -0,0 +1,5 @@ +--- +"@leejpsd/nextjs-cache-handler": patch +--- + +`cacheHandler` (singular): `revalidateTag` no longer resolves when the tag state could not be written because there is no Redis connection (failed initialization or the reconnect cooldown). It previously returned normally and emitted a `tag.invalidate.*` metric with `backend: "redis"`, so a caller could not tell an unwritten invalidation from a confirmed one while other instances kept serving the old entry (#13). It now rejects, exactly as it already did when the write itself failed or timed out, and no success metric is emitted. The invalidation is still applied in the calling process first. Memory-only modes (`fallback: "always"`, build phase, `instance-local:` tags) are unchanged. diff --git a/docs/api.md b/docs/api.md index 3af74a1..35308d4 100644 --- a/docs/api.md +++ b/docs/api.md @@ -40,7 +40,7 @@ ctx contract are accepted (`ctx.cacheControl.revalidate` / `kind` and | `client` | `RedisClientFactory \| RedisClientConfig` | **required** | factory function or lazy config object | | `keyPrefix` | `string` | `"next-cache:"` / `"next-incremental:"` | multi-app Redis sharing | | `buildNamespace` | `string \| () => string` | `DEPLOYMENT_VERSION ?? GIT_HASH ?? NEXT_DEPLOYMENT_ID ?? "unversioned"` | per-deploy key isolation; function form defers env read | -| `abortTimeoutMs` | `number` | `1500` | per-operation deadline; timeout ⇒ miss (reads) / ignored (writes) / thrown (hard invalidation) | +| `abortTimeoutMs` | `number` | `1500` | per-operation deadline; timeout ⇒ miss (reads) / ignored (writes) / thrown (hard invalidation, and `revalidateTag` with an `expire`). An invalidation that cannot be written at all (no connection, reconnect cooldown) is thrown the same way | | `fallback` | `"auto" \| "always" \| "never"` | `"auto"` | `always` = memory only (never connect); `never` = strict, Redis failures surface as misses | | `memoryMaxEntries` | `number` | `1000` | LRU cap for the in-memory fallback (and its tag index) | | `compression` | `"gzip" \| "brotli"` | off | transparent Redis value compression (node:zlib). Reads auto-detect, so mixed fleets interoperate; < 1 KiB stored plain | diff --git a/src/incremental/handler.ts b/src/incremental/handler.ts index ad79805..6eaf36f 100644 --- a/src/incremental/handler.ts +++ b/src/incremental/handler.ts @@ -545,7 +545,15 @@ export class IncrementalRedisCacheHandler { this.state.opts.abortTimeoutMs, async () => { const client = await this.state.conn.getOrConnect(); - if (!client) return; + if (!client) { + // No connection (failed init, or inside the reconnect cooldown): + // nothing was written, so other instances still hold the entry. + // Treat it like a failed write instead of falling through to the + // success metric below. + throw new Error( + "[next-cache] revalidateTag: Redis unavailable, tag state was not written" + ); + } await Promise.all( list.map((t) => client.set(tagMetaKey(this.state, t), JSON.stringify(payload), { @@ -563,7 +571,9 @@ export class IncrementalRedisCacheHandler { this.state.logger.warn("revalidateTag() failed", { message: (err as Error).message, }); - // Hard expirations should propagate so callers know to retry. + // An invalidation with a deadline (no durations, or durations with an + // `expire`) must propagate so the caller knows it was not confirmed and + // can retry. The local stamp above already took effect in this process. if (payload.expired !== undefined) throw err; } } diff --git a/tests/unit/incremental.test.ts b/tests/unit/incremental.test.ts index acf7b0b..b37701e 100644 --- a/tests/unit/incremental.test.ts +++ b/tests/unit/incremental.test.ts @@ -552,3 +552,95 @@ describe("incremental cacheHandler — build phase skip", () => { expect(setSpy).not.toHaveBeenCalled(); }); }); + +describe("incremental cacheHandler — revalidateTag without a Redis connection (#13)", () => { + // A factory that throws stands in for failed auth / cluster discovery: + // ConnectionManager.getOrConnect() returns null and then stays null for + // the reconnect cooldown. + function setupUnreachable(fallback?: "auto" | "never") { + const events: { type: string; backend: unknown }[] = []; + const Handler = createIncrementalCacheHandler({ + client: async () => { + throw new Error("simulated initialization failure"); + }, + abortTimeoutMs: 100, + ...(fallback ? { fallback } : {}), + logger: { debug() {}, info() {}, warn() {}, error() {} }, + onMetric: (e) => { + if (e.type.startsWith("tag.invalidate")) { + events.push({ type: e.type, backend: e.meta?.backend }); + } + }, + }); + return { Handler, events }; + } + + it.each([ + ["auto", undefined], + ["never", "never" as const], + ])("hard invalidation rejects instead of reporting success (fallback: %s)", async (_label, fallback) => { + const { Handler, events } = setupUnreachable(fallback); + const h = new Handler(); + + await expect(h.revalidateTag("posts")).rejects.toThrow(/Redis unavailable/); + // Second call lands inside the reconnect cooldown: still not a success. + await expect(h.revalidateTag("posts")).rejects.toThrow(/Redis unavailable/); + expect(events).toEqual([]); + }); + + it("revalidateTag(tag, { expire }) rejects too, like a failed write does", async () => { + const { Handler, events } = setupUnreachable(); + const h = new Handler(); + + await expect(h.revalidateTag("posts", { expire: 0 })).rejects.toThrow(/Redis unavailable/); + await expect(h.revalidateTag("posts", { expire: 31536000 })).rejects.toThrow(/Redis unavailable/); + expect(events).toEqual([]); + }); + + it("the invalidation still applies locally before the rejection", async () => { + // The process that called revalidateTag must not keep serving the entry + // from its own memory just because the remote write could not be made. + const { Handler } = setupUnreachable(); + const h = new Handler(); + await h.set( + "/page", + { kind: "APP_PAGE", body: Buffer.from("html"), headers: { "x-next-cache-tags": "posts" } }, + { kind: "APP_PAGE", cacheControl: { revalidate: 300 } } + ); + expect(await h.get("/page", { kind: "APP_PAGE" })).not.toBeNull(); + + vi.setSystemTime(new Date(T0 + 10)); + await expect(h.revalidateTag("posts")).rejects.toThrow(/Redis unavailable/); + + h.resetRequestCache(); + expect(await h.get("/page", { kind: "APP_PAGE" })).toBeNull(); + }); + + it("durations without an expire stay best-effort but never report a Redis write", async () => { + const { Handler, events } = setupUnreachable(); + const h = new Handler(); + + await expect(h.revalidateTag("posts", {})).resolves.toBeUndefined(); + expect(events).toEqual([]); + }); + + it("memory-only modes are unaffected: no connection is attempted and nothing rejects", async () => { + const events: string[] = []; + const factory = vi.fn(async () => { + throw new Error("must not be called"); + }); + const Handler = createIncrementalCacheHandler({ + client: factory, + abortTimeoutMs: 100, + fallback: "always", + onMetric: (e) => { + if (e.type.startsWith("tag.invalidate")) events.push(`${e.type}:${String(e.meta?.backend)}`); + }, + }); + const h = new Handler(); + + await expect(h.revalidateTag("posts")).resolves.toBeUndefined(); + expect(factory).not.toHaveBeenCalled(); + expect(events).toEqual(["tag.invalidate.hard:memory"]); + }); +});