82 lines
5.0 KiB
Rust
82 lines
5.0 KiB
Rust
use std::{collections::HashMap, io::{BufRead, BufReader}, sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}, time::Duration};
|
|
use reqwest::{blocking::Client, Url};
|
|
use serde::Deserialize;
|
|
use tauri::{ipc::Channel, State, WebviewWindow};
|
|
|
|
#[derive(Default)]
|
|
pub struct CompletionState { requests: Mutex<HashMap<String, Arc<AtomicBool>>> }
|
|
impl CompletionState {
|
|
pub fn close_window(&self, window: &str) {
|
|
if let Ok(mut requests) = self.requests.lock() {
|
|
requests.retain(|key, flag| { if key.starts_with(&format!("{window}:")) { flag.store(true, Ordering::Relaxed); false } else { true } });
|
|
}
|
|
}
|
|
}
|
|
#[derive(Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct CompletionRequest { endpoint: String, route: String, body: Option<String>, timeout_ms: Option<u64> }
|
|
fn target(endpoint: &str, route: &str) -> Result<Url, String> {
|
|
let mut url = Url::parse(endpoint).map_err(|_| "Enter a local server URL.")?;
|
|
if !matches!(url.scheme(), "http" | "https") || !matches!(url.host_str(), Some("127.0.0.1" | "[::1]" | "localhost"))
|
|
|| !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some()
|
|
|| !matches!(url.path(), "" | "/" | "/v1" | "/v1/") {
|
|
return Err("This trial connects only to a loopback model server.".into());
|
|
}
|
|
if !matches!(route, "/v1/models" | "/v1/chat/completions" | "/api/tags" | "/api/generate") { return Err("Unsupported completion route.".into()); }
|
|
if url.host_str() == Some("localhost") { url.set_host(Some("127.0.0.1")).map_err(|_| "Invalid local host.")?; }
|
|
url.set_path(route); Ok(url)
|
|
}
|
|
#[tauri::command]
|
|
pub fn completion_cancel(window: WebviewWindow, state: State<'_, CompletionState>, id: String) {
|
|
if let Ok(requests) = state.requests.lock() { if let Some(flag) = requests.get(&format!("{}:{id}", window.label())) { flag.store(true, Ordering::Relaxed); } }
|
|
}
|
|
#[tauri::command]
|
|
pub async fn completion_request(window: WebviewWindow, state: State<'_, CompletionState>, id: String, request: CompletionRequest, on_line: Channel<String>) -> Result<(), String> {
|
|
if id.len() > 80 || request.body.as_ref().is_some_and(|v| v.len() > 32768) { return Err("Completion request is too large.".into()); }
|
|
let url = target(&request.endpoint, &request.route)?;
|
|
let flag = Arc::new(AtomicBool::new(false));
|
|
let key = format!("{}:{id}", window.label());
|
|
{
|
|
let mut requests = state.requests.lock().map_err(|_| "Completion state is unavailable.")?;
|
|
if requests.len() >= 16 { return Err("The local server is busy. Wait before retrying.".into()); }
|
|
requests.insert(key.clone(), flag.clone());
|
|
}
|
|
let result = tauri::async_runtime::spawn_blocking(move || {
|
|
let client = Client::builder().no_proxy().redirect(reqwest::redirect::Policy::none())
|
|
.connect_timeout(Duration::from_secs(2)).timeout(Duration::from_millis(request.timeout_ms.unwrap_or(5000).clamp(100, 15000)))
|
|
.build().map_err(|_| "Could not create a local connection.".to_string())?;
|
|
if flag.load(Ordering::Relaxed) { return Ok(()); }
|
|
let call = if let Some(body) = request.body { client.post(url).header("Content-Type", "application/json").body(body) } else { client.get(url) };
|
|
let response = call.send().map_err(|e| if e.is_timeout() { "The local model timed out." } else { "Cannot connect to the local model server." }.to_string())?;
|
|
if !response.status().is_success() { return Err(format!("Local server returned HTTP {}.", response.status().as_u16())); }
|
|
let mut reader = BufReader::new(response);
|
|
let mut total = 0;
|
|
loop {
|
|
if flag.load(Ordering::Relaxed) { return Ok(()); }
|
|
let mut bytes = Vec::new();
|
|
let count = std::io::Read::take(&mut reader, 65537).read_until(b'\n', &mut bytes).map_err(|_| "The local response ended unexpectedly.".to_string())?;
|
|
if count == 0 { break; }
|
|
total += count;
|
|
if count > 65536 || total > 262144 { return Err("Local response exceeded the size limit.".into()); }
|
|
if flag.load(Ordering::Relaxed) { return Ok(()); }
|
|
let line = String::from_utf8(bytes).map_err(|_| "Local response is not UTF-8.".to_string())?;
|
|
if on_line.send(line).is_err() { break; }
|
|
}
|
|
Ok(())
|
|
}).await.map_err(|_| "Local completion task stopped.".to_string());
|
|
if let Ok(mut requests) = state.requests.lock() { requests.remove(&key); }
|
|
result?
|
|
}
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn only_loopback_and_fixed_routes() {
|
|
assert_eq!(target("http://localhost:8080/v1", "/v1/models").unwrap().as_str(), "http://127.0.0.1:8080/v1/models");
|
|
for address in ["https://example.com", "http://127.0.0.1.example.com", "http://user@localhost", "file:///a", "http://localhost/?key=x", "http://localhost/path"] {
|
|
assert!(target(address, "/v1/models").is_err(), "{address}");
|
|
}
|
|
assert!(target("http://127.0.0.1:8080", "/shutdown").is_err());
|
|
}
|
|
}
|