Skip to main content

weirdnet_agent/remote/
pool.rs

1//! The asking side of remote inference: a pool of inference nodes.
2//!
3//! [`Pool`] sends a [`Request`] to the first node of its [`NodeSource`] that takes it
4//! (infer/2, falling back to infer/1 on nodes that only serve that), streams the answer to an
5//! [`EventSink`], and moves on to the next node when one fails:
6//!
7//! - **Before any text** (unreachable, busy, no such model, no `Accepted` in time): the next
8//!   node is tried, as `RemoteModel` always did. `Queued` frames reset the accept timeout.
9//! - **During the answer** (the stream drops, the node fails, or no frame arrives within the
10//!   [`Stall`] timeout, after which the pool sends `Cancel` itself rather than wait out
11//!   `weirdnet-net`'s 30 s stream resume): with [`PoolOptions::resume`] on, the request goes to
12//!   the next node as the same job with `attempt + 1` and the text shown so far as
13//!   `assistant_prefix`, but only to a node whose `Accepted` says `resume: true`. Frames are
14//!   placed by offset, so nothing is shown twice. At most [`PoolOptions::max_resumes`] resumes
15//!   per answer; each is recorded in the answer's [`Meta::resumes`]. With resume off, or once
16//!   nothing more can take it, the partial answer comes back in [`Interrupted`].
17//! - **Continue:** a request that already carries an `assistant_prefix` (the user asked to
18//!   continue a stopped or cut-off answer) continues that text: the answer starts from the
19//!   prefix ([`Answer::prefix`]; `text` and `reasoning` include it, events carry only what is
20//!   new), and only nodes whose `Accepted` says `resume: true` take it. Failover keeps the
21//!   prefix whether or not resume is on; infer/1 nodes are skipped.
22//!
23//! - **Images and audio:** a request whose messages carry image or audio parts
24//!   ([`Request::needs`]) is routed by the catalog first ([`Catalog::route`]): a named model must
25//!   list those inputs, and with none named the pool picks one that does. When the catalog says
26//!   no model takes them, the request fails with `BadRequest` before any node runs it. With no
27//!   catalog to ask, the nodes decide (model nodes refuse inputs their model can't read). Such
28//!   requests never go to infer/1 nodes, which predate content parts.
29//!
30//! The pool also queries and subscribes to the [`catalog`], sends embeddings, transcription
31//! requests ([`Pool::transcribe`]) and speech requests ([`Pool::speak`], [`Pool::speak_stream`],
32//! failing over only before the audio starts), and runs [`Job`]s in the background. It has no networking of its own: a [`Dialer`] opens
33//! channels and a [`NodeSource`] says which nodes to try, in order. The `pool` cargo feature
34//! provides both over `weirdnet-net` (`crate::pool`).
35
36use std::collections::BTreeMap;
37use std::sync::Arc;
38use std::time::Duration;
39
40use tokio::time::Instant;
41
42use async_trait::async_trait;
43use tokio::sync::{mpsc, watch};
44use tokio::task::JoinHandle;
45
46use super::catalog::{self, Catalog};
47use super::infer::v2::{
48    self, AudioHeader, ClientFrame, EmbedRequest, Finish, Meta, Prefix, Request, Resume, ServerFrame, SpeakRequest, TranscribeRequest, Transcript,
49    Usage, chars,
50};
51use super::infer::{self as v1, DEFAULT_ACCEPT_TIMEOUT};
52use super::{Channel, Dialer, RemoteError, request_id};
53use crate::cancel::CancelToken;
54use crate::model::{DeltaSink, ModelTurn, ToolCall};
55use crate::speech::AudioFormat;
56
57/// Resumes per answer when [`PoolOptions::resume`] is on.
58pub const DEFAULT_MAX_RESUMES: u32 = 2;
59
60/// When an accepted stream counts as stalled: no frame for `max(min, factor × the recent gap
61/// between frames)`, capped at `max`. Before the first frame after `Accepted` (prompt
62/// processing) the wait is `max`. The defaults (15 s, 3×, 25 s) stay under `weirdnet-net`'s
63/// 30 s stream resume window, so the pool cancels and moves on before the transport would give
64/// up.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66#[non_exhaustive]
67pub struct Stall {
68    pub min: Duration,
69    pub factor: u32,
70    pub max: Duration,
71}
72
73impl Default for Stall {
74    fn default() -> Self {
75        Self { min: Duration::from_secs(15), factor: 3, max: Duration::from_secs(25) }
76    }
77}
78
79impl Stall {
80    pub fn new(min: Duration, factor: u32, max: Duration) -> Self {
81        Self { min, factor, max }
82    }
83
84    /// The wait for the first frame after `Accepted`.
85    pub fn first(&self) -> Duration {
86        self.max.max(self.min)
87    }
88
89    /// The timeout given the recent gap between frames.
90    pub fn timeout(&self, recent_gap: Option<Duration>) -> Duration {
91        let scaled = recent_gap.map(|g| g * self.factor).unwrap_or_default();
92        scaled.max(self.min).min(self.max.max(self.min))
93    }
94}
95
96/// The recent gap between frames: a moving average.
97#[derive(Debug, Default)]
98struct Gaps {
99    last: Option<Instant>,
100    recent: Option<Duration>,
101}
102
103impl Gaps {
104    fn wait(&self, stall: &Stall) -> Duration {
105        if self.last.is_none() { stall.first() } else { stall.timeout(self.recent) }
106    }
107
108    fn tick(&mut self) {
109        let now = Instant::now();
110        if let Some(last) = self.last {
111            let gap = now - last;
112            self.recent = Some(match self.recent {
113                Some(r) => (r * 3 + gap) / 4,
114                None => gap,
115            });
116        }
117        self.last = Some(now);
118    }
119}
120
121/// How a [`Pool`] behaves.
122#[derive(Debug, Clone, PartialEq, Eq)]
123#[non_exhaustive]
124pub struct PoolOptions {
125    /// How long a node has to accept (reset by each `Queued`), and to open a channel.
126    pub accept_timeout: Duration,
127    pub stall: Stall,
128    /// Continue an interrupted answer on another node. On by default; `RemoteModel` turns it off.
129    pub resume: bool,
130    pub max_resumes: u32,
131    /// Try infer/1 on nodes that do not serve infer/2 (only before any text has streamed).
132    pub infer_v1_fallback: bool,
133    /// The certificate presented with every request (for Weirdnet a CBOR `NodeCert`).
134    pub cert: Option<Vec<u8>>,
135}
136
137impl Default for PoolOptions {
138    fn default() -> Self {
139        Self {
140            accept_timeout: DEFAULT_ACCEPT_TIMEOUT,
141            stall: Stall::default(),
142            resume: true,
143            max_resumes: DEFAULT_MAX_RESUMES,
144            infer_v1_fallback: true,
145            cert: None,
146        }
147    }
148}
149
150impl PoolOptions {
151    pub fn with_accept_timeout(mut self, timeout: Duration) -> Self {
152        self.accept_timeout = timeout;
153        self
154    }
155
156    pub fn with_stall(mut self, stall: Stall) -> Self {
157        self.stall = stall;
158        self
159    }
160
161    pub fn with_resume(mut self, resume: bool) -> Self {
162        self.resume = resume;
163        self
164    }
165
166    pub fn with_max_resumes(mut self, max: u32) -> Self {
167        self.max_resumes = max;
168        self
169    }
170
171    pub fn with_infer_v1_fallback(mut self, on: bool) -> Self {
172        self.infer_v1_fallback = on;
173        self
174    }
175
176    pub fn with_cert(mut self, cert: Option<Vec<u8>>) -> Self {
177        self.cert = cert;
178        self
179    }
180}
181
182/// Which inference nodes to try, best first (for example the local one, then the closest).
183#[async_trait]
184pub trait NodeSource: Send + Sync {
185    async fn nodes(&self) -> Vec<String>;
186}
187
188#[async_trait]
189impl NodeSource for Vec<String> {
190    async fn nodes(&self) -> Vec<String> {
191        self.clone()
192    }
193}
194
195/// What the pool reports while an answer streams.
196#[derive(Debug, Clone, PartialEq)]
197#[non_exhaustive]
198pub enum PoolEvent {
199    /// Waiting on `node` at this place.
200    Queued {
201        node: String,
202        position: u32,
203    },
204    Accepted {
205        node: String,
206        model: String,
207        resume: bool,
208    },
209    Text(String),
210    Reasoning(String),
211    ToolCall(ToolCall),
212    Usage(Usage),
213    /// The answer continues on `node` from `offset` characters.
214    Resumed {
215        node: String,
216        offset: u64,
217    },
218    /// Response metadata the node knew before the answer, such as a cache hit (0.4.1 servers
219    /// and later; the final [`Answer::meta`] has it too).
220    Meta(Meta),
221}
222
223/// Where a [`Pool`] streams [`PoolEvent`]s. A [`DeltaSink`] takes the text and reasoning.
224pub trait EventSink: Send + Sync {
225    fn event(&self, event: PoolEvent);
226}
227
228impl EventSink for DeltaSink {
229    fn event(&self, event: PoolEvent) {
230        match event {
231            PoolEvent::Text(t) => self.text(t),
232            PoolEvent::Reasoning(t) => self.reasoning(t),
233            _ => {}
234        }
235    }
236}
237
238impl EventSink for mpsc::UnboundedSender<PoolEvent> {
239    fn event(&self, event: PoolEvent) {
240        let _ = self.send(event);
241    }
242}
243
244/// An [`EventSink`] that drops everything.
245#[derive(Debug, Clone, Copy, Default)]
246pub struct NoEvents;
247
248impl EventSink for NoEvents {
249    fn event(&self, _: PoolEvent) {}
250}
251
252/// A whole answer.
253#[derive(Debug, Clone, PartialEq, Default)]
254#[non_exhaustive]
255pub struct Answer {
256    pub text: String,
257    pub reasoning: String,
258    pub tool_calls: Vec<ToolCall>,
259    pub finish_reason: Option<String>,
260    pub usage: Option<Usage>,
261    pub meta: Meta,
262    /// The inference node that finished it.
263    pub node: String,
264    /// The model it reported.
265    pub model: String,
266    /// The `assistant_prefix` the request asked to continue (empty if none). `text` and
267    /// `reasoning` start with it; [`Answer::continuation`] is the text after it.
268    pub prefix: Prefix,
269}
270
271impl Answer {
272    /// As a model turn (text and tool calls).
273    pub fn turn(&self) -> ModelTurn {
274        ModelTurn { text: self.text.clone(), tool_calls: self.tool_calls.clone() }
275    }
276
277    /// The text generated after [`Answer::prefix`] (all of it when there is none).
278    pub fn continuation(&self) -> &str {
279        let at = self.text.char_indices().nth(self.prefix.len as usize).map_or(self.text.len(), |(i, _)| i);
280        &self.text[at..]
281    }
282
283    /// Something was generated beyond the prefix.
284    fn has_output(&self) -> bool {
285        chars(&self.text) > self.prefix.len || chars(&self.reasoning) > self.prefix.reasoning_len || !self.tool_calls.is_empty()
286    }
287
288    /// The text and reasoning so far, as the prefix of a next attempt.
289    fn shown(&self) -> Option<Prefix> {
290        (!self.text.is_empty() || !self.reasoning.is_empty()).then(|| Prefix::new(self.text.clone(), self.reasoning.clone()))
291    }
292}
293
294/// An answer that could not be finished: why, what was shown, and every node tried.
295#[derive(Debug, Clone, PartialEq, thiserror::Error)]
296#[error("{error}")]
297#[non_exhaustive]
298pub struct Interrupted {
299    pub error: RemoteError,
300    /// What streamed before it stopped (empty if nothing did).
301    pub partial: Box<Answer>,
302    /// Each node tried and why it did not finish.
303    pub tried: Vec<(String, RemoteError)>,
304}
305
306impl Interrupted {
307    /// Some of the answer was shown.
308    pub fn streamed(&self) -> bool {
309        self.partial.has_output()
310    }
311}
312
313/// Embeddings for each input, in order.
314#[derive(Debug, Clone, PartialEq, Default)]
315#[non_exhaustive]
316pub struct Embeddings {
317    pub vectors: Vec<Vec<f32>>,
318    pub model: String,
319    pub node: String,
320    pub meta: Meta,
321    /// Prompt tokens, when the serving node reports them (0.4.1 servers and later).
322    pub usage: Option<Usage>,
323}
324
325/// A transcript and where it came from ([`Pool::transcribe`]).
326#[derive(Debug, Clone, PartialEq, Default)]
327#[non_exhaustive]
328pub struct Transcription {
329    pub transcript: Transcript,
330    /// The backend that served it, as its node named it in `Accepted`.
331    pub model: String,
332    pub node: String,
333    pub meta: Meta,
334    /// Token counts, when the serving node reports them.
335    pub usage: Option<Usage>,
336}
337
338/// Speech and where it came from ([`Pool::speak`], since 0.5.11).
339#[derive(Debug, Clone, PartialEq, Default)]
340#[non_exhaustive]
341pub struct Speech {
342    /// The whole file, in `format`.
343    pub audio: Vec<u8>,
344    pub format: AudioFormat,
345    /// Hz, when the node said.
346    pub sample_rate: Option<u32>,
347    /// When the node said.
348    pub channels: Option<u16>,
349    /// The backend that served it, as its node named it in `Accepted`.
350    pub model: String,
351    pub node: String,
352    pub meta: Meta,
353    /// Characters spoken, audio milliseconds and engine tokens, as the node reports them.
354    pub usage: Option<Usage>,
355}
356
357/// Speech arriving from the node that started it ([`Pool::speak_stream`], since 0.5.11): the
358/// header is known, the audio comes with [`next`](Self::next). A failure from here on is final
359/// (no other node is tried). Dropping it mid-way closes the stream, which stops the node.
360pub struct SpeechStream {
361    ch: Channel,
362    id: String,
363    header: AudioHeader,
364    model: String,
365    node: String,
366    offset: u64,
367    wait: Duration,
368    cancel: CancelToken,
369    end: Option<(Meta, Option<Usage>)>,
370}
371
372impl std::fmt::Debug for SpeechStream {
373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374        f.debug_struct("SpeechStream")
375            .field("id", &self.id)
376            .field("header", &self.header)
377            .field("model", &self.model)
378            .field("node", &self.node)
379            .field("offset", &self.offset)
380            .finish()
381    }
382}
383
384impl SpeechStream {
385    /// The format, and the rate and channels when known.
386    pub fn header(&self) -> AudioHeader {
387        self.header
388    }
389
390    /// The backend serving it, as its node named it in `Accepted`.
391    pub fn model(&self) -> &str {
392        &self.model
393    }
394
395    pub fn node(&self) -> &str {
396        &self.node
397    }
398
399    /// Bytes of audio received so far.
400    pub fn received(&self) -> u64 {
401        self.offset
402    }
403
404    /// The `Done` metadata, once [`next`](Self::next) has returned `Ok(None)`.
405    pub fn meta(&self) -> Option<&Meta> {
406        self.end.as_ref().map(|(m, _)| m)
407    }
408
409    /// The usage, once [`next`](Self::next) has returned `Ok(None)` (if the node reported it).
410    pub fn usage(&self) -> Option<Usage> {
411        self.end.as_ref().and_then(|(_, u)| *u)
412    }
413
414    /// The next piece of audio, in order; `Ok(None)` when the speech is complete. `Err` when the
415    /// node fails, the stream drops or stalls (no frame within the pool's stall cap), or the
416    /// cancel token fires (the node is told to stop).
417    pub async fn next(&mut self) -> Result<Option<Vec<u8>>, RemoteError> {
418        if self.end.is_some() {
419            return Ok(None);
420        }
421        loop {
422            let next = tokio::select! {
423                _ = self.cancel.cancelled() => {
424                    let _ = self.ch.send_cbor(&ClientFrame::Cancel { id: self.id.clone() }).await;
425                    return Err(RemoteError::Cancelled);
426                }
427                r = tokio::time::timeout(self.wait, self.ch.recv_cbor::<ServerFrame>()) => r,
428            };
429            let frame = match next {
430                Err(_) => {
431                    let _ = self.ch.send_cbor(&ClientFrame::Cancel { id: self.id.clone() }).await;
432                    return Err(RemoteError::Stalled { ms: self.wait.as_millis() as u64 });
433                }
434                Ok(Err(e)) => return Err(e),
435                Ok(Ok(None)) => return Err(RemoteError::Closed),
436                Ok(Ok(Some(f))) => f,
437            };
438            if frame.id() != self.id {
439                continue;
440            }
441            match frame {
442                ServerFrame::Audio { offset, data, .. } if offset == self.offset => {
443                    self.offset += data.len() as u64;
444                    if !data.is_empty() {
445                        return Ok(Some(data));
446                    }
447                }
448                ServerFrame::Audio { offset, .. } => {
449                    return Err(RemoteError::protocol(format!("audio at byte {offset} where byte {} was next", self.offset)));
450                }
451                ServerFrame::Working { .. } | ServerFrame::Usage { .. } => {}
452                ServerFrame::Done { finish, .. } => {
453                    self.end = Some((finish.meta, finish.usage));
454                    return Ok(None);
455                }
456                ServerFrame::Failed { error, .. } => return Err(error),
457                ServerFrame::Cancelled { .. } => return Err(RemoteError::Failed { message: "cancelled by the node".into() }),
458                other => return Err(RemoteError::protocol(format!("unexpected frame {other:?}"))),
459            }
460        }
461    }
462
463    /// Reads the rest and returns the whole [`Speech`].
464    pub async fn collect(mut self) -> Result<Speech, RemoteError> {
465        let mut audio = Vec::new();
466        while let Some(piece) = self.next().await? {
467            audio.extend_from_slice(&piece);
468        }
469        let (meta, usage) = self.end.take().unwrap_or_default();
470        Ok(Speech {
471            audio,
472            format: self.header.format,
473            sample_rate: self.header.sample_rate,
474            channels: self.header.channels,
475            model: std::mem::take(&mut self.model),
476            node: std::mem::take(&mut self.node),
477            meta,
478            usage,
479        })
480    }
481}
482
483enum Fail {
484    Cancelled,
485    /// The node does not serve the protocol.
486    Unsupported(RemoteError),
487    /// The node would not resume.
488    NoResume,
489    Error(RemoteError),
490}
491
492/// The error to report when every node failed, kind intact: the last node answer
493/// ([`RemoteError::is_node_answer`]), else the last error; `Unavailable(none)` with no nodes.
494pub(crate) fn reported<'a>(errors: impl DoubleEndedIterator<Item = &'a RemoteError> + Clone, none: &str) -> RemoteError {
495    let mut last = errors.clone().rev();
496    errors.rev().find(|e| e.is_node_answer()).or_else(|| last.next()).cloned().unwrap_or_else(|| RemoteError::unavailable(none))
497}
498
499/// Places `text` at `offset` in `buf`: `Ok(Some(new))` with the part that was not there yet,
500/// `Ok(None)` if it was all there, `Err` on a gap.
501fn splice(buf: &mut String, offset: u64, text: &str) -> Result<Option<String>, u64> {
502    let have = chars(buf);
503    if offset > have {
504        return Err(offset - have);
505    }
506    let skip = (have - offset) as usize;
507    let new: String = text.chars().skip(skip).collect();
508    if new.is_empty() {
509        return Ok(None);
510    }
511    buf.push_str(&new);
512    Ok(Some(new))
513}
514
515/// A pool of inference nodes. Cheap to clone.
516#[derive(Clone)]
517pub struct Pool {
518    dialer: Arc<dyn Dialer>,
519    nodes: Arc<dyn NodeSource>,
520    opts: PoolOptions,
521}
522
523impl Pool {
524    pub fn new(dialer: Arc<dyn Dialer>, nodes: impl NodeSource + 'static) -> Self {
525        Self { dialer, nodes: Arc::new(nodes), opts: PoolOptions::default() }
526    }
527
528    pub fn with_options(mut self, opts: PoolOptions) -> Self {
529        self.opts = opts;
530        self
531    }
532
533    pub fn options(&self) -> &PoolOptions {
534        &self.opts
535    }
536
537    pub(crate) fn dialer(&self) -> &Arc<dyn Dialer> {
538        &self.dialer
539    }
540
541    pub(crate) fn options_mut(&mut self) -> &mut PoolOptions {
542        &mut self.opts
543    }
544
545    /// The nodes it would try now, in order.
546    pub async fn nodes(&self) -> Vec<String> {
547        self.nodes.nodes().await
548    }
549
550    async fn open(&self, node: &str, protocol: &str, cancel: &CancelToken) -> Result<Channel, Fail> {
551        let open = tokio::select! {
552            r = tokio::time::timeout(self.opts.accept_timeout, self.dialer.open(node, protocol)) => r,
553            _ = cancel.cancelled() => return Err(Fail::Cancelled),
554        };
555        match open {
556            Ok(Ok(ch)) => Ok(ch),
557            Ok(Err(e @ RemoteError::Unsupported { .. })) => Err(Fail::Unsupported(e)),
558            Ok(Err(e)) => Err(Fail::Error(e)),
559            Err(_) => Err(Fail::Error(RemoteError::Timeout)),
560        }
561    }
562
563    /// Runs one answer to the end, failing over (and, with resume on, resuming) between nodes.
564    pub async fn infer(&self, mut request: Request, events: &dyn EventSink, cancel: &CancelToken) -> Result<Answer, Interrupted> {
565        if request.cert.is_none() {
566            request.cert.clone_from(&self.opts.cert);
567        }
568        let needed = request.needs();
569        if !needed.is_text() {
570            let refuse = |error| Err(Interrupted { error, partial: Box::default(), tried: Vec::new() });
571            if let Some(Err(message)) = request.inline_messages().unwrap_or_default().iter().map(|m| m.content.check()).find(Result::is_err) {
572                return refuse(RemoteError::BadRequest { message });
573            }
574            match self.catalog().await {
575                Ok(catalog) => match catalog.route(request.model.as_deref(), needed) {
576                    Ok(model) => request.model = model,
577                    Err(e) => return refuse(e),
578                },
579                Err(e) if e.is_request_error() => return refuse(e),
580                // No catalog to ask: the nodes decide.
581                Err(_) => {}
582            }
583        }
584        let mut answer = Answer::default();
585        // Continue: the answer starts from the caller's prefix, so the node's frames (which
586        // start at its length) line up, and failover keeps it.
587        if let Some(p) = request.assistant_prefix.clone().filter(|p| !p.is_empty() && p.is_consistent()) {
588            answer.text.clone_from(&p.text);
589            answer.reasoning.clone_from(&p.reasoning);
590            answer.prefix = p;
591        }
592        let mut tried: Vec<(String, RemoteError)> = Vec::new();
593        let mut resumes: Vec<Resume> = Vec::new();
594        let mut next = request;
595        let mut first = true;
596        let interrupted = |error, partial, tried| Interrupted { error, partial: Box::new(partial), tried };
597        for node in self.nodes.nodes().await {
598            if cancel.is_cancelled() {
599                return Err(interrupted(RemoteError::Cancelled, answer, tried));
600            }
601            let resuming = answer.has_output();
602            if !first {
603                next = next.next_attempt();
604                next.assistant_prefix = answer.shown();
605            }
606            first = false;
607            let pending = resuming.then(|| chars(&answer.text));
608            let outcome = match self.attempt(&node, &next, &mut answer, pending, &mut resumes, events, cancel).await {
609                Err(Fail::Unsupported(e)) if self.opts.infer_v1_fallback && next.assistant_prefix.is_none() && needed.is_text() => {
610                    match self.attempt_v1(&node, &next, &mut answer, events, cancel).await {
611                        Err(Fail::Unsupported(_)) => Err(Fail::Unsupported(e)),
612                        other => other,
613                    }
614                }
615                other => other,
616            };
617            match outcome {
618                Ok(finish) => {
619                    answer.finish_reason = finish.finish_reason;
620                    if finish.usage.is_some() {
621                        answer.usage = finish.usage;
622                    }
623                    answer.meta = finish.meta;
624                    answer.meta.resumes.extend(resumes);
625                    answer.node = node;
626                    return Ok(answer);
627                }
628                Err(Fail::Cancelled) => return Err(interrupted(RemoteError::Cancelled, answer, tried)),
629                Err(Fail::NoResume) => {
630                    tried.push((node, RemoteError::Unsupported { message: "the node cannot resume or continue an answer".into() }))
631                }
632                Err(Fail::Unsupported(e)) => tried.push((node, e)),
633                Err(Fail::Error(e)) if e.is_request_error() => {
634                    tried.push((node, e.clone()));
635                    return Err(interrupted(e, answer, tried));
636                }
637                Err(Fail::Error(e)) => {
638                    tried.push((node, e.clone()));
639                    if answer.has_output() && (!self.opts.resume || resumes.len() as u32 >= self.opts.max_resumes) {
640                        return Err(interrupted(e, answer, tried));
641                    }
642                }
643            }
644        }
645        let error = reported(tried.iter().map(|(_, e)| e), "no inference node to run on");
646        Err(interrupted(error, answer, tried))
647    }
648
649    #[allow(clippy::too_many_arguments)]
650    async fn attempt(
651        &self,
652        node: &str,
653        request: &Request,
654        answer: &mut Answer,
655        resume_from: Option<u64>,
656        resumes: &mut Vec<Resume>,
657        events: &dyn EventSink,
658        cancel: &CancelToken,
659    ) -> Result<Finish, Fail> {
660        let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
661        let id = request.id.clone();
662        let mut sent = request.clone();
663        sent.early_meta = true;
664        ch.send_cbor(&ClientFrame::Infer(sent)).await.map_err(Fail::Error)?;
665        let wants_resume = request.assistant_prefix.as_ref().is_some_and(|p| !p.is_empty());
666        let mut accepted = false;
667        let mut gaps = Gaps::default();
668        let calls_before = answer.tool_calls.len();
669        loop {
670            let wait = if accepted { gaps.wait(&self.opts.stall) } else { self.opts.accept_timeout };
671            let next = tokio::select! {
672                _ = cancel.cancelled() => {
673                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
674                    return Err(Fail::Cancelled);
675                }
676                r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
677            };
678            let frame = match next {
679                Err(_) => {
680                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
681                    let e = if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout };
682                    return Err(Fail::Error(e));
683                }
684                Ok(Err(e)) => return Err(Fail::Error(e)),
685                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
686                Ok(Ok(Some(f))) => f,
687            };
688            if frame.id() != id {
689                continue;
690            }
691            match frame {
692                ServerFrame::Queued { position, .. } if !accepted => events.event(PoolEvent::Queued { node: node.into(), position }),
693                ServerFrame::Accepted { model, resume, .. } if !accepted => {
694                    if wants_resume && !resume {
695                        let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
696                        return Err(Fail::NoResume);
697                    }
698                    accepted = true;
699                    answer.model.clone_from(&model);
700                    events.event(PoolEvent::Accepted { node: node.into(), model, resume });
701                    if let Some(offset) = resume_from {
702                        resumes.push(Resume::new(offset, node));
703                        events.event(PoolEvent::Resumed { node: node.into(), offset });
704                    }
705                }
706                ServerFrame::Delta { offset, text, .. } if accepted => match splice(&mut answer.text, offset, &text) {
707                    Ok(Some(new)) => {
708                        gaps.tick();
709                        events.event(PoolEvent::Text(new));
710                    }
711                    Ok(None) => gaps.tick(),
712                    Err(gap) => {
713                        let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
714                        return Err(Fail::Error(RemoteError::protocol(format!("{gap} characters of the answer are missing"))));
715                    }
716                },
717                ServerFrame::Reasoning { offset, text, .. } if accepted => match splice(&mut answer.reasoning, offset, &text) {
718                    Ok(Some(new)) => {
719                        gaps.tick();
720                        events.event(PoolEvent::Reasoning(new));
721                    }
722                    Ok(None) => gaps.tick(),
723                    Err(gap) => {
724                        let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
725                        return Err(Fail::Error(RemoteError::protocol(format!("{gap} characters of the reasoning are missing"))));
726                    }
727                },
728                ServerFrame::ToolCall { index, call, .. } if accepted => {
729                    gaps.tick();
730                    // Calls are whole; after a resume one already held may come again.
731                    let slot = calls_before + index as usize;
732                    let seen = answer.tool_calls.iter().any(|c| c.name == call.name && c.arguments == call.arguments);
733                    if slot >= answer.tool_calls.len() && !seen {
734                        answer.tool_calls.push(call.clone());
735                        events.event(PoolEvent::ToolCall(call));
736                    }
737                }
738                ServerFrame::Usage { usage, .. } if accepted => {
739                    gaps.tick();
740                    answer.usage = Some(usage);
741                    events.event(PoolEvent::Usage(usage));
742                }
743                ServerFrame::Meta { meta, .. } if accepted => {
744                    gaps.tick();
745                    events.event(PoolEvent::Meta(meta));
746                }
747                ServerFrame::Done { finish, .. } if accepted => return Ok(finish),
748                ServerFrame::Failed { error, .. } => {
749                    return Err(match error {
750                        e @ RemoteError::Unsupported { .. } if !accepted => Fail::Unsupported(e),
751                        e => Fail::Error(e),
752                    });
753                }
754                ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
755                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
756            }
757        }
758    }
759
760    /// One try on an infer/1 node (0.3 and older): inline messages and tools only, no resume.
761    async fn attempt_v1(
762        &self,
763        node: &str,
764        request: &Request,
765        answer: &mut Answer,
766        events: &dyn EventSink,
767        cancel: &CancelToken,
768    ) -> Result<Finish, Fail> {
769        let Some(messages) = request.inline_messages() else {
770            return Err(Fail::Unsupported(RemoteError::Unsupported { message: "infer/1 takes inline messages only".into() }));
771        };
772        let mut ch = self.open(node, v1::PROTOCOL, cancel).await?;
773        let id = request_id();
774        let req = v1::InferRequest { id: id.clone(), model: request.model.clone(), messages: messages.to_vec(), tools: request.tools.clone() };
775        ch.send(&v1::ClientMsg::Infer { request: req }).await.map_err(Fail::Error)?;
776        let mut accepted = false;
777        loop {
778            let next = tokio::select! {
779                _ = cancel.cancelled() => {
780                    let _ = ch.send(&v1::ClientMsg::Cancel { id }).await;
781                    return Err(Fail::Cancelled);
782                }
783                m = async {
784                    if accepted {
785                        Ok(ch.recv::<v1::ServerMsg>().await)
786                    } else {
787                        tokio::time::timeout(self.opts.accept_timeout, ch.recv::<v1::ServerMsg>()).await
788                    }
789                } => m,
790            };
791            let msg = match next {
792                Err(_) => return Err(Fail::Error(RemoteError::Timeout)),
793                Ok(Err(e)) => return Err(Fail::Error(e)),
794                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
795                Ok(Ok(Some(m))) => m,
796            };
797            match msg {
798                v1::ServerMsg::Accepted { id: rid, model } if rid == id => {
799                    accepted = true;
800                    answer.model.clone_from(&model);
801                    events.event(PoolEvent::Accepted { node: node.into(), model, resume: false });
802                }
803                v1::ServerMsg::Delta { id: rid, text } if rid == id && accepted => {
804                    answer.text.push_str(&text);
805                    events.event(PoolEvent::Text(text));
806                }
807                v1::ServerMsg::Done { id: rid, turn } if rid == id && accepted => {
808                    answer.text = turn.text;
809                    let calls = !turn.tool_calls.is_empty();
810                    for call in turn.tool_calls {
811                        answer.tool_calls.push(call.clone());
812                        events.event(PoolEvent::ToolCall(call));
813                    }
814                    let mut finish = Finish::new(if calls { "tool_calls" } else { "stop" });
815                    finish.meta.served_by = Some(node.to_string());
816                    return Ok(finish);
817                }
818                v1::ServerMsg::Failed { id: rid, error } if rid == id => return Err(Fail::Error(error)),
819                v1::ServerMsg::Cancelled { id: rid } if rid == id => {
820                    return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() }));
821                }
822                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected message {other:?}")))),
823            }
824        }
825    }
826
827    /// Embeddings for every input, from the first node that serves them all (infer/2 only).
828    pub async fn embed(&self, mut request: EmbedRequest, cancel: &CancelToken) -> Result<Embeddings, RemoteError> {
829        if request.cert.is_none() {
830            request.cert.clone_from(&self.opts.cert);
831        }
832        let mut tried = Vec::new();
833        for node in self.nodes.nodes().await {
834            match self.embed_on(&node, &request, cancel).await {
835                Ok(e) => return Ok(e),
836                Err(Fail::Cancelled) => return Err(RemoteError::Cancelled),
837                Err(Fail::Error(e) | Fail::Unsupported(e)) if e.is_request_error() => return Err(e),
838                Err(Fail::Error(e) | Fail::Unsupported(e)) => tried.push(e),
839                Err(Fail::NoResume) => {}
840            }
841            request.id = request_id();
842        }
843        Err(reported(tried.iter(), "no inference node to run on"))
844    }
845
846    async fn embed_on(&self, node: &str, request: &EmbedRequest, cancel: &CancelToken) -> Result<Embeddings, Fail> {
847        let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
848        let id = request.id.clone();
849        ch.send_cbor(&ClientFrame::Embed(request.clone())).await.map_err(Fail::Error)?;
850        let mut out = Embeddings { node: node.to_string(), ..Default::default() };
851        let mut got: BTreeMap<u32, Vec<f32>> = BTreeMap::new();
852        let mut accepted = false;
853        let mut gaps = Gaps::default();
854        loop {
855            let wait = if accepted { gaps.wait(&self.opts.stall) } else { self.opts.accept_timeout };
856            let next = tokio::select! {
857                _ = cancel.cancelled() => {
858                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
859                    return Err(Fail::Cancelled);
860                }
861                r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
862            };
863            let frame = match next {
864                Err(_) => {
865                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
866                    return Err(Fail::Error(if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout }));
867                }
868                Ok(Err(e)) => return Err(Fail::Error(e)),
869                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
870                Ok(Ok(Some(f))) => f,
871            };
872            if frame.id() != id {
873                continue;
874            }
875            match frame {
876                ServerFrame::Queued { .. } if !accepted => {}
877                ServerFrame::Accepted { model, .. } if !accepted => {
878                    accepted = true;
879                    out.model = model;
880                }
881                ServerFrame::Embedding { index, vector, .. } if accepted => {
882                    gaps.tick();
883                    got.insert(index, v2::bytes_f32(&vector).map_err(Fail::Error)?);
884                }
885                ServerFrame::Done { finish, .. } if accepted => {
886                    if got.len() != request.inputs.len() || got.keys().enumerate().any(|(i, k)| *k as usize != i) {
887                        return Err(Fail::Error(RemoteError::protocol(format!("{} of {} embeddings arrived", got.len(), request.inputs.len()))));
888                    }
889                    out.vectors = got.into_values().collect();
890                    out.meta = finish.meta;
891                    out.usage = finish.usage;
892                    return Ok(out);
893                }
894                ServerFrame::Failed { error, .. } => return Err(Fail::Error(error)),
895                ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
896                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
897            }
898        }
899    }
900
901    /// The transcript of one audio clip, from the first node that serves it (infer/2, nodes from
902    /// 0.5.8). Node errors fail over to the next node; a `BadRequest` (no audio, or a named model
903    /// that does not transcribe) comes back at once. A node too old to read the request closes
904    /// the stream, which counts as `Unsupported`. With no model named, each node picks its own
905    /// transcriber; to pick one across the pool first, see
906    /// [`Catalog::route_transcribe`](super::catalog::Catalog::route_transcribe).
907    pub async fn transcribe(&self, mut request: TranscribeRequest, cancel: &CancelToken) -> Result<Transcription, RemoteError> {
908        request.check()?;
909        if request.cert.is_none() {
910            request.cert.clone_from(&self.opts.cert);
911        }
912        let mut tried = Vec::new();
913        for node in self.nodes.nodes().await {
914            match self.transcribe_on(&node, &request, cancel).await {
915                Ok(t) => return Ok(t),
916                Err(Fail::Cancelled) => return Err(RemoteError::Cancelled),
917                Err(Fail::Error(e) | Fail::Unsupported(e)) if e.is_request_error() => return Err(e),
918                Err(Fail::Error(e) | Fail::Unsupported(e)) => tried.push(e),
919                Err(Fail::NoResume) => {}
920            }
921            request.id = request_id();
922        }
923        Err(reported(tried.iter(), "no inference node to run on"))
924    }
925
926    async fn transcribe_on(&self, node: &str, request: &TranscribeRequest, cancel: &CancelToken) -> Result<Transcription, Fail> {
927        let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
928        let id = request.id.clone();
929        ch.send_cbor(&ClientFrame::Transcribe(request.clone())).await.map_err(Fail::Error)?;
930        let mut out = Transcription { node: node.to_string(), ..Default::default() };
931        let mut transcript = None;
932        let mut accepted = false;
933        loop {
934            // Between `Accepted` and the transcript only `Working` keepalives arrive (every
935            // `QUEUE_KEEPALIVE`), so the wait after acceptance is the stall cap.
936            let wait = if accepted { self.opts.stall.max } else { self.opts.accept_timeout };
937            let next = tokio::select! {
938                _ = cancel.cancelled() => {
939                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
940                    return Err(Fail::Cancelled);
941                }
942                r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
943            };
944            let frame = match next {
945                Err(_) => {
946                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
947                    return Err(Fail::Error(if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout }));
948                }
949                Ok(Err(e)) => return Err(Fail::Error(e)),
950                // A node before 0.5.8 can't read the request and closes the stream unanswered.
951                Ok(Ok(None)) if !accepted => {
952                    return Err(Fail::Unsupported(RemoteError::Unsupported {
953                        message: format!("node {node} closed the stream without answering; it may predate transcription (weirdnet-agent 0.5.8)"),
954                    }));
955                }
956                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
957                Ok(Ok(Some(f))) => f,
958            };
959            if frame.id() != id {
960                continue;
961            }
962            match frame {
963                ServerFrame::Queued { .. } if !accepted => {}
964                ServerFrame::Accepted { model, .. } if !accepted => {
965                    accepted = true;
966                    out.model = model;
967                }
968                ServerFrame::Working { .. } if accepted => {}
969                ServerFrame::Transcript { transcript: t, .. } if accepted && transcript.is_none() => transcript = Some(t),
970                ServerFrame::Done { finish, .. } if accepted => {
971                    let Some(t) = transcript else {
972                        return Err(Fail::Error(RemoteError::protocol("transcription finished without a transcript")));
973                    };
974                    out.transcript = t;
975                    out.meta = finish.meta;
976                    out.usage = finish.usage;
977                    return Ok(out);
978                }
979                ServerFrame::Failed { error, .. } => return Err(Fail::Error(error)),
980                ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
981                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
982            }
983        }
984    }
985
986    /// Speech for one request, whole ([`speak_stream`](Self::speak_stream) read to the end).
987    /// Since 0.5.11.
988    pub async fn speak(&self, request: SpeakRequest, cancel: &CancelToken) -> Result<Speech, RemoteError> {
989        self.speak_stream(request, cancel).await?.collect().await
990    }
991
992    /// Starts speech for one request on the first node that serves it (infer/2, nodes from
993    /// 0.5.11) and returns once that node has sent `SpeechStart`, with the audio to read from the
994    /// [`SpeechStream`]. Before `SpeechStart` node errors fail over to the next node (an
995    /// unreachable or busy node, one with no speaker that covers the request (`Unsupported`), one
996    /// too old to read the request, which closes the stream); a `BadRequest` (empty input, a
997    /// clone without consent, a named model that doesn't speak or lacks what the request needs)
998    /// comes back at once. After `SpeechStart` nothing fails over: another node would start the
999    /// speech again with another voice draw. With no model named, each node picks its own
1000    /// speaker; to pick one across the pool first, see
1001    /// [`Catalog::route_speak`](super::catalog::Catalog::route_speak). Since 0.5.11.
1002    pub async fn speak_stream(&self, mut request: SpeakRequest, cancel: &CancelToken) -> Result<SpeechStream, RemoteError> {
1003        request.check()?;
1004        if request.cert.is_none() {
1005            request.cert.clone_from(&self.opts.cert);
1006        }
1007        let mut tried = Vec::new();
1008        for node in self.nodes.nodes().await {
1009            match self.speak_on(&node, &request, cancel).await {
1010                Ok(s) => return Ok(s),
1011                Err(Fail::Cancelled) => return Err(RemoteError::Cancelled),
1012                Err(Fail::Error(e) | Fail::Unsupported(e)) if e.is_request_error() => return Err(e),
1013                Err(Fail::Error(e) | Fail::Unsupported(e)) => tried.push(e),
1014                Err(Fail::NoResume) => {}
1015            }
1016            request.id = request_id();
1017        }
1018        Err(reported(tried.iter(), "no inference node to run on"))
1019    }
1020
1021    async fn speak_on(&self, node: &str, request: &SpeakRequest, cancel: &CancelToken) -> Result<SpeechStream, Fail> {
1022        let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
1023        let id = request.id.clone();
1024        ch.send_cbor(&ClientFrame::Speak(request.clone())).await.map_err(Fail::Error)?;
1025        let mut model = String::new();
1026        let mut accepted = false;
1027        loop {
1028            // Between `Accepted` and `SpeechStart` only `Working` keepalives arrive (every
1029            // `QUEUE_KEEPALIVE`), so the wait after acceptance is the stall cap.
1030            let wait = if accepted { self.opts.stall.max } else { self.opts.accept_timeout };
1031            let next = tokio::select! {
1032                _ = cancel.cancelled() => {
1033                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
1034                    return Err(Fail::Cancelled);
1035                }
1036                r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
1037            };
1038            let frame = match next {
1039                Err(_) => {
1040                    let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
1041                    return Err(Fail::Error(if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout }));
1042                }
1043                Ok(Err(e)) => return Err(Fail::Error(e)),
1044                // A node before 0.5.11 can't read the request and closes the stream unanswered.
1045                Ok(Ok(None)) if !accepted => {
1046                    return Err(Fail::Unsupported(RemoteError::Unsupported {
1047                        message: format!("node {node} closed the stream without answering; it may predate speech out (weirdnet-agent 0.5.11)"),
1048                    }));
1049                }
1050                Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
1051                Ok(Ok(Some(f))) => f,
1052            };
1053            if frame.id() != id {
1054                continue;
1055            }
1056            match frame {
1057                ServerFrame::Queued { .. } if !accepted => {}
1058                ServerFrame::Accepted { model: m, .. } if !accepted => {
1059                    accepted = true;
1060                    model = m;
1061                }
1062                ServerFrame::Working { .. } if accepted => {}
1063                ServerFrame::SpeechStart { format, sample_rate, channels, .. } if accepted => {
1064                    let mut header = AudioHeader::new(format);
1065                    header.sample_rate = sample_rate;
1066                    header.channels = channels;
1067                    return Ok(SpeechStream {
1068                        ch,
1069                        id,
1070                        header,
1071                        model,
1072                        node: node.to_string(),
1073                        offset: 0,
1074                        wait: self.opts.stall.max,
1075                        cancel: cancel.clone(),
1076                        end: None,
1077                    });
1078                }
1079                ServerFrame::Failed { error, .. } => return Err(Fail::Error(error)),
1080                ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
1081                other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
1082            }
1083        }
1084    }
1085
1086    /// The catalog of the first node that answers.
1087    pub async fn catalog(&self) -> Result<Catalog, RemoteError> {
1088        let mut tried = Vec::new();
1089        for node in self.nodes.nodes().await {
1090            let r = tokio::time::timeout(self.opts.accept_timeout, async {
1091                let mut ch = self.dialer.open(&node, catalog::PROTOCOL).await?;
1092                catalog::query(&mut ch, self.opts.cert.clone()).await
1093            })
1094            .await
1095            .unwrap_or(Err(RemoteError::Timeout));
1096            match r {
1097                Ok(c) => return Ok(c),
1098                Err(e) if e.is_request_error() => return Err(e),
1099                Err(e) => tried.push(e),
1100            }
1101        }
1102        Err(reported(tried.iter(), "no inference node to ask"))
1103    }
1104
1105    /// Follows the catalog: the first node that answers streams its changes; when it goes away
1106    /// the next one takes over. Stops when the [`CatalogWatch`] is dropped.
1107    pub fn subscribe(&self) -> CatalogWatch {
1108        let (tx, rx) = watch::channel(None);
1109        let pool = self.clone();
1110        let task = tokio::spawn(async move {
1111            let mut backoff = Duration::from_millis(200);
1112            loop {
1113                for node in pool.nodes.nodes().await {
1114                    let opened = tokio::time::timeout(pool.opts.accept_timeout, pool.dialer.open(&node, catalog::PROTOCOL)).await;
1115                    let Ok(Ok(mut ch)) = opened else { continue };
1116                    let sent = catalog::subscribe(&mut ch, pool.opts.cert.clone(), |c| {
1117                        tx.send_replace(Some((node.clone(), c)));
1118                    });
1119                    tokio::select! {
1120                        r = sent => if r.is_ok() { backoff = Duration::from_millis(200) },
1121                        _ = tx.closed() => return,
1122                    }
1123                }
1124                tokio::select! {
1125                    _ = tokio::time::sleep(backoff) => {}
1126                    _ = tx.closed() => return,
1127                }
1128                backoff = (backoff * 2).min(Duration::from_secs(30));
1129            }
1130        });
1131        CatalogWatch { rx, task }
1132    }
1133
1134    /// Runs a job in the background: the same failover and resume as [`Pool::infer`], with its
1135    /// events on [`Job::events`]. Batch work usually sets `Priority::Batch`.
1136    pub fn submit(&self, request: Request) -> Job {
1137        let (tx, events) = mpsc::unbounded_channel();
1138        let cancel = CancelToken::new();
1139        let job_id = request.job_id.clone();
1140        let pool = self.clone();
1141        let c = cancel.clone();
1142        let handle = tokio::spawn(async move { pool.infer(request, &tx, &c).await });
1143        Job { job_id, cancel, handle, events }
1144    }
1145}
1146
1147/// A followed catalog ([`Pool::subscribe`]).
1148pub struct CatalogWatch {
1149    rx: watch::Receiver<Option<(String, Catalog)>>,
1150    task: JoinHandle<()>,
1151}
1152
1153impl CatalogWatch {
1154    /// The latest catalog and the node it came from, if one has arrived.
1155    pub fn current(&self) -> Option<(String, Catalog)> {
1156        self.rx.borrow().clone()
1157    }
1158
1159    /// Waits for the next catalog.
1160    pub async fn changed(&mut self) -> Option<(String, Catalog)> {
1161        self.rx.changed().await.ok()?;
1162        self.rx.borrow_and_update().clone()
1163    }
1164}
1165
1166impl Drop for CatalogWatch {
1167    fn drop(&mut self) {
1168        self.task.abort();
1169    }
1170}
1171
1172/// A job running in the background ([`Pool::submit`]).
1173pub struct Job {
1174    job_id: String,
1175    cancel: CancelToken,
1176    handle: JoinHandle<Result<Answer, Interrupted>>,
1177    events: mpsc::UnboundedReceiver<PoolEvent>,
1178}
1179
1180impl Job {
1181    pub fn job_id(&self) -> &str {
1182        &self.job_id
1183    }
1184
1185    pub fn cancel(&self) {
1186        self.cancel.cancel();
1187    }
1188
1189    /// The job's events as they happen.
1190    pub fn events(&mut self) -> &mut mpsc::UnboundedReceiver<PoolEvent> {
1191        &mut self.events
1192    }
1193
1194    /// Waits for the job to end.
1195    pub async fn wait(self) -> Result<Answer, Interrupted> {
1196        match self.handle.await {
1197            Ok(r) => r,
1198            Err(e) => Err(Interrupted { error: RemoteError::Failed { message: e.to_string() }, partial: Box::default(), tried: Vec::new() }),
1199        }
1200    }
1201}
1202
1203#[cfg(test)]
1204mod tests {
1205    use super::*;
1206
1207    #[test]
1208    fn splice_places_by_offset() {
1209        let mut b = String::new();
1210        assert_eq!(splice(&mut b, 0, "Hel"), Ok(Some("Hel".into())));
1211        assert_eq!(splice(&mut b, 3, "lo"), Ok(Some("lo".into())));
1212        assert_eq!(splice(&mut b, 0, "Hell"), Ok(None));
1213        assert_eq!(splice(&mut b, 4, "o wö"), Ok(Some(" wö".into())));
1214        assert_eq!(b, "Hello wö");
1215        assert_eq!(splice(&mut b, 10, "x"), Err(2));
1216    }
1217
1218    #[test]
1219    fn the_stall_timeout_follows_the_token_gap_within_bounds() {
1220        let s = Stall::default();
1221        assert_eq!(s.timeout(None), Duration::from_secs(15));
1222        assert_eq!(s.timeout(Some(Duration::from_secs(1))), Duration::from_secs(15));
1223        assert_eq!(s.timeout(Some(Duration::from_secs(7))), Duration::from_secs(21));
1224        assert_eq!(s.timeout(Some(Duration::from_secs(20))), Duration::from_secs(25), "stays under net's 30 s resume window");
1225    }
1226}