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
329pub(crate) fn 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 dialer(&self) -> &Arc<dyn Dialer> {
375 &self.dialer
376 }
377
378 pub(crate) fn options_mut(&mut self) -> &mut PoolOptions {
379 &mut self.opts
380 }
381
382 pub async fn nodes(&self) -> Vec<String> {
384 self.nodes.nodes().await
385 }
386
387 async fn open(&self, node: &str, protocol: &str, cancel: &CancelToken) -> Result<Channel, Fail> {
388 let open = tokio::select! {
389 r = tokio::time::timeout(self.opts.accept_timeout, self.dialer.open(node, protocol)) => r,
390 _ = cancel.cancelled() => return Err(Fail::Cancelled),
391 };
392 match open {
393 Ok(Ok(ch)) => Ok(ch),
394 Ok(Err(e @ RemoteError::Unsupported { .. })) => Err(Fail::Unsupported(e)),
395 Ok(Err(e)) => Err(Fail::Error(e)),
396 Err(_) => Err(Fail::Error(RemoteError::Timeout)),
397 }
398 }
399
400 pub async fn infer(&self, mut request: Request, events: &dyn EventSink, cancel: &CancelToken) -> Result<Answer, Interrupted> {
402 if request.cert.is_none() {
403 request.cert.clone_from(&self.opts.cert);
404 }
405 let needed = request.needs();
406 if !needed.is_text() {
407 let refuse = |error| Err(Interrupted { error, partial: Box::default(), tried: Vec::new() });
408 if let Some(Err(message)) = request.inline_messages().unwrap_or_default().iter().map(|m| m.content.check()).find(Result::is_err) {
409 return refuse(RemoteError::BadRequest { message });
410 }
411 match self.catalog().await {
412 Ok(catalog) => match catalog.route(request.model.as_deref(), needed) {
413 Ok(model) => request.model = model,
414 Err(e) => return refuse(e),
415 },
416 Err(e) if e.is_request_error() => return refuse(e),
417 Err(_) => {}
419 }
420 }
421 let mut answer = Answer::default();
422 if let Some(p) = request.assistant_prefix.clone().filter(|p| !p.is_empty() && p.is_consistent()) {
425 answer.text.clone_from(&p.text);
426 answer.reasoning.clone_from(&p.reasoning);
427 answer.prefix = p;
428 }
429 let mut tried: Vec<(String, RemoteError)> = Vec::new();
430 let mut resumes: Vec<Resume> = Vec::new();
431 let mut next = request;
432 let mut first = true;
433 let interrupted = |error, partial, tried| Interrupted { error, partial: Box::new(partial), tried };
434 for node in self.nodes.nodes().await {
435 if cancel.is_cancelled() {
436 return Err(interrupted(RemoteError::Cancelled, answer, tried));
437 }
438 let resuming = answer.has_output();
439 if !first {
440 next = next.next_attempt();
441 next.assistant_prefix = answer.shown();
442 }
443 first = false;
444 let pending = resuming.then(|| chars(&answer.text));
445 let outcome = match self.attempt(&node, &next, &mut answer, pending, &mut resumes, events, cancel).await {
446 Err(Fail::Unsupported(e)) if self.opts.infer_v1_fallback && next.assistant_prefix.is_none() && needed.is_text() => {
447 match self.attempt_v1(&node, &next, &mut answer, events, cancel).await {
448 Err(Fail::Unsupported(_)) => Err(Fail::Unsupported(e)),
449 other => other,
450 }
451 }
452 other => other,
453 };
454 match outcome {
455 Ok(finish) => {
456 answer.finish_reason = finish.finish_reason;
457 if finish.usage.is_some() {
458 answer.usage = finish.usage;
459 }
460 answer.meta = finish.meta;
461 answer.meta.resumes.extend(resumes);
462 answer.node = node;
463 return Ok(answer);
464 }
465 Err(Fail::Cancelled) => return Err(interrupted(RemoteError::Cancelled, answer, tried)),
466 Err(Fail::NoResume) => {
467 tried.push((node, RemoteError::Unsupported { message: "the node cannot resume or continue an answer".into() }))
468 }
469 Err(Fail::Unsupported(e)) => tried.push((node, e)),
470 Err(Fail::Error(e)) if e.is_request_error() => {
471 tried.push((node, e.clone()));
472 return Err(interrupted(e, answer, tried));
473 }
474 Err(Fail::Error(e)) => {
475 tried.push((node, e.clone()));
476 if answer.has_output() && (!self.opts.resume || resumes.len() as u32 >= self.opts.max_resumes) {
477 return Err(interrupted(e, answer, tried));
478 }
479 }
480 }
481 }
482 let error = reported(tried.iter().map(|(_, e)| e), "no inference node to run on");
483 Err(interrupted(error, answer, tried))
484 }
485
486 #[allow(clippy::too_many_arguments)]
487 async fn attempt(
488 &self,
489 node: &str,
490 request: &Request,
491 answer: &mut Answer,
492 resume_from: Option<u64>,
493 resumes: &mut Vec<Resume>,
494 events: &dyn EventSink,
495 cancel: &CancelToken,
496 ) -> Result<Finish, Fail> {
497 let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
498 let id = request.id.clone();
499 let mut sent = request.clone();
500 sent.early_meta = true;
501 ch.send_cbor(&ClientFrame::Infer(sent)).await.map_err(Fail::Error)?;
502 let wants_resume = request.assistant_prefix.as_ref().is_some_and(|p| !p.is_empty());
503 let mut accepted = false;
504 let mut gaps = Gaps::default();
505 let calls_before = answer.tool_calls.len();
506 loop {
507 let wait = if accepted { gaps.wait(&self.opts.stall) } else { self.opts.accept_timeout };
508 let next = tokio::select! {
509 _ = cancel.cancelled() => {
510 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
511 return Err(Fail::Cancelled);
512 }
513 r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
514 };
515 let frame = match next {
516 Err(_) => {
517 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
518 let e = if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout };
519 return Err(Fail::Error(e));
520 }
521 Ok(Err(e)) => return Err(Fail::Error(e)),
522 Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
523 Ok(Ok(Some(f))) => f,
524 };
525 if frame.id() != id {
526 continue;
527 }
528 match frame {
529 ServerFrame::Queued { position, .. } if !accepted => events.event(PoolEvent::Queued { node: node.into(), position }),
530 ServerFrame::Accepted { model, resume, .. } if !accepted => {
531 if wants_resume && !resume {
532 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
533 return Err(Fail::NoResume);
534 }
535 accepted = true;
536 answer.model.clone_from(&model);
537 events.event(PoolEvent::Accepted { node: node.into(), model, resume });
538 if let Some(offset) = resume_from {
539 resumes.push(Resume::new(offset, node));
540 events.event(PoolEvent::Resumed { node: node.into(), offset });
541 }
542 }
543 ServerFrame::Delta { offset, text, .. } if accepted => match splice(&mut answer.text, offset, &text) {
544 Ok(Some(new)) => {
545 gaps.tick();
546 events.event(PoolEvent::Text(new));
547 }
548 Ok(None) => gaps.tick(),
549 Err(gap) => {
550 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
551 return Err(Fail::Error(RemoteError::protocol(format!("{gap} characters of the answer are missing"))));
552 }
553 },
554 ServerFrame::Reasoning { offset, text, .. } if accepted => match splice(&mut answer.reasoning, offset, &text) {
555 Ok(Some(new)) => {
556 gaps.tick();
557 events.event(PoolEvent::Reasoning(new));
558 }
559 Ok(None) => gaps.tick(),
560 Err(gap) => {
561 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
562 return Err(Fail::Error(RemoteError::protocol(format!("{gap} characters of the reasoning are missing"))));
563 }
564 },
565 ServerFrame::ToolCall { index, call, .. } if accepted => {
566 gaps.tick();
567 let slot = calls_before + index as usize;
569 let seen = answer.tool_calls.iter().any(|c| c.name == call.name && c.arguments == call.arguments);
570 if slot >= answer.tool_calls.len() && !seen {
571 answer.tool_calls.push(call.clone());
572 events.event(PoolEvent::ToolCall(call));
573 }
574 }
575 ServerFrame::Usage { usage, .. } if accepted => {
576 gaps.tick();
577 answer.usage = Some(usage);
578 events.event(PoolEvent::Usage(usage));
579 }
580 ServerFrame::Meta { meta, .. } if accepted => {
581 gaps.tick();
582 events.event(PoolEvent::Meta(meta));
583 }
584 ServerFrame::Done { finish, .. } if accepted => return Ok(finish),
585 ServerFrame::Failed { error, .. } => {
586 return Err(match error {
587 e @ RemoteError::Unsupported { .. } if !accepted => Fail::Unsupported(e),
588 e => Fail::Error(e),
589 });
590 }
591 ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
592 other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
593 }
594 }
595 }
596
597 async fn attempt_v1(
599 &self,
600 node: &str,
601 request: &Request,
602 answer: &mut Answer,
603 events: &dyn EventSink,
604 cancel: &CancelToken,
605 ) -> Result<Finish, Fail> {
606 let Some(messages) = request.inline_messages() else {
607 return Err(Fail::Unsupported(RemoteError::Unsupported { message: "infer/1 takes inline messages only".into() }));
608 };
609 let mut ch = self.open(node, v1::PROTOCOL, cancel).await?;
610 let id = request_id();
611 let req = v1::InferRequest { id: id.clone(), model: request.model.clone(), messages: messages.to_vec(), tools: request.tools.clone() };
612 ch.send(&v1::ClientMsg::Infer { request: req }).await.map_err(Fail::Error)?;
613 let mut accepted = false;
614 loop {
615 let next = tokio::select! {
616 _ = cancel.cancelled() => {
617 let _ = ch.send(&v1::ClientMsg::Cancel { id }).await;
618 return Err(Fail::Cancelled);
619 }
620 m = async {
621 if accepted {
622 Ok(ch.recv::<v1::ServerMsg>().await)
623 } else {
624 tokio::time::timeout(self.opts.accept_timeout, ch.recv::<v1::ServerMsg>()).await
625 }
626 } => m,
627 };
628 let msg = match next {
629 Err(_) => return Err(Fail::Error(RemoteError::Timeout)),
630 Ok(Err(e)) => return Err(Fail::Error(e)),
631 Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
632 Ok(Ok(Some(m))) => m,
633 };
634 match msg {
635 v1::ServerMsg::Accepted { id: rid, model } if rid == id => {
636 accepted = true;
637 answer.model.clone_from(&model);
638 events.event(PoolEvent::Accepted { node: node.into(), model, resume: false });
639 }
640 v1::ServerMsg::Delta { id: rid, text } if rid == id && accepted => {
641 answer.text.push_str(&text);
642 events.event(PoolEvent::Text(text));
643 }
644 v1::ServerMsg::Done { id: rid, turn } if rid == id && accepted => {
645 answer.text = turn.text;
646 let calls = !turn.tool_calls.is_empty();
647 for call in turn.tool_calls {
648 answer.tool_calls.push(call.clone());
649 events.event(PoolEvent::ToolCall(call));
650 }
651 let mut finish = Finish::new(if calls { "tool_calls" } else { "stop" });
652 finish.meta.served_by = Some(node.to_string());
653 return Ok(finish);
654 }
655 v1::ServerMsg::Failed { id: rid, error } if rid == id => return Err(Fail::Error(error)),
656 v1::ServerMsg::Cancelled { id: rid } if rid == id => {
657 return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() }));
658 }
659 other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected message {other:?}")))),
660 }
661 }
662 }
663
664 pub async fn embed(&self, mut request: EmbedRequest, cancel: &CancelToken) -> Result<Embeddings, RemoteError> {
666 if request.cert.is_none() {
667 request.cert.clone_from(&self.opts.cert);
668 }
669 let mut tried = Vec::new();
670 for node in self.nodes.nodes().await {
671 match self.embed_on(&node, &request, cancel).await {
672 Ok(e) => return Ok(e),
673 Err(Fail::Cancelled) => return Err(RemoteError::Cancelled),
674 Err(Fail::Error(e) | Fail::Unsupported(e)) if e.is_request_error() => return Err(e),
675 Err(Fail::Error(e) | Fail::Unsupported(e)) => tried.push(e),
676 Err(Fail::NoResume) => {}
677 }
678 request.id = request_id();
679 }
680 Err(reported(tried.iter(), "no inference node to run on"))
681 }
682
683 async fn embed_on(&self, node: &str, request: &EmbedRequest, cancel: &CancelToken) -> Result<Embeddings, Fail> {
684 let mut ch = self.open(node, v2::PROTOCOL, cancel).await?;
685 let id = request.id.clone();
686 ch.send_cbor(&ClientFrame::Embed(request.clone())).await.map_err(Fail::Error)?;
687 let mut out = Embeddings { node: node.to_string(), ..Default::default() };
688 let mut got: BTreeMap<u32, Vec<f32>> = BTreeMap::new();
689 let mut accepted = false;
690 let mut gaps = Gaps::default();
691 loop {
692 let wait = if accepted { gaps.wait(&self.opts.stall) } else { self.opts.accept_timeout };
693 let next = tokio::select! {
694 _ = cancel.cancelled() => {
695 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
696 return Err(Fail::Cancelled);
697 }
698 r = tokio::time::timeout(wait, ch.recv_cbor::<ServerFrame>()) => r,
699 };
700 let frame = match next {
701 Err(_) => {
702 let _ = ch.send_cbor(&ClientFrame::Cancel { id }).await;
703 return Err(Fail::Error(if accepted { RemoteError::Stalled { ms: wait.as_millis() as u64 } } else { RemoteError::Timeout }));
704 }
705 Ok(Err(e)) => return Err(Fail::Error(e)),
706 Ok(Ok(None)) => return Err(Fail::Error(RemoteError::Closed)),
707 Ok(Ok(Some(f))) => f,
708 };
709 if frame.id() != id {
710 continue;
711 }
712 match frame {
713 ServerFrame::Queued { .. } if !accepted => {}
714 ServerFrame::Accepted { model, .. } if !accepted => {
715 accepted = true;
716 out.model = model;
717 }
718 ServerFrame::Embedding { index, vector, .. } if accepted => {
719 gaps.tick();
720 got.insert(index, v2::bytes_f32(&vector).map_err(Fail::Error)?);
721 }
722 ServerFrame::Done { finish, .. } if accepted => {
723 if got.len() != request.inputs.len() || got.keys().enumerate().any(|(i, k)| *k as usize != i) {
724 return Err(Fail::Error(RemoteError::protocol(format!("{} of {} embeddings arrived", got.len(), request.inputs.len()))));
725 }
726 out.vectors = got.into_values().collect();
727 out.meta = finish.meta;
728 out.usage = finish.usage;
729 return Ok(out);
730 }
731 ServerFrame::Failed { error, .. } => return Err(Fail::Error(error)),
732 ServerFrame::Cancelled { .. } => return Err(Fail::Error(RemoteError::Failed { message: "cancelled by the node".into() })),
733 other => return Err(Fail::Error(RemoteError::protocol(format!("unexpected frame {other:?}")))),
734 }
735 }
736 }
737
738 pub async fn catalog(&self) -> Result<Catalog, RemoteError> {
740 let mut tried = Vec::new();
741 for node in self.nodes.nodes().await {
742 let r = tokio::time::timeout(self.opts.accept_timeout, async {
743 let mut ch = self.dialer.open(&node, catalog::PROTOCOL).await?;
744 catalog::query(&mut ch, self.opts.cert.clone()).await
745 })
746 .await
747 .unwrap_or(Err(RemoteError::Timeout));
748 match r {
749 Ok(c) => return Ok(c),
750 Err(e) if e.is_request_error() => return Err(e),
751 Err(e) => tried.push(e),
752 }
753 }
754 Err(reported(tried.iter(), "no inference node to ask"))
755 }
756
757 pub fn subscribe(&self) -> CatalogWatch {
760 let (tx, rx) = watch::channel(None);
761 let pool = self.clone();
762 let task = tokio::spawn(async move {
763 let mut backoff = Duration::from_millis(200);
764 loop {
765 for node in pool.nodes.nodes().await {
766 let opened = tokio::time::timeout(pool.opts.accept_timeout, pool.dialer.open(&node, catalog::PROTOCOL)).await;
767 let Ok(Ok(mut ch)) = opened else { continue };
768 let sent = catalog::subscribe(&mut ch, pool.opts.cert.clone(), |c| {
769 tx.send_replace(Some((node.clone(), c)));
770 });
771 tokio::select! {
772 r = sent => if r.is_ok() { backoff = Duration::from_millis(200) },
773 _ = tx.closed() => return,
774 }
775 }
776 tokio::select! {
777 _ = tokio::time::sleep(backoff) => {}
778 _ = tx.closed() => return,
779 }
780 backoff = (backoff * 2).min(Duration::from_secs(30));
781 }
782 });
783 CatalogWatch { rx, task }
784 }
785
786 pub fn submit(&self, request: Request) -> Job {
789 let (tx, events) = mpsc::unbounded_channel();
790 let cancel = CancelToken::new();
791 let job_id = request.job_id.clone();
792 let pool = self.clone();
793 let c = cancel.clone();
794 let handle = tokio::spawn(async move { pool.infer(request, &tx, &c).await });
795 Job { job_id, cancel, handle, events }
796 }
797}
798
799pub struct CatalogWatch {
801 rx: watch::Receiver<Option<(String, Catalog)>>,
802 task: JoinHandle<()>,
803}
804
805impl CatalogWatch {
806 pub fn current(&self) -> Option<(String, Catalog)> {
808 self.rx.borrow().clone()
809 }
810
811 pub async fn changed(&mut self) -> Option<(String, Catalog)> {
813 self.rx.changed().await.ok()?;
814 self.rx.borrow_and_update().clone()
815 }
816}
817
818impl Drop for CatalogWatch {
819 fn drop(&mut self) {
820 self.task.abort();
821 }
822}
823
824pub struct Job {
826 job_id: String,
827 cancel: CancelToken,
828 handle: JoinHandle<Result<Answer, Interrupted>>,
829 events: mpsc::UnboundedReceiver<PoolEvent>,
830}
831
832impl Job {
833 pub fn job_id(&self) -> &str {
834 &self.job_id
835 }
836
837 pub fn cancel(&self) {
838 self.cancel.cancel();
839 }
840
841 pub fn events(&mut self) -> &mut mpsc::UnboundedReceiver<PoolEvent> {
843 &mut self.events
844 }
845
846 pub async fn wait(self) -> Result<Answer, Interrupted> {
848 match self.handle.await {
849 Ok(r) => r,
850 Err(e) => Err(Interrupted { error: RemoteError::Failed { message: e.to_string() }, partial: Box::default(), tried: Vec::new() }),
851 }
852 }
853}
854
855#[cfg(test)]
856mod tests {
857 use super::*;
858
859 #[test]
860 fn splice_places_by_offset() {
861 let mut b = String::new();
862 assert_eq!(splice(&mut b, 0, "Hel"), Ok(Some("Hel".into())));
863 assert_eq!(splice(&mut b, 3, "lo"), Ok(Some("lo".into())));
864 assert_eq!(splice(&mut b, 0, "Hell"), Ok(None));
865 assert_eq!(splice(&mut b, 4, "o wö"), Ok(Some(" wö".into())));
866 assert_eq!(b, "Hello wö");
867 assert_eq!(splice(&mut b, 10, "x"), Err(2));
868 }
869
870 #[test]
871 fn the_stall_timeout_follows_the_token_gap_within_bounds() {
872 let s = Stall::default();
873 assert_eq!(s.timeout(None), Duration::from_secs(15));
874 assert_eq!(s.timeout(Some(Duration::from_secs(1))), Duration::from_secs(15));
875 assert_eq!(s.timeout(Some(Duration::from_secs(7))), Duration::from_secs(21));
876 assert_eq!(s.timeout(Some(Duration::from_secs(20))), Duration::from_secs(25), "stays under net's 30 s resume window");
877 }
878}