Skip to content

feat: Add command timeout #2981

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions docs/client-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
| legacyMode | `false` | Maintain some backwards compatibility (see the [Migration Guide](./v3-to-v4.md)) |
| isolationPoolOptions | | See the [Isolated Execution Guide](./isolated-execution.md) |
| pingInterval | | Send `PING` command at interval (in ms). Useful with ["Azure Cache for Redis"](https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-best-practices-connection#idle-timeout) |
| commandTimeout | | Throw an error and abort a command if it takes longer than the specified time (in milliseconds). |

## Reconnect Strategy

Expand Down
18 changes: 17 additions & 1 deletion packages/client/lib/client/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { strict as assert } from 'node:assert';
import testUtils, { GLOBAL, waitTillBeenCalled } from '../test-utils';
import RedisClient, { RedisClientOptions, RedisClientType } from '.';
import { AbortError, ClientClosedError, ClientOfflineError, ConnectionTimeoutError, DisconnectsClientError, ErrorReply, MultiErrorReply, SocketClosedUnexpectedlyError, WatchError } from '../errors';
import { AbortError, ClientClosedError, ClientOfflineError, ConnectionTimeoutError, CommandTimeoutError, DisconnectsClientError, ErrorReply, MultiErrorReply, SocketClosedUnexpectedlyError, WatchError } from '../errors';
import { defineScript } from '../lua-script';
import { spy } from 'sinon';
import { once } from 'node:events';
Expand Down Expand Up @@ -231,6 +231,22 @@ describe('Client', () => {
}, GLOBAL.SERVERS.OPEN);
});

testUtils.testWithClient('CommandTimeoutError', async client => {
const promise = assert.rejects(client.sendCommand(['PING']), CommandTimeoutError),
start = process.hrtime.bigint();

while (process.hrtime.bigint() - start < 50_000_000) {
// block the event loop for 1ms, to make sure the connection will timeout
}

await promise;
}, {
...GLOBAL.SERVERS.OPEN,
clientOptions: {
commandTimeout: 50,
}
});

testUtils.testWithClient('undefined and null should not break the client', async client => {
await assert.rejects(
client.sendCommand([null as any, undefined as any]),
Expand Down
33 changes: 31 additions & 2 deletions packages/client/lib/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { BasicAuth, CredentialsError, CredentialsProvider, StreamingCredentialsP
import RedisCommandsQueue, { CommandOptions } from './commands-queue';
import { EventEmitter } from 'node:events';
import { attachConfig, functionArgumentsPrefix, getTransformReply, scriptArgumentsPrefix } from '../commander';
import { ClientClosedError, ClientOfflineError, DisconnectsClientError, WatchError } from '../errors';
import { ClientClosedError, ClientOfflineError, CommandTimeoutError, DisconnectsClientError, WatchError } from '../errors';
import { URL } from 'node:url';
import { TcpSocketConnectOpts } from 'node:net';
import { PUBSUB_TYPE, PubSubType, PubSubListener, PubSubTypeListeners, ChannelListeners } from './pub-sub';
Expand Down Expand Up @@ -80,6 +80,10 @@ export interface RedisClientOptions<
* TODO
*/
commandOptions?: CommandOptions<TYPE_MAPPING>;
/**
* Provides a timeout in milliseconds.
*/
commandTimeout?: number;
}

type WithCommands<
Expand Down Expand Up @@ -730,9 +734,34 @@ export default class RedisClient<
return Promise.reject(new ClientOfflineError());
}

let controller: AbortController;
if (this._self.#options?.commandTimeout) {
controller = new AbortController()
options = {
...options,
abortSignal: controller.signal
}
}
const promise = this._self.#queue.addCommand<T>(args, options);

this._self.#scheduleWrite();
return promise;
if (!this._self.#options?.commandTimeout) {
return promise;
}

return new Promise<T>((resolve, reject) => {
const timeoutId = setTimeout(() => {
controller.abort();
reject(new CommandTimeoutError());
}, this._self.#options?.commandTimeout)
promise.then(result => {
clearInterval(timeoutId);
resolve(result)
}).catch(error => {
clearInterval(timeoutId);
reject(error)
});
})
}

async SELECT(db: number): Promise<void> {
Expand Down
6 changes: 6 additions & 0 deletions packages/client/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ export class ConnectionTimeoutError extends Error {
}
}

export class CommandTimeoutError extends Error {
constructor() {
super('Command timeout');
}
}

export class ClientClosedError extends Error {
constructor() {
super('The client is closed');
Expand Down