Skip to main content

finlight/
stream.rs

1//! Real-time streams (`client.stream()`, `client.raw_stream()`).
2//!
3//! One background task per stream owns the socket. It answers control frames (pong, admitted,
4//! preempted, errors) before your code sees anything, so a slow consumer never trips the
5//! watchdog. It pings every `ping_interval`, replaces a connection without a pong for
6//! `watchdog_timeout`, renews the connection after `rotation_interval` and redials with the
7//! same subscribe after every drop. Duplicates are filtered per stream.
8
9use std::collections::{HashSet, VecDeque};
10use std::fmt;
11use std::panic::{AssertUnwindSafe, catch_unwind};
12use std::pin::Pin;
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::{Arc, Mutex};
15use std::task::{Context, Poll};
16use std::time::{Duration, SystemTime};
17
18use futures_core::Stream;
19use serde_json::{Map, Value};
20use sha2::{Digest, Sha256};
21use tokio::sync::{mpsc, watch};
22use tokio::task::JoinHandle;
23use tokio::time::{Instant, Interval, MissedTickBehavior};
24
25use crate::config::Config;
26use crate::error::{
27    ApiError, ApiErrorData, ApiErrorKind, Error, FieldIssue, PreemptedError, Result,
28};
29use crate::frames::{self, Frame};
30use crate::http::backoff;
31use crate::models::{StreamEvent, StreamEventKind, decode_article};
32use crate::time::{epoch_millis, parse_rfc3339_nanos};
33use crate::vocab::{ConnectionErrorCode, PreemptReason, ProblemCode, ReconnectReason};
34use crate::ws::{DialOutcome, WsConn, WsMessage, dial};
35
36type Hook<T> = Arc<dyn Fn(&T) + Send + Sync>;
37
38/// Sent with every `connection.admitted`. It arrives before the subscribe is validated, so it
39/// does not mean the subscribe was accepted.
40#[derive(Debug, Clone, PartialEq, Eq)]
41#[non_exhaustive]
42pub struct AdmittedInfo {
43    /// Lease id of the connection.
44    pub lease_id: Option<String>,
45    /// Server time in epoch milliseconds.
46    pub server_now: Option<i64>,
47    /// The `clientNonce` echoed back.
48    pub client_nonce: Option<String>,
49}
50
51/// Sent after every new connection except the first one.
52#[derive(Debug, Clone, PartialEq, Eq)]
53#[non_exhaustive]
54pub struct ReconnectInfo {
55    /// Last timestamp seen on this stream: enriched `availableAt` (falling back to
56    /// `firstSeenAt`), raw `firstSeenAt`; `None` when nothing arrived yet. Use it to fill gaps
57    /// through `articles().search()`; the SDK does not backfill.
58    pub last_seen_at: Option<String>,
59    /// Why the stream connected again.
60    pub reason: ReconnectReason,
61    /// Connections this stream opened so far, the new one included. Refused and failed dials
62    /// do not count.
63    pub connection: u32,
64}
65
66/// Sent each time a stream waits for the WebSocket quota of the next period.
67#[derive(Debug)]
68#[non_exhaustive]
69pub struct QuotaWaitInfo {
70    /// The preemption (`Error::Preempted`) or refused dial (`Error::Api`, 403) that caused the wait.
71    pub error: Error,
72    /// Time until the next attempt.
73    pub next_attempt_in: Duration,
74    /// Quota waits in a row, starting at 1.
75    pub attempt: u32,
76}
77
78/// Options of a stream: `takeover` and hooks. Hooks run on the stream's task; a panic in a
79/// hook is caught and logged and never ends the stream.
80#[derive(Clone, Default)]
81pub struct StreamOptions {
82    takeover: bool,
83    on_admitted: Option<Hook<AdmittedInfo>>,
84    on_reconnect: Option<Hook<ReconnectInfo>>,
85    on_error: Option<Hook<Error>>,
86    on_quota_wait: Option<Hook<QuotaWaitInfo>>,
87}
88
89impl StreamOptions {
90    /// No takeover, no hooks.
91    pub fn new() -> Self {
92        Self::default()
93    }
94
95    /// Send `x-takeover: true`: at the connection limit, replace your stalest connection.
96    /// Default off.
97    pub fn takeover(mut self, value: bool) -> Self {
98        self.takeover = value;
99        self
100    }
101
102    /// Called for every `connection.admitted`.
103    pub fn on_admitted(mut self, hook: impl Fn(&AdmittedInfo) + Send + Sync + 'static) -> Self {
104        self.on_admitted = Some(Arc::new(hook));
105        self
106    }
107
108    /// Called after every new connection except the first one.
109    pub fn on_reconnect(mut self, hook: impl Fn(&ReconnectInfo) + Send + Sync + 'static) -> Self {
110        self.on_reconnect = Some(Arc::new(hook));
111        self
112    }
113
114    /// Called for problems that do not end the stream.
115    pub fn on_error(mut self, hook: impl Fn(&Error) + Send + Sync + 'static) -> Self {
116        self.on_error = Some(Arc::new(hook));
117        self
118    }
119
120    /// Called for every wait for the WebSocket quota (see `Config::quota_reconnect`).
121    pub fn on_quota_wait(mut self, hook: impl Fn(&QuotaWaitInfo) + Send + Sync + 'static) -> Self {
122        self.on_quota_wait = Some(Arc::new(hook));
123        self
124    }
125}
126
127impl fmt::Debug for StreamOptions {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.debug_struct("StreamOptions")
130            .field("takeover", &self.takeover)
131            .field("on_admitted", &self.on_admitted.is_some())
132            .field("on_reconnect", &self.on_reconnect.is_some())
133            .field("on_error", &self.on_error.is_some())
134            .field("on_quota_wait", &self.on_quota_wait.is_some())
135            .finish()
136    }
137}
138
139struct Shared {
140    last_seen_at: Mutex<Option<String>>,
141    closed: AtomicBool,
142}
143
144/// A live stream of [`StreamEvent`]s.
145///
146/// Poll it with `while let Some(e) = stream.next().await` (`futures_util::StreamExt`). A
147/// terminal problem (refused key, plan without WebSockets, validation, a `connection_limit`
148/// preemption, a used-up quota with `quota_reconnect` off) arrives as one `Err`, then the
149/// stream ends with `None`. Dropping the stream or calling [`FinlightStream::close`] closes the
150/// socket with 1000 and stops all background work.
151pub struct FinlightStream {
152    rx: mpsc::UnboundedReceiver<Result<StreamEvent>>,
153    stop: Option<watch::Sender<bool>>,
154    task: Option<JoinHandle<()>>,
155    shared: Arc<Shared>,
156    finished: bool,
157}
158
159impl FinlightStream {
160    /// Stops the stream: closes the socket with 1000 and waits until the background task ended.
161    pub async fn close(&mut self) {
162        if let Some(stop) = self.stop.take() {
163            let _ = stop.send(true);
164        }
165        if let Some(task) = self.task.take() {
166            let _ = task.await;
167        }
168        self.finished = true;
169        self.shared.closed.store(true, Ordering::SeqCst);
170    }
171
172    /// Last timestamp seen (see [`ReconnectInfo::last_seen_at`]).
173    pub fn last_seen_at(&self) -> Option<String> {
174        self.shared
175            .last_seen_at
176            .lock()
177            .map(|g| g.clone())
178            .unwrap_or(None)
179    }
180
181    /// `true` once the stream ended or was closed.
182    pub fn closed(&self) -> bool {
183        self.finished || self.shared.closed.load(Ordering::SeqCst)
184    }
185}
186
187impl Stream for FinlightStream {
188    type Item = Result<StreamEvent>;
189
190    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
191        let this = self.get_mut();
192        if this.finished {
193            return Poll::Ready(None);
194        }
195        match this.rx.poll_recv(cx) {
196            Poll::Ready(Some(Ok(item))) => Poll::Ready(Some(Ok(item))),
197            Poll::Ready(Some(Err(err))) => {
198                this.finished = true;
199                Poll::Ready(Some(Err(err)))
200            }
201            Poll::Ready(None) => {
202                this.finished = true;
203                Poll::Ready(None)
204            }
205            Poll::Pending => Poll::Pending,
206        }
207    }
208}
209
210impl Drop for FinlightStream {
211    fn drop(&mut self) {
212        if let Some(stop) = self.stop.take() {
213            let _ = stop.send(true);
214        }
215    }
216}
217
218impl fmt::Debug for FinlightStream {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        f.debug_struct("FinlightStream")
221            .field("closed", &self.closed())
222            .field("last_seen_at", &self.last_seen_at())
223            .finish()
224    }
225}
226
227pub(crate) fn start(
228    cfg: Arc<Config>,
229    raw: bool,
230    subscribe: Map<String, Value>,
231    options: StreamOptions,
232) -> FinlightStream {
233    let (tx, rx) = mpsc::unbounded_channel();
234    let (stop_tx, stop_rx) = watch::channel(false);
235    let shared = Arc::new(Shared {
236        last_seen_at: Mutex::new(None),
237        closed: AtomicBool::new(false),
238    });
239    let driver = Driver {
240        url: cfg.stream_url(raw),
241        dedupe: Dedupe::new(cfg.dedupe_cache_size),
242        cfg,
243        raw,
244        subscribe,
245        options,
246        tx,
247        stop: stop_rx,
248        shared: shared.clone(),
249        connections: 0,
250        failures: 0,
251        quota_waits: 0,
252        search_failed: 0,
253        pending_quota_error: None,
254        last_seen_nanos: None,
255    };
256    let task = tokio::spawn(driver.run());
257    FinlightStream {
258        rx,
259        stop: Some(stop_tx),
260        task: Some(task),
261        shared,
262        finished: false,
263    }
264}
265
266#[derive(Debug, Clone, Copy)]
267enum Delay {
268    Now,
269    Backoff,
270    Long,
271    Quota,
272}
273
274enum Plan {
275    Terminal(Error),
276    Reconnect(ReconnectReason, Delay),
277}
278
279enum Next {
280    Stop,
281    Plan(Plan),
282}
283
284struct Conn {
285    ws: WsConn,
286    ping: Interval,
287    watchdog: Instant,
288    rotation: Instant,
289}
290
291impl Conn {
292    fn new(ws: WsConn, cfg: &Config) -> Self {
293        let now = Instant::now();
294        let mut ping = tokio::time::interval_at(now + cfg.ping_interval, cfg.ping_interval);
295        ping.set_missed_tick_behavior(MissedTickBehavior::Delay);
296        Conn {
297            ws,
298            ping,
299            watchdog: now + cfg.watchdog_timeout,
300            rotation: now + cfg.rotation_interval,
301        }
302    }
303
304    async fn send_text(&mut self, text: String) -> bool {
305        self.ws.send_text(&text).await.is_ok()
306    }
307
308    /// Closes with 1000 (graceful) and drops the socket.
309    async fn close(mut self) {
310        let _ = tokio::time::timeout(Duration::from_secs(5), self.ws.send_close(1000)).await;
311    }
312
313    /// Closes with 1000 and waits (at most 5 s) until the server confirms the close, so the
314    /// server has let go of the connection before the next dial.
315    async fn close_and_wait(mut self) {
316        let _ = tokio::time::timeout(Duration::from_secs(5), async {
317            if self.ws.send_close(1000).await.is_err() {
318                return;
319            }
320            while let Some(Ok(msg)) = self.ws.next().await {
321                if matches!(msg, WsMessage::Close(_)) {
322                    return;
323                }
324            }
325        })
326        .await;
327    }
328}
329
330struct Dedupe {
331    cap: usize,
332    order: VecDeque<String>,
333    keys: HashSet<String>,
334}
335
336impl Dedupe {
337    fn new(cap: usize) -> Self {
338        Dedupe {
339            cap,
340            order: VecDeque::new(),
341            keys: HashSet::new(),
342        }
343    }
344
345    /// `true` when the key was seen before (and refreshes it).
346    fn seen(&mut self, key: String) -> bool {
347        if self.cap == 0 {
348            return false;
349        }
350        if self.keys.contains(&key) {
351            if let Some(pos) = self.order.iter().position(|k| *k == key) {
352                self.order.remove(pos);
353            }
354            self.order.push_back(key);
355            return true;
356        }
357        self.keys.insert(key.clone());
358        self.order.push_back(key);
359        while self.order.len() > self.cap {
360            if let Some(old) = self.order.pop_front() {
361                self.keys.remove(&old);
362            }
363        }
364        false
365    }
366}
367
368const NO_WEBSOCKETS_PREFIX: &str = "Your subscription does not include WebSockets";
369const QUOTA_PREFIX: &str = "WebSocket quota exceeded";
370const TOO_MANY_PREFIX: &str = "Too many concurrent connections";
371
372fn refusal_message(body: Option<&str>) -> Option<String> {
373    let value: Value = serde_json::from_str(body?).ok()?;
374    let obj = value.as_object()?;
375    obj.get("message")
376        .or_else(|| obj.get("error"))
377        .and_then(Value::as_str)
378        .map(str::to_owned)
379}
380
381fn dial_error(
382    status: u16,
383    message: Option<&str>,
384    body: Option<&str>,
385    detail: Option<String>,
386) -> ApiError {
387    let detail = detail.or_else(|| message.map(str::to_owned));
388    let mut text = format!("WebSocket connection refused with HTTP {status}");
389    if let Some(d) = &detail {
390        text.push_str(&format!(": {d}"));
391    }
392    ApiError::new(ApiErrorData {
393        status,
394        code: None,
395        r#type: None,
396        title: Some("WebSocket connection refused".to_owned()),
397        detail,
398        request_id: None,
399        errors: Vec::new(),
400        api_kind: ApiErrorKind::from_status(status),
401        limit_type: None,
402        retry_after: None,
403        raw: body.map(str::to_owned),
404        message: text,
405    })
406}
407
408fn stream_error(
409    code: Option<&ConnectionErrorCode>,
410    message: Option<&str>,
411    details: Option<&Value>,
412) -> ApiError {
413    let mut errors = Vec::new();
414    if let Some(Value::Array(items)) = details {
415        for item in items.iter().filter_map(Value::as_object) {
416            let constraints: std::collections::BTreeMap<String, String> = item
417                .get("constraints")
418                .and_then(Value::as_object)
419                .map(|c| {
420                    c.iter()
421                        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_owned())))
422                        .collect()
423                })
424                .unwrap_or_default();
425            let issue = if constraints.is_empty() {
426                None
427            } else {
428                Some(constraints.values().cloned().collect::<Vec<_>>().join("; "))
429            };
430            errors.push(FieldIssue {
431                field: item.get("field").and_then(Value::as_str).map(str::to_owned),
432                issue,
433                // Closed vocabularies (sourceTypes, include) name the accepted values.
434                allowed_values: item
435                    .get("allowedValues")
436                    .and_then(Value::as_array)
437                    .map(|list| {
438                        list.iter()
439                            .filter_map(Value::as_str)
440                            .map(str::to_owned)
441                            .collect()
442                    }),
443                constraints: Some(constraints),
444            });
445        }
446    }
447    let problem = code.map(|c| ProblemCode::from(c.as_str()));
448    let api_kind = problem
449        .as_ref()
450        .map(ApiErrorKind::from_code)
451        .unwrap_or(ApiErrorKind::Other);
452    let mut raw = Map::new();
453    raw.insert(
454        "code".into(),
455        code.map(|c| Value::String(c.as_str().to_owned()))
456            .unwrap_or(Value::Null),
457    );
458    raw.insert(
459        "message".into(),
460        message
461            .map(|m| Value::String(m.to_owned()))
462            .unwrap_or(Value::Null),
463    );
464    if let Some(d) = details {
465        raw.insert("details".into(), d.clone());
466    }
467    let text = format!(
468        "stream error {}: {}",
469        code.map(|c| c.as_str()).unwrap_or("(no code)"),
470        message.unwrap_or_default()
471    );
472    ApiError::new(ApiErrorData {
473        status: 0,
474        code: problem,
475        r#type: None,
476        title: Some("Stream error".to_owned()),
477        detail: message.map(str::to_owned),
478        request_id: None,
479        errors,
480        api_kind,
481        limit_type: None,
482        retry_after: None,
483        raw: Some(Value::Object(raw).to_string()),
484        message: text.trim_end().to_owned(),
485    })
486}
487
488fn call_hook<T>(name: &str, hook: &Option<Hook<T>>, arg: &T) {
489    if let Some(hook) = hook {
490        if catch_unwind(AssertUnwindSafe(|| hook(arg))).is_err() {
491            tracing::error!(target: "finlight", "the {name} hook panicked; the stream continues");
492        }
493    }
494}
495
496enum Event {
497    Stop,
498    Current(Option<std::io::Result<WsMessage>>),
499    Old(Option<std::io::Result<WsMessage>>),
500    Ping,
501    Watchdog,
502    Rotate,
503}
504
505struct Driver {
506    cfg: Arc<Config>,
507    url: String,
508    raw: bool,
509    subscribe: Map<String, Value>,
510    options: StreamOptions,
511    tx: mpsc::UnboundedSender<Result<StreamEvent>>,
512    stop: watch::Receiver<bool>,
513    shared: Arc<Shared>,
514    connections: u32,
515    failures: u32,
516    quota_waits: u32,
517    search_failed: u32,
518    pending_quota_error: Option<Error>,
519    dedupe: Dedupe,
520    last_seen_nanos: Option<i128>,
521}
522
523impl Driver {
524    async fn run(mut self) {
525        let mut reason = ReconnectReason::Closed;
526        let mut first = true;
527        loop {
528            if *self.stop.borrow() {
529                break;
530            }
531            let outcome = tokio::select! {
532                o = dial(&self.cfg, &self.url, self.options.takeover) => o,
533                _ = self.stop.changed() => break,
534            };
535            let plan = match outcome {
536                DialOutcome::Open(ws) => match self.run_connection(*ws, reason, first).await {
537                    Next::Stop => break,
538                    Next::Plan(plan) => plan,
539                },
540                DialOutcome::Refused { status, body } => self.classify_refusal(status, body),
541                DialOutcome::Failed(err) => {
542                    if matches!(err, Error::Validation(_)) {
543                        Plan::Terminal(err)
544                    } else {
545                        self.report(err);
546                        Plan::Reconnect(ReconnectReason::DialFailed, Delay::Backoff)
547                    }
548                }
549            };
550            first = false;
551            match plan {
552                Plan::Terminal(err) => {
553                    tracing::warn!(target: "finlight", "the stream ended: {err}");
554                    let _ = self.tx.send(Err(err));
555                    break;
556                }
557                Plan::Reconnect(next_reason, delay) => {
558                    let wait = self.delay(delay);
559                    if wait > Duration::ZERO {
560                        tracing::info!(target: "finlight", reason = %next_reason, "reconnecting the stream in {wait:?}");
561                        tokio::select! {
562                            _ = tokio::time::sleep(wait) => {}
563                            _ = self.stop.changed() => break,
564                        }
565                    }
566                    reason = next_reason;
567                }
568            }
569        }
570        self.shared.closed.store(true, Ordering::SeqCst);
571    }
572
573    fn delay(&mut self, kind: Delay) -> Duration {
574        let cfg = &self.cfg;
575        match kind {
576            Delay::Now => Duration::ZERO,
577            Delay::Backoff => {
578                let d = backoff(
579                    cfg.reconnect_base_delay,
580                    cfg.reconnect_max_delay,
581                    self.failures,
582                );
583                self.failures = self.failures.saturating_add(1);
584                d
585            }
586            Delay::Long => cfg.long_backoff + cfg.long_backoff.mul_f64(fastrand::f64() * 0.2),
587            Delay::Quota => {
588                let wait = cfg.quota_reconnect_interval;
589                self.quota_waits = self.quota_waits.saturating_add(1);
590                let error = self
591                    .pending_quota_error
592                    .take()
593                    .unwrap_or_else(|| Error::Api(dial_error(403, Some(QUOTA_PREFIX), None, None)));
594                tracing::warn!(
595                    target: "finlight",
596                    attempt = self.quota_waits,
597                    "the WebSocket quota is used up ({error}); the stream tries again in {wait:?}"
598                );
599                let info = QuotaWaitInfo {
600                    error,
601                    next_attempt_in: wait,
602                    attempt: self.quota_waits,
603                };
604                call_hook("on_quota_wait", &self.options.on_quota_wait, &info);
605                wait
606            }
607        }
608    }
609
610    fn report(&self, err: Error) {
611        tracing::warn!(target: "finlight", "stream problem: {err}");
612        call_hook("on_error", &self.options.on_error, &err);
613    }
614
615    fn quota_plan(&mut self, error: Error) -> Plan {
616        if !self.cfg.quota_reconnect {
617            return Plan::Terminal(error);
618        }
619        self.pending_quota_error = Some(error);
620        Plan::Reconnect(ReconnectReason::QuotaExceeded, Delay::Quota)
621    }
622
623    fn classify_refusal(&mut self, status: u16, body: Option<String>) -> Plan {
624        let message = refusal_message(body.as_deref());
625        let text = message.clone().unwrap_or_default();
626        let err = |detail: Option<String>| {
627            dial_error(status, message.as_deref(), body.as_deref(), detail)
628        };
629        match status {
630            401 => Plan::Terminal(Error::Api(err(None))),
631            403 if text.starts_with(NO_WEBSOCKETS_PREFIX) => Plan::Terminal(Error::Api(err(None))),
632            403 if text.starts_with(QUOTA_PREFIX) => self.quota_plan(Error::Api(err(None))),
633            403 if text.starts_with(TOO_MANY_PREFIX) => {
634                self.report(Error::Api(err(Some(format!(
635                    "{text} The connection limit is shared by enriched, raw and older SDK streams; \
636                     the SDK retries after a long wait. Set StreamOptions::takeover(true) to replace \
637                     your stalest connection."
638                )))));
639                Plan::Reconnect(ReconnectReason::ConnectionLimit, Delay::Long)
640            }
641            403 => {
642                self.report(Error::Api(err(None)));
643                Plan::Reconnect(ReconnectReason::DialRefused, Delay::Long)
644            }
645            429 => {
646                self.report(Error::Api(err(None)));
647                Plan::Reconnect(ReconnectReason::RateLimited, Delay::Long)
648            }
649            500..=599 => Plan::Reconnect(ReconnectReason::DialRefused, Delay::Backoff),
650            _ => {
651                self.report(Error::Api(err(None)));
652                Plan::Reconnect(ReconnectReason::DialRefused, Delay::Backoff)
653            }
654        }
655    }
656
657    fn subscribe_text(&self) -> String {
658        let mut frame = self.subscribe.clone();
659        frame.insert(
660            "clientNonce".into(),
661            Value::String(format!("c-{}", uuid::Uuid::new_v4())),
662        );
663        Value::Object(frame).to_string()
664    }
665
666    fn set_last_seen(&mut self, value: &str) {
667        let Some(nanos) = parse_rfc3339_nanos(value) else {
668            return;
669        };
670        if self.last_seen_nanos.is_none_or(|seen| nanos >= seen) {
671            self.last_seen_nanos = Some(nanos);
672            if let Ok(mut guard) = self.shared.last_seen_at.lock() {
673                *guard = Some(value.to_owned());
674            }
675        }
676    }
677
678    fn last_seen(&self) -> Option<String> {
679        self.shared
680            .last_seen_at
681            .lock()
682            .map(|g| g.clone())
683            .unwrap_or(None)
684    }
685
686    /// A refused dial while renewing the connection. The old connection is still open and
687    /// still counts against the connection limit, so a refusal is expected on plans at their
688    /// limit: the old connection is closed and the stream dials again at once, without
689    /// `on_error`. Only refusals that end a stream end it here too.
690    fn rotation_refusal(&mut self, status: u16, body: Option<String>) -> Plan {
691        let text = refusal_message(body.as_deref()).unwrap_or_default();
692        let terminal = status == 401
693            || (status == 403 && text.starts_with(NO_WEBSOCKETS_PREFIX))
694            || (status == 403 && text.starts_with(QUOTA_PREFIX) && !self.cfg.quota_reconnect);
695        if terminal {
696            return self.classify_refusal(status, body);
697        }
698        tracing::info!(
699            target: "finlight",
700            "the renewal dial was refused with HTTP {status}; closing the old connection and dialing again now"
701        );
702        Plan::Reconnect(ReconnectReason::Rotation, Delay::Now)
703    }
704
705    async fn run_connection(&mut self, ws: WsConn, reason: ReconnectReason, first: bool) -> Next {
706        self.connections += 1;
707        let mut cur = Conn::new(ws, &self.cfg);
708        let mut old: Option<Conn> = None;
709        if !cur.send_text(self.subscribe_text()).await {
710            return Next::Plan(Plan::Reconnect(ReconnectReason::Closed, Delay::Backoff));
711        }
712        if !first {
713            let info = ReconnectInfo {
714                last_seen_at: self.last_seen(),
715                reason,
716                connection: self.connections,
717            };
718            call_hook("on_reconnect", &self.options.on_reconnect, &info);
719        }
720        loop {
721            let rotating = old.is_some();
722            let event = {
723                let old_next = async {
724                    match old.as_mut() {
725                        Some(c) => c.ws.next().await,
726                        None => std::future::pending().await,
727                    }
728                };
729                tokio::select! {
730                    biased;
731                    _ = self.stop.changed() => Event::Stop,
732                    m = cur.ws.next() => Event::Current(m),
733                    m = old_next => Event::Old(m),
734                    _ = cur.ping.tick() => Event::Ping,
735                    _ = tokio::time::sleep_until(cur.watchdog) => Event::Watchdog,
736                    _ = tokio::time::sleep_until(cur.rotation), if !rotating => Event::Rotate,
737                }
738            };
739            match event {
740                Event::Stop => {
741                    cur.close().await;
742                    if let Some(o) = old.take() {
743                        o.close().await;
744                    }
745                    return Next::Stop;
746                }
747                Event::Ping => {
748                    let ping = format!(
749                        "{{\"action\":\"ping\",\"t\":{}}}",
750                        epoch_millis(SystemTime::now())
751                    );
752                    if !cur.send_text(ping).await {
753                        tracing::debug!(target: "finlight", "could not send a ping");
754                    }
755                }
756                Event::Watchdog => {
757                    tracing::warn!(
758                        target: "finlight",
759                        "no pong for {:?}; replacing the stream connection",
760                        self.cfg.watchdog_timeout
761                    );
762                    drop(cur);
763                    if let Some(o) = old.take() {
764                        o.close().await;
765                    }
766                    return Next::Plan(Plan::Reconnect(ReconnectReason::Watchdog, Delay::Now));
767                }
768                Event::Rotate => {
769                    tracing::info!(target: "finlight", "renewing the stream connection before the 2 h gateway limit");
770                    let outcome = tokio::select! {
771                        o = dial(&self.cfg, &self.url, self.options.takeover) => o,
772                        _ = self.stop.changed() => {
773                            cur.close().await;
774                            return Next::Stop;
775                        }
776                    };
777                    match outcome {
778                        DialOutcome::Open(ws) => {
779                            self.connections += 1;
780                            let mut fresh = Conn::new(*ws, &self.cfg);
781                            if !fresh.send_text(self.subscribe_text()).await {
782                                cur.close_and_wait().await;
783                                return Next::Plan(Plan::Reconnect(
784                                    ReconnectReason::Rotation,
785                                    Delay::Now,
786                                ));
787                            }
788                            let info = ReconnectInfo {
789                                last_seen_at: self.last_seen(),
790                                reason: ReconnectReason::Rotation,
791                                connection: self.connections,
792                            };
793                            call_hook("on_reconnect", &self.options.on_reconnect, &info);
794                            old = Some(std::mem::replace(&mut cur, fresh));
795                        }
796                        DialOutcome::Refused { status, body } => {
797                            cur.close_and_wait().await;
798                            return Next::Plan(self.rotation_refusal(status, body));
799                        }
800                        DialOutcome::Failed(err) => {
801                            // Dial again at once; a failure of that dial is reported as usual.
802                            tracing::warn!(target: "finlight", "the renewal dial failed ({err}); dialing again now");
803                            cur.close_and_wait().await;
804                            return Next::Plan(Plan::Reconnect(
805                                ReconnectReason::Rotation,
806                                Delay::Now,
807                            ));
808                        }
809                    }
810                }
811                Event::Old(msg) => match msg {
812                    Some(Ok(WsMessage::Text(text))) => {
813                        // The old connection of a rotation still delivers until the new one is admitted.
814                        if let Some(frame) = frames::decode(text.as_str()) {
815                            if let Frame::Article { .. } | Frame::Other { .. } = frame {
816                                self.deliver(frame, text.as_str());
817                            }
818                        }
819                    }
820                    Some(Ok(WsMessage::Close(_))) | Some(Err(_)) | None => old = None,
821                    Some(Ok(_)) => {}
822                },
823                Event::Current(msg) => {
824                    let close_code = match msg {
825                        Some(Ok(WsMessage::Text(text))) => {
826                            match self.handle_frame(text.as_str(), &mut cur, &mut old).await {
827                                None => continue,
828                                Some(plan) => {
829                                    cur.close().await;
830                                    if let Some(o) = old.take() {
831                                        o.close().await;
832                                    }
833                                    return Next::Plan(plan);
834                                }
835                            }
836                        }
837                        Some(Ok(WsMessage::Close(code))) => code,
838                        Some(Ok(WsMessage::Ping(payload))) => {
839                            if cur.ws.send_pong(&payload).await.is_err() {
840                                tracing::debug!(target: "finlight", "could not answer a WebSocket ping");
841                            }
842                            continue;
843                        }
844                        Some(Ok(_)) => continue,
845                        Some(Err(e)) => {
846                            tracing::debug!(target: "finlight", "stream connection error: {e}");
847                            None
848                        }
849                        None => None,
850                    };
851                    if let Some(o) = old.take() {
852                        o.close().await;
853                    }
854                    if close_code == Some(1008) {
855                        return Next::Plan(Plan::Terminal(Error::Api(ApiError::new(
856                            ApiErrorData {
857                                status: 1008,
858                                code: None,
859                                r#type: None,
860                                title: Some("Policy violation".to_owned()),
861                                detail: Some(
862                                    "the server closed the stream with code 1008".to_owned(),
863                                ),
864                                request_id: None,
865                                errors: Vec::new(),
866                                api_kind: ApiErrorKind::Other,
867                                limit_type: None,
868                                retry_after: None,
869                                raw: None,
870                                message:
871                                    "the server closed the stream with code 1008 (policy violation)"
872                                        .to_owned(),
873                            },
874                        ))));
875                    }
876                    tracing::info!(target: "finlight", code = ?close_code, "the stream connection closed");
877                    return Next::Plan(Plan::Reconnect(ReconnectReason::Closed, Delay::Backoff));
878                }
879            }
880        }
881    }
882
883    /// Handles a frame of the current connection. `Some(plan)` ends the connection.
884    async fn handle_frame(
885        &mut self,
886        text: &str,
887        cur: &mut Conn,
888        old: &mut Option<Conn>,
889    ) -> Option<Plan> {
890        let Some(frame) = frames::decode(text) else {
891            tracing::warn!(target: "finlight", "ignored a stream frame that is not a JSON object");
892            return None;
893        };
894        match frame {
895            Frame::Pong => {
896                cur.watchdog = Instant::now() + self.cfg.watchdog_timeout;
897                // The connection works: the reconnect backoff starts over.
898                self.failures = 0;
899                None
900            }
901            Frame::Admitted {
902                lease_id,
903                server_now,
904                client_nonce,
905            } => {
906                // Admitted comes before the subscribe is checked and the initial search runs,
907                // so it does not reset the reconnect backoff; a pong or an article does.
908                self.quota_waits = 0;
909                if let Some(o) = old.take() {
910                    o.close().await;
911                }
912                let info = AdmittedInfo {
913                    lease_id,
914                    server_now,
915                    client_nonce,
916                };
917                call_hook("on_admitted", &self.options.on_admitted, &info);
918                None
919            }
920            Frame::Preempted {
921                reason,
922                new_lease_id,
923                timestamp,
924            } => {
925                let quota = reason == PreemptReason::QuotaExceeded;
926                let err = Error::Preempted(PreemptedError::new(reason, new_lease_id, timestamp));
927                Some(if quota {
928                    self.quota_plan(err)
929                } else {
930                    Plan::Terminal(err)
931                })
932            }
933            Frame::Error {
934                code,
935                message,
936                details,
937            } => {
938                let err = stream_error(code.as_ref(), message.as_deref(), details.as_ref());
939                match code {
940                    Some(ConnectionErrorCode::ValidationFailed) => {
941                        Some(Plan::Terminal(Error::Api(err)))
942                    }
943                    Some(ConnectionErrorCode::HandshakeFailed) => {
944                        tracing::warn!(target: "finlight", "the stream handshake failed; reconnecting");
945                        Some(Plan::Reconnect(
946                            ReconnectReason::HandshakeFailed,
947                            Delay::Backoff,
948                        ))
949                    }
950                    Some(ConnectionErrorCode::SearchFailed) => {
951                        self.search_failed += 1;
952                        if self.search_failed >= self.cfg.search_failed_threshold.max(1) {
953                            self.search_failed = 0;
954                            self.report(Error::Api(err));
955                        } else {
956                            tracing::warn!(target: "finlight", "the initial stream search failed; reconnecting");
957                        }
958                        Some(Plan::Reconnect(
959                            ReconnectReason::SearchFailed,
960                            Delay::Backoff,
961                        ))
962                    }
963                    _ => {
964                        // PING_ON_DEFAULT_ROUTE, INTERNAL_ERROR, unknown codes and v2-form errors.
965                        self.report(Error::Api(err));
966                        None
967                    }
968                }
969            }
970            frame @ (Frame::Article { .. } | Frame::Other { .. }) => {
971                if matches!(frame, Frame::Article { .. }) {
972                    self.failures = 0;
973                }
974                self.deliver(frame, text);
975                None
976            }
977            Frame::Ignored(why) => {
978                tracing::debug!(target: "finlight", "ignored a stream frame: {why}");
979                None
980            }
981        }
982    }
983
984    fn deliver(&mut self, frame: Frame, text: &str) {
985        match frame {
986            Frame::Article {
987                event,
988                updated,
989                data,
990            } => {
991                self.search_failed = 0;
992                let article = match decode_article(&data, "data") {
993                    Ok(a) => a,
994                    Err(err) => {
995                        self.report(Error::decode(
996                            format!("skipped a stream article that could not be decoded: {err}"),
997                            None,
998                            Some(text.to_owned()),
999                            None,
1000                        ));
1001                        return;
1002                    }
1003                };
1004                let digest = hex::encode(Sha256::digest(data.get().as_bytes()));
1005                let key = format!("{}\n{}\n{digest}", event.as_str(), article.id);
1006                if self.dedupe.seen(key) {
1007                    tracing::debug!(target: "finlight", id = %article.id, "dropped a duplicate {event}");
1008                    return;
1009                }
1010                let seen = if self.raw {
1011                    article.first_seen_at.clone()
1012                } else {
1013                    article
1014                        .available_at
1015                        .clone()
1016                        .or_else(|| article.first_seen_at.clone())
1017                };
1018                if let Some(seen) = seen {
1019                    self.set_last_seen(&seen);
1020                }
1021                let kind = if updated {
1022                    StreamEventKind::Updated
1023                } else {
1024                    StreamEventKind::Created
1025                };
1026                let _ = self.tx.send(Ok(StreamEvent::new(
1027                    kind,
1028                    event,
1029                    Some(article),
1030                    Arc::from(text),
1031                )));
1032            }
1033            Frame::Other { event } => {
1034                tracing::debug!(target: "finlight", %event, "unknown stream event");
1035                let _ = self.tx.send(Ok(StreamEvent::new(
1036                    StreamEventKind::Other,
1037                    event,
1038                    None,
1039                    Arc::from(text),
1040                )));
1041            }
1042            _ => {}
1043        }
1044    }
1045}