1use std::collections::HashMap;
14use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15use std::sync::{Mutex, OnceLock};
16use std::time::Duration;
17
18use futures_util::StreamExt;
19use nostr_sdk::prelude::*;
20
21type Targets = HashMap<RelayUrl, Vec<Filter>>;
23
24#[derive(Clone, Debug, PartialEq, Eq)]
26pub enum CatchUp {
27 Relay(String),
29 All { away_ms: u64 },
31}
32
33static HANDLER: OnceLock<Box<dyn Fn(CatchUp) + Send + Sync>> = OnceLock::new();
34
35pub fn set_catch_up(handler: impl Fn(CatchUp) + Send + Sync + 'static) {
37 let _ = HANDLER.set(Box::new(handler));
38}
39
40fn catch_up(what: CatchUp) {
41 match HANDLER.get() {
42 Some(handler) => handler(what),
43 None => crate::log_debug!("[live] no catch-up handler for {what:?}"),
44 }
45}
46
47const HEAL_EVERY: Duration = Duration::from_secs(120);
49const FIRST_BACKOFF: Duration = Duration::from_secs(1);
51pub(crate) const MAX_BACKOFF: Duration = Duration::from_secs(300);
52const BACKOFF_RESET_MS: u64 = 10 * 60 * 1000;
54const KEEP_GRACE: Duration = Duration::from_millis(500);
56const GAP_SETTLE: Duration = Duration::from_secs(3);
58
59static KEPT: std::sync::LazyLock<Mutex<HashMap<SubscriptionId, (u64, Targets)>>> = std::sync::LazyLock::new(Default::default);
63
64static WATCHING: std::sync::LazyLock<Mutex<std::collections::HashSet<u64>>> = std::sync::LazyLock::new(Default::default);
66
67static CLOSES: std::sync::LazyLock<Mutex<HashMap<(RelayUrl, SubscriptionId), (u32, u64)>>> =
70 std::sync::LazyLock::new(Default::default);
71
72#[derive(Default)]
73struct Gaps(Mutex<Vec<String>>, AtomicBool);
74
75fn backoff(closes: u32) -> Duration {
76 FIRST_BACKOFF.saturating_mul(1u32 << closes.min(9)).min(MAX_BACKOFF)
77}
78
79fn backing_off(relay: &RelayUrl, id: &SubscriptionId) -> bool {
81 let closes = CLOSES.lock().unwrap_or_else(|e| e.into_inner());
82 closes
83 .get(&(relay.clone(), id.clone()))
84 .is_some_and(|&(n, last)| now_ms().saturating_sub(last) < backoff(n.saturating_sub(1)).as_millis() as u64)
85}
86
87pub fn keep(id: &SubscriptionId, targets: Targets) {
89 if targets.is_empty() {
90 return;
91 }
92 let session = crate::db::current_session_id();
93 let mut kept = KEPT.lock().unwrap_or_else(|e| e.into_inner());
94 kept.retain(|_, (s, _)| *s == session);
96 kept.insert(id.clone(), (session, targets));
97}
98
99pub fn keep_output<S, F>(out: &Output<SubscriptionId, S, F>, filters: Vec<Filter>) {
101 let targets = out.success.keys().chain(out.failed.keys()).map(|url| (url.clone(), filters.clone())).collect();
102 keep(&out.value, targets);
103}
104
105pub fn forget(id: &SubscriptionId) {
107 KEPT.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
108}
109
110fn kept_on(id: &SubscriptionId, relay: &RelayUrl) -> Option<Vec<Filter>> {
111 let session = crate::db::current_session_id();
112 let kept = KEPT.lock().unwrap_or_else(|e| e.into_inner());
113 kept.get(id).filter(|(s, _)| *s == session).and_then(|(_, t)| t.get(relay).cloned())
114}
115
116fn now_ms() -> u64 {
117 web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
119}
120
121pub fn watch(client: &Client) {
124 if !WATCHING.lock().unwrap_or_else(|e| e.into_inner()).insert(crate::db::current_session_id()) {
125 return;
126 }
127 let mut notifications = client.notifications();
128 let c = client.clone();
129 crate::db::spawn_bound(async move {
130 while let Some(n) = notifications.next().await {
131 if crate::db::session_stopped() {
132 return;
133 }
134 let ClientNotification::Message { relay_url, message } = n else { continue };
135 let RelayMessage::Closed { subscription_id, message } = *message else { continue };
136 if message.starts_with("auth-required:") {
138 continue;
139 }
140 let (c, id, reason) = (c.clone(), subscription_id.into_owned(), message.into_owned());
141 crate::db::spawn_bound(async move {
142 crate::rt::time::sleep(KEEP_GRACE).await;
144 if kept_on(&id, &relay_url).is_some() {
145 crate::log_warn!("[live] {relay_url} closed {id}: {reason}");
146 schedule_restore(c, relay_url, id);
147 }
148 });
149 }
150 });
151 let c = client.clone();
152 crate::db::spawn_bound(async move {
153 loop {
154 crate::rt::time::sleep(HEAL_EVERY).await;
155 if crate::db::session_stopped() {
156 return;
157 }
158 heal(&c).await;
159 }
160 });
161}
162
163fn schedule_restore(client: Client, relay: RelayUrl, id: SubscriptionId) {
164 let wait = {
165 let mut map = CLOSES.lock().unwrap_or_else(|e| e.into_inner());
166 let now = now_ms();
167 let entry = map.entry((relay.clone(), id.clone())).or_insert((0, now));
168 if now.saturating_sub(entry.1) > BACKOFF_RESET_MS {
169 entry.0 = 0;
170 }
171 let n = entry.0;
172 *entry = (n.saturating_add(1), now);
173 backoff(n)
174 };
175 crate::db::spawn_bound(async move {
176 crate::rt::time::sleep(wait).await;
177 restore(&client, &relay, &id).await;
178 });
179}
180
181async fn restore(client: &Client, relay: &RelayUrl, id: &SubscriptionId) -> bool {
183 let Some(filters) = kept_on(id, relay) else { return false };
184 let connected = matches!(client.relay(relay).await, Ok(Some(r)) if r.status() == RelayStatus::Connected);
185 if !connected {
186 return false;
188 }
189 match client.subscribe(ReqTarget::single(relay.clone(), filters)).with_id(id.clone()).await {
190 Ok(_) if kept_on(id, relay).is_none() => {
191 if let Ok(Some(r)) = client.relay(relay).await {
193 let _ = r.unsubscribe(id).await;
194 }
195 false
196 }
197 Ok(_) => {
198 println!("[live] {relay}: restored {id}");
199 gap(relay.to_string());
200 true
201 }
202 Err(e) => {
203 crate::log_warn!("[live] {relay}: restoring {id} failed: {e}");
204 false
205 }
206 }
207}
208
209pub async fn heal(client: &Client) -> usize {
212 let session = crate::db::current_session_id();
213 let wanted: Vec<(SubscriptionId, RelayUrl)> = KEPT
214 .lock()
215 .unwrap_or_else(|e| e.into_inner())
216 .iter()
217 .filter(|(_, (s, _))| *s == session)
218 .flat_map(|(id, (_, targets))| targets.keys().map(move |url| (id.clone(), url.clone())))
219 .collect();
220 let mut restored = 0;
221 for (id, url) in wanted {
222 let Ok(Some(relay)) = client.relay(&url).await else { continue };
223 if relay.status() != RelayStatus::Connected || backing_off(&url, &id) || relay.subscription(&id).await.is_some() {
224 continue;
225 }
226 if restore(client, &url, &id).await {
227 restored += 1;
228 }
229 }
230 if restored > 0 {
231 crate::log_warn!("[live] healed {restored} dropped live subscription(s)");
232 }
233 restored
234}
235
236fn gap(relay: String) {
238 let gaps = crate::db::current_session().scoped::<Gaps, Gaps>();
239 {
240 let mut pending = gaps.0.lock().unwrap_or_else(|e| e.into_inner());
241 if !pending.contains(&relay) {
242 pending.push(relay);
243 }
244 }
245 if gaps.1.swap(true, Ordering::SeqCst) {
246 return;
247 }
248 crate::db::spawn_bound(async move {
249 crate::rt::time::sleep(GAP_SETTLE).await;
250 let relays = std::mem::take(&mut *gaps.0.lock().unwrap_or_else(|e| e.into_inner()));
251 gaps.1.store(false, Ordering::SeqCst);
252 if crate::db::session_is_live() {
253 for relay in relays {
254 catch_up(CatchUp::Relay(relay));
255 }
256 }
257 });
258}
259
260#[derive(Default)]
261struct Reviving(AtomicBool, AtomicU64);
262
263const REVIVE_COOLDOWN_MS: u64 = 20_000;
265
266const FULL_CATCH_UP_AFTER_MS: u64 = 15 * 60 * 1000;
268
269pub async fn revive(client: &Client, away_ms: u64, suspended: bool) {
275 let state = crate::db::current_session().scoped::<Reviving, Reviving>();
276 if now_ms().saturating_sub(state.1.load(Ordering::SeqCst)) < REVIVE_COOLDOWN_MS || state.0.swap(true, Ordering::SeqCst) {
277 return;
278 }
279 let budget = crate::relay_request_timeout(Duration::from_secs(4)) + crate::relay_connect_timeout(Duration::from_secs(8));
281 let redialled = crate::rt::time::timeout(budget, probe_or_redial(client)).await.unwrap_or(0);
282 if !crate::db::session_stopped() {
283 let healed = heal(client).await;
284 let full = suspended || away_ms >= FULL_CATCH_UP_AFTER_MS || redialled + healed > 0;
285 println!(
286 "[live] back after {}: {redialled} relay(s) redialled, {healed} subscription(s) healed{}",
287 crate::clock::describe_span(away_ms / 1000),
288 if full { ", catching up" } else { "" }
289 );
290 if full {
291 crate::community::v2::realtime::force_refresh_subscription(client).await;
292 catch_up(CatchUp::All { away_ms });
293 }
294 }
295 state.1.store(now_ms(), Ordering::SeqCst);
296 state.0.store(false, Ordering::SeqCst);
297}
298
299pub async fn probe_or_redial(client: &Client) -> usize {
303 let probe = crate::relay_request_timeout(Duration::from_secs(4));
304 let connect = crate::relay_connect_timeout(Duration::from_secs(8));
305 futures_util::stream::iter(client.relays().all().await)
306 .map(|(url, relay)| {
307 let client = client.clone();
308 async move {
309 if crate::transport::refuses(url.as_str()).is_some() {
310 return false;
311 }
312 if relay.status() == RelayStatus::Connected {
313 let filter = Filter::new().id(EventId::from_byte_array([0; 32]));
315 let answered = crate::rt::time::timeout(
316 probe + Duration::from_secs(1),
317 client.fetch_events(ReqTarget::single(url.to_string(), [filter])).timeout(probe),
318 )
319 .await;
320 if matches!(answered, Ok(Ok(_))) {
321 return false;
322 }
323 crate::log_warn!("[live] {url}: no answer after being away, redialling");
324 relay.disconnect();
325 let _ = relay.try_connect().timeout(connect).await;
326 return true;
327 }
328 if crate::transport::cycle::revivable(&relay) {
329 let _ = relay.try_connect().timeout(connect).await;
330 }
331 false
332 }
333 })
334 .buffer_unordered(8)
335 .filter(|redialled| std::future::ready(*redialled))
336 .count()
337 .await
338}
339
340#[cfg(not(target_arch = "wasm32"))]
341pub use wake::start_wake_watch;
342
343#[cfg(not(target_arch = "wasm32"))]
344mod wake {
345 use std::sync::atomic::{AtomicBool, Ordering};
346 use std::time::Duration;
347
348 const TICK: Duration = Duration::from_secs(10);
350 const SUSPENDED_MS: u64 = 45_000;
352
353 static STARTED: AtomicBool = AtomicBool::new(false);
354
355 pub fn start_wake_watch() {
358 if STARTED.swap(true, Ordering::SeqCst) {
359 return;
360 }
361 crate::rt::spawn(async {
363 let mut last = super::now_ms();
364 loop {
365 crate::rt::time::sleep(TICK).await;
366 let now = super::now_ms();
367 let late = now.saturating_sub(last).saturating_sub(TICK.as_millis() as u64);
368 last = now;
369 if late < SUSPENDED_MS || !crate::db::session_is_live() {
370 continue;
371 }
372 let Some(client) = crate::state::nostr_client() else { continue };
373 let away = late + TICK.as_millis() as u64;
374 crate::db::spawn_bound(async move { super::revive(&client, away, true).await });
375 }
376 });
377 }
378}
379
380#[cfg(all(test, not(target_arch = "wasm32")))]
381mod tests {
382 use super::*;
383 use crate::ClientRelayExt;
384 use std::sync::Arc;
385 use futures_util::SinkExt;
386 use tokio_tungstenite::tungstenite::Message;
387
388 async fn closing_relay(reason: &'static str) -> (String, Arc<Mutex<Vec<String>>>) {
391 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
392 let url = format!("ws://{}", listener.local_addr().unwrap());
393 let reqs = Arc::new(Mutex::new(Vec::<String>::new()));
394 let seen = reqs.clone();
395 tokio::spawn(async move {
397 while let Ok((stream, _)) = listener.accept().await {
398 let seen = seen.clone();
399 tokio::spawn(async move {
401 let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await else { return };
402 while let Some(Ok(msg)) = ws.next().await {
403 let Message::Text(text) = msg else { continue };
404 let v: serde_json::Value = serde_json::from_str(text.as_str()).unwrap();
405 if v[0] != "REQ" {
406 continue;
407 }
408 let id = v[1].as_str().unwrap().to_string();
409 let first = {
410 let mut seen = seen.lock().unwrap();
411 let first = !seen.contains(&id);
412 seen.push(id.clone());
413 first
414 };
415 let reply = if first {
416 serde_json::json!(["CLOSED", id, reason])
417 } else {
418 serde_json::json!(["EOSE", id])
419 };
420 let _ = ws.send(Message::text(reply.to_string())).await;
421 }
422 });
423 }
424 });
425 (url, reqs)
426 }
427
428 async fn asked(reqs: &Mutex<Vec<String>>, id: &SubscriptionId, times: usize) -> bool {
429 for _ in 0..60 {
430 if reqs.lock().unwrap().iter().filter(|r| *r == &id.to_string()).count() >= times {
431 return true;
432 }
433 tokio::time::sleep(Duration::from_millis(100)).await;
434 }
435 false
436 }
437
438 #[tokio::test]
439 async fn a_live_subscription_a_relay_closes_is_sent_again() {
440 let (url, reqs) = closing_relay("error: at most 200 open subscriptions").await;
441 let client = Client::builder().build();
442 client.add_managed_relay(&url).await.unwrap();
443 client.connect().and_wait(Duration::from_secs(5)).await;
444 watch(&client);
445
446 let filter = Filter::new().kind(Kind::GiftWrap).limit(0);
447 let out = client.subscribe(filter.clone()).await.unwrap();
448 keep_output(&out, vec![filter]);
449
450 assert!(asked(&reqs, &out.value, 2).await, "the closed subscription is asked for again");
451 let relay = client.relay(&url).await.unwrap().unwrap();
452 assert!(relay.subscription(&out.value).await.is_some(), "and the pool holds it, so a reconnect re-sends it");
453 }
454
455 #[tokio::test]
456 async fn a_closed_subscription_nobody_keeps_is_left_closed() {
457 let (url, reqs) = closing_relay("error: shutting down").await;
458 let client = Client::builder().build();
459 client.add_managed_relay(&url).await.unwrap();
460 client.connect().and_wait(Duration::from_secs(5)).await;
461 watch(&client);
462
463 let out = client.subscribe(Filter::new().kind(Kind::TextNote).limit(0)).await.unwrap();
464 tokio::time::sleep(KEEP_GRACE + FIRST_BACKOFF + Duration::from_millis(800)).await;
465 assert!(!asked(&reqs, &out.value, 2).await, "an unkept subscription is not revived");
466 }
467
468 #[tokio::test]
469 async fn a_subscription_forgotten_before_its_close_is_judged_stays_closed() {
470 let (url, reqs) = closing_relay("error: at most 200 open subscriptions").await;
471 let client = Client::builder().build();
472 client.add_managed_relay(&url).await.unwrap();
473 client.connect().and_wait(Duration::from_secs(5)).await;
474 watch(&client);
475
476 let filter = Filter::new().kind(Kind::GiftWrap).limit(0);
477 let out = client.subscribe(filter.clone()).await.unwrap();
478 keep_output(&out, vec![filter]);
479 forget(&out.value);
480 tokio::time::sleep(KEEP_GRACE + FIRST_BACKOFF + Duration::from_millis(800)).await;
481 assert!(!asked(&reqs, &out.value, 2).await, "a replaced subscription is not brought back");
482 }
483
484 #[tokio::test]
485 async fn heal_waits_out_the_backoff_of_a_recent_close() {
486 let (url, reqs) = closing_relay("error: at most 200 open subscriptions").await;
487 let client = Client::builder().build();
488 client.add_managed_relay(&url).await.unwrap();
489 client.connect().and_wait(Duration::from_secs(5)).await;
490 watch(&client);
491
492 let filter = Filter::new().kind(Kind::GiftWrap).limit(0);
493 let out = client.subscribe(filter.clone()).await.unwrap();
494 keep_output(&out, vec![filter]);
495 let relay_url = RelayUrl::parse(&url).unwrap();
496 for _ in 0..30 {
497 if backing_off(&relay_url, &out.value) {
498 break;
499 }
500 tokio::time::sleep(Duration::from_millis(50)).await;
501 }
502 assert!(backing_off(&relay_url, &out.value), "the close was seen");
503 assert_eq!(heal(&client).await, 0, "the scheduled restore owns the retry");
504 assert!(asked(&reqs, &out.value, 2).await, "and it still runs");
505 }
506
507 #[tokio::test]
508 async fn heal_restores_what_a_relay_dropped_and_leaves_held_ones_alone() {
509 let (url, reqs) = closing_relay("error: at most 200 open subscriptions").await;
510 let client = Client::builder().build();
511 client.add_managed_relay(&url).await.unwrap();
512 client.connect().and_wait(Duration::from_secs(5)).await;
513
514 let filter = Filter::new().kind(Kind::GiftWrap).limit(0);
515 let out = client.subscribe(filter.clone()).await.unwrap();
516 keep_output(&out, vec![filter]);
517 let relay = client.relay(&url).await.unwrap().unwrap();
518 for _ in 0..50 {
519 if relay.subscription(&out.value).await.is_none() {
520 break;
521 }
522 tokio::time::sleep(Duration::from_millis(50)).await;
523 }
524 assert!(relay.subscription(&out.value).await.is_none(), "nostr-sdk forgot the closed subscription");
525
526 assert_eq!(heal(&client).await, 1);
527 assert!(relay.subscription(&out.value).await.is_some());
528 assert_eq!(heal(&client).await, 0, "a held subscription is not sent again");
529 assert!(asked(&reqs, &out.value, 2).await);
530 assert_eq!(reqs.lock().unwrap().iter().filter(|r| *r == &out.value.to_string()).count(), 2);
531 }
532}