1use crate::store::TaskStore;
5use futures::{SinkExt, StreamExt};
6use std::sync::Arc;
7use std::time::{Duration, Instant};
8use tokio::sync::Notify;
9use tokio_tungstenite::tungstenite::{Message, client::IntoClientRequest};
10
11const CURSOR_KEY: &str = "relay_cursor";
12const PING_EVERY: Duration = Duration::from_secs(300);
13const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
14const MAX_BACKOFF_SECS: u64 = 300;
15const STABLE_SESSION: Duration = Duration::from_secs(60);
18
19#[derive(serde::Deserialize)]
20struct Incoming {
21 #[serde(rename = "type")]
22 kind: String,
23 #[serde(default)]
24 seq: i64,
25 #[serde(default)]
26 event: String,
27 #[serde(default)]
28 action: String,
29 #[serde(default)]
30 repo: String,
31 #[serde(default)]
32 payload: Option<serde_json::Value>,
33}
34
35pub async fn run(url: String, token: String, store: Arc<TaskStore>, notify: Arc<Notify>) {
37 let mut backoff = 1;
38
39 loop {
40 let started = Instant::now();
41 match session(&url, &token, &store, ¬ify, PING_EVERY).await {
42 Ok(()) => tracing::warn!("relay stream closed, reconnecting"),
43 Err(e) => tracing::warn!(err = %e, "relay stream failed, reconnecting"),
44 }
45
46 let wait = retry_after(backoff, started.elapsed());
47 tokio::time::sleep(Duration::from_secs(wait)).await;
48 backoff = (wait * 2).min(MAX_BACKOFF_SECS);
49 }
50}
51
52fn retry_after(backoff: u64, lasted: Duration) -> u64 {
54 if lasted >= STABLE_SESSION { 1 } else { backoff }
55}
56
57async fn session(
58 url: &str,
59 token: &str,
60 store: &TaskStore,
61 notify: &Notify,
62 ping_every: Duration,
63) -> anyhow::Result<()> {
64 let ws_url = format!("{}/ws", url.trim_end_matches('/'))
65 .replacen("https://", "wss://", 1)
66 .replacen("http://", "ws://", 1);
67 let mut request = ws_url.into_client_request()?;
68 request
69 .headers_mut()
70 .insert("authorization", format!("Bearer {token}").parse()?);
71 let (mut ws, _) =
72 tokio::time::timeout(CONNECT_TIMEOUT, tokio_tungstenite::connect_async(request))
73 .await
74 .map_err(|_| anyhow::anyhow!("relay connect timed out"))??;
75
76 let after = cursor(store).await;
77 let hello = serde_json::json!({ "v": 1, "type": "hello", "after": after });
78 ws.send(Message::Text(hello.to_string())).await?;
79 tracing::info!(after, "relay stream connected");
80
81 let mut ping = tokio::time::interval(ping_every);
82 ping.tick().await;
83 let mut awaiting = false;
86
87 loop {
88 tokio::select! {
89 _ = ping.tick() => {
90 if awaiting {
91 anyhow::bail!("relay stream idle, no pong");
92 }
93
94 ws.send(Message::Text("ping".to_string())).await?;
95 awaiting = true;
96 }
97 msg = ws.next() => match msg {
98 None => return Ok(()),
99 Some(msg) => {
100 awaiting = false;
101 match msg? {
102 Message::Text(text) => handle(&text, store, notify).await,
103 Message::Close(_) => return Ok(()),
104 _ => {}
105 }
106 }
107 },
108 }
109 }
110}
111
112async fn cursor(store: &TaskStore) -> i64 {
113 store
114 .kv_get(CURSOR_KEY)
115 .await
116 .ok()
117 .flatten()
118 .and_then(|v| v.parse().ok())
119 .unwrap_or(0)
120}
121
122pub(crate) async fn handle(text: &str, store: &TaskStore, notify: &Notify) {
124 if text == "pong" {
125 return;
126 }
127
128 let msg: Incoming = match serde_json::from_str(text) {
129 Ok(msg) => msg,
130 Err(e) => {
131 tracing::warn!(err = %e, "unreadable relay message");
132 return;
133 }
134 };
135
136 match msg.kind.as_str() {
137 "gap" => {
138 tracing::warn!("relay deleted events this client never read, syncing every project");
139 notify.notify_one();
140 }
141 "event" => {
142 if msg.event == "issues" && msg.action == "closed" {
144 let number = msg
145 .payload
146 .as_ref()
147 .and_then(|p| p.pointer("/issue/number"))
148 .and_then(serde_json::Value::as_i64);
149
150 if let Some(number) = number {
151 let key = format!("dep_blocker_read_at:{}#{number}", msg.repo);
152
153 if let Err(e) = store.kv_delete(&key).await {
154 tracing::warn!(err = %e, key, "failed to release a closed blocker");
155 }
156 }
157 }
158
159 if let Err(e) = store.kv_set(CURSOR_KEY, &msg.seq.to_string()).await {
160 tracing::warn!(err = %e, seq = msg.seq, "failed to store the relay cursor");
161 }
162
163 notify.notify_one();
164 }
165 _ => {}
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 async fn woke(notify: &Notify) -> bool {
174 tokio::time::timeout(Duration::from_millis(200), notify.notified())
175 .await
176 .is_ok()
177 }
178
179 #[tokio::test]
180 async fn an_event_stores_the_cursor_and_wakes_the_sync() {
181 let store = TaskStore::open_memory().await.unwrap();
182 let notify = Notify::new();
183 handle(
184 r#"{"type":"event","seq":7,"event":"pull_request","action":"opened","repo":"o/r","payload":{}}"#,
185 &store,
186 ¬ify,
187 )
188 .await;
189
190 assert_eq!(cursor(&store).await, 7);
191 assert!(woke(¬ify).await);
192 }
193
194 #[tokio::test]
195 async fn a_closed_issue_releases_its_blocker_cache_entry() {
196 let store = TaskStore::open_memory().await.unwrap();
197 store
198 .kv_set("dep_blocker_read_at:o/r#12", "1")
199 .await
200 .unwrap();
201 store
202 .kv_set("dep_blocker_read_at:o/r#13", "1")
203 .await
204 .unwrap();
205 handle(
206 r#"{"type":"event","seq":1,"event":"issues","action":"closed","repo":"o/r","payload":{"issue":{"number":12}}}"#,
207 &store,
208 &Notify::new(),
209 )
210 .await;
211
212 assert_eq!(
213 store.kv_get("dep_blocker_read_at:o/r#12").await.unwrap(),
214 None
215 );
216 assert!(
217 store
218 .kv_get("dep_blocker_read_at:o/r#13")
219 .await
220 .unwrap()
221 .is_some()
222 );
223 }
224
225 #[tokio::test]
226 async fn a_gap_wakes_the_sync_and_keeps_the_cursor() {
227 let store = TaskStore::open_memory().await.unwrap();
228 store.kv_set(CURSOR_KEY, "3").await.unwrap();
229 let notify = Notify::new();
230 handle(r#"{"type":"gap","oldest":50}"#, &store, ¬ify).await;
231
232 assert_eq!(cursor(&store).await, 3);
233 assert!(woke(¬ify).await);
234 }
235
236 #[tokio::test]
237 async fn pong_and_unknown_messages_change_nothing() {
238 let store = TaskStore::open_memory().await.unwrap();
239 let notify = Notify::new();
240 handle("pong", &store, ¬ify).await;
241 handle("not json", &store, ¬ify).await;
242
243 assert_eq!(cursor(&store).await, 0);
244 assert!(!woke(¬ify).await);
245 }
246
247 #[expect(
248 clippy::result_large_err,
249 reason = "the handshake callback returns tungstenite's large error type"
250 )]
251 #[tokio::test]
252 async fn a_session_says_hello_with_the_cursor_and_applies_events() {
253 use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
254
255 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
256 let addr = listener.local_addr().unwrap();
257 let server = tokio::spawn(async move {
258 let (tcp, _) = listener.accept().await.unwrap();
259 let mut auth = String::new();
260 let mut ws =
261 tokio_tungstenite::accept_hdr_async(tcp, |req: &Request, res: Response| {
262 auth = req
263 .headers()
264 .get("authorization")
265 .and_then(|v| v.to_str().ok())
266 .unwrap_or_default()
267 .to_string();
268 Ok(res)
269 })
270 .await
271 .unwrap();
272 let hello = ws.next().await.unwrap().unwrap().into_text().unwrap();
273 let event = r#"{"type":"event","seq":9,"event":"issues","action":"opened","repo":"o/r","payload":{}}"#;
274 ws.send(Message::Text(event.to_string())).await.unwrap();
275 ws.close(None).await.unwrap();
276 (auth, hello)
277 });
278
279 let store = TaskStore::open_memory().await.unwrap();
280 store.kv_set(CURSOR_KEY, "4").await.unwrap();
281 let notify = Notify::new();
282 session(
283 &format!("http://{addr}"),
284 "tok",
285 &store,
286 ¬ify,
287 PING_EVERY,
288 )
289 .await
290 .unwrap();
291
292 let (auth, hello) = server.await.unwrap();
293 assert_eq!(auth, "Bearer tok");
294 let hello: serde_json::Value = serde_json::from_str(&hello).unwrap();
295 assert_eq!(
296 hello,
297 serde_json::json!({ "v": 1, "type": "hello", "after": 4 })
298 );
299 assert_eq!(cursor(&store).await, 9);
300 assert!(woke(¬ify).await);
301 }
302
303 #[tokio::test]
304 async fn a_silent_server_ends_the_session_with_an_error() {
305 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
306 let addr = listener.local_addr().unwrap();
307 let server = tokio::spawn(async move {
308 let (tcp, _) = listener.accept().await.unwrap();
309 let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
310 while ws.next().await.is_some() {}
311 });
312
313 let store = TaskStore::open_memory().await.unwrap();
314 let err = tokio::time::timeout(
315 Duration::from_secs(5),
316 session(
317 &format!("http://{addr}"),
318 "tok",
319 &store,
320 &Notify::new(),
321 Duration::from_millis(50),
322 ),
323 )
324 .await
325 .expect("session should end on its own")
326 .unwrap_err();
327
328 assert!(err.to_string().contains("no pong"));
329 server.abort();
330 }
331
332 #[test]
333 fn a_socket_closed_at_once_keeps_the_backoff_growing() {
334 let quick = Duration::from_secs(1);
335 let mut backoff = 1;
336 let mut waits = Vec::new();
337
338 for _ in 0..12 {
339 let wait = retry_after(backoff, quick);
340 waits.push(wait);
341 backoff = (wait * 2).min(MAX_BACKOFF_SECS);
342 }
343
344 assert_eq!(waits[..9], [1, 2, 4, 8, 16, 32, 64, 128, 256]);
345 assert_eq!(waits[9..], [300, 300, 300]);
346 assert_eq!(retry_after(300, STABLE_SESSION), 1);
347 }
348}