use std::time::Duration;
use ai_api::{Error, Flow, OnFail, OnReply, OnThink, clean_text as clean};
use crossfire::{MTx, mpsc::List};
use crate::event::Event;
const CANCEL: &str = "已取消";
const ERR_CAP: usize = 120;
pub struct Job {
tx: MTx<List<Event>>,
reply: bool,
id: u32,
ended: bool,
}
impl Job {
pub(crate) fn new(tx: MTx<List<Event>>, id: u32, reply: bool) -> Self {
Self {
tx,
reply,
id,
ended: false,
}
}
fn end(&mut self, err: Option<String>) {
self.ended = true;
let _ = self.tx.send(Event::End { id: self.id, err });
}
pub fn reply(&self) -> Reply {
Reply {
tx: self.reply.then(|| self.tx.clone()),
id: self.id,
}
}
pub fn retry(&self) -> Retry {
Retry {
tx: self.tx.clone(),
id: self.id,
}
}
pub fn done(mut self) {
self.end(None);
}
pub fn fail(mut self, err: &str) {
self.end(Some(clean(err).into_owned()));
}
}
pub struct Reply {
tx: Option<MTx<List<Event>>>,
id: u32,
}
pub struct Retry {
tx: MTx<List<Event>>,
id: u32,
}
fn brief(raw: &str) -> String {
let cleaned = clean(raw);
let mut out = String::with_capacity(cleaned.len().min(ERR_CAP + 4));
for word in cleaned.split_whitespace() {
let sep = usize::from(!out.is_empty());
if out.len() + sep + word.len() > ERR_CAP {
let end = word.floor_char_boundary(ERR_CAP.saturating_sub(out.len() + sep));
if end > 0 {
if sep > 0 {
out.push(' ');
}
out.push_str(&word[..end]);
}
out.push('…');
return out;
}
if sep > 0 {
out.push(' ');
}
out.push_str(word);
}
out
}
fn text(tx: &MTx<List<Event>>, id: u32, s: &str, reply: bool) -> Flow {
let _ = tx.send(Event::Text {
id,
text: clean(s).into_owned(),
reply,
});
Flow::Continue
}
impl OnThink for Job {
fn think(&mut self, s: &str) -> Flow {
text(&self.tx, self.id, s, false)
}
}
impl OnReply for Reply {
fn reply(&mut self, s: &str) -> Flow {
if let Some(tx) = &self.tx {
text(tx, self.id, s, true)
} else {
Flow::Continue
}
}
}
impl OnFail for Retry {
fn fail(&mut self, round: usize, retry: usize, wait: Duration, base: &str, err: &Error) {
let _ = self.tx.send(Event::Retry {
id: self.id,
nth: round,
total: retry,
wait,
base: clean(base).trim().to_owned(),
err: brief(&err.to_string()),
});
}
}
impl Drop for Job {
fn drop(&mut self) {
if !self.ended {
self.end(Some(CANCEL.into()));
}
}
}