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

Locking timeout #24

Open
wants to merge 5 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
20 changes: 20 additions & 0 deletions errors.js
@@ -0,0 +1,20 @@
'use strict';

class AbortError extends Error {
constructor(message) {
super(message);
this.name = 'AbortError';
}
}

class TimeoutError extends Error {
constructor(message) {
super(message);
this.name = 'TimeoutError';
}
}

module.exports = {
AbortError,
TimeoutError,
};
1 change: 1 addition & 0 deletions test.js
Expand Up @@ -8,6 +8,7 @@ const tests = [
'deadlock',
'recursive-deadlock',
'thread-main',
'lock-time',
];

(async () => {
Expand Down
48 changes: 48 additions & 0 deletions test/lock-time.js
@@ -0,0 +1,48 @@
'use strict';

const assert = require('assert').strict;
const { locks } = require('..');
const { sleep } = require('./test-utils.js');
const { TimeoutError } = require('../errors.js');

module.exports = async () => {
await (async () => {
const caseName = 'Should release a resource after timeout deadline';
const startTs = Date.now();

await locks
.request('LockTime', { timeout: 100 }, async () => {
await sleep(200);
})
.catch(() => {});

const isCaseSuccess = Date.now() - startTs < 200;
assert.strictEqual(isCaseSuccess, true, caseName);
})();

await (async () => {
const caseName = 'Should release a resource and throw the TimeoutError';
let error;

await locks
.request('LockTime', { timeout: 100 }, async () => {
await sleep(200);
})
.catch(err => (error = err));

const isCaseSuccess = error instanceof TimeoutError;
assert.strictEqual(isCaseSuccess, true, caseName);
})();

await (async () => {
const caseName = 'Should release a resource after handler complete a task';
const startTs = Date.now();

await locks.request('LockTime', { timeout: 200 }, async () => {
await sleep(100);
});

const isCaseSuccess = Date.now() - startTs < 200;
assert.strictEqual(isCaseSuccess, true, caseName);
})();
};
8 changes: 1 addition & 7 deletions test/steps.js
Expand Up @@ -2,13 +2,7 @@

const assert = require('assert').strict;
const { locks } = require('..');

const sleep = msec =>
new Promise(resolve => {
setTimeout(() => {
resolve();
}, msec);
});
const { sleep } = require('./test-utils.js');

let counter = 0;

Expand Down
10 changes: 10 additions & 0 deletions test/test-utils.js
@@ -0,0 +1,10 @@
'use strict';

const sleep = msec =>
new Promise(resolve => {
setTimeout(resolve, msec);
});

module.exports = {
sleep,
};
6 changes: 1 addition & 5 deletions test/thread-worker.js
@@ -1,14 +1,10 @@
'use strict';

const threads = require('worker_threads');
const { sleep } = require('./test-utils.js');

const { locks } = require('..');

const sleep = msec =>
new Promise(resolve => {
setTimeout(resolve, msec);
});

(async () => {
if (threads.threadId === 2) {
await sleep(10);
Expand Down
51 changes: 26 additions & 25 deletions web-locks.js
Expand Up @@ -2,6 +2,7 @@

const { EventEmitter } = require('events');
const threads = require('worker_threads');
const { AbortError, TimeoutError } = require('./errors');
const { isMainThread, parentPort } = threads;
const isWorkerThread = !isMainThread;

Expand All @@ -22,9 +23,9 @@ class Lock {
if (!buffer) Atomics.store(this.flag, 0, UNLOCKED);
}

enter(handler) {
return new Promise(resolve => {
this.queue.push({ handler, resolve });
enter(handler, timeout, signal) {
return new Promise((resolve, reject) => {
this.queue.push({ handler, resolve, reject, timeout, signal });
this.trying = true;
setTimeout(() => {
this.tryEnter();
Expand All @@ -38,11 +39,25 @@ class Lock {
if (prev === LOCKED) return;
this.owner = true;
this.trying = false;
const { handler, resolve } = this.queue.shift();
handler(this).finally(() => {
let timer;

const { handler, resolve, reject, timeout, signal } = this.queue.shift();

const finalize = error => {
this.leave();
resolve();
});
if (timer !== undefined) {
clearTimeout(timer);
timer = undefined;
}
if (error) reject(error);
else resolve();
};

if (signal) signal.on('abort', finalize);
if (timeout)
timer = setTimeout(finalize, timeout, new TimeoutError('Time Out'));
Comment on lines +57 to +58
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
if (timeout)
timer = setTimeout(finalize, timeout, new TimeoutError('Time Out'));
if (timeout) {
timer = setTimeout(finalize, timeout, new TimeoutError('Time Out'));
}


handler(this).finally(finalize);
}

leave() {
Expand Down Expand Up @@ -89,7 +104,7 @@ class LockManager {
handler = options;
options = {};
}
const { mode = 'exclusive', signal = null } = options;
const { mode = 'exclusive', signal = null, timeout } = options;

let lock = this.collection.get(name);
if (!lock) {
Expand All @@ -100,16 +115,9 @@ class LockManager {
locks.send(message);
}

const finished = lock.enter(handler);
let aborted = null;
if (signal) {
aborted = new Promise((resolve, reject) => {
signal.on('abort', reject);
});
await Promise.race([finished, aborted]);
} else {
await finished;
}
const finished = lock.enter(handler, timeout, signal);

await finished;

setTimeout(() => {
lock.tryEnter();
Expand Down Expand Up @@ -163,13 +171,6 @@ class LockManager {
}
}

class AbortError extends Error {
constructor(message) {
super(message);
this.name = 'AbortError';
}
}

class AbortSignal extends EventEmitter {
constructor() {
super();
Expand Down