communication between service worker instances - service-worker

I'm trying to establish a communication channel between an installing service worker and an activated service worker.
I've tried to do the following:
on the installing service worker:
if ((self.registration.active == null) ||
(self.registration.active.state != "activated")) {
return;
}
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(event){
if (event.data.error) {
console.log("got error from active");
}
else {
console.log("got answer from active");
}
};
self.registration.active.postMessage({message: 'hey', port: messageChannel.port2}, [messageChannel.port2]);
on the active service worker:
self.addEventListener('message', function(event) {
console.log('received message');
});
This isn't working, I'm getting nothing...
Ideas?

Here's how I ended up implementing this.
Each serviceWorker at startup (code at the worker's global scope) connects to a broadcast channel like so:
var comChannel = new BroadcastChannel('SWCom');
comChannel.addEventListener('message', event => {
handleMessageEvent(event);
});
This channel is shared only between service workers.
To post a message to other SW, a SW can just broadcast on the channel comChannel.postMessage('hey there'); and any registered listener will be invoked.
One complication I had, not really related to the channel, is that I had a hard time identifying each SW life cycle state. If I want to communicate between SW it can't really serve any purpose if I don't know who's whom within each one of them. A SW cannot currently get a ref to its own ServiveWorker object, there's an open issue about it in the standard - https://github.com/w3c/ServiceWorker/issues/1077
In my usecase, I bypassed this limitation by performing the communication upon install (fits my needs...), like so:
self.addEventListener('install', function(event) {
if (self.registration.active != null) {
// if we got here it means this is a new SW that's
// starting install and there's an active one running.
// So we can send a message on the broadcast channel,
// whomever answers should be the active SW.
}
// ..
// installation code
// ..
}
One thing to note - I'm not sure this is well implemented.
I believe there are other states a SW can be at (redundant, deleted?, others?), so maybe there can be more then two ServiceWorkers alive, and then the assumption on the identity of the answering side on the channel might be wrong...

Jake provides some excellent examples of messaging that you may be able to derive a solution from. https://gist.github.com/jakearchibald/a1ca502713f41dfb77172be4523a9a4c
You may need to use the page itself as a proxy for sending/receiving messages between Service workers:
[SW1] <== message ==> [Page JS] <== message ==> [SW2]

Related

Twilio worker client disconnect reason

I'm trying to ensure single worker session/window at a time.
In order to achieve this I have added a parameter closeExistingSessions to the createWorker and it's disconnecting (websocket) the other workerClient as expected.
Just wondering if there is a way to know the disconnect reason using this disconnected event listener so that I can show a relevant message to the end user.
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
worker.on("disconnected", function(<ANY_ERROR_CODE_OR_SOMETHING_HERE?!>) {
console.log("Websocket has disconnected");
});
We are getting the reason (The reason the Worker websocket disconnected) as parameter to the disconnected callback.
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
worker.on("disconnected", function(reason) {
console.log(reason.message);
});
And the reason for disconnecting due to existing sessions is 'Websocket disconnected due to new connection being registered'
Hope Twilio will keep their docs up to date

Managing Server Side Events with a Service Worker

I am building a web app to display on my iPad to control my raspberry pi acting as an audio recorder. Part of the need is to maintain an event source open so that the server can send Server Side Events. A specific instance of the app can grab control of the recording process, but will loose control if the server sees sse link closes. This is just protection against a client disappearing and leaving the control held (control of the process does needed to be renewed at least every 5 minutes - but I don't really want to wait that long in the normal case of someone just closing the browser tab.)
Part of my need is to push the browser to the background so I can then open up the camera and record a video.
I built this app and had it almost working see https://github.com/akc42/pi_record.git (master branch).
Until I pushed the browser to the background and found IOS shut down the page and broke the sse link.
I tried restructuring to use a private web worker to manage the sse link, massing messages between the web worker and the main javascript thread - again almost working (see workers branch of above repository). But that got shutdown too!
My last thought is to use a service worker, but how to structure the app?
Clearly the service worker must act as a client to the server for the server side events. It must keep the connection open, but it also needs to keep track of multiple tabs in the browser which may or may not try and grab control of the interface, and only allow one tab to do so.
I can think of three approaches - but its difficult to see which is better. At least I have never even seen any mention of approach 2 and 3 below , but it seems to me that one of these two might actually be the simplest.
Approach 1
Move the code I have now for separate web workers into the service worker. However we will need to add to the message passing some form of ID between window and service. So I can record which tab actually grabbed control of the interface and therefore exclude other tabs from doing so (ie simulate a failed attempt to take control).
As far as I can work out MessageEvent.ports[0] could be a unique object which I could store in a Map somewhere, but I am not entirely convinced that the MessageChannel wouldn't close if the browser moved to the background.
Approach 2
have a set of phantom urls in the service worker that simulate all the different message types (and parameters) that where previously sent my the tab to its private web worker.
The fetch event provides a clientid (which I can use to difference between who actually grabbed control) and which I can use to then do Clients.get(clientid).postMessage() (or Clients.matchAll when a broadcast response is needed)
Code would be something like
self.addEventListener('fetch', (event) => {
const requestURL = new URL(event.request.url);
if (/^\/api\//.test(requestURL.pathname)) {
event.respondWith(fetch(event.request)); //all api requests are a direct pass through
} else if (/^\/service\//.test(requestURL.pathname)) {
/*
process these like a message passing with one extra to say the client is going away.
*/
if (urlRecognised) {
event.respondWith(new Response('OK', {status: 200}));
} else {
event.respondWith(new Response(`Unknown request ${requestURL.pathname}`, {status: 404}));
}
} else {
event.respondWith(async () => {
const cache = await caches.open('recorder');
const cachedResponse = await cache.match(event.request);
const networkResponsePromise = fetch(event.request);
event.waitUntil(async () => {
const networkResponse = await networkResponsePromise;
await cache.put(event.request, networkResponse.clone());
});
// Returned the cached response if we have one, otherwise return the network response.
return cachedResponse || networkResponsePromise;
});
}
});
The top of the the fetch event just passes the standard api requests made by the client straight through. I can't cache these (although I could be more sophisticated and perhaps pre reject those not supported).
The second section matches phantom urls /service/something
The last section is taken from Jake Archibald's offline cookbook and tries to use the cache, but updates the cache in the background if any of the static files have changed.
Approach 3
Similar to the approach above, in that we would have phantom urls and use the clientid as a unique marker, but actually try and simulate a server side event stream with one url.
I'm thinking the code with be more like
...
} else if (/^\/service\//.test(requestURL.pathname)) {
const stream = new TransformStream();
const writer = stream.writeable.getWriter();
event.respondWith(async () => {
const streamFinishedPromise = new Promise(async (resolve,reject) => {
event.waitUntil(async () => {
/* eventually close the link */
await streamFinishedPromise;
});
try {
while (true) writer.write(await nextMessageFromServerSideEventStream());
} catch(e) {
writer.close();
resolve();
}
});
return new Response(stream.readable,{status:200}) //probably need eventstream headers too
}
I am thinking that approach 2 could be the simplest, given where I am now but I am concerned that I can see nothing when searching for how to use service workers that discusses this phantom url approach.
Can anyone comment on any of these approaches and provide guidance on how to best program the tricky bits (for instance does Approach 1 message channel close when the browser is moved to the background on an iPad, or how do you really keep a response channel open, and does that get closed when the browser moves to the background in Approach 3)
The simple truth is that none of these approaches will work. What I didn't realise when I asked the question is that a service worker is re-run by the browser when ever there is something to do and that run only lasts for the length of time of the processing of an event. Although eventWaitUntil can prolong that, the only reference to how long I can find is that the browser is still at liberty to cancel it if it appears it might never close. I can't imagine than in a period of several hours it won't get cancelled. So an Event Source will close effectively terminate its link to the server.
So my only option to achieve what I want is to have the server carry on when the Event Source closes and find some other mechanism to release resources held on behalf of the client

Make periodic HTTP requests with service worker

Is it possible to make HTTP requests in background with service worker, when users are not visiting my webpage. I want to make periodic requests to my webpage (e.g. 3 seconds)?
There is a feature called periodicSync, but i didn't understand how to use it.
I've not tried implementing this but for me the clearest overview has been this explanation.
Making periodic requests involves first handling the Service Worker ready event, invoking the periodicSync.register() function with config options. The register() function returns a Promise that allows you to deal with success or rejection of the periodic sync registration.
registration.periodicSync.register()
Pass a 'config' object parameter with the following properties:
tag
minPeriod
powerState
networkState
You may then register listeners against the periodicSync event. E.g (slightly simplified example based on the explanation.
self.addEventListener('periodicsync', function(event) {
if (event.registration.tag == 'my-tag') {
event.waitUntil(doTheWork()); // "do the work" asynchronously via a Promise.
}
else {
// unknown sync, may be old, best to unregister
event.registration.unregister();
}
});

Preventing strangers accessing WEBRTC pages

I am creating a sample application to tryout WEBRTC. I came across a tutorial that explains the process. I tried copying the code and it seems to work.
Question is:
I ONLY want a few people to access the page that containing the stream. How can i prevent other unauthorised users from accessing my page. A tutorial that walks through the process would be ideal.
the language i am using to develop is Grails.
You can use authentication plugin for the grails to deny unauthorized request. You can even use Socket.io over Node.js to prevent unauthorized users where you can check "userid":
// socket.io nodejs side code
io.sockets.on('connection', function (socket) {
var userid = socket.handshake.query.userid;
// verify userid
if (typeof objUserArrays[userid] == 'undefined') {
// don't broadcast messages; so that user can NEVER join any room.
return;
}
});
and browser side code:
var socket = io.connect('http://your-domain.com/?userid=something');
For last snippet; you can check meeting.js's openSignalingChannel method:
meeting.openSignalingChannel = function(callback) {
return io.connect('http://your-domain.com/?userid=something').on('message', callback);
};

Pusher auto reconnect when detecting errors / disconnect

Is there some way to reconnect to Pusher if any error or non-connected state is found?
Here's our connection code:
var pusher = new Pusher('<apikey>', {encrypted: true});
var state = pusher.connection.state;
pusher.connection.bind( 'error', function( err ) {
console.log(err);
});
pusher.connection.bind('state_change', function(states) {
// states = {previous: 'oldState', current: 'newState'}
console.log(states);
});
The Pusher JavaScript library automatically attempts reconnection. You don't need to add any code to support this.
I can't find this anywhere in the Pusher docs, but I know this for a fact as I worked for Pusher for 2 years.
You can test by going to http://test.pusher.com/ and disconnecting from the Internet and then reconnecting again. The logging will show it is auto-reconnecting.

Resources