Repository navigation
Description
Following CONTRIBUTING.md, I would like feedback on the error contract before a PR. A proposed patch and focused validation results are included below; no PR or release has been submitted.
Problem
With the singular handler from @leejpsd/nextjs-cache-handler 1.0.0, a hard invalidation can resolve even though cluster initialization/authentication failed and no remote marker write was confirmed.
The observed path is in base commit 348ec052836407b1aadecf7c811e1a920766fad9: ConnectionManager.getOrConnect() catches initialization failure and returns null; incremental revalidateTag returns from the callback when there is no client, then emits a Redis invalidation-success metric. A caller cannot distinguish that outcome from a confirmed write. An unconfirmed invalidation may leave other processes serving older entries.
Expected: a remote invalidation without confirmed writes rejects so the caller can handle or retry it. Explicit local/build-only paths should retain their local behavior.
Upstream check on 2026-10-23: main is still at the pinned commit above and npm latest is 1.0.0. I reviewed the repository issue/PR and release collections. Issue #1 and its follow-up fix concern explicit-tag freshness/SWR in the plural handler and route rendering; this report concerns the singular handler resolving after initialization fails without a confirmed marker write. No equivalent report or pertinent correction was found in the sources checked.
Minimal source-derived reproducer
This reduction exercises the same initialization-failure path without a Redis server, driver connection or Next application. It is derived from the confirmed path and has not been executed as a separate test. The executed real-cluster observation is described in the next section. No tests were rerun while preparing this issue text.
In a clean checkout:
git clone https://github.com/leejpsd/nextjs-cache-handler.git cache-handler-repro
cd cache-handler-repro
git checkout --detach 348ec052836407b1aadecf7c811e1a920766fad9
npm ci --ignore-scripts
npm run build
# Save the following script as repro-minimal.mjs in this checkout.
node repro-minimal.mjs// Source-derived reduction; not executed as a separate test.
// Save in a clean package checkout after building dist (see issue body).
import { createIncrementalCacheHandler } from './dist/incremental/index.js';
const Handler = createIncrementalCacheHandler({
client: async () => {
throw new Error('simulated initialization failure');
},
fallback: 'never',
isBuildPhase: () => false,
abortTimeoutMs: 500,
keyPrefix: 'invalidation-repro:',
buildNamespace: 'repro',
});
const handler = new Handler();
for (const attempt of [1, 2]) {
try {
await handler.revalidateTag('fixture', { expire: 0 });
console.log('attempt', attempt, 'RESOLVED');
} catch (error) {
console.log('attempt', attempt, 'REJECTED', error.message);
}
}The unpatched source path is expected to print RESOLVED for both calls, despite the simulated failure. The second call exercises the connection cooldown. With the proposed patch, both calls are expected to print REJECTED with the initialization error. These are source-derived expected outcomes, not a captured execution of this reduced script.
Executed real-cluster observation
The original failure was executed with published 1.0.0, Node.js 24.22.0, ioredis 6.0.0, Next.js 16.4.2 and an isolated Valkey 8.0.11 TLS cluster with three primaries. Certificate trust/identity was valid for the test cluster, and the healthy-credential control supported shared reads/invalidation and a fresh process.
The failing handler configuration used:
client: {
type: 'cluster',
nodes: [{ host: 'r1', port: 6379 }],
password: 'incorrect-test-only',
tls: true,
},
hashTag: true,
fallback: 'never',
abortTimeoutMs: 500,Two calls to revalidateTag('fixture', { expire: 0 }), separated by approximately 1.2 seconds, resolved without throwing while authentication/discovery failed. Logs included "Failed to refresh slots cache." and "None of startup nodes is available". The successful-credential control distinguishes this from an unavailable fixture. All credentials, tags and hostnames here are synthetic.
Source inspection also shows that the singular catch only rethrows when payload.expired is defined. The soft-error path is an additional source-level finding; the original unpatched cluster reproduction above used hard invalidation. The proposal deliberately makes unconfirmed soft invalidation reject as well.
Proposed patch
The complete diff below is against the pinned base: 13 files, 491 insertions and 16 deletions. Patch SHA256: cac42d02f654aa2f3b3c9ff5aee5e3965af9d489599d2e0571d9f0b92e68c558.
- Preserve the connection error through initial failure/cooldown and require a connected client for remote singular invalidation.
- Propagate unconfirmed marker-write/deadline errors for hard and soft invalidation. Entry get/set fallback policy and explicit local/build paths remain as before.
- Dispose failed candidates. Await already-starting ioredis/Cluster clients before applying a readiness guard; remove listeners/timers on readiness, failure or bounded wait timeout. This avoids a regression in the proposed fix for factories returning auto-connecting clients.
- Expose cluster ACL username, complete TLS options, dnsLookup and optional connection/command/discovery limits. Preserve the native cluster connectTimeout when the new option is omitted, including explicit override/zero support.
- Include a changeset, aligned README/API docs and portable unit/live-server regressions. The changeset proposes major because the soft-error contract changes; no version bump has been applied.
The local tarball still carries version 1.0.0 from the checkout and differs from published 1.0.0. The patch hash above identifies this contribution; a local package version alone does not identify it.
Existing focused validation of this patch
All results below were recorded before drafting this issue. The final patch/artifact remained unchanged for the additional runtime checks.
| Runtime / driver | Focused results |
|---|---|
| Node.js 24.22.0 / ioredis 5.10.1 | 29 readiness/configuration unit cases; 4 live single-node factory/invalidation cases passed |
| Node.js 24.22.0 / ioredis 6.0.0 | 7 focused runtime observations passed: factory invalidation/failure and default/override compatibility |
| Node.js 20.20.2 / ioredis 5.10.1 | 29 focused unit cases and 5 real TLS Cluster checks passed |
| Node.js 22.23.4 / ioredis 5.10.1 | The same 29 focused unit cases and 5 real TLS Cluster checks passed |
The real Cluster checks cover an auto-connecting factory, concurrent legacy/hard/soft marker acknowledgements, verified TLS/ACL on discovered primaries, authentication failure/cooldown without a remote-success metric or marker, recovery through a fresh factory on the same handler, and CJS alongside ESM entrypoints. Live servers were isolated Valkey 8.0.11 fixtures with three primaries for the Cluster runs.
Source/test typechecks, lint of affected TypeScript files, ESM/CJS/declaration build, changeset parsing, publint 0.3.18 and attw 0.17.4 passed for the prepared contribution. The included docs/testing-redis-invalidation.md explains the portable focused tests. No private application/workspace or AWS account is required for those included tests.
These counts are scoped executions, not a summed count of distinct scenarios or a claim that the full suite passed. Linux dependencies were installed once from the original lock under Node.js 22 and reused for the Node.js 20 runtime checks. The existing dist was reused for those runtime checks; independent npm ci/build/typecheck jobs under each runtime and the complete upstream CI were not executed.
Not covered: managed AWS behavior, replica failover/promotion durability, IAM rotation, capacity, or Next/HTTP integration under Node.js 20/22. Node.js 20/22 were checked because they are in the pinned workflow, without changing an application's runtime policy. Deadlines report an unconfirmed outcome; already-dispatched Redis operations may complete later or have partially written markers.
Feedback requested
Does rejecting unconfirmed singular invalidation, including the soft path, fit the intended contract? Please confirm the preferred release level and whether the cluster configuration additions should be split from the invalidation fix before a PR.
Complete proposed patch (for review; no PR opened)
diff --git a/.changeset/confirm-remote-invalidation.md b/.changeset/confirm-remote-invalidation.md
new file mode 100644
index 0000000..7414462
--- /dev/null
+++ b/.changeset/confirm-remote-invalidation.md
@@ -0,0 +1,14 @@
+---
+"@leejpsd/nextjs-cache-handler": major
+---
+
+Require confirmed remote marker writes for singular cache invalidation, including
+soft invalidation. Connection failures, reconnect cooldowns, rejected writes and
+deadlines reject the caller instead of reporting successful remote invalidation.
+This intentionally changes the soft-error contract; entry reads/writes and explicit
+local/build-only paths retain their fallback behavior.
+
+Wait for auto-connecting ioredis factories to become ready before admitting the
+client, and clean up listeners on readiness, failure or a bounded wait timeout.
+Expose cluster ACL username, full TLS options, DNS lookup and connection/command/
+discovery limits while preserving ioredis's connection timeout when unspecified.
diff --git a/README.md b/README.md
index 38eeece..640f6c5 100644
--- a/README.md
+++ b/README.md
@@ -227,13 +227,31 @@ interface CacheHandlerOptions {
type RedisClientConfig =
| { type: "redis"; url: string; password?: string; tls?: boolean; connectTimeout?: number }
| { type: "ioredis"; url: string; password?: string; tls?: boolean; connectTimeout?: number }
- | { type: "cluster"; nodes: { host: string; port: number }[]; password?: string; tls?: boolean }
+ | { type: "cluster"; nodes: { host: string; port: number }[];
+ username?: string; password?: string;
+ tls?: boolean | import("node:tls").ConnectionOptions;
+ dnsLookup?: (host: string, callback: (error: NodeJS.ErrnoException | null | undefined,
+ address: string, family?: number) => void) => void;
+ connectTimeout?: number; commandTimeout?: number; slotsRefreshTimeout?: number }
| { type: "sentinel"; sentinels: { host: string; port: number }[]; name: string;
password?: string; sentinelPassword?: string; tls?: boolean; connectTimeout?: number };
```
Full reference: [`docs/api.md`](./docs/api.md).
+Remote singular `revalidateTag` rejects when marker writes are not confirmed,
+including soft invalidation, initial connection failure and retry cooldown.
+Local memory state and logging are not remote acknowledgements. Entry reads and
+writes retain their existing fallback behavior; explicitly local/build-only
+operations remain local. Deadlines stop waiting, without rolling back Redis writes.
+The changeset proposes a major release for this soft-error contract change.
+
+Factories wrapping auto-connecting ioredis clients wait for readiness without
+starting a second connection. Cluster `connectTimeout` is forwarded only when
+specified, preserving the driver's native default. Optional cluster TLS objects,
+ACL username and DNS lookup support verified connections to discovered nodes.
+See [focused regression instructions](./docs/testing-redis-invalidation.md).
+
---
## Production checklist
diff --git a/docs/api.md b/docs/api.md
index 3af74a1..e705738 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 (entry writes) / thrown (remote singular invalidation, hard or soft) |
| `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 |
@@ -58,14 +58,23 @@ ctx contract are accepted (`ctx.cacheControl.revalidate` / `kind` and
```ts
| { type: "redis"; url; password?; tls?; connectTimeout? } // node-redis v5
| { type: "ioredis"; url; password?; tls?; connectTimeout? }
-| { type: "cluster"; nodes: {host, port}[]; password?; tls? } // ioredis Cluster — set hashTag: true
+| { type: "cluster"; nodes: {host, port}[]; username?; password?;
+ tls?: boolean | import("node:tls").ConnectionOptions;
+ dnsLookup?; connectTimeout?; commandTimeout?; slotsRefreshTimeout? }
+ // ioredis Cluster — set hashTag: true
| { type: "sentinel"; sentinels: {host, port}[]; name; // ioredis Sentinel — master discovery + failover
password?; sentinelPassword?; tls?; connectTimeout? }
```
`tls: true` enables TLS explicitly; `rediss://` URLs auto-enable it on the
-`redis` client type. All ioredis-family clients use lazy connect,
-`maxRetriesPerRequest: 1`, and auto-pipelining.
+`redis` client type. Clients constructed from ioredis-family configuration use
+lazy connect and auto-pipelining. A factory can also wrap an auto-connecting
+client with `adaptIoredis` or `adaptCluster`: the adapter waits for `ready`
+without calling `connect()` again. An error or a connection close/end rejects
+the wait. Its budget is the positive configured `connectTimeout`, or 10 seconds
+when absent/disabled; listeners and the timer are removed on every outcome.
+The handler's separate operation deadline still applies and does not cancel a
+connection or command already in progress.
Connection management: a failed connect is retried with exponential backoff
(1s base, doubling, capped at 30s); during the cooldown operations fast-fail
@@ -143,6 +152,29 @@ setups), `meterName`, `counterName`, `histogramName`.
- **`instance-local:` tag prefix** (singular): entries tagged
`instance-local:*` are stored in process memory only and never touch Redis.
- **Error policy**: reads never throw (degrade to miss); writes are
- best-effort; hard tag invalidation (`updateTags` with `expire: 0`, ISR
- `revalidateTag` hard path) propagates errors so callers can retry.
+ best-effort; hard plural tag invalidation (`updateTags` with `expire: 0`) and
+ remote singular `revalidateTag` propagate errors so callers can retry. The singular handler
+ requires confirmed remote marker writes for both soft and hard invalidation,
+ including initial connection failure and reconnect cooldown. Memory markers,
+ logging and a pending retry do not confirm invalidation on other instances.
+ Explicit build/local-only paths remain local. Reads and entry writes keep
+ their existing best-effort/fallback behavior.
- **`CacheTimeoutError`** is exported from the root for `instanceof` checks.
+
+For cluster TLS, `tls: true` keeps the existing defaults. A TLS options object
+allows a custom CA and server identity without disabling certificate checks.
+`username`, `password` and TLS options are passed to every discovered node;
+`dnsLookup` is passed to ioredis Cluster (for example, preserve managed endpoint
+hostnames with `(address, callback) => callback(null, address)`). Static ACL
+credentials are supported; this does not implement IAM credential rotation.
+For cluster clients, `connectTimeout` is only forwarded when configured, retaining
+ioredis's native default (currently 10000ms). The existing single-node/Sentinel
+configuration default remains 1500ms. `commandTimeout` and cluster
+`slotsRefreshTimeout` are optional. Handler deadlines stop waiting, but do not
+cancel an already dispatched Redis operation; a rejected call may have partially
+written markers and callers must treat the result as unconfirmed, not rolled back.
+
+The newly explicit soft-error rejection is an intentional compatibility change;
+the accompanying changeset proposes a major release for maintainer review. It
+does not relax remote confirmation or select a production release. See
+[focused regression instructions](./testing-redis-invalidation.md).
diff --git a/docs/testing-redis-invalidation.md b/docs/testing-redis-invalidation.md
new file mode 100644
index 0000000..d5c66ca
--- /dev/null
+++ b/docs/testing-redis-invalidation.md
@@ -0,0 +1,50 @@
+# Focused invalidation and factory regressions
+
+These tests exercise the unpublished source changes. They do not require a Next.js
+application, private workspace, AWS account or prebuilt project image. Use the
+repository lockfile with a supported Node.js runtime. Install dependencies with
+`npm ci --ignore-scripts` and use the local tools below; no global CLI is required.
+
+## Unit regressions (no service)
+
+```sh
+node node_modules/vitest/vitest.mjs run tests/unit/ioredis-readiness.test.ts tests/unit/client-config.test.ts
+```
+
+The readiness tests cover both public ioredis adapters: already connecting,
+connected-but-not-ready and reconnecting clients; already ready/lazy/ended
+clients; error, close/end, bounded timeout and listener/timer cleanup. The timeout
+configuration tests construct real lazy clients without network I/O and check the
+native cluster default, explicit override and zero value.
+
+## Real auto-connecting factory
+
+Start one **disposable local** Redis-compatible server, for example:
+
+```sh
+docker run --rm --name next-cache-factory-test -p 127.0.0.1:6390:6379 redis:7-alpine redis-server --save "" --appendonly no
+```
+
+Leave it running and execute in another terminal:
+
+```sh
+node node_modules/vitest/vitest.mjs run --config vitest.integration.config.ts tests/integration/ioredis-factory-invalidation.test.ts
+```
+
+The default destination is `redis://127.0.0.1:6390`. The existing
+`INTEGRATION_REDIS_URL` environment variable can select another disposable local
+instance. A healthy control must answer PONG. Each positive case creates a real
+auto-connecting `new Redis()` inside the factory, then confirms concurrent tag
+marker writes for legacy hard, explicit hard and soft invalidation. Only one
+factory instance should be created per handler. The negative uses a reserved and
+released loopback port and must reject without a remote-success metric.
+
+The tests use a random key prefix and delete only their own markers; they do not
+flush the database. They fail if the required fixture is unavailable. Stop the
+dedicated container with `docker stop next-cache-factory-test` after the run.
+Do not point this suite at a production or shared business cache.
+
+These focused tests do not claim managed TLS, cluster failover, durability through
+promotion, IAM rotation, capacity or a complete upstream CI matrix. The separate
+cluster/TLS evidence can accompany a contribution with its exact versions and
+limits. Run additional existing suites only when the changed behavior warrants it.
diff --git a/src/incremental/handler.ts b/src/incremental/handler.ts
index 8ba0dd2..5122bf5 100644
--- a/src/incremental/handler.ts
+++ b/src/incremental/handler.ts
@@ -534,8 +534,7 @@ export class IncrementalRedisCacheHandler {
"incremental.revalidateTag",
this.state.opts.abortTimeoutMs,
async () => {
- const client = await this.state.conn.getOrConnect();
- if (!client) return;
+ const client = await this.state.conn.getOrConnectOrThrow();
await Promise.all(
list.map((t) =>
client.set(tagMetaKey(this.state, t), JSON.stringify(payload), {
@@ -553,8 +552,9 @@ export class IncrementalRedisCacheHandler {
this.state.logger.warn("revalidateTag() failed", {
message: (err as Error).message,
});
- // Hard expirations should propagate so callers know to retry.
- if (payload.expired !== undefined) throw err;
+ // Both hard and soft invalidation require confirmed remote writes.
+ // Local tag state alone cannot invalidate another process's entries.
+ throw err;
}
}
diff --git a/src/shared/client/adapter-ioredis.ts b/src/shared/client/adapter-ioredis.ts
index 61aad87..7bcc557 100644
--- a/src/shared/client/adapter-ioredis.ts
+++ b/src/shared/client/adapter-ioredis.ts
@@ -14,6 +14,44 @@ import { nodeRequire } from "../node-require.js";
type AnyRedis = Redis | Cluster;
+/** Observe an existing attempt without starting another connection. */
+function waitForReady(client: AnyRedis, isClusterClient: boolean): Promise<void> {
+ const configuredTimeout = isClusterClient
+ ? (client as Cluster).options.redisOptions?.connectTimeout
+ : (client as Redis).options.connectTimeout;
+ // A factory may disable the driver's socket timeout. The readiness wait
+ // must still be bounded; handlers also keep their own operation deadline.
+ const timeoutMs = configuredTimeout && configuredTimeout > 0 ? configuredTimeout : 10_000;
+
+ return new Promise<void>((resolve, reject) => {
+ const cleanup = () => {
+ clearTimeout(timer);
+ client.removeListener("ready", onReady);
+ client.removeListener("error", onError);
+ client.removeListener("close", onClose);
+ client.removeListener("end", onClose);
+ };
+ const onReady = () => {
+ cleanup();
+ resolve();
+ };
+ const onError = (error: Error) => {
+ cleanup();
+ reject(error);
+ };
+ const onClose = () => onError(new Error("Redis connection closed before ready"));
+ const timer = setTimeout(
+ () => onError(new Error(`Redis readiness timed out after ${timeoutMs}ms`)),
+ timeoutMs
+ );
+ client.once("ready", onReady);
+ client.once("error", onError);
+ client.once("close", onClose);
+ client.once("end", onClose);
+ if (client.status === "ready") onReady();
+ });
+}
+
function adapt(client: AnyRedis, isClusterClient = false): RedisClientLike {
return {
get isOpen() {
@@ -22,8 +60,11 @@ function adapt(client: AnyRedis, isClusterClient = false): RedisClientLike {
return client.status === "ready";
},
connect: async () => {
- if (client.status !== "ready" && client.status !== "connecting") {
+ if (client.status === "ready") return;
+ if (client.status === "wait" || client.status === "end") {
await client.connect();
+ } else {
+ await waitForReady(client, isClusterClient);
}
},
get: (k) => client.get(k),
@@ -211,9 +252,20 @@ export function createIoredisCluster(
(IORedis.default as unknown as { Cluster: typeof import("ioredis").Cluster })
.Cluster;
return new ClusterCtor(config.nodes, {
+ ...(config.dnsLookup ? { dnsLookup: config.dnsLookup } : {}),
+ ...(config.slotsRefreshTimeout !== undefined
+ ? { slotsRefreshTimeout: config.slotsRefreshTimeout }
+ : {}),
redisOptions: {
+ username: config.username,
password: config.password,
- tls: config.tls ? {} : undefined,
+ tls: config.tls === true ? {} : config.tls || undefined,
+ ...(config.connectTimeout !== undefined
+ ? { connectTimeout: config.connectTimeout }
+ : {}),
+ ...(config.commandTimeout !== undefined
+ ? { commandTimeout: config.commandTimeout }
+ : {}),
},
enableReadyCheck: true,
lazyConnect: true,
diff --git a/src/shared/client/index.ts b/src/shared/client/index.ts
index ec212eb..e5769f7 100644
--- a/src/shared/client/index.ts
+++ b/src/shared/client/index.ts
@@ -78,6 +78,7 @@ export class ConnectionManager {
private connecting: Promise<RedisClientLike | null> | null = null;
private consecutiveFailures = 0;
private lastFailureAt = 0;
+ private lastError: Error | null = null;
private readonly baseCooldownMs: number;
private readonly maxCooldownMs: number;
@@ -108,17 +109,22 @@ export class ConnectionManager {
this.connecting = (async () => {
disposeQuietly(stale);
+ let candidate: RedisClientLike | null = null;
try {
- const c = await buildClient(this.source);
+ const c = (candidate = await buildClient(this.source));
c.on("error", (err) => this.onError(err));
if (!c.isOpen) await c.connect();
+ if (!c.isOpen) throw new Error("Redis client did not become ready");
this.client = c;
this.consecutiveFailures = 0;
+ this.lastError = null;
return c;
} catch (err) {
+ disposeQuietly(candidate);
this.consecutiveFailures += 1;
this.lastFailureAt = Date.now();
- this.onError(err as Error);
+ this.lastError = err instanceof Error ? err : new Error(String(err));
+ this.onError(this.lastError);
return null;
} finally {
this.connecting = null;
@@ -128,12 +134,22 @@ export class ConnectionManager {
return this.connecting;
}
+ /** Mutations must not interpret an unavailable connection as an ACK. */
+ async getOrConnectOrThrow(): Promise<RedisClientLike> {
+ const client = await this.getOrConnect();
+ if (!client) {
+ throw this.lastError ?? new Error("Redis connection is unavailable");
+ }
+ return client;
+ }
+
reset(): void {
disposeQuietly(this.client);
this.client = null;
this.connecting = null;
this.consecutiveFailures = 0;
this.lastFailureAt = 0;
+ this.lastError = null;
}
}
diff --git a/src/types.ts b/src/types.ts
index 8575d76..e298259 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -1,4 +1,5 @@
// Public API types. Exported from `@leejpsd/nextjs-cache-handler`.
+import type { ConnectionOptions as TlsConnectionOptions } from "node:tls";
/**
* Minimal Redis client surface used by both handlers. Adapters in
@@ -82,8 +83,23 @@ export type RedisClientConfig =
| {
type: "cluster";
nodes: Array<{ host: string; port: number }>;
+ /** ACL username, applied to every discovered data node. */
+ username?: string;
password?: string;
- tls?: boolean;
+ /** TLS options (CA, servername, etc.) for every discovered data node. */
+ tls?: boolean | TlsConnectionOptions;
+ /** Preserve hostnames where required by managed TLS endpoints. */
+ dnsLookup?: (
+ hostname: string,
+ callback: (
+ error: NodeJS.ErrnoException | null | undefined,
+ address: string,
+ family?: number
+ ) => void
+ ) => void;
+ connectTimeout?: number;
+ commandTimeout?: number;
+ slotsRefreshTimeout?: number;
}
| {
type: "sentinel";
diff --git a/tests/integration/ioredis-factory-invalidation.test.ts b/tests/integration/ioredis-factory-invalidation.test.ts
new file mode 100644
index 0000000..7b79eaf
--- /dev/null
+++ b/tests/integration/ioredis-factory-invalidation.test.ts
@@ -0,0 +1,103 @@
+/** Run against a disposable local Redis using the existing integration config. */
+import { randomUUID } from "node:crypto";
+import { createServer } from "node:net";
+
+import Redis from "ioredis";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+
+import { createIncrementalCacheHandler } from "../../src/incremental/index.js";
+import { adaptIoredis } from "../../src/shared/client/adapter-ioredis.js";
+
+import { getRedisUrl } from "./_redis-helpers.js";
+
+describe("auto-connecting ioredis factory invalidation", () => {
+ const prefix = `factory-regression:${randomUUID()}:`;
+ const clients: Redis[] = [];
+ const keys: string[] = [];
+ let control: Redis;
+
+ beforeAll(async () => {
+ control = new Redis(getRedisUrl(), { lazyConnect: true, retryStrategy: () => null });
+ control.on("error", () => {});
+ await control.connect();
+ expect(await control.ping()).toBe("PONG");
+ });
+ afterEach(async () => {
+ for (const client of clients.splice(0)) client.disconnect();
+ if (keys.length) await control.del(...keys.splice(0));
+ });
+ afterAll(() => control?.disconnect());
+
+ it.each([undefined, { expire: 0 }, {}])(
+ "waits for the factory's initial connection and confirms both writes (%j)",
+ async (durations) => {
+ let creations = 0;
+ const Handler = createIncrementalCacheHandler({
+ client: () => {
+ const client = new Redis(getRedisUrl(), { retryStrategy: () => null });
+ client.on("error", () => {});
+ clients.push(client);
+ creations++;
+ return adaptIoredis(client);
+ },
+ keyPrefix: prefix,
+ buildNamespace: "test",
+ fallback: "never",
+ isBuildPhase: () => false,
+ abortTimeoutMs: 3000,
+ });
+ const handler = new Handler();
+ const tags = [randomUUID(), randomUUID()];
+ keys.push(...tags.map((tag) => `${prefix}tag:${tag}`));
+ await Promise.all(tags.map((tag) => handler.revalidateTag(tag, durations)));
+ expect(creations).toBe(1);
+ for (const key of keys) {
+ const marker = JSON.parse((await control.get(key))!);
+ if (durations && durations.expire === undefined) {
+ expect(marker.stale).toBeTypeOf("number");
+ expect(marker.expired).toBeUndefined();
+ } else {
+ expect(marker.expired).toBeTypeOf("number");
+ }
+ }
+ }
+ );
+
+ it("rejects a failed auto-connection without reporting a remote acknowledgement", async () => {
+ // Reserve/release a loopback port; never aim the negative at another service.
+ const reserved = createServer();
+ await new Promise<void>((resolve, reject) => {
+ reserved.once("error", reject);
+ reserved.listen(0, "127.0.0.1", resolve);
+ });
+ const address = reserved.address();
+ if (!address || typeof address === "string") throw new Error("Expected loopback port");
+ await new Promise<void>((resolve, reject) =>
+ reserved.close((e) => (e ? reject(e) : resolve()))
+ );
+ const metrics: string[] = [];
+ const Handler = createIncrementalCacheHandler({
+ client: () => {
+ const client = new Redis({
+ host: "127.0.0.1",
+ port: address.port,
+ retryStrategy: () => null,
+ });
+ client.on("error", () => {});
+ clients.push(client);
+ return adaptIoredis(client);
+ },
+ keyPrefix: prefix,
+ fallback: "never",
+ isBuildPhase: () => false,
+ abortTimeoutMs: 3000,
+ onMetric: (event) => {
+ if (event.type.startsWith("tag.invalidate") && event.meta?.backend === "redis") {
+ metrics.push(event.type);
+ }
+ },
+ });
+ await expect(new Handler().revalidateTag("unavailable", { expire: 0 })).rejects.toThrow();
+ expect(metrics).toEqual([]);
+ });
+});
diff --git a/tests/unit/client-config.test.ts b/tests/unit/client-config.test.ts
index 603cf28..842fd8c 100644
--- a/tests/unit/client-config.test.ts
+++ b/tests/unit/client-config.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
+import Redis from "ioredis";
import {
createIoredisClient,
@@ -10,6 +11,28 @@ import { buildClient } from "../../src/shared/client/index.js";
// These construct real ioredis instances with lazyConnect: true — no network
// I/O happens until connect() is called, which these tests never do.
+describe("cluster connection timeout compatibility", () => {
+ it.each([undefined, 2500, 0])(
+ "preserves the native default or explicit value (%s)",
+ (timeout) => {
+ const cluster = createIoredisCluster({
+ type: "cluster",
+ nodes: [{ host: "127.0.0.1", port: 7000 }],
+ ...(timeout !== undefined ? { connectTimeout: timeout } : {}),
+ });
+ const node = new Redis({ ...cluster.options.redisOptions, lazyConnect: true });
+ const native = new Redis({ lazyConnect: true });
+ try {
+ expect(node.options.connectTimeout).toBe(timeout ?? native.options.connectTimeout);
+ } finally {
+ node.disconnect();
+ native.disconnect();
+ cluster.disconnect();
+ }
+ }
+ );
+});
+
describe("client factories — Sentinel", () => {
it("createIoredisSentinel passes sentinel endpoints and master name through", () => {
const client = createIoredisSentinel({
diff --git a/tests/unit/connection.test.ts b/tests/unit/connection.test.ts
index 1fbc673..c14b469 100644
--- a/tests/unit/connection.test.ts
+++ b/tests/unit/connection.test.ts
@@ -128,6 +128,21 @@ describe("ConnectionManager — retry after connect failure (no permanent latch)
});
describe("ConnectionManager — dropped-connection replacement", () => {
+ it("disposes a failed candidate before retrying with a fresh client", async () => {
+ const failed = makeFakeClient();
+ const error = new Error("authentication rejected");
+ failed.connect = async () => { throw error; };
+ const good = makeFakeClient();
+ const factory = vi.fn<() => RedisClientLike>()
+ .mockReturnValueOnce(failed).mockReturnValue(good);
+ const mgr = new ConnectionManager(factory, () => {}, RETRY);
+ await expect(mgr.getOrConnectOrThrow()).rejects.toBe(error);
+ expect(failed.disposeCalls).toBe(1);
+ await expect(mgr.getOrConnectOrThrow()).rejects.toBe(error);
+ vi.advanceTimersByTime(101);
+ expect(await mgr.getOrConnectOrThrow()).toBe(good);
+ });
+
it("builds a fresh client immediately when the current one is no longer open, and disposes the dead one", async () => {
const first = makeFakeClient();
const second = makeFakeClient();
diff --git a/tests/unit/incremental.test.ts b/tests/unit/incremental.test.ts
index fc53096..6091942 100644
--- a/tests/unit/incremental.test.ts
+++ b/tests/unit/incremental.test.ts
@@ -33,6 +33,40 @@ function setup() {
return { Handler, client };
}
+describe("incremental invalidation requires remote confirmation", () => {
+ it.each([undefined, { expire: 0 }, {}])(
+ "rejects a failed connect and cooldown, then permits a confirmed retry (%j)",
+ async (durations) => {
+ const client = new MockRedisClient();
+ const error = new Error("authentication rejected");
+ vi.spyOn(client, "connect").mockRejectedValueOnce(error);
+ const Handler = createIncrementalCacheHandler({
+ client: () => client,
+ fallback: "never",
+ isBuildPhase: () => false,
+ });
+ const h = new Handler();
+ await expect(h.revalidateTag("posts", durations)).rejects.toBe(error);
+ await expect(h.revalidateTag("posts", durations)).rejects.toBe(error);
+ expect(await h.get("/missing")).toBeNull();
+ vi.advanceTimersByTime(1001);
+ await expect(h.revalidateTag("posts", durations)).resolves.toBeUndefined();
+ }
+ );
+
+ it.each([undefined, { expire: 0 }, {}])(
+ "rejects a failed marker write and permits a confirmed retry (%j)",
+ async (durations) => {
+ const { Handler, client } = setup();
+ const error = new Error("marker write rejected");
+ vi.spyOn(client, "set").mockRejectedValueOnce(error);
+ const h = new Handler();
+ await expect(h.revalidateTag("posts", durations)).rejects.toBe(error);
+ await expect(h.revalidateTag("posts", durations)).resolves.toBeUndefined();
+ }
+ );
+});
+
describe("incremental cacheHandler — basic ISR round-trip", () => {
it("set then get returns the stored record", async () => {
const { Handler } = setup();
diff --git a/tests/unit/ioredis-readiness.test.ts b/tests/unit/ioredis-readiness.test.ts
new file mode 100644
index 0000000..9b24577
--- /dev/null
+++ b/tests/unit/ioredis-readiness.test.ts
@@ -0,0 +1,102 @@
+import { EventEmitter } from "node:events";
+
+import type { Cluster, Redis } from "ioredis";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { adaptCluster, adaptIoredis } from "../../src/shared/client/adapter-ioredis.js";
+
+// Exercise the public adapter's event contract without opening sockets.
+class StartingClient extends EventEmitter {
+ status = "connecting";
+ options = { connectTimeout: 50, redisOptions: { connectTimeout: 50 } };
+ connect = vi.fn(async () => {
+ this.status = "ready";
+ });
+}
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => vi.useRealTimers());
+
+describe.each(["redis", "cluster"] as const)("ioredis readiness — %s", (kind) => {
+ function setup() {
+ const raw = new StartingClient();
+ const client =
+ kind === "cluster"
+ ? adaptCluster(raw as unknown as Cluster)
+ : adaptIoredis(raw as unknown as Redis);
+ return { raw, client };
+ }
+
+ function expectClean(raw: StartingClient) {
+ expect(raw.eventNames()).toEqual([]);
+ expect(vi.getTimerCount()).toBe(0);
+ }
+
+ it.each(["connecting", "connect", "reconnecting"])(
+ "waits for ready from %s without starting a parallel connect",
+ async (status) => {
+ const { raw, client } = setup();
+ raw.status = status;
+ const pending = client.connect();
+ expect(raw.connect).not.toHaveBeenCalled();
+ expect(client.isOpen).toBe(false);
+ raw.status = "ready";
+ raw.emit("ready");
+ await pending;
+ expect(client.isOpen).toBe(true);
+ expectClean(raw);
+ }
+ );
+
+ it.each(["wait", "end"])("starts a new connection from %s", async (status) => {
+ const { raw, client } = setup();
+ raw.status = status;
+ await client.connect();
+ expect(raw.connect).toHaveBeenCalledTimes(1);
+ expect(client.isOpen).toBe(true);
+ expectClean(raw);
+ });
+
+ it("does nothing when already ready", async () => {
+ const { raw, client } = setup();
+ raw.status = "ready";
+ await client.connect();
+ expect(raw.connect).not.toHaveBeenCalled();
+ expectClean(raw);
+ });
+
+ it("preserves the connection error and removes its listeners", async () => {
+ const { raw, client } = setup();
+ const error = new Error("authentication rejected");
+ const rejected = expect(client.connect()).rejects.toBe(error);
+ raw.emit("error", error);
+ await rejected;
+ expectClean(raw);
+ });
+
+ it.each(["close", "end"])("rejects on %s before ready", async (event) => {
+ const { raw, client } = setup();
+ const rejected = expect(client.connect()).rejects.toThrow("closed before ready");
+ raw.emit(event);
+ await rejected;
+ expectClean(raw);
+ });
+
+ it("bounds an attempt which never becomes ready", async () => {
+ const { raw, client } = setup();
+ const rejected = expect(client.connect()).rejects.toThrow("readiness timed out after 50ms");
+ await vi.advanceTimersByTimeAsync(50);
+ await rejected;
+ expectClean(raw);
+ });
+
+ it("retains a finite readiness budget when socket timeouts are disabled", async () => {
+ const { raw, client } = setup();
+ raw.options.connectTimeout = 0;
+ raw.options.redisOptions.connectTimeout = 0;
+ const rejected = expect(client.connect()).rejects.toThrow("readiness timed out after 10000ms");
+ await vi.advanceTimersByTimeAsync(10_000);
+ await rejected;
+ expectClean(raw);
+ });
+});
Activity
leejpsd commentedon Nov 13, 2026
Sorry for the three-week silence on this, and thank you for the careful report. You were right, and I could reproduce it on 1.0.2: with no connection,
getOrConnect()returnsnull,revalidateTagreturns normally and atag.invalidate.*metric withbackend: "redis"is emitted although nothing was written. A failed or timed-out write already rejected, so only the no-connection path was silent. That also contradicteddocs/api.md.Fixed in #23 and released in 1.0.3. The no-connection case now goes through the same path as a failed write: it rejects, no success metric is emitted, and the local stamp is still applied first so the calling process is invalidated.
On your questions:
revalidateTagwith anexpire(so'max'too) when the write failed, which is why I treated this as a bug fix rather than a contract change. Durations without anexpirestay best-effort.dnsLookup, limits) are separate changes. If you still want them, one PR each would be easiest to review. I have not reviewed those parts of your patch yet.One thing I measured on Next.js 16.4.6 that may matter for your setup: Next only awaits the handler for
updateTag()in a Server Action, where the request now fails with a 500 during an outage. ForrevalidateTag(tag, 'max'), in a Server Action or a Route Handler, Next runs the handler after the response, so the rejection shows up in the server log but not in the HTTP status.I verified the fix against a single Redis that I stopped mid-run, not against a TLS cluster with failing auth like yours. If 1.0.3 still resolves in your cluster setup, please tell me.