tinystore 0.11.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! A config's environment: a setting's variable is a prefix and its path in
//! upper snake case, `APP_LIMITS_MAX_RPS` for `limits.maxRps`, or a name the
//! program gives it, such as the `PORT` platforms set. `NAME_FILE` gives a
//! setting its file's text, as Docker and Kubernetes pass secrets.

use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;

use serde_json::Value;

use super::declaration::{Choices, ChosenAt, Declaration, Keys, Kind, Node, Rules, Setting, Shape, did_you_mean};
use super::explain::Origin;
use super::files::{Picked, Walked, walk_entries};
use super::rules;
use crate::typos::meant;

/// The longest text a config takes from a variable.
const MOST_BYTES: usize = 16 << 10;
/// What a `.env` file may hold; a file past it is no program's settings.
const MOST_DOTENV: usize = 1 << 20;

/// The variables a config reads: the prefix's, those `var` names, from the
/// process, or from what `from` gives in its place, as a test does.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Env {
    prefix: String,
    names: Vec<(String, String)>,
    files: Vec<Dotenv>,
    from: Option<Vec<(String, String)>>,
    /// The texts of the files `NAME_FILE` variables name, as a program's SDK
    /// read them; none when the core reads them itself.
    sent: Option<Texts>,
}

/// A `.env` file: one the core reads, or one a program's SDK read and sent.
#[derive(Clone, PartialEq, Eq)]
enum Dotenv {
    Path(PathBuf),
    #[cfg_attr(
        not(all(feature = "config", any(test, feature = "wire", feature = "records"))),
        expect(dead_code, reason = "only an SDK over the wire and a store's logger send it")
    )]
    Sent {
        name: String,
        text: String,
    },
}

// The variables' names alone, and the files' names: what each holds may be a secret.
impl std::fmt::Debug for Env {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let from: Option<Vec<&String>> = self.from.as_ref().map(|from| from.iter().map(|(name, _)| name).collect());
        f.debug_struct("Env")
            .field("prefix", &self.prefix)
            .field("names", &self.names)
            .field("files", &self.files)
            .field("from", &from)
            .finish_non_exhaustive()
    }
}

impl std::fmt::Debug for Dotenv {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Dotenv::Path(path) => std::fmt::Debug::fmt(path, f),
            Dotenv::Sent { name, .. } => std::fmt::Debug::fmt(name, f),
        }
    }
}

impl Env {
    /// Variables named by `prefix` and each setting's path: `APP_PORT`.
    pub fn prefix(prefix: impl Into<String>) -> Env {
        Env { prefix: prefix.into(), ..Env::default() }
    }

    /// The setting at `path` reads `name` in place of its prefixed variable.
    pub fn var(mut self, path: &str, name: &str) -> Env {
        self.names.push((path.to_owned(), name.to_owned()));
        self
    }

    /// `.env` files, whose variables count where the process has none; one
    /// that does not exist is skipped, a later one over an earlier.
    pub fn files<P: Into<PathBuf>>(mut self, files: impl IntoIterator<Item = P>) -> Env {
        self.files.extend(files.into_iter().map(|file| Dotenv::Path(file.into())));
        self
    }

    /// These variables in place of the process's: the only environment the
    /// config reads.
    pub fn from<K: Into<String>, V: Into<String>>(mut self, variables: impl IntoIterator<Item = (K, V)>) -> Env {
        self.from = Some(variables.into_iter().map(|(name, value)| (name.into(), value.into())).collect());
        self
    }
}

impl Env {
    /// What a program's SDK read where the program runs: its variables, the
    /// texts of the files their `NAME_FILE` name, and its `.env` files.
    #[cfg_attr(
        not(all(feature = "config", any(test, feature = "wire", feature = "records"))),
        expect(dead_code, reason = "only an SDK over the wire and a store's logger send it")
    )]
    pub(super) fn sent(mut self, variables: Vec<(String, String)>, files: Texts, dotenv: Vec<(String, String)>) -> Env {
        self.files = dotenv.into_iter().map(|(name, text)| Dotenv::Sent { name, text }).collect();
        self.from = Some(variables);
        self.sent = Some(files);
        self
    }

    /// The variable that gives the setting at `path`.
    pub(super) fn name_of(&self, path: &str) -> String {
        let given = self.names.iter().rev().find(|(named, _)| named == path);
        given.map_or_else(|| prefixed(&self.prefix, path), |(_, name)| name.clone())
    }
}

impl From<&str> for Env {
    fn from(prefix: &str) -> Env {
        Env::prefix(prefix)
    }
}

/// What the environment gave: each setting's value by its path, with the
/// variable and where its text came from, each value of a chosen group's
/// setting the same way, the entries a map's variable made, and the
/// variables with the prefix that name no setting.
#[derive(Debug, Default)]
pub(super) struct Read {
    pub(super) given: Vec<(String, Value, Origin)>,
    pub(super) picked: Vec<(Picked, Origin)>,
    pub(super) entries: Vec<(String, String)>,
    pub(super) unused: Vec<Unused>,
}

/// A variable with the prefix that names no setting, and the variable of a
/// setting it may have meant.
#[derive(Clone, Debug)]
pub(super) struct Unused {
    pub(super) name: String,
    meant: Option<String>,
}

impl std::fmt::Display for Unused {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let near = did_you_mean(self.meant.clone());
        write!(f, "{}: a variable with the prefix that names no setting{near}", self.name)
    }
}

/// The texts of the files `NAME_FILE` variables name, by their path.
pub(super) type Texts = HashMap<String, String>;

/// A variable's text and the `.env` file it came from, if one did.
type Variables = HashMap<String, (String, Option<String>)>;

/// What `env` gives the settings of `declaration`, the fields of the entries
/// `keys` names among them, or every problem with it.
///
/// A map of entries' own variable, `APP_INSTANCE` as JSON, is read first, so
/// that a field's variable, `APP_INSTANCE_AIMEE_PASSWORD`, also reaches an
/// entry it made. A chosen group's settings are read as the group its
/// chooser's variable picks, else as `before` says the layers before did.
pub(super) fn read(env: &Env, declaration: &Declaration, keys: &Keys, before: &Choices) -> Result<Read, Vec<String>> {
    let variables = variables(env)?;
    let mut read = Read::default();
    let mut problems = Vec::new();
    let mut keys = keys.clone();
    let mut maps = Vec::new();
    for (path, entries) in declaration.entries() {
        let name = env.name_of(&path);
        match variable(env, &variables, &name, &WHOLE_MAP) {
            Ok(None) => {}
            Ok(Some((Value::Object(map), from))) => {
                let mut walked = Walked::after(before);
                walk_entries(entries, &map, &path, &mut walked);
                problems.extend(walked.problems.into_iter().map(|problem| format!("{from}: {problem}")));
                read.given.extend(walked.given.into_iter().map(|(path, value)| (path, value, from.clone())));
                read.picked.extend(walked.picked.into_iter().map(|picked| (picked, from.clone())));
                for (path, key) in walked.entries {
                    keys.entry(path.clone()).or_default().insert(key.clone());
                    read.entries.push((path, key));
                }
            }
            Ok(Some(_)) => problems.push(format!("{name}: a map of entries is given as JSON")),
            Err(problem) => problems.push(problem),
        }
        maps.push(name);
    }
    let here = Here { env, variables: &variables, given: &read.given };
    let chosen = chosen_here(declaration, &keys, before, &here);
    let shape = Shape { entries: keys, chosen };
    let names = names(env, declaration, &shape)?;
    for (path, (name, setting)) in &names {
        match variable(env, &variables, name, setting) {
            Ok(None) => {}
            Ok(Some((value, from))) => read.take(&shape.chosen, path, value, from),
            Err(problem) => problems.push(problem),
        }
    }
    read.unused = unused(env, &variables, &names, &maps);
    if problems.is_empty() { Ok(read) } else { Err(problems) }
}

/// What this environment gives a setting before its variables are read
/// one by one: its own variable, else what the map's JSON variable gave it.
struct Here<'a> {
    env: &'a Env,
    variables: &'a Variables,
    given: &'a [(String, Value, Origin)],
}

impl Here<'_> {
    /// The value here of the setting at `path`; none for a text that does
    /// not read, which is refused where it is read as its setting.
    fn value(&self, declaration: &Declaration, path: &str) -> Option<Value> {
        let setting = declaration.setting(path)?;
        let own = variable(self.env, self.variables, &self.env.name_of(path), setting).ok().flatten();
        let from_map = || self.given.iter().rev().find(|(given, ..)| given == path).map(|(_, value, _)| value.clone());
        own.map(|(value, _)| value).or_else(from_map)
    }
}

/// The group each chosen group's settings are read as here: the one its
/// chooser here names, else the one the layers before chose, else its
/// chooser's default.
fn chosen_here(declaration: &Declaration, keys: &Keys, before: &Choices, here: &Here<'_>) -> Choices {
    let picked = |at: &ChosenAt<'_>| match here.value(declaration, &at.chooser) {
        Some(value) => at.chosen.named(Some(&value)).map(|(name, _)| name.to_owned()),
        None => before.get(&at.path).cloned().or_else(|| at.default.map(str::to_owned)),
    };
    declaration.chosen(keys).into_iter().filter_map(|at| Some((at.path.clone(), picked(&at)?))).collect()
}

impl Read {
    /// Takes a variable's value of the setting at `path`, kept with the group
    /// it was read as when it is a setting of a chosen group.
    fn take(&mut self, chosen: &Choices, path: &str, value: Value, from: Origin) {
        let under = |node: &String| path.strip_prefix(node.as_str()).is_some_and(|rest| rest.starts_with('.'));
        match chosen.iter().find(|(node, _)| under(node)) {
            Some((node, group)) => {
                let picked = Picked { node: node.clone(), group: group.clone(), path: path.to_owned(), value };
                self.picked.push((picked, from));
            }
            None => self.given.push((path.to_owned(), value, from)),
        }
    }
}

/// What a map of entries' own variable is read as: a map given as JSON. Its
/// text, as any map's, is never quoted, since it may hold an entry's secret:
/// a refusal says where its JSON stops reading.
static WHOLE_MAP: Setting = Setting {
    kind: Kind::Object,
    rules: Rules { min: None, max: None, one_of: None },
    default: None,
    required: false,
    live: false,
    secret: false,
};

/// A variable's text as its setting keeps it; the text of a secret is never
/// quoted, nor, as `rules` words it, that of a map, a list or any value.
fn parsed(setting: &Setting, text: &str) -> Result<Value, String> {
    if text.len() > MOST_BYTES {
        return Err(format!("{} bytes, past the {MOST_BYTES} a setting takes", text.len()));
    }
    rules::parse(setting, text).map_err(|why| if setting.secret { "its text does not read".to_owned() } else { why })
}

/// Every setting's variable by the setting's path, each named once: two
/// entries whose keys are one variable's, `site-3` and `site_3`, are refused.
fn names<'a>(
    env: &Env,
    declaration: &'a Declaration,
    shape: &Shape,
) -> Result<BTreeMap<String, (String, &'a Setting)>, Vec<String>> {
    let mut problems = Vec::new();
    let mut names = BTreeMap::new();
    for (path, setting) in declaration.settings_of(shape) {
        names.insert(path.clone(), (env.name_of(&path), setting));
    }
    for (path, _) in &env.names {
        if declaration.setting(path).is_none() && !matches!(declaration.node(path), Some(Node::Entries(_))) {
            let near = meant(path, declaration.settings().into_iter().map(|(path, _)| path));
            problems.push(format!("a variable is named for {path}, which is no setting{}", did_you_mean(near)));
        }
    }
    // A setting reads NAME and NAME_FILE, so `db`'s APP_DB_FILE is also the
    // name `db.file` would read.
    let mut taken: HashMap<String, &str> = HashMap::new();
    for (path, (name, _)) in &names {
        for read in [name.clone(), format!("{name}_FILE")] {
            if let Some(other) = taken.insert(key(&read), path)
                && other != path.as_str()
            {
                problems.push(format!("{read} would give both {other} and {path}"));
                break;
            }
        }
    }
    if problems.is_empty() { Ok(names) } else { Err(problems) }
}

/// A setting's variable: the prefix and its path in upper snake case.
pub(super) fn prefixed(prefix: &str, path: &str) -> String {
    let name = upper_snake(path);
    if prefix.is_empty() { name } else { format!("{prefix}_{name}") }
}

/// A path's words apart in capitals, as Go, Bun and Python spelled them: a
/// dot, a dash, a capital after a small letter or a digit, or one before a
/// small letter after capitals begins a word.
///
/// ```text
/// dbUrl → DB_URL     HTTPServer → HTTP_SERVER     v2Api → V2_API     limits.maxRps → LIMITS_MAX_RPS
/// ```
pub(super) fn upper_snake(path: &str) -> String {
    let chars: Vec<char> = path.chars().collect();
    let mut name = String::with_capacity(path.len() + 4);
    for (at, &c) in chars.iter().enumerate() {
        if c == '.' || c == '-' {
            name.push('_');
            continue;
        }
        if at > 0 && crate::text::starts_word(&chars, at) {
            name.push('_');
        }
        name.extend(c.to_uppercase());
    }
    name
}

/// A file's text, refused past `most` bytes before more of it is read.
fn read_at_most(path: &std::path::Path, most: usize) -> std::io::Result<String> {
    use std::io::Read;
    let mut text = String::new();
    std::fs::File::open(path)?.take(most as u64 + 1).read_to_string(&mut text)?;
    if text.len() > most {
        return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("past the {most} bytes it may hold")));
    }
    Ok(text)
}

/// A name as variables are looked up: Windows does not tell `Path` from
/// `PATH`, and neither does a config there.
fn key(name: &str) -> String {
    if cfg!(windows) { name.to_uppercase() } else { name.to_owned() }
}

/// The variables of the process, or those `from` gives, over the `.env`
/// files' own.
fn variables(env: &Env) -> Result<Variables, Vec<String>> {
    let mut variables = Variables::new();
    for file in &env.files {
        let (shown, text) = match file {
            Dotenv::Sent { name, text } => (name.clone(), text.clone()),
            Dotenv::Path(path) => match read_at_most(path, MOST_DOTENV) {
                Ok(text) => (path.display().to_string(), text),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                Err(error) => return Err(vec![format!("{}: {error}", path.display())]),
            },
        };
        let read = dotenv(&text).map_err(|why| vec![format!("{shown}: {why}")])?;
        variables.extend(read.into_iter().map(|(name, value)| (key(&name), (value, Some(shown.clone())))));
    }
    let process: Vec<(String, String)> = match &env.from {
        Some(given) => given.clone(),
        None => std::env::vars_os()
            .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
            .collect(),
    };
    variables.extend(process.into_iter().map(|(name, value)| (key(&name), (value, None))));
    Ok(variables)
}

/// A variable's value as its setting keeps it, and where its text came from;
/// none when neither `NAME` nor `NAME_FILE` is set, and both set is refused.
/// A text that does not read is refused, named by the variable that gave it.
fn variable(
    env: &Env,
    variables: &Variables,
    name: &str,
    setting: &Setting,
) -> Result<Option<(Value, Origin)>, String> {
    let file_name = format!("{name}_FILE");
    let given = |variable: &str, text: &str, dotenv: Option<&String>, file: Option<&String>| {
        let value = parsed(setting, text).map_err(|why| format!("{variable}: {why}"))?;
        let from = Origin::Env { variable: variable.to_owned(), dotenv: dotenv.cloned(), file: file.cloned() };
        Ok(Some((value, from)))
    };
    match (variables.get(&key(name)), variables.get(&key(&file_name))) {
        (Some(_), Some(_)) => Err(format!("{name} and {file_name} are both set")),
        (Some((text, dotenv)), None) => given(name, text, dotenv.as_ref(), None),
        // The .env file that set a NAME_FILE variable is not kept: `explain`
        // names the file it read, which holds the text.
        (None, Some((path, _))) => {
            let text = match &env.sent {
                Some(sent) => sent
                    .get(path)
                    .cloned()
                    .ok_or_else(|| format!("{file_name}: {path}: the program could not read it"))?,
                None => {
                    read_at_most(path.as_ref(), MOST_BYTES).map_err(|error| format!("{file_name}: {path}: {error}"))?
                }
            };
            given(&file_name, &without_newline(text), None, Some(path))
        }
        (None, None) => Ok(None),
    }
}

/// A file's text without the one newline an editor or `echo` ends it with.
fn without_newline(mut text: String) -> String {
    if text.ends_with('\n') {
        text.pop();
        if text.ends_with('\r') {
            text.pop();
        }
    }
    text
}

/// The variables with the prefix that name no setting: a misspelt name is
/// said, not ignored, and so is a field of an entry no layer before made.
fn unused(
    env: &Env,
    variables: &Variables,
    names: &BTreeMap<String, (String, &Setting)>,
    maps: &[String],
) -> Vec<Unused> {
    if env.prefix.is_empty() {
        return Vec::new();
    }
    let start = key(&format!("{}_", env.prefix));
    let named = names.values().map(|(name, _)| name).chain(maps);
    let read: Vec<String> = named.flat_map(|name| [key(name), key(&format!("{name}_FILE"))]).collect();
    let mut unused: Vec<String> = variables
        .iter()
        .filter(|(name, _)| name.starts_with(&start) && !read.contains(name))
        .map(|(name, _)| name.clone())
        .collect();
    unused.sort();
    unused
        .into_iter()
        .map(|name| Unused { meant: meant(&name, names.values().map(|(name, _)| name.as_str())), name })
        .collect()
}

/// The variables a `.env` file sets, a later name over an earlier:
///
/// ```text
/// # a comment
/// export PORT=3000
/// URL=postgres://localhost/app  # a comment after a space
/// GREETING="two\nlines"         # \n, \r, \t, \" and \\ inside double quotes
/// PATTERN='$literal\n'          # nothing is read inside single quotes
/// ```
///
/// A quoted value may run over lines.
pub(super) fn dotenv(text: &str) -> Result<Vec<(String, String)>, String> {
    let mut values = Vec::new();
    let (mut rest, mut line) = (text, 1);
    while !rest.is_empty() {
        let (assigned, after) = assignment(rest).map_err(|why| format!("line {line}: {why}"))?;
        line += rest[..rest.len() - after.len()].matches('\n').count();
        if let Some(pair) = assigned {
            values.retain(|(name, _): &Assigned| *name != pair.0);
            values.push(pair);
        }
        rest = after;
    }
    Ok(values)
}

/// A variable's name and the value a line sets it to.
type Assigned = (String, String);

/// One line, or the lines of a quoted value: the name and value it sets,
/// none for a blank or a comment, and the text after it.
fn assignment(text: &str) -> Result<(Option<Assigned>, &str), String> {
    let (line, rest) = text.split_once('\n').unwrap_or((text, ""));
    let trimmed = line.trim();
    if trimmed.is_empty() || trimmed.starts_with('#') {
        return Ok((None, rest));
    }
    // a line is never quoted: one with no `=` may be a value run over lines, a secret's
    let equals = line.find('=').ok_or_else(|| "not NAME=value".to_owned())?;
    let name = line[..equals].trim();
    let name = name.strip_prefix("export ").map_or(name, str::trim);
    if !is_variable_name(name) {
        return Err("what stands before its = is no variable's name".to_owned());
    }
    let value_start =
        equals + 1 + (line[equals + 1..].len() - line[equals + 1..].trim_start_matches([' ', '\t']).len());
    let opening = line.as_bytes().get(value_start).copied();
    if let Some(quote @ (b'"' | b'\'')) = opening {
        let (value, after) = quoted(&text[value_start..], quote)?;
        return Ok((Some((name.to_owned(), value)), after));
    }
    let mut value = &line[value_start..];
    if let Some(comment) = value.find(" #") {
        value = &value[..comment];
    }
    Ok((Some((name.to_owned(), value.trim_end_matches([' ', '\t', '\r']).to_owned())), rest))
}

/// A quoted value from its opening quote, and the text after the line its
/// closing quote is on.
fn quoted(text: &str, quote: u8) -> Result<(String, &str), String> {
    let bytes = text.as_bytes();
    let mut value = Vec::new();
    let mut at = 1;
    while at < bytes.len() {
        match bytes[at] {
            byte if byte == quote => {
                let after = text[at + 1..].split_once('\n').map_or("", |(_, after)| after);
                return Ok((String::from_utf8_lossy(&value).into_owned(), after));
            }
            b'\\' if quote == b'"' && at + 1 < bytes.len() => {
                at += 1;
                // Only the five escapes are read: `"D:\dev"` keeps its backslash.
                match bytes[at] {
                    b'n' | b'r' | b't' | b'"' | b'\\' => value.push(unescaped(bytes[at])),
                    other => value.extend([b'\\', other]),
                }
            }
            byte => value.push(byte),
        }
        at += 1;
    }
    Err(format!("a value opened with {} is never closed", quote as char))
}

fn unescaped(byte: u8) -> u8 {
    match byte {
        b'n' => b'\n',
        b'r' => b'\r',
        b't' => b'\t',
        other => other,
    }
}

/// Letters, digits after the first, and `_`.
fn is_variable_name(name: &str) -> bool {
    !name.is_empty()
        && name.chars().enumerate().all(|(at, c)| c == '_' || c.is_alphabetic() || (at > 0 && c.is_ascii_digit()))
}

#[cfg(test)]
#[path = "env_tests.rs"]
mod tests;