Skip to content
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

Handle unhandled errors in socket.reconnectStrategry #2226

Merged
merged 7 commits into from
Aug 22, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
56 changes: 39 additions & 17 deletions packages/client/lib/client/socket.spec.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,63 @@
import { strict as assert } from 'assert';
import { SinonFakeTimers, useFakeTimers, spy } from 'sinon';
import RedisSocket from './socket';
import RedisSocket, { RedisSocketOptions } from './socket';

describe('Socket', () => {
function createSocket(options: RedisSocketOptions): RedisSocket {
const socket = new RedisSocket(
() => Promise.resolve(),
options
);

socket.on('error', (err) => {
// ignore errors
console.log(err);
});

return socket;
}

describe('reconnectStrategy', () => {
let clock: SinonFakeTimers;
beforeEach(() => clock = useFakeTimers());
afterEach(() => clock.restore());

it('custom strategy', () => {
const reconnectStrategy = spy((retries: number): number | Error => {
it('custom strategy', async () => {
const reconnectStrategy = spy((retries: number) => {
assert.equal(retries + 1, reconnectStrategy.callCount);

if (retries === 50) {
return Error('50');
}
if (retries === 50) return new Error('50');

const time = retries * 2;
queueMicrotask(() => clock.tick(time));
return time;
});

const socket = new RedisSocket(
() => Promise.resolve(),
{
host: 'error',
reconnectStrategy
}
);

socket.on('error', () => {
// ignore errors
const socket = createSocket({
host: 'error',
reconnectStrategy
});

return assert.rejects(socket.connect(), {
await assert.rejects(socket.connect(), {
message: '50'
});

assert.equal(socket.isOpen, false);
});

it('should handle errors', async () => {
const socket = createSocket({
host: 'error',
reconnectStrategy(retries: number) {
if (retries === 1) return new Error('done');
queueMicrotask(() => clock.tick(500));
throw new Error();
}
});

await assert.rejects(socket.connect());

assert.equal(socket.isOpen, false);
});
});
});
27 changes: 21 additions & 6 deletions packages/client/lib/client/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import { RedisCommandArguments } from '../commands';
import { ConnectionTimeoutError, ClientClosedError, SocketClosedUnexpectedlyError, ReconnectStrategyError } from '../errors';
import { promiseTimeout } from '../utils';

type ReconnectStrategy = (retires: number) => number | Error;
leibale marked this conversation as resolved.
Show resolved Hide resolved

export interface RedisSocketCommonOptions {
connectTimeout?: number;
noDelay?: boolean;
keepAlive?: number | false;
reconnectStrategy?(retries: number): number | Error;
reconnectStrategy?: ReconnectStrategy;
}

type RedisNetSocketOptions = Partial<net.SocketConnectOpts> & {
Expand Down Expand Up @@ -44,10 +46,6 @@ export default class RedisSocket extends EventEmitter {
return options;
}

static #defaultReconnectStrategy(retries: number): number {
return Math.min(retries * 50, 500);
}

static #isTlsSocket(options: RedisSocketOptions): options is RedisTlsSocketOptions {
return (options as RedisTlsSocketOptions).tls === true;
}
Expand Down Expand Up @@ -87,6 +85,23 @@ export default class RedisSocket extends EventEmitter {
this.#options = RedisSocket.#initiateOptions(options);
}

reconnectStrategy(retries: number): number | Error {
if (this.#options.reconnectStrategy) {
try {
const retryIn = this.#options.reconnectStrategy(retries);
if (typeof retryIn !== 'number' && !(retryIn instanceof Error)) {
throw new TypeError('Reconnect strategy should return `number | Error`');
}

return retryIn;
} catch (err) {
this.emit('error', err);
}
}

return Math.min(retries * 50, 500);
}

async connect(): Promise<void> {
if (this.#isOpen) {
throw new Error('Socket already opened');
Expand Down Expand Up @@ -118,7 +133,7 @@ export default class RedisSocket extends EventEmitter {
} catch (err) {
this.emit('error', err);

const retryIn = (this.#options?.reconnectStrategy ?? RedisSocket.#defaultReconnectStrategy)(retries);
const retryIn = this.reconnectStrategy(retries);
if (retryIn instanceof Error) {
this.#isOpen = false;
throw new ReconnectStrategyError(retryIn, err);
Expand Down