Skip to content

Commit

Permalink
Fix SharedService clientId locking with multiple services.
Browse files Browse the repository at this point in the history
  • Loading branch information
shoestringresearch committed Jul 31, 2023
1 parent b58e81d commit 8be5af2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
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

0 comments on commit 8be5af2

Please sign in to comment.