tursodatabase / libsql

libSQL is a fork of SQLite that is both Open Source, and Open Contributions.
https://turso.tech/libsql
MIT License
9.54k stars 252 forks source link

feat(libsql-server): send correct sse response #1671

Closed notrab closed 1 month ago

notrab commented 1 month ago

This PR adds proper SSE responses for the /beta/listen endpoint. The previous behaviour used JSON Line formatting.

Changes

  1. Added a keep-alive mechanism to maintain long-lived connections, reducing reconnection overhead.
  2. Modified the event stream to conform to the SSE format.
  3. Updated error handling (error event type) and event filtering to work with the new SSE format.
  4. Refactored handle_listen to return an SseStream.
  5. Removed the explicit header setting as Sse handles this automatically.

Example Usage

The below is now possible:

const eventSource = new EventSource('http://127.0.0.1:8080/beta/listen?table=mytable&action=insert,update');

eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received changes:', data);
};

eventSource.onerror = (error) => {
  console.error('EventSource failed:', error);
};

eventSource.addEventListener('error', (event) => {
  const errorMessage = event.data;
  console.error('Server error:', errorMessage);
});

// To close the connection
// eventSource.close();
ccadenac commented 1 month ago

Tested locally and events are being sent out in the correct format as shown in the attached Postman screenshot. sandbox