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

docs(pattern): add timeout section #2281

Open
wants to merge 3 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/gitbook/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
* [Process Step Jobs](patterns/process-step-jobs.md)
* [Failing fast when Redis is down](patterns/failing-fast-when-redis-is-down.md)
* [Stop retrying jobs](patterns/stop-retrying-jobs.md)
* [Timeout](patterns/timeout.md)
* [Redis Cluster](patterns/redis-cluster.md)

## BullMQ Pro
Expand Down
73 changes: 73 additions & 0 deletions docs/gitbook/patterns/timeout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Timeout

Sometimes, it is useful to timeout a processor function but you should be aware that async processes are not going to be cancelled immediately, even if you timeout a process, you need to validate that your process is in a cancelled state:

```typescript
import { AbortController } from 'node-abort-controller';

enum Step {
Initial,
Second,
Finish,
}

const worker = new Worker(
'queueName',
async job => {
let { step, timeout } = job.data;

const abortController = new AbortController();

const timeoutCall = setTimeout(() => {
abortController.abort();
}, timeout);
abortController.signal.addEventListener(
'abort',
() => clearTimeout(timeoutCall),
{ once: true },
);
while (step !== Step.Finish) {
switch (step) {
case Step.Initial: {
if (abortController.signal.aborted) {
throw new Error('Timeout');
}
await doInitialStepStuff(1000);
await job.updateData({
step: Step.Second,
timeout,
});
step = Step.Second;
break;
}
case Step.Second: {
await doSecondStepStuff();
if (abortController.signal.aborted) {
throw new Error('Timeout');
}
await job.updateData({
step: Step.Finish,
timeout,
});
step = Step.Finish;
return Step.Finish;
}
default: {
throw new Error('invalid step');
}
}
abortController.abort();
}
},
{ connection },
);
```

{% hint style="info" %}
It's better to split a long process into little functions/steps to be able to stop an execution by validating if we reach the timeout in each transition using an AbortController instance.
{% endhint %}

## Read more:

- 📋 [Process Step jobs](./process-step-jobs.md)
- 📋 [Cancellation by using Observables](../bullmq-pro/observables/cancelation.md)
3 changes: 1 addition & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,11 @@ export function delay(
return new Promise(resolve => {
let timeout: ReturnType<typeof setTimeout> | undefined;
const callback = () => {
abortController?.signal.removeEventListener('abort', callback);
clearTimeout(timeout);
resolve();
};
timeout = setTimeout(callback, ms);
abortController?.signal.addEventListener('abort', callback);
abortController?.signal.addEventListener('abort', callback, { once: true });
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

});
}

Expand Down
107 changes: 107 additions & 0 deletions tests/test_worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { expect } from 'chai';
import { default as IORedis } from 'ioredis';
import { after, times } from 'lodash';
import { describe, beforeEach, it, before, after as afterAll } from 'mocha';
import { AbortController } from 'node-abort-controller';
import * as sinon from 'sinon';
import { v4 } from 'uuid';
import {
Expand Down Expand Up @@ -3425,6 +3426,112 @@ describe('workers', function () {
});
});

describe('when using timeout pattern', () => {
it('should stop processing until checking aborted signal', async function () {
this.timeout(8000);

enum Step {
Initial,
Second,
Finish,
}

const worker = new Worker(
queueName,
async job => {
let { step, timeout } = job.data;
const abortController = new AbortController();

const timeoutCall = setTimeout(() => {
abortController.abort();
}, timeout);
abortController.signal.addEventListener(
'abort',
() => clearTimeout(timeoutCall),
{ once: true },
);
while (step !== Step.Finish) {
switch (step) {
case Step.Initial: {
if (abortController.signal.aborted) {
throw new Error('Timeout');
}
await delay(1000);
await job.updateData({
step: Step.Second,
timeout,
});
step = Step.Second;
break;
}
case Step.Second: {
if (abortController.signal.aborted) {
throw new Error('Timeout');
}
await delay(1000);
await job.updateData({
step: Step.Finish,
timeout,
});
step = Step.Finish;
return Step.Finish;
}
default: {
throw new Error('invalid step');
}
}
}
abortController.abort();
},
{ connection, prefix },
);

await worker.waitUntilReady();

let start = Date.now();
await queue.add('test', { step: Step.Initial, timeout: 3000 });

await new Promise<void>(resolve => {
worker.once('completed', job => {
const elapse = Date.now() - start;
expect(job?.data.step).to.be.equal(Step.Finish);
expect(elapse).to.be.greaterThan(2000);
expect(elapse).to.be.lessThan(2500);
resolve();
});
});

start = Date.now();
await queue.add('test', { step: Step.Initial, timeout: 1500 });

await new Promise<void>(resolve => {
worker.once('completed', job => {
const elapse = Date.now() - start;
expect(job?.data.step).to.be.equal(Step.Finish);
expect(elapse).to.be.greaterThan(2000);
expect(elapse).to.be.lessThan(2500);
resolve();
});
});

start = Date.now();
await queue.add('test', { step: Step.Initial, timeout: 500 });

await new Promise<void>(resolve => {
worker.once('failed', (job, error) => {
const elapse = Date.now() - start;
expect(job?.data.step).to.be.equal(Step.Second);
expect(error.message).to.be.equal('Timeout');
expect(elapse).to.be.greaterThan(1000);
expect(elapse).to.be.lessThan(1500);
resolve();
});
});

await worker.close();
});
});

it('should not retry a job if the custom backoff returns -1', async () => {
let tries = 0;

Expand Down