Skip to main content

libkeri_watcher/
http.rs

1//! Async driver for [`DelegationWatch`] over libkeri-http.
2//!
3//! The owner keeps its `Habery`; the driver borrows it between fetches, so
4//! the libkeri state is never shared across tasks.
5
6use std::time::Duration;
7
8use libkeri::Habery;
9use libkeri_http::Client;
10
11use crate::{DelegationWatch, Outcome, WatchError};
12
13/// Poll the delegator's witnesses every `interval` until the delegator has
14/// approved, or `timeout` passes. Returns the approved event with its source
15/// seal couple, for the delegate's witnesses.
16///
17/// A witness that is unreachable or has nothing fully witnessed yet (keripy
18/// answers 404 until then) counts as pending.
19pub async fn wait_for_approval(
20    client: &Client,
21    hby: &mut Habery,
22    watch: &mut DelegationWatch,
23    interval: Duration,
24    timeout: Duration,
25) -> Result<Vec<u8>, WatchError> {
26    if let Outcome::Approved(msg) = watch.check(hby)? {
27        return Ok(msg);
28    }
29    let deadline = tokio::time::Instant::now() + timeout;
30    loop {
31        let req = watch.next_request(hby)?;
32        let body = client.get_oobi(&req.url).await.unwrap_or_default();
33        if let Outcome::Approved(msg) = watch.feed(hby, &body)? {
34            return Ok(msg);
35        }
36        if tokio::time::Instant::now() + interval > deadline {
37            return Err(WatchError::Timeout {
38                what: format!(
39                    "{} to approve {} at sn {}",
40                    watch.delpre(),
41                    watch.delegate(),
42                    watch.sn()
43                ),
44                polls: watch.polls(),
45            });
46        }
47        tokio::time::sleep(interval).await;
48    }
49}