bigtext 0.19.1

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! HTTP for the providers: one agent with BigText's proxy (none for a server on this
//! computer), errors with the provider's own message, retries when the provider is busy, and a
//! reader of server-sent events for streamed answers.

use std::io::{self, BufRead, BufReader, Read};
use std::time::Duration;

use crate::jobs::CancelToken;

/// What went wrong with a request.
#[derive(Clone, Debug, PartialEq)]
pub enum AiError {
    Cancelled,
    /// No answer: the name did not resolve, the connection was refused or timed out.
    Network(String),
    /// The provider answered with an error status, and its message.
    Status {
        code: u16,
        message: String,
        /// Seconds to wait, from a `retry-after` header.
        retry_after: Option<u64>,
    },
    /// The answer was not what the protocol says it should be.
    Protocol(String),
    /// Not set up yet: no address, model or key.
    Setup(String),
}

impl AiError {
    /// Worth trying again after a pause: rate limits, an overloaded or failing server, a
    /// dropped connection.
    pub fn retryable(&self) -> bool {
        match self {
            AiError::Status { code, .. } => matches!(code, 408 | 429 | 500 | 502 | 503 | 504 | 529),
            AiError::Network(_) => true,
            _ => false,
        }
    }

    /// A message for the user (English; the app translates the fixed parts).
    pub fn user_text(&self) -> String {
        match self {
            AiError::Cancelled => "Stopped.".into(),
            AiError::Network(e) => format!("Could not reach the provider: {e}"),
            AiError::Status { code, message, .. } => {
                let what = match code {
                    400 => "The provider did not accept the request",
                    401 => "The provider did not accept the key",
                    403 => "The provider refused access",
                    404 => "The provider does not know this address or model",
                    408 | 504 => "The provider took too long to answer",
                    413 => "The request is too large for the provider",
                    429 => "Too many requests or no credit left",
                    500 | 502 | 503 => "The provider has a problem",
                    529 => "The provider is overloaded",
                    _ => "The provider answered with an error",
                };
                let mut t = if message.is_empty() {
                    format!("{what} (HTTP {code}).")
                } else {
                    format!("{what} (HTTP {code}): {message}")
                };
                // An Anthropic organization key that is not scoped to a workspace.
                if *code == 400 && message.contains("anthropic-workspace-id") {
                    t.push_str(" In BigText: enter the workspace's ID under AI → AI settings → Workspace ID (bigtext-cli ask --workspace ID), or set ANTHROPIC_WORKSPACE_ID.");
                }
                t
            }
            AiError::Protocol(e) => format!("Unexpected answer from the provider: {e}"),
            AiError::Setup(e) => e.clone(),
        }
    }
}

impl std::fmt::Display for AiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.user_text())
    }
}

/// Whether `url` points at this computer (`localhost`, `127.0.0.1`, `::1`): such a server gets
/// no proxy and counts as local for privacy. Another computer on the local network does not.
pub fn is_local(url: &str) -> bool {
    let rest = url
        .split_once("://")
        .map(|(_, r)| r)
        .unwrap_or(url)
        .trim_start_matches(|c: char| c.is_whitespace());
    let host_port = rest.split(['/', '?', '#']).next().unwrap_or("");
    // user:pass@host
    let host_port = host_port.rsplit_once('@').map(|x| x.1).unwrap_or(host_port);
    let host = if let Some(v6) = host_port.strip_prefix('[') {
        v6.split(']').next().unwrap_or("")
    } else {
        host_port.split(':').next().unwrap_or("")
    };
    let host = host.to_ascii_lowercase();
    host == "localhost"
        || host.ends_with(".localhost")
        || host == "::1"
        || host.strip_prefix("127.").is_some_and(|r| {
            r.split('.').count() == 3 && r.split('.').all(|p| p.parse::<u8>().is_ok())
        })
}

pub(crate) fn agent(local: bool) -> ureq::Agent {
    ureq::Agent::config_builder()
        .user_agent(format!("BigText/{}", env!("CARGO_PKG_VERSION")))
        .timeout_connect(Some(Duration::from_secs(15)))
        // A local model on a CPU can take minutes before its first word; a cloud model streams.
        .timeout_per_read(Some(Duration::from_secs(if local { 600 } else { 180 })))
        .http_status_as_error(false)
        .proxy(if local {
            None
        } else {
            crate::net_proxy::proxy()
        })
        .build()
        .new_agent()
}

/// `secret` replaced by "…" in `text`, so an error message never shows a key.
pub(crate) fn scrub(text: &str, secret: Option<&str>) -> String {
    match secret.filter(|s| s.len() >= 6) {
        Some(s) => text.replace(s, "…"),
        None => text.to_string(),
    }
}

/// The message in a provider's error body: Anthropic's and OpenAI's `{"error": {"message"}}`,
/// Ollama's `{"error": "…"}`, or the start of the text.
pub(crate) fn error_message(body: &str) -> String {
    let msg = serde_json::from_str::<serde_json::Value>(body)
        .ok()
        .and_then(|v| {
            let e = v.get("error")?;
            e.get("message")
                .and_then(|m| m.as_str())
                .or_else(|| e.as_str())
                .map(str::to_string)
        })
        .or_else(|| {
            serde_json::from_str::<serde_json::Value>(body)
                .ok()?
                .get("message")?
                .as_str()
                .map(str::to_string)
        });
    let msg = msg.unwrap_or_else(|| body.trim().to_string());
    let mut m: String = msg.chars().take(400).collect();
    if m.len() < msg.len() {
        m.push('…');
    }
    m
}

fn network(e: ureq::Error) -> AiError {
    match e {
        ureq::Error::StatusCode(code) => AiError::Status {
            code,
            message: String::new(),
            retry_after: None,
        },
        ureq::Error::Timeout(_) => AiError::Network("the connection timed out".into()),
        ureq::Error::Io(e) => AiError::Network(e.to_string()),
        e => AiError::Network(e.to_string()),
    }
}

/// An answer's body: a stream of events, or (from a server that does not stream) all of it.
pub(crate) enum Body {
    Stream(Sse<BufReader<ureq::BodyReader<'static>>>),
    Whole(String),
}

/// Sends `body` as JSON and returns the answer, or the provider's error with its message.
pub(crate) fn post(
    url: &str,
    headers: &[(&str, String)],
    body: &[u8],
    secret: Option<&str>,
    cancel: &CancelToken,
) -> Result<Body, AiError> {
    if cancel.is_cancelled() {
        return Err(AiError::Cancelled);
    }
    let local = is_local(url);
    let mut req = agent(local)
        .post(url)
        .header("content-type", "application/json")
        .header("accept", "text/event-stream, application/json");
    for (k, v) in headers {
        req = req.header(*k, v.as_str());
    }
    let resp = req.send(body).map_err(network)?;
    let status = resp.status().as_u16();
    let retry_after = resp
        .headers()
        .get("retry-after")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.trim().parse::<u64>().ok());
    let stream = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .is_some_and(|t| t.contains("event-stream"));
    let (_, b) = resp.into_parts();
    if !(200..300).contains(&status) {
        let text = read_limited(b.into_reader(), 64 * 1024);
        return Err(AiError::Status {
            code: status,
            message: scrub(&error_message(&text), secret),
            retry_after,
        });
    }
    if stream {
        Ok(Body::Stream(Sse::new(BufReader::new(b.into_reader()))))
    } else {
        Ok(Body::Whole(read_limited(b.into_reader(), 16 << 20)))
    }
}

/// A GET that returns the body (the model list).
pub(crate) fn get(
    url: &str,
    headers: &[(&str, String)],
    secret: Option<&str>,
) -> Result<String, AiError> {
    let mut req = agent(is_local(url)).get(url);
    for (k, v) in headers {
        req = req.header(*k, v.as_str());
    }
    let resp = req.call().map_err(network)?;
    let status = resp.status().as_u16();
    let (_, b) = resp.into_parts();
    let text = read_limited(b.into_reader(), 16 << 20);
    if !(200..300).contains(&status) {
        return Err(AiError::Status {
            code: status,
            message: scrub(&error_message(&text), secret),
            retry_after: None,
        });
    }
    Ok(text)
}

fn read_limited(r: impl Read, max: u64) -> String {
    let mut out = Vec::new();
    let _ = r.take(max).read_to_end(&mut out);
    String::from_utf8_lossy(&out).into_owned()
}

/// Runs `f`, trying again up to twice when the provider is busy or the connection dropped
/// (after its `retry-after`, or 2 and then 6 seconds), unless cancelled meanwhile.
pub(crate) fn with_retries<T>(
    cancel: &CancelToken,
    mut f: impl FnMut() -> Result<T, AiError>,
) -> Result<T, AiError> {
    let mut tries = 0;
    loop {
        match f() {
            Err(e) if e.retryable() && tries < 2 && !cancel.is_cancelled() => {
                let wait = match &e {
                    AiError::Status {
                        retry_after: Some(s),
                        ..
                    } if *s <= 30 => *s,
                    AiError::Status {
                        retry_after: Some(_),
                        ..
                    } => return Err(e),
                    _ => [2, 6][tries],
                };
                tries += 1;
                let until = std::time::Instant::now() + Duration::from_secs(wait);
                while std::time::Instant::now() < until {
                    if cancel.is_cancelled() {
                        return Err(AiError::Cancelled);
                    }
                    std::thread::sleep(Duration::from_millis(100));
                }
            }
            r => return r,
        }
    }
}

/// A line longer than this in an event stream is an error, not a reason to use all memory.
const SSE_LINE_MAX: usize = 8 << 20;

/// Server-sent events: `event:` and `data:` lines, an empty line ends an event.
pub struct Sse<R> {
    r: R,
    line: Vec<u8>,
}

impl<R: BufRead> Sse<R> {
    pub fn new(r: R) -> Sse<R> {
        Sse {
            r,
            line: Vec::new(),
        }
    }

    /// The next event as (name, data); `None` at the end of the stream.
    pub fn next_event(&mut self) -> io::Result<Option<(String, String)>> {
        let mut event = String::new();
        let mut data = String::new();
        let mut any = false;
        loop {
            self.line.clear();
            let n = (&mut self.r)
                .take(SSE_LINE_MAX as u64 + 1)
                .read_until(b'\n', &mut self.line)?;
            if n > SSE_LINE_MAX {
                return Err(io::Error::other("an event is too long"));
            }
            if n == 0 {
                return Ok(any.then_some((event, data)));
            }
            let mut l: &[u8] = &self.line;
            while let Some(x) = l.strip_suffix(b"\n").or_else(|| l.strip_suffix(b"\r")) {
                l = x;
            }
            if l.is_empty() {
                if any {
                    return Ok(Some((event, data)));
                }
                continue;
            }
            if l.starts_with(b":") {
                continue;
            }
            let l = String::from_utf8_lossy(l);
            let (field, value) = match l.split_once(':') {
                Some((f, v)) => (f, v.strip_prefix(' ').unwrap_or(v)),
                None => (l.as_ref(), ""),
            };
            match field {
                "event" => {
                    event = value.to_string();
                    any = true;
                }
                "data" => {
                    if !data.is_empty() {
                        data.push('\n');
                    }
                    data.push_str(value);
                    any = true;
                }
                _ => {}
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn local_addresses() {
        for u in [
            "http://localhost:11434/v1",
            "http://127.0.0.1:1234/v1",
            "http://[::1]:8080/v1",
            "localhost:8000",
            "http://LOCALHOST/v1",
            "http://user:pw@127.0.0.1:9/v1",
        ] {
            assert!(is_local(u), "{u}");
        }
        for u in [
            "https://api.anthropic.com/v1",
            "http://192.168.1.5:11434/v1",
            "http://localhost.example.com/v1",
            "http://127.0.0.1.example.com/",
            "http://10.0.0.1/v1",
        ] {
            assert!(!is_local(u), "{u}");
        }
    }

    #[test]
    fn events_are_split_and_joined() {
        let text = ": keep-alive\r\nevent: a\r\ndata: one\r\ndata: two\r\n\r\ndata: {\"x\":1}\n\n\nevent: end\ndata:\n";
        let mut s = Sse::new(text.as_bytes());
        assert_eq!(
            s.next_event().unwrap(),
            Some(("a".into(), "one\ntwo".into()))
        );
        assert_eq!(
            s.next_event().unwrap(),
            Some((String::new(), "{\"x\":1}".into()))
        );
        assert_eq!(s.next_event().unwrap(), Some(("end".into(), String::new())));
        assert_eq!(s.next_event().unwrap(), None);
    }

    #[test]
    fn error_messages() {
        assert_eq!(
            error_message(
                r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#
            ),
            "invalid x-api-key"
        );
        assert_eq!(
            error_message(r#"{"error":"model 'x' not found"}"#),
            "model 'x' not found"
        );
        assert_eq!(error_message("  Bad Gateway \n"), "Bad Gateway");
        assert_eq!(
            scrub(
                "Incorrect API key provided: sk-abcdef123",
                Some("sk-abcdef123")
            ),
            "Incorrect API key provided: …"
        );
        let e = AiError::Status {
            code: 401,
            message: "invalid x-api-key".into(),
            retry_after: None,
        };
        assert!(e.user_text().contains("did not accept the key"));
        let ws = AiError::Status {
            code: 400,
            message: "This API key is not scoped to a workspace, so this request must include the anthropic-workspace-id header with the ID of the workspace to use.".into(),
            retry_after: None,
        };
        assert!(ws.user_text().contains("AI → AI settings → Workspace ID"));
        assert!(!e.retryable());
        assert!(AiError::Status {
            code: 529,
            message: String::new(),
            retry_after: None
        }
        .retryable());
    }

    #[test]
    fn retries_stop_at_two_and_on_cancel() {
        let cancel = CancelToken::new();
        let mut n = 0;
        let r: Result<(), AiError> = with_retries(&cancel, || {
            n += 1;
            Err(AiError::Status {
                code: 429,
                message: String::new(),
                retry_after: Some(0),
            })
        });
        assert!(r.is_err());
        assert_eq!(n, 3);
        let mut n = 0;
        let r: Result<(), AiError> = with_retries(&cancel, || {
            n += 1;
            Err(AiError::Status {
                code: 400,
                message: String::new(),
                retry_after: None,
            })
        });
        assert!(r.is_err());
        assert_eq!(n, 1);
        cancel.cancel();
        let r: Result<(), AiError> = with_retries(&cancel, || Err(AiError::Network("x".into())));
        assert!(matches!(r, Err(AiError::Network(_))));
    }
}