-
Notifications
You must be signed in to change notification settings - Fork 28
Add SSE change notifications #196
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
robertbak
wants to merge
2
commits into
GothenburgBitFactory:main
Choose a base branch
from
robertbak:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # Change Notifications | ||
|
|
||
| The HTTP server exposes `GET /v1/client/events` as a Server-Sent Events stream. | ||
| Like other client endpoints, the request must include `X-Client-Id`. | ||
|
|
||
| This endpoint is disabled by default. Enable it with `--sync-events` or the | ||
| `SYNC_EVENTS=true` environment variable. | ||
|
|
||
| When `AddVersion` accepts a new version for that client, the stream emits a | ||
| `version` event: | ||
|
|
||
| ```text | ||
| event: version | ||
| data: {"clientId":"..."} | ||
| ``` | ||
|
|
||
| This endpoint is only an invalidation signal. Clients should perform a normal | ||
| TaskChampion sync after receiving an event. | ||
|
|
||
| ## Simple Listener | ||
|
|
||
| This example runs a command for every received `version` event. | ||
|
|
||
| ```bash | ||
| #!/usr/bin/env bash | ||
| set -euo pipefail | ||
|
|
||
| server_url="${TASKCHAMPION_SYNC_SERVER_URL:?set TASKCHAMPION_SYNC_SERVER_URL}" | ||
| client_id="${TASKCHAMPION_SYNC_CLIENT_ID:?set TASKCHAMPION_SYNC_CLIENT_ID}" | ||
|
|
||
| curl -fsSN \ | ||
| -H "Accept: text/event-stream" \ | ||
| -H "X-Client-Id: ${client_id}" \ | ||
| "${server_url%/}/v1/client/events" | | ||
| while IFS= read -r line; do | ||
| case "${line}" in | ||
| data:*) | ||
| echo "TaskChampion changed: ${line#data: }" | ||
| task sync | ||
| ;; | ||
| esac | ||
| done | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| use crate::api::{ServerState, CLIENT_ID_HEADER}; | ||
| use actix_web::{error, get, http::header, web, HttpRequest, HttpResponse, Result}; | ||
| use futures::{ | ||
| channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}, | ||
| StreamExt, | ||
| }; | ||
| use serde::Serialize; | ||
| use std::{ | ||
| collections::HashMap, | ||
| sync::{Arc, Mutex}, | ||
| }; | ||
| use taskchampion_sync_server_core::ClientId; | ||
|
|
||
| #[derive(Clone, Debug, Serialize)] | ||
| #[serde(rename_all = "camelCase")] | ||
| pub(crate) struct ChangeEvent { | ||
| pub(crate) client_id: ClientId, | ||
| } | ||
|
|
||
| #[derive(Clone, Default)] | ||
| pub(crate) struct ChangeNotifier { | ||
| subscribers: Arc<Mutex<HashMap<ClientId, Vec<UnboundedSender<ChangeEvent>>>>>, | ||
| } | ||
|
|
||
| impl ChangeNotifier { | ||
| pub(crate) fn subscribe(&self, client_id: ClientId) -> UnboundedReceiver<ChangeEvent> { | ||
| let (tx, rx) = unbounded(); | ||
| self.subscribers | ||
| .lock() | ||
| .expect("change notifier mutex poisoned") | ||
| .entry(client_id) | ||
| .or_default() | ||
| .push(tx); | ||
| rx | ||
| } | ||
|
|
||
| pub(crate) fn notify(&self, client_id: ClientId) { | ||
| let event = ChangeEvent { client_id }; | ||
| let mut subscribers = self | ||
| .subscribers | ||
| .lock() | ||
| .expect("change notifier mutex poisoned"); | ||
| if let Some(client_subscribers) = subscribers.get_mut(&client_id) { | ||
| client_subscribers | ||
| .retain(|subscriber| subscriber.unbounded_send(event.clone()).is_ok()); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[get("/v1/client/events")] | ||
| pub(crate) async fn service( | ||
| req: HttpRequest, | ||
| server_state: web::Data<Arc<ServerState>>, | ||
| ) -> Result<HttpResponse> { | ||
| if !server_state.web_config.sync_events { | ||
| return Err(error::ErrorNotFound("sync events are not enabled")); | ||
| } | ||
|
|
||
| let client_id = server_state.client_id_header(&req)?; | ||
| let stream = server_state.changes.subscribe(client_id).map(|event| { | ||
| let json = serde_json::to_string(&event).expect("change event serializes"); | ||
| Ok::<_, actix_web::Error>(web::Bytes::from(format!( | ||
| "event: version\n\ | ||
| data: {json}\n\ | ||
| \n" | ||
| ))) | ||
| }); | ||
|
|
||
| Ok(HttpResponse::Ok() | ||
| .append_header((header::CONTENT_TYPE, "text/event-stream")) | ||
| .append_header((header::CACHE_CONTROL, "no-store, max-age=0")) | ||
| .append_header((header::CONNECTION, "keep-alive")) | ||
| .append_header((CLIENT_ID_HEADER, client_id.to_string())) | ||
| .streaming(stream)) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod test { | ||
| use super::*; | ||
| use crate::web::{WebConfig, WebServer}; | ||
| use actix_web::{http::StatusCode, test, App}; | ||
| use taskchampion_sync_server_core::{InMemoryStorage, ServerConfig}; | ||
| use uuid::Uuid; | ||
|
|
||
| #[actix_rt::test] | ||
| async fn notifier_delivers_events_for_matching_client() { | ||
| let notifier = ChangeNotifier::default(); | ||
| let client_id = Uuid::new_v4(); | ||
| let mut rx = notifier.subscribe(client_id); | ||
|
|
||
| notifier.notify(client_id); | ||
| let event = rx.next().await.unwrap(); | ||
| assert_eq!(event.client_id, client_id); | ||
| } | ||
|
|
||
| #[actix_rt::test] | ||
| async fn events_endpoint_uses_client_id_header() { | ||
| let client_id = Uuid::new_v4(); | ||
| let server = WebServer::new( | ||
| ServerConfig::default(), | ||
| WebConfig { | ||
| sync_events: true, | ||
| ..WebConfig::default() | ||
| }, | ||
| InMemoryStorage::new(), | ||
| ); | ||
| let app = App::new().configure(|sc| server.config(sc)); | ||
| let app = test::init_service(app).await; | ||
|
|
||
| let req = test::TestRequest::get() | ||
| .uri("/v1/client/events") | ||
| .append_header((CLIENT_ID_HEADER, client_id.to_string())) | ||
| .to_request(); | ||
| let resp = test::call_service(&app, req).await; | ||
|
|
||
| assert_eq!(resp.status(), StatusCode::OK); | ||
| assert_eq!( | ||
| resp.headers().get(header::CONTENT_TYPE).unwrap(), | ||
| "text/event-stream" | ||
| ); | ||
| } | ||
|
|
||
| #[actix_rt::test] | ||
| async fn events_endpoint_is_disabled_by_default() { | ||
| let client_id = Uuid::new_v4(); | ||
| let server = WebServer::new( | ||
| ServerConfig::default(), | ||
| WebConfig::default(), | ||
| InMemoryStorage::new(), | ||
| ); | ||
| let app = App::new().configure(|sc| server.config(sc)); | ||
| let app = test::init_service(app).await; | ||
|
|
||
| let req = test::TestRequest::get() | ||
| .uri("/v1/client/events") | ||
| .append_header((CLIENT_ID_HEADER, client_id.to_string())) | ||
| .to_request(); | ||
| let resp = test::call_service(&app, req).await; | ||
|
|
||
| assert_eq!(resp.status(), StatusCode::NOT_FOUND); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hm, even the
client_idis redundant here -- it was supplied in a header to subscribe. Does it make sense to just make this an empty JSON object, since the HTTP stream already includesevent: version?