aboutsummaryrefslogtreecommitdiffstats
path: root/crates/asist-core/src/http.rs
blob: 32b6680cb3bfcd323fd78f7b37787d209819ce5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
//! Cliente HTTP/1.1 mínimo para hablar con los servidores locales.
//!
//! Los tres motores (llama-server, tts-server) escuchan en localhost sobre HTTP
//! plano, así que no hace falta TLS ni un runtime asíncrono. A cambio de las
//! ~300 líneas de aquí se gana lo único que ninguna librería genérica da
//! cómodo y que este pipeline necesita de verdad: **abortar una respuesta a
//! media descarga**. Cuando el usuario interrumpe al asistente hay que dejar de
//! leer audio ya generado y cerrar el socket en ese mismo instante; con un
//! cliente que sólo expone `read_to_end` eso no se puede hacer.

use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpStream;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use crate::error::{Error, Result};

/// Bandera compartida que aborta una lectura en curso.
///
/// Se comprueba entre bloques, así que el corte ocurre como muy tarde un
/// `read` después de activarla —del orden de milisegundos con los tamaños de
/// bloque que usan los servidores.
#[derive(Clone, Default)]
pub struct Cancel(Arc<AtomicBool>);

impl Cancel {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn cancel(&self) {
        self.0.store(true, Ordering::SeqCst);
    }

    pub fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::SeqCst)
    }

    pub fn reset(&self) {
        self.0.store(false, Ordering::SeqCst);
    }
}

#[derive(Clone, Debug)]
pub struct HttpClient {
    /// `host:puerto` del servidor local.
    pub authority: String,
    pub connect_timeout: Duration,
    /// Tiempo máximo sin recibir un solo byte. No es el tiempo total: una
    /// síntesis larga puede tardar minutos siempre que siga fluyendo.
    pub read_timeout: Duration,
}

impl HttpClient {
    pub fn new(authority: impl Into<String>) -> Self {
        Self {
            authority: authority.into(),
            connect_timeout: Duration::from_secs(5),
            read_timeout: Duration::from_secs(120),
        }
    }

    pub fn with_read_timeout(mut self, timeout: Duration) -> Self {
        self.read_timeout = timeout;
        self
    }

    fn connect(&self, path: &str) -> Result<TcpStream> {
        let addr = resolve(&self.authority, path)?;
        let stream = TcpStream::connect_timeout(&addr, self.connect_timeout).map_err(|e| {
            Error::Transport {
                url: format!("http://{}{}", self.authority, path),
                source: e,
            }
        })?;
        stream.set_read_timeout(Some(self.read_timeout))?;
        // Los cuerpos son pequeños y la latencia manda: nada de Nagle.
        let _ = stream.set_nodelay(true);
        Ok(stream)
    }

    fn send(&self, method: &str, path: &str, body: Option<&[u8]>) -> Result<Response> {
        let mut stream = self.connect(path)?;
        let mut head = format!(
            "{method} {path} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nAccept: */*\r\n",
            self.authority
        );
        if let Some(body) = body {
            head.push_str("Content-Type: application/json\r\n");
            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
        }
        head.push_str("\r\n");

        let url = format!("http://{}{}", self.authority, path);
        let io = |e: std::io::Error| Error::Transport {
            url: url.clone(),
            source: e,
        };
        stream.write_all(head.as_bytes()).map_err(io)?;
        if let Some(body) = body {
            stream.write_all(body).map_err(io)?;
        }
        stream.flush().map_err(io)?;

        Response::read_head(BufReader::new(stream), url)
    }

    /// GET que devuelve el cuerpo completo ya decodificado.
    pub fn get(&self, path: &str) -> Result<Vec<u8>> {
        self.send("GET", path, None)?.into_body()
    }

    /// POST de JSON que devuelve el cuerpo completo.
    pub fn post_json(&self, path: &str, body: &serde_json::Value) -> Result<Vec<u8>> {
        let payload = serde_json::to_vec(body)?;
        self.send("POST", path, Some(&payload))?.into_body()
    }

    /// POST de JSON cuya respuesta se consume a trozos según llega.
    ///
    /// `on_chunk` recibe cada bloque en cuanto está disponible y devuelve
    /// `false` para cortar; junto a `cancel` son las dos vías por las que el
    /// barge-in detiene una síntesis a medias.
    pub fn post_json_streaming(
        &self,
        path: &str,
        body: &serde_json::Value,
        cancel: &Cancel,
        mut on_chunk: impl FnMut(&[u8]) -> bool,
    ) -> Result<()> {
        let payload = serde_json::to_vec(body)?;
        let mut response = self.send("POST", path, Some(&payload))?;
        response.error_for_status()?;
        response.stream(cancel, &mut on_chunk)
    }

    /// POST de JSON que entrega la respuesta línea a línea (SSE de llama-server).
    pub fn post_json_lines(
        &self,
        path: &str,
        body: &serde_json::Value,
        cancel: &Cancel,
        mut on_line: impl FnMut(&str) -> bool,
    ) -> Result<()> {
        let mut pending = Vec::new();
        self.post_json_streaming(path, body, cancel, |chunk| {
            pending.extend_from_slice(chunk);
            while let Some(nl) = pending.iter().position(|b| *b == b'\n') {
                let line: Vec<u8> = pending.drain(..=nl).collect();
                let line = String::from_utf8_lossy(&line);
                if !on_line(line.trim_end_matches(['\r', '\n'])) {
                    return false;
                }
            }
            true
        })
    }

    /// Sondea `/health` y devuelve `true` si el servidor está listo.
    pub fn healthy(&self, path: &str) -> bool {
        self.get(path).is_ok()
    }
}

fn resolve(authority: &str, path: &str) -> Result<std::net::SocketAddr> {
    use std::net::ToSocketAddrs;
    authority
        .to_socket_addrs()
        .map_err(|e| Error::Transport {
            url: format!("http://{authority}{path}"),
            source: e,
        })?
        .next()
        .ok_or_else(|| Error::Config(format!("no se pudo resolver «{authority}»")))
}

/// Codificación del cuerpo anunciada por el servidor.
enum Body {
    Chunked,
    Length(usize),
    /// Sin longitud ni chunked: el cuerpo acaba cuando cierra el socket.
    UntilClose,
}

pub struct Response {
    pub status: u16,
    url: String,
    reader: BufReader<TcpStream>,
    body: Body,
}

impl Response {
    fn read_head(mut reader: BufReader<TcpStream>, url: String) -> Result<Self> {
        let io = |e: std::io::Error| Error::Transport {
            url: url.clone(),
            source: e,
        };

        let mut line = String::new();
        reader.read_line(&mut line).map_err(io)?;
        let status = line
            .split_whitespace()
            .nth(1)
            .and_then(|s| s.parse::<u16>().ok())
            .ok_or_else(|| Error::Config(format!("respuesta HTTP ilegible de {url}: {line:?}")))?;

        let mut body = Body::UntilClose;
        loop {
            let mut header = String::new();
            if reader.read_line(&mut header).map_err(io)? == 0 {
                break;
            }
            let header = header.trim_end();
            if header.is_empty() {
                break;
            }
            let Some((name, value)) = header.split_once(':') else {
                continue;
            };
            let (name, value) = (name.trim().to_ascii_lowercase(), value.trim());
            match name.as_str() {
                "transfer-encoding" if value.eq_ignore_ascii_case("chunked") => {
                    body = Body::Chunked;
                }
                "content-length" => {
                    if let Ok(n) = value.parse() {
                        body = Body::Length(n);
                    }
                }
                _ => {}
            }
        }

        Ok(Self {
            status,
            url,
            reader,
            body,
        })