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

Fix SharedService clientId locking with multiple services. #107

Merged
merged 1 commit into from
Jul 31, 2023
Merged
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
22 changes: 16 additions & 6 deletions demo/SharedService-sw/SharedService.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,11 @@ export class SharedService extends EventTarget {

// Acquire a Web Lock named after the clientId. This lets other contexts
// track this context's lifetime.
await new Promise(resolve => {
navigator.locks.request(clientId, () => new Promise(releaseLock => {
resolve();
this.#onClose.signal.addEventListener('abort', releaseLock);
}));
});
// TODO: It would be better to lock on the clientId+serviceName (passing
// that lock name in the service request). That would allow independent
// instance lifetime tracking.
await SharedService.#acquireContextLock(clientId);

return clientId;
}

Expand Down Expand Up @@ -250,6 +249,17 @@ export class SharedService extends EventTarget {
}
});
}

static #acquireContextLock = (function() {
let p;
return function(clientId) {
return p ? p : p = new Promise(resolve => {
navigator.locks.request(clientId, () => new Promise(_ => {
resolve();
}));
});
}
})();
}

/**
Expand Down
21 changes: 15 additions & 6 deletions demo/SharedService/SharedService.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,10 @@ export class SharedService extends EventTarget {

// Acquire a Web Lock named after the clientId. This lets other contexts
// track this context's lifetime.
await new Promise(resolve => {
navigator.locks.request(clientId, () => new Promise(releaseLock => {
resolve();
this.#onClose.signal.addEventListener('abort', releaseLock);
}));
});
// TODO: It would be better to lock on the clientId+serviceName (passing
// that lock name in the service request). That would allow independent
// instance lifetime tracking.
await SharedService.#acquireContextLock(clientId);

// Configure message forwarding via the SharedWorker. This must be
// done after acquiring the clientId lock to avoid a race condition
Expand Down Expand Up @@ -248,6 +246,17 @@ export class SharedService extends EventTarget {
}
});
}

static #acquireContextLock = (function() {
let p;
return function(clientId) {
return p ? p : p = new Promise(resolve => {
navigator.locks.request(clientId, () => new Promise(_ => {
resolve();
}));
});
}
})();
}

/**
Expand Down