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