Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/revalidate-tag-unconfirmed-write.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
14 changes: 12 additions & 2 deletions src/incremental/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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), {
Expand All @@ -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;
}
}
Expand Down
92 changes: 92 additions & 0 deletions tests/unit/incremental.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"]);
});
});
Loading