jishi / node-sonos-http-api

An HTTP API bridge for Sonos easing automation. Hostable on any node.js capable device, like a raspberry pi or similar.
http://jishi.github.io/node-sonos-http-api/
MIT License
1.84k stars 462 forks source link

Add HTTP event source endpoint #868

Closed timotto closed 1 year ago

timotto commented 1 year ago

This pull requests adds a new endpoint /events serving status updates as Server Side Events analogous to the webhook mechanism.

It improves upon the webhook mechanism, because multiple clients can connect to the server simultaneously to receive updates, and there is no server configuration required to define the target.

Server Side Events can be consumed by Browser JavaScript using the EventSource class. It's also possible to just use a plain HTTP client like curl to subscribe to the updates, eg curl localhost:5005/events.

jishi commented 1 year ago

This seems like a nice addition, but the implementation seems very simplistic. There is no error handling or identification on lost sockets...but maybe the close event is enough, I can't say. I'm assuming this relies on some sort of long polling? And the clients handle reconnects?

Also, some documentation how to use it would be nice.

Consider moving the HttpEventServer and HttpEventSource into a separate file to unclutter the http-api-server file.

timotto commented 1 year ago

Thank you for the feedback! I will add a section to the README below the Webhook section and move the additional code into a separate file in the lib/helpers directory.

The implementation is in fact that simple, I did verify the cleanup of closed sockets using console.log statements. Either the server will notice the lost connection eventually, or the close event happens at the next attempt to send an event. That's a fairly common behavior for server side event handlers.

It is a long polling connection. It's similar to WebSockets - probably the predecessor, but does not have a back channel for the client to send requests back to the server. However, this makes it much easier to implement. Similar to WebSockets, the client must monitor the connection and handle errors by re-connecting.

jishi commented 1 year ago

Nice, thanks!