1use std::collections::BTreeMap;
29use std::sync::Arc;
30use std::time::Duration;
31
32use tokio::time::Instant;
33
34use async_trait::async_trait;
35use tokio::sync::{mpsc, watch};
36use tokio::task::JoinHandle;
37
38use super::catalog::{self, Catalog};
39use super::infer::v2::{self, ClientFrame, EmbedRequest, Finish, Meta, Prefix, Request, Resume, ServerFrame, Usage, chars};
40use super::infer::{self as v1, DEFAULT_ACCEPT_TIMEOUT};
41use super::{Channel, Dialer, RemoteError, request_id};
42use crate::cancel::CancelToken;
43use crate::model::{DeltaSink, ModelTurn, ToolCall};
44
45pub const DEFAULT_MAX_RESUMES: u32 = 2;
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54#[non_exhaustive]
55pub struct Stall {
56 pub min: Duration,
57 pub factor: u32,
58 pub max: Duration,
59}
60
61impl Default for Stall {
62 fn default() -> Self {
63 Self { min: Duration::from_secs(15), factor: 3, max: Duration::from_secs(25) }
64 }
65}
66
67impl Stall {
68 pub fn new(min: Duration, factor: u32, max: Duration) -> Self {
69 Self { min, factor, max }
70 }
71
72 pub fn first(&self) -> Duration {
74 self.max.max(self.min)
75 }
76
77 pub fn timeout(&self, recent_gap: Option<Duration>) -> Duration {
79 let scaled = recent_gap.map(|g| g * self.factor).unwrap_or_default();
80 scaled.max(self.min).min(self.max.max(self.min))
81 }
82}
83
84#[derive(Debug, Default)]
86struct Gaps {
87 last: Option<Instant>,
88 recent: Option<Duration>,
89}
90
91impl Gaps {
92 fn wait(&self, stall: &Stall) -> Duration {
93 if self.last.is_none() { stall.first() } else { stall.timeout(self.recent) }
94 }
95
96 fn tick(&mut self) {
97 let now = Instant::now();
98 if let Some(last) = self.last {
99 let gap = now - last;
100 self.recent = Some(match self.recent {
101 Some(r) => (r * 3 + gap) / 4,
102 None => gap,
103 });
104 }
105 self.last = Some(now);
106 }
107}
108
109#[derive(Debug, Clone, PartialEq, Eq)]
111#[non_exhaustive]
112pub struct PoolOptions {
113 pub accept_timeout: Duration,
115 pub stall: Stall,
116 pub resume: bool,
118 pub max_resumes: u32,
119 pub infer_v1_fallback: bool,
121 pub cert: Option<Vec<u8>>,
123}
124
125impl Default for PoolOptions {
126 fn default() -> Self {
127 Self {
128 accept_timeout: DEFAULT_ACCEPT_TIMEOUT,
129 stall: Stall::default(),
130 resume: true,
131 max_resumes: DEFAULT_MAX_RESUMES,
132 infer_v1_fallback: true,
133 cert: None,
134 }
135 }
136}
137
138impl PoolOptions {
139 pub fn with_accept_timeout(mut self, timeout: Duration) -> Self {
140 self.accept_timeout = timeout;
141 self
142 }
143
144 pub fn with_stall(mut self, stall: Stall) -> Self {
145 self.stall = stall;
146 self
147 }
148
149 pub fn with_resume(mut self, resume: bool) -> Self {
150 self.resume = resume;
151 self
152 }
153
154 pub fn with_max_resumes(mut self, max: u32) -> Self {
155 self.max_resumes = max;
156 self
157 }
158
159 pub fn with_infer_v1_fallback(mut self, on: bool) -> Self {
160 self.infer_v1_fallback = on;
161 self
162 }
163
164 pub fn with_cert(mut self, cert: Option<Vec<u8>>) -> Self {
165 self.cert = cert;
166 self
167 }
168}
169
170#[async_trait]
172pub trait NodeSource: Send + Sync {
173 async fn nodes(&self) -> Vec<String>;
174}
175
176#[async_trait]
177impl NodeSource for Vec<String> {
178 async fn nodes(&self) -> Vec<String> {
179 self.clone()
180 }
181}
182
183#[derive(Debug, Clone, PartialEq)]
185#[non_exhaustive]
186pub enum PoolEvent {
187 Queued {
189 node: String,
190 position: u32,
191 },
192 Accepted {
193 node: String,
194 model: String,
195 resume: bool,
196 },
197 Text(String),
198 Reasoning(String),
199 ToolCall(ToolCall),
200 Usage(Usage),
201 Resumed {
203 node: String,
204 offset: u64,
205 },
206 Meta(Meta),
209}
210
211pub trait EventSink: Send + Sync {
213 fn event(&self, event: PoolEvent);
214}
215
216impl EventSink for DeltaSink {
217 fn event(&self, event: PoolEvent) {
218 match event {
219 PoolEvent::Text(t) => self.text(t),
220 PoolEvent::Reasoning(t) => self.reasoning(t),
221 _ => {}
222 }
223 }
224}
225
226impl EventSink for mpsc::UnboundedSender<PoolEvent> {
227 fn event(&self, event: PoolEvent) {
228 let _ = self.send(event);
229 }
230}
231
232#[derive(Debug, Clone, Copy, Default)]
234pub struct NoEvents;
235
236impl EventSink for NoEvents {
237 fn event(&self, _: PoolEvent) {}
238}
239
240#[derive(Debug, Clone, PartialEq, Default)]
242#[non_exhaustive]
243pub struct Answer {
244 pub text: String,
245 pub reasoning: String,
246 pub tool_calls: Vec<ToolCall>,
247 pub finish_reason: Option<String>,
248 pub usage: Option<Usage>,
249 pub meta: Meta,
250 pub node: String,
252 pub model: String,
254 pub prefix: Prefix,
257}
258
259impl Answer {
260 pub fn turn(&self) -> ModelTurn {
262 ModelTurn { text: self.text.clone(), tool_calls: self.tool_calls.clone() }
263 }
264
265 pub fn continuation(&self) -> &str {
267 let at = self.text.char_indices().nth(self.prefix.len as usize).map_or(self.text.len(), |(i, _)| i);
268 &self.text[at..]
269 }
270
271 fn has_output(&self) -> bool {
273 chars(&self.text) > self.prefix.len || chars(&self.reasoning) > self.prefix.reasoning_len || !self.tool_calls.is_empty()
274 }
275
276 fn shown(&self) -> Option<Prefix> {
278 (!self.text.is_empty() || !self.reasoning.is_empty()).then(|| Prefix::new(self.text.clone(), self.reasoning.clone()))
279 }
280}
281
282#[derive(Debug, Clone, PartialEq, thiserror::Error)]
284#[error("{error}")]
285#[non_exhaustive]
286pub struct Interrupted {
287 pub error: RemoteError,
288 pub partial: Box<Answer>,
290 pub tried: Vec<(String, RemoteError)>,
292}
293
294impl Interrupted {
295 pub fn streamed(&self) -> bool {
297 self.partial.has_output()
298 }
299}
300
301#[derive(Debug, Clone, PartialEq, Default)]
303#[non_exhaustive]
304pub struct Embeddings {
305 pub vectors: Vec<Vec<f32>>,
306 pub model: String,
307 pub node: String,
308 pub meta: Meta,
309 pub usage: Option<Usage>,
311}
312
313enum Fail {
314 Cancelled,
315 Unsupported(RemoteError),
317 NoResume,
319 Error(RemoteError),
320}
321
322fn reported<'a>(errors: impl DoubleEndedIterator<Item = &'a RemoteError> + Clone, none: &str) -> RemoteError {
325 let mut last = errors.clone().rev();
326 errors.rev().find(|e| e.is_node_answer()).or_else(|| last.next()).cloned().unwrap_or_else(|| RemoteError::unavailable(none))
327}
328
329fn splice(buf: &mut String, offset: u64, text: &str) -> Result<Option<String>, u64> {
332 let have = chars(buf);
333 if offset > have {
334 return Err(offset - have);
335 }
336 let skip = (have - offset) as usize;
337 let new: String = text.chars().skip(skip).collect();
338 if new.is_empty() {
339 return Ok(None);
340 }
341 buf.push_str(&new);
342 Ok(Some(new))
343}
344
345#[derive(Clone)]
347pub struct Pool {
348 dialer: Arc<dyn Dialer>,
349 nodes: Arc<dyn NodeSource>,
350 opts: PoolOptions,
351}
352
353impl Pool {
354 pub fn new(dialer: Arc<dyn Dialer>, nodes: impl NodeSource + 'static) -> Self {
355 Self { dialer, nodes: Arc::new(nodes), opts: PoolOptions::default() }
356 }
357
358 pub fn with_options(mut self, opts: PoolOptions) -> Self {
359 self.opts = opts;
360 self
361 }
362
363 pub fn options(&self) -> &PoolOptions {
364 &self.opts
365 }
366
367 pub(crate) fn options_mut(&mut self) -> &mut PoolOptions {
368 &mut self.opts
369 }
370
371 pub async fn nodes(&self) -> Vec<String> {
373 self.nodes.nodes().await
374 }
375
376 async fn open(&self, node: &str, protocol: &str, cancel: &CancelToken) -> Result<Channel, Fail> {
377 let open = tokio::select! {
378 r = tokio::time::timeout(self.opts.accept_timeout, self.dialer.open(node, protocol)) => r,
379 _ = cancel.cancelled() => return Err(Fail::Cancelled),
380 };
381 match open {
382 Ok(Ok(ch)) => Ok(ch),
383 Ok(Err(e @ RemoteError::Unsupported { .. })) => Err(Fail::Unsupported(e)),
384 Ok(Err(e)) => Err(Fail::Error(e)),
385 Err(_) => Err(Fail::Error(RemoteError::Timeout)),
386 }
387 }
388
389 pub async fn infer(&self, mut request: Request, events: &dyn EventSink, cancel: &CancelToken) -> Result<Answer, Interrupted> {
391 if request.cert.is_none() {
392 request.cert.clone_from(&self.opts.cert);
393 }
394 let mut answer = Answer::default();
395 if let Some(p) = request.assistant_prefix.clone().filter(|p| !p.is_empty() && p.is_consistent()) {
398 answer.text.clone_from(&p.text);
399 answer.reasoning.clone_from(&p.reasoning);
400 answer.prefix = p;
401 }
402 let mut tried: Vec<(String, RemoteError)> = Vec::new();
403 let mut resumes: Vec<Resume> = Vec::new();
404 let mut next = request;
405 let mut first = true;
406 let interrupted = |error, partial, tried| Interrupted { error, partial: Box::new(partial), tried };
407 for node in self.nodes.nodes().await {
408 if cancel.is_cancelled() {
409 return Err(interrupted(RemoteError::Cancelled, answer, tried));
410 }
411 let resuming = answer.has_output();
412 if !first {
413 next = next.next_attempt();
414 next.assistant_prefix = answer.shown();
415 }
416 first = false;
417 let pending = resuming.then(|| chars(&answer.text));
418 let outcome = match self.attempt(&node, &next, &mut answer, pending, &mut resumes, events, cancel).await {
419 Err(Fail::Unsupported(e)) if self.opts.infer_v1_fallback && next.assistant_prefix.is_none() => {
420 match self.attempt_v1(&node, &next, &mut answer, events, cancel).await {
421 Err(Fail::Unsupported(_)) => Err(Fail::Unsupported(e)),
422 other => other,
423 }
424 }
425 other => other,
426 };
427 match outcome {
428 Ok(finish) => {
429 answer.finish_reason = finish.finish_reason;
430 if finish.usage.is_some() {
431 answer.usage = finish.usage;
432 }
433 answer.meta = finish.meta;
434 answer.meta.resumes.extend(resumes);
435 answer.node = node;
436 return Ok(answer);
437 }
438 Err(Fail::Cancelled) => return Err(interrupted(RemoteError::Cancelled, answer, tried)),
439 Err(Fail::NoResume) => {
440 tried.push((node, RemoteError::Unsupported { message: "the node cannot resume or continue an answer".into() }))
441 }
442 Err(Fail::Unsupported(e)) => tried.push((node, e)),
443 Err(Fail::Error(e)) if e.is_request_error() => {
444 tried.push((node, e.clone()));
445 return Err(interrupted(e, answer, tried));
446 }
447 Err(Fail::Error(e)) => {
448 tried.push((node, e.clone()));
449 if answer.has_output() && (!self.opts.resume || resumes.len() as u32 >= self.opts.max_resumes) {
450 return Err(interrupted(e, answer, tried));
451 }
452 }
453 }
454 }
455 let error = reported(tried.iter().map(|(_, e)| e), "no inference node to run on");
456 Err(interrupted(error, answer, tried))
457 }
458
459 #[allow(clippy::too_many_arguments)]
460 async fn attempt(
461 &self,
462 node: &str,
463 request: &Request,
464 answer: &mut Answer,
465 resume_from: Option<u64>,
466 resumes: &mut Vec<Resume>,
467 events: &dyn EventSink,
468 cancel: &CancelToken,
469 ) -> Result<Finish, Fail> {
470 let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
471 let id = request.id.clone();
472 let mut sent = request.clone();
473 sent.early_meta = true;
474 ch.send_cbor(&ClientFrame::Infer(sent)).await.map_err(Fail::Error)?;
475 let wants_resume = request.assistant_prefix.as_ref().is_some_and(|p| !p.is_empty());
476 let mut accepted = false;
477 let mut gaps = Gaps::default();
478 let calls_before = answer.tool_calls.len();
479 loop {
480 let wait = if accepted { gaps.wait(&self.opts.stall) } else { self.opts.accept_timeout };
481 let next = tokio::select! {
482 _ = cancel.cancelled() => {
483 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
484 return Err(Fail::Cancelled);
485 }
486 r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
487 };
488 let frame = match next {
489 Err(_) => {
490 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
491 let e = if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout };
492 return Err(Fail::Error(e));
493 }
494 Ok(Err(e)) => return Err(Fail::Error(e)),
495 Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
496 Ok(Ok(Some(f))) => f,
497 };
498 if frame.id() != id {
499 continue;
500 }
501 match frame {
502 ServerFrame::Queued { position, .. } if !accepted => events.event(PoolEvent::Queued { node: node.into(), position }),
503 ServerFrame::Accepted { model, resume, .. } if !accepted => {
504 if wants_resume && !resume {
505 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
506 return Err(Fail::NoResume);
507 }
508 accepted = true;
509 answer.model.clone_from(&model);
510 events.event(PoolEvent::Accepted { node: node.into(), model, resume });
511 if let Some(offset) = resume_from {
512 resumes.push(Resume::new(offset, node));
513 events.event(PoolEvent::Resumed { node: node.into(), offset });
514 }
515 }
516 ServerFrame::Delta { offset, text, .. } if accepted => match splice(&mut answer.text, offset, &text) {
517 Ok(Some(new)) => {
518 gaps.tick();
519 events.event(PoolEvent::Text(new));
520 }
521 Ok(None) => gaps.tick(),
522 Err(gap) => {
523 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
524 return Err(Fail::Error(RemoteError::protocol(format!("{gap} characters of the answer are missing"))));
525 }
526 },
527 ServerFrame::Reasoning { offset, text, .. } if accepted => match splice(&mut answer.reasoning, offset, &text) {
528 Ok(Some(new)) => {
529 gaps.tick();
530 events.event(PoolEvent::Reasoning(new));
531 }
532 Ok(None) => gaps.tick(),
533 Err(gap) => {
534 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
535 return Err(Fail::Error(RemoteError::protocol(format!("{gap} characters of the reasoning are missing"))));
536 }
537 },
538 ServerFrame::ToolCall { index, call, .. } if accepted => {
539 gaps.tick();
540 let slot = calls_before + index as usize;
542 let seen = answer.tool_calls.iter().any(|c| c.name == call.name && c.arguments == call.arguments);
543 if slot >= answer.tool_calls.len() && !seen {
544 answer.tool_calls.push(call.clone());
545 events.event(PoolEvent::ToolCall(call));
546 }
547 }
548 ServerFrame::Usage { usage, .. } if accepted => {
549 gaps.tick();
550 answer.usage = Some(usage);
551 events.event(PoolEvent::Usage(usage));
552 }
553 ServerFrame::Meta { meta, .. } if accepted => {
554 gaps.tick();
555 events.event(PoolEvent::Meta(meta));
556 }
557 ServerFrame::Done { finish, .. } if accepted => return Ok(finish),
558 ServerFrame::Failed { error, .. } => {
559 return Err(match error {
560 e @ RemoteError::Unsupported { .. } if !accepted => Fail::Unsupported(e),
561 e => Fail::Error(e),
562 });
563 }
564 ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
565 other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
566 }
567 }
568 }
569
570 async fn attempt_v1(
572 &self,
573 node: &str,
574 request: &Request,
575 answer: &mut Answer,
576 events: &dyn EventSink,
577 cancel: &CancelToken,
578 ) -> Result<Finish, Fail> {
579 let Some(messages) = request.inline_messages() else {
580 return Err(Fail::Unsupported(RemoteError::Unsupported { message: "infer/1 takes inline messages only".into() }));
581 };
582 let mut ch = self.open(node, v1::PROTOCOL, cancel).await?;
583 let id = request_id();
584 let req = v1::InferRequest { id: id.clone(), model: request.model.clone(), messages: messages.to_vec(), tools: request.tools.clone() };
585 ch.send(&v1::ClientMsg::Infer { request: req }).await.map_err(Fail::Error)?;
586 let mut accepted = false;
587 loop {
588 let next = tokio::select! {
589 _ = cancel.cancelled() => {
590 let _ = ch.send(&v1::ClientMsg::Cancel { id }).await;
591 return Err(Fail::Cancelled);
592 }
593 m = async {
594 if accepted {
595 Ok(ch.recv::<v1::ServerMsg>().await)
596 } else {
597 tokio::time::timeout(self.opts.accept_timeout, ch.recv::<v1::ServerMsg>()).await
598 }
599 } => m,
600 };
601 let msg = match next {
602 Err(_) => return Err(Fail::Error(RemoteError::Timeout)),
603 Ok(Err(e)) => return Err(Fail::Error(e)),
604 Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
605 Ok(Ok(Some(m))) => m,
606 };
607 match msg {
608 v1::ServerMsg::Accepted { id: rid, model } if rid == id => {
609 accepted = true;
610 answer.model.clone_from(&model);
611 events.event(PoolEvent::Accepted { node: node.into(), model, resume: false });
612 }
613 v1::ServerMsg::Delta { id: rid, text } if rid == id && accepted => {
614 answer.text.push_str(&text);
615 events.event(PoolEvent::Text(text));
616 }
617 v1::ServerMsg::Done { id: rid, turn } if rid == id && accepted => {
618 answer.text = turn.text;
619 let calls = !turn.tool_calls.is_empty();
620 for call in turn.tool_calls {
621 answer.tool_calls.push(call.clone());
622 events.event(PoolEvent::ToolCall(call));
623 }
624 let mut finish = Finish::new(if calls { "tool_calls" } else { "stop" });
625 finish.meta.served_by = Some(node.to_string());
626 return Ok(finish);
627 }
628 v1::ServerMsg::Failed { id: rid, error } if rid == id => return Err(Fail::Error(error)),
629 v1::ServerMsg::Cancelled { id: rid } if rid == id => {
630 return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() }));
631 }
632 other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected message {other:?}")))),
633 }
634 }
635 }
636
637 pub async fn embed(&self, mut request: EmbedRequest, cancel: &CancelToken) -> Result<Embeddings, RemoteError> {
639 if request.cert.is_none() {
640 request.cert.clone_from(&self.opts.cert);
641 }
642 let mut tried = Vec::new();
643 for node in self.nodes.nodes().await {
644 match self.embed_on(&node, &request, cancel).await {
645 Ok(e) => return Ok(e),
646 Err(Fail::Cancelled) => return Err(RemoteError::Cancelled),
647 Err(Fail::Error(e) | Fail::Unsupported(e)) if e.is_request_error() => return Err(e),
648 Err(Fail::Error(e) | Fail::Unsupported(e)) => tried.push(e),
649 Err(Fail::NoResume) => {}
650 }
651 request.id = request_id();
652 }
653 Err(reported(tried.iter(), "no inference node to run on"))
654 }
655
656 async fn embed_on(&self, node: &str, request: &EmbedRequest, cancel: &CancelToken) -> Result<Embeddings, Fail> {
657 let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
658 let id = request.id.clone();
659 ch.send_cbor(&ClientFrame::Embed(request.clone())).await.map_err(Fail::Error)?;
660 let mut out = Embeddings { node: node.to_string(), ..Default::default() };
661 let mut got: BTreeMap<u32, Vec<f32>> = BTreeMap::new();
662 let mut accepted = false;
663 let mut gaps = Gaps::default();
664 loop {
665 let wait = if accepted { gaps.wait(&self.opts.stall) } else { self.opts.accept_timeout };
666 let next = tokio::select! {
667 _ = cancel.cancelled() => {
668 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
669 return Err(Fail::Cancelled);
670 }
671 r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
672 };
673 let frame = match next {
674 Err(_) => {
675 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
676 return Err(Fail::Error(if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout }));
677 }
678 Ok(Err(e)) => return Err(Fail::Error(e)),
679 Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
680 Ok(Ok(Some(f))) => f,
681 };
682 if frame.id() != id {
683 continue;
684 }
685 match frame {
686 ServerFrame::Queued { .. } if !accepted => {}
687 ServerFrame::Accepted { model, .. } if !accepted => {
688 accepted = true;
689 out.model = model;
690 }
691 ServerFrame::Embedding { index, vector, .. } if accepted => {
692 gaps.tick();
693 got.insert(index, v2::bytes_f32(&vector).map_err(Fail::Error)?);
694 }
695 ServerFrame::Done { finish, .. } if accepted => {
696 if got.len() != request.inputs.len() || got.keys().enumerate().any(|(i, k)| *k as usize != i) {
697 return Err(Fail::Error(RemoteError::protocol(format!("{} of {} embeddings arrived", got.len(), request.inputs.len()))));
698 }
699 out.vectors = got.into_values().collect();
700 out.meta = finish.meta;
701 out.usage = finish.usage;
702 return Ok(out);
703 }
704 ServerFrame::Failed { error, .. } => return Err(Fail::Error(error)),
705 ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
706 other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
707 }
708 }
709 }
710
711 pub async fn catalog(&self) -> Result<Catalog, RemoteError> {
713 let mut tried = Vec::new();
714 for node in self.nodes.nodes().await {
715 let r = tokio::time::timeout(self.opts.accept_timeout, async {
716 let mut ch = self.dialer.open(&node, catalog::PROTOCOL).await?;
717 catalog::query(&mut ch, self.opts.cert.clone()).await
718 })
719 .await
720 .unwrap_or(Err(RemoteError::Timeout));
721 match r {
722 Ok(c) => return Ok(c),
723 Err(e) if e.is_request_error() => return Err(e),
724 Err(e) => tried.push(e),
725 }
726 }
727 Err(reported(tried.iter(), "no inference node to ask"))
728 }
729
730 pub fn subscribe(&self) -> CatalogWatch {
733 let (tx, rx) = watch::channel(None);
734 let pool = self.clone();
735 let task = tokio::spawn(async move {
736 let mut backoff = Duration::from_millis(200);
737 loop {
738 for node in pool.nodes.nodes().await {
739 let opened = tokio::time::timeout(pool.opts.accept_timeout, pool.dialer.open(&node, catalog::PROTOCOL)).await;
740 let Ok(Ok(mut ch)) = opened else { continue };
741 let sent = catalog::subscribe(&mut ch, pool.opts.cert.clone(), |c| {
742 tx.send_replace(Some((node.clone(), c)));
743 });
744 tokio::select! {
745 r = sent => if r.is_ok() { backoff = Duration::from_millis(200) },
746 _ = tx.closed() => return,
747 }
748 }
749 tokio::select! {
750 _ = tokio::time::sleep(backoff) => {}
751 _ = tx.closed() => return,
752 }
753 backoff = (backoff * 2).min(Duration::from_secs(30));
754 }
755 });
756 CatalogWatch { rx, task }
757 }
758
759 pub fn submit(&self, request: Request) -> Job {
762 let (tx, events) = mpsc::unbounded_channel();
763 let cancel = CancelToken::new();
764 let job_id = request.job_id.clone();
765 let pool = self.clone();
766 let c = cancel.clone();
767 let handle = tokio::spawn(async move { pool.infer(request, &tx, &c).await });
768 Job { job_id, cancel, handle, events }
769 }
770}
771
772pub struct CatalogWatch {
774 rx: watch::Receiver<Option<(String, Catalog)>>,
775 task: JoinHandle<()>,
776}
777
778impl CatalogWatch {
779 pub fn current(&self) -> Option<(String, Catalog)> {
781 self.rx.borrow().clone()
782 }
783
784 pub async fn changed(&mut self) -> Option<(String, Catalog)> {
786 self.rx.changed().await.ok()?;
787 self.rx.borrow_and_update().clone()
788 }
789}
790
791impl Drop for CatalogWatch {
792 fn drop(&mut self) {
793 self.task.abort();
794 }
795}
796
797pub struct Job {
799 job_id: String,
800 cancel: CancelToken,
801 handle: JoinHandle<Result<Answer, Interrupted>>,
802 events: mpsc::UnboundedReceiver<PoolEvent>,
803}
804
805impl Job {
806 pub fn job_id(&self) -> &str {
807 &self.job_id
808 }
809
810 pub fn cancel(&self) {
811 self.cancel.cancel();
812 }
813
814 pub fn events(&mut self) -> &mut mpsc::UnboundedReceiver<PoolEvent> {
816 &mut self.events
817 }
818
819 pub async fn wait(self) -> Result<Answer, Interrupted> {
821 match self.handle.await {
822 Ok(r) => r,
823 Err(e) => Err(Interrupted { error: RemoteError::Failed { message: e.to_string() }, partial: Box::default(), tried: Vec::new() }),
824 }
825 }
826}
827
828#[cfg(test)]
829mod tests {
830 use super::*;
831
832 #[test]
833 fn splice_places_by_offset() {
834 let mut b = String::new();
835 assert_eq!(splice(&mut b, 0, "Hel"), Ok(Some("Hel".into())));
836 assert_eq!(splice(&mut b, 3, "lo"), Ok(Some("lo".into())));
837 assert_eq!(splice(&mut b, 0, "Hell"), Ok(None));
838 assert_eq!(splice(&mut b, 4, "o wö"), Ok(Some(" wö".into())));
839 assert_eq!(b, "Hello wö");
840 assert_eq!(splice(&mut b, 10, "x"), Err(2));
841 }
842
843 #[test]
844 fn the_stall_timeout_follows_the_token_gap_within_bounds() {
845 let s = Stall::default();
846 assert_eq!(s.timeout(None), Duration::from_secs(15));
847 assert_eq!(s.timeout(Some(Duration::from_secs(1))), Duration::from_secs(15));
848 assert_eq!(s.timeout(Some(Duration::from_secs(7))), Duration::from_secs(21));
849 assert_eq!(s.timeout(Some(Duration::from_secs(20))), Duration::from_secs(25), "stays under net's 30 s resume window");
850 }
851}