mkruisselbrink / navigator-connect

Apache License 2.0
25 stars 8 forks source link

How should messages to long running connections get delivered #34

Open mkruisselbrink opened 9 years ago

mkruisselbrink commented 9 years ago

Regardless of if the navigator.connect API is based on MessagePort or some other custom type to represent a connection, for long running connections (that survive a Service Worker being killed and restarted) messages sent over this connection will have to be delivered as some kind of global-ish event.

Now it doesn't really make sense to deliver one message to multiple service workers, so somehow we need to pick which service worker should receive events from a particular connection. An easy option would be to always deliver all messages to the active worker for a particular service worker registration. So every connection would be associated with a particular service worker registration, connections can survive a new version of service worker replacing an old version, etc. This all works nicely, except if a new service worker would like to do something with long running connections in its install event. Any messages sent to these connections from the other side would end up in the currently active version instead of in the newly installing version.

I think there are a couple of directions we can go with this. To make things concrete I'll be assuming the current StashedMessagePort api, but most of this applies regardless what the actual API ends up being.

One option would be to completely disallow creating any kind of persistent connections until a worker is activating. In the stashed port proposal (and in any other API where persisting a connection is an explicit step after setting up the connection) this doesn't seem like it would cause any major problems. A worker can still connect to any services it likes, delaying resolving its install event promise until after a connection is set up and even use the regular non-persistent MessagePort onmessage event to communicate with any services it connects to. The only thing it can't do is persist these connections. If it needs a persistent connection to some other service it would need to reconnect/persist these connections in the activate event. If persistence is implicit for any connection made/accepted from a service worker this becomes more problematic, so this would be an argument in favor of having a separate persist/stash step after setting up a connection.

Another option would be somehow allow stashing ports in the oninstall event but either hold messages to these ports until the worker becomes active, or make sure these messages get delivered to the worker that stashed the ports (until that worker becomes redundant). This does seem harder to understand though, and doesn't give much benefit over just not allowing stashing of ports from the oninstall event.