Event for worker termination
The AbstractWorker mixin provides an onerror prop to get notified when the worker throws. However, graceful or forced termination is not detectable right now.
I have found a bunch of situations where I’d like to be notified when a worker is being terminated. In my head, all of these are desired sources for this notification:
DedicatedWorkerGlobalScope.close()SharedWorkerGlobalScope.close()Worker.terminate()- graceful termination (i.e. script ends with no listeners active)
- exceptions
Proposal: Expose an onterminate prop (and/or terminate event) to AbstractWorker.
I could swear we already had an issue for this, but the closest I can find is #1766 and #1885.
#1607, #5323, #5362, and #5363 are also somewhat related.
@hiroshige-g may be interested.
My interest is test-only (to write a couple of worker termination WPTs). cc/ @nhiroki for implementation perspective.
There is interest from Deno users on this topic. Node also implements a similar close event for worker_threads.
I'm supportive of this proposal if there are valid use cases in real applications. This will also help us to write more solid WPTs as @hiroshige-g mentioned.
I'm curious how this event should behave on close of the owner context, that is, unload of the parent document or termination of the parent worker. Do we want to guarantee that the event is always fired before the context close? IMHO I think we shouldn't guarantee that as it will degrade navigation performance. On the other hand, this will impair the reliability of the event and may not satisfy some of the use cases.
I'm curious how this event should behave on close of the owner context, that is, unload of the parent document or termination of the parent worker. Do we want to guarantee that the event is always fired before the context close? IMHO I think we shouldn't guarantee that as it will degrade navigation performance. On the other hand, this will impair the reliability of the event and may not satisfy some of the use cases.
A worker doesn't survive for long if its parent document has closed; see the "closing orphan workers" step in the worker event loop. And while the behavior of nested dedicated workers when their dedicated worker parent dies is not very clear in the spec, implementations also don't keep the nested worker alive for long (see #7840). So it doesn't seem like this is worth worrying about too much.
@andreubotella What about shared workers? There could be several windows referencing same worker.