Skip to main content

kardia_include/
include.rs

1use std::fmt;
2use std::io::ErrorKind;
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::{Arc, OnceLock, Weak};
6use std::time::Duration;
7
8use futures::FutureExt;
9use futures::future::{BoxFuture, Shared};
10use kardia_core::{Context, Disposer, Error, Inject, PathSegment, Plugin, PluginDef, Result};
11use kardia_fs::{Fs, FsExt, WatchOptions};
12use kardia_loader::{EXPR_KEY, EntryChange, Loader, Location, TreeBackend, TreeHandle, expr_source, value_at};
13use parking_lot::Mutex;
14use serde::Deserialize;
15use serde_json::Value;
16
17use crate::journal::{Journal, apply_journal, merge, reconcile, record};
18use crate::patch::{
19    Owner, PatchIndex, Patched, apply_patches, ensure_ids, ensure_insert_ids, random_id, route_journal,
20};
21use crate::tree::{find, flatten, group_list, id_of};
22use crate::yaml::{self, Position, Syntax};
23
24#[derive(Debug, Clone, PartialEq, Deserialize)]
25#[serde(rename_all = "camelCase")]
26pub struct IncludeConfig {
27    pub path: String,
28    /// Written if the file does not exist yet.
29    #[serde(default)]
30    pub initial: Option<Vec<Value>>,
31    #[serde(default)]
32    pub patches: Vec<Value>,
33    /// Re-read the file whenever it changes (needs the `fs` service).
34    #[serde(default)]
35    pub watch: bool,
36}
37
38/// Grafts the entries of a YAML / JSON file into the loader as a subtree,
39/// and writes runtime changes of those entries back to the file.
40pub struct IncludePlugin;
41
42impl Plugin for IncludePlugin {
43    const NAME: &'static str = "include";
44    type Config = IncludeConfig;
45
46    fn inject() -> Inject {
47        Inject::new().with(<Loader as kardia_core::Service>::NAME).with("fs")
48    }
49
50    async fn apply(ctx: Context, config: Arc<IncludeConfig>) -> Result<()> {
51        Include::run(ctx, (*config).clone(), Arc::new(|from, to| std::fs::rename(from, to))).await
52    }
53}
54
55/// How the write-back replaces the file with its temp copy.
56type Rename = Arc<dyn Fn(&Path, &Path) -> std::io::Result<()> + Send + Sync>;
57
58impl IncludePlugin {
59    /// The plugin with `rename` in place of [`std::fs::rename`] (fault injection).
60    pub fn with_rename(rename: impl Fn(&Path, &Path) -> std::io::Result<()> + Send + Sync + 'static) -> PluginDef {
61        let rename: Rename = Arc::new(rename);
62        PluginDef::typed(move |ctx, config: Arc<IncludeConfig>| Include::run(ctx, (*config).clone(), rename.clone()))
63            .name(Self::NAME)
64            .inject(Self::inject())
65    }
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Stage {
70    Read,
71    Parse,
72    Validate,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct ConfigIssue {
77    pub message: String,
78    pub position: Position,
79}
80
81/// A config file that could not be read, parsed or validated.
82#[derive(Debug, Clone, thiserror::Error)]
83pub struct ConfigFileError {
84    pub stage: Stage,
85    pub path: PathBuf,
86    pub cause: Option<String>,
87    pub issues: Vec<ConfigIssue>,
88    not_found: bool,
89}
90
91impl fmt::Display for ConfigFileError {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        let stage = match self.stage {
94            Stage::Read => "read",
95            Stage::Parse => "parse",
96            Stage::Validate => "validate",
97        };
98        write!(f, "failed to {stage} config file {}", self.path.display())?;
99        if let Some(cause) = &self.cause {
100            write!(f, ": {cause}")?;
101        }
102        for issue in &self.issues {
103            let Position { line, column } = issue.position;
104            write!(f, "\n  - {} (at {}:{line}:{column})", issue.message, self.path.display())?;
105        }
106        Ok(())
107    }
108}
109
110#[derive(Clone, Copy, PartialEq, Eq)]
111enum Kind {
112    Json,
113    Yaml,
114}
115
116/// The file changed between the pre-check and the rename.
117#[derive(Debug, thiserror::Error)]
118#[error("the config file changed while it was being written")]
119struct StaleWrite;
120
121struct Snapshot {
122    content: String,
123    /// Parsed, ids assigned, unpatched.
124    data: Vec<Value>,
125    syntax: Syntax,
126}
127
128struct Anonymous {
129    id: String,
130    parent: Option<String>,
131    options: Value,
132}
133
134type Task = Shared<BoxFuture<'static, ()>>;
135
136#[derive(Default)]
137struct State {
138    patches: Vec<Value>,
139    cache: Option<Snapshot>,
140    journal: Journal,
141    /// The batch being written: out of the journal, not yet in the cache.
142    /// Trees applied meanwhile include it, so that it does not vanish from
143    /// the running tree while the write is in flight.
144    writing: Journal,
145    index: PatchIndex,
146    anonymous: Vec<Anonymous>,
147    dirty_read: bool,
148    dirty_write: bool,
149    draining: Option<Task>,
150    /// Only the latest intended tree is applied; older ones are skipped.
151    pending: Option<Vec<Value>>,
152    applying: Option<Task>,
153    disposed: bool,
154}
155
156/// A running include.
157#[derive(Clone)]
158pub struct Include(Arc<Inner>);
159
160struct Inner {
161    ctx: Context,
162    loader: Loader,
163    tree: OnceLock<TreeHandle>,
164    filename: PathBuf,
165    kind: Kind,
166    watch: bool,
167    state: Mutex<State>,
168    seq: AtomicU64,
169    rename: Rename,
170}
171
172const RENAME_RETRIES: u32 = 10;
173const RENAME_BACKOFF: Duration = Duration::from_millis(20);
174
175impl Include {
176    async fn run(ctx: Context, config: IncludeConfig, rename: Rename) -> Result<()> {
177        let loader = (*ctx.get::<Loader>()?).clone();
178        let url = ctx.get::<Fs>()?.resolve(&config.path)?;
179        let filename = url
180            .to_file_path()
181            .map_err(|_| kardia_core::ValidationError::message("include.path must resolve to a local file URL"))?;
182        let kind = match filename.extension().and_then(|ext| ext.to_str()) {
183            Some("json") => Kind::Json,
184            Some("yaml" | "yml") => Kind::Yaml,
185            ext => return Err(Error::msg(format!("extension \"{}\" not supported", ext.unwrap_or_default()))),
186        };
187        let mut patches = config.patches.clone();
188        ensure_insert_ids(&mut patches, &mut |_| false);
189        let include = Include(Arc::new(Inner {
190            ctx: ctx.clone(),
191            loader: loader.clone(),
192            tree: OnceLock::new(),
193            filename,
194            kind,
195            watch: config.watch,
196            state: Mutex::new(State { patches, ..Default::default() }),
197            seq: AtomicU64::new(0),
198            rename,
199        }));
200        let tree_ctx = ctx.intercept("fs", serde_json::json!({"baseUrl": url.join(".")?.as_str()}));
201        let tree = loader.create_tree(&tree_ctx, Arc::new(Backend(Arc::downgrade(&include.0))));
202        let _ = include.0.tree.set(tree);
203
204        // new patches are applied in place; another path or watch mode restarts
205        let updates = include.clone();
206        let path = config.path.clone();
207        ctx.on_update_with(move |next: &IncludeConfig| {
208            if next.path != path || next.watch != updates.0.watch {
209                return None;
210            }
211            let mut patches = next.patches.clone();
212            ensure_insert_ids(&mut patches, &mut |_| false);
213            let mut state = updates.0.state.lock();
214            state.patches = patches;
215            updates.schedule_apply(&mut state);
216            let applying = state.applying.clone();
217            Some(
218                async move {
219                    if let Some(applying) = applying {
220                        applying.await;
221                    }
222                    Ok(())
223                }
224                .boxed(),
225            )
226        })?;
227        if config.watch {
228            let watcher = include.clone();
229            ctx.inject(Inject::of::<(Fs,)>(), move |ctx| {
230                let include = watcher.clone();
231                async move {
232                    let watch = ctx.get::<Fs>()?.watch(&include.0.filename, WatchOptions::default())?;
233                    watch.on_change(move |_| {
234                        let include = include.clone();
235                        tokio::spawn(async move { include.refresh().await });
236                    });
237                    Ok(())
238                }
239            })?;
240        }
241
242        if let Err(error) = include.read().await {
243            // only a missing file falls back to `initial`
244            if !error.not_found {
245                return Err(error.into());
246            }
247            let Some(mut initial) = config.initial.clone() else {
248                return Err(Error::msg(format!("config file not found: {}", include.0.filename.display())));
249            };
250            ensure_ids(&mut initial, &mut |_| false);
251            include.write_text(&include.dump(&initial), None).await?;
252            include.read().await?;
253        }
254        let stopping = include.clone();
255        ctx.defer("include", Disposer::future(move || async move { stopping.stop().await }))?;
256        let applying = include.0.state.lock().applying.clone();
257        if let Some(applying) = applying {
258            applying.await;
259        }
260        Ok(())
261    }
262
263    /// The include behind a tree it created.
264    pub fn of(tree: &TreeHandle) -> Option<Include> {
265        tree.handle()?.downcast::<Inner>().ok().map(Include)
266    }
267
268    pub fn filename(&self) -> &Path {
269        &self.0.filename
270    }
271
272    pub fn tree(&self) -> &TreeHandle {
273        self.0.tree.get().expect("set at start")
274    }
275
276    /// Re-reads the file and reconciles the tree with it (what a watcher
277    /// triggers), then waits for every pending read and write.
278    pub async fn refresh(&self) {
279        self.0.state.lock().dirty_read = true;
280        self.drain();
281        self.flush().await;
282    }
283
284    /// Resolves once every pending read and write has been processed and
285    /// the tree reflects the outcome.
286    pub async fn flush(&self) {
287        loop {
288            let (draining, applying) = {
289                let state = self.0.state.lock();
290                (state.draining.clone(), state.applying.clone())
291            };
292            if draining.is_none() && applying.is_none() {
293                return;
294            }
295            if let Some(draining) = draining {
296                draining.await;
297            }
298            if let Some(applying) = applying {
299                applying.await;
300            }
301        }
302    }
303
304    /// Flushes what the user last did, then removes the tree's entries.
305    pub async fn stop(&self) {
306        {
307            let mut state = self.0.state.lock();
308            state.disposed = true;
309            state.pending = None;
310            if !state.journal.is_empty() {
311                state.dirty_write = true;
312            }
313        }
314        self.drain();
315        self.flush().await;
316        self.tree().root().stop();
317    }
318
319    /// Called synchronously by the loader once a tree-side change is in place.
320    fn commit(&self, change: &EntryChange) {
321        let parent = (change.group != self.tree().root())
322            .then(|| change.group.owner().and_then(|owner| id_of(&owner.options()).map(String::from)))
323            .flatten();
324        let position = change.group.data().iter().position(|options| id_of(options) == Some(&change.id)).unwrap_or(0);
325        {
326            let mut state = self.0.state.lock();
327            let moved = change.from.is_some();
328            record(
329                &mut state.journal,
330                &change.id,
331                change.options.as_ref(),
332                change.legacy.as_ref(),
333                moved,
334                parent,
335                position,
336            );
337            state.dirty_write = true;
338        }
339        self.drain();
340    }
341
342    fn drain(&self) {
343        let mut state = self.0.state.lock();
344        if state.draining.is_some() {
345            return;
346        }
347        let this = self.clone();
348        let task = tokio::spawn(async move { this.drain_loop().await });
349        state.draining = Some(async move { drop(task.await) }.boxed().shared());
350    }
351
352    async fn drain_loop(&self) {
353        loop {
354            let (read, write) = {
355                let mut state = self.0.state.lock();
356                if !state.dirty_read && !state.dirty_write {
357                    // checked and released together, so a new trigger starts a new drain
358                    state.draining = None;
359                    return;
360                }
361                (std::mem::take(&mut state.dirty_read), state.dirty_write)
362            };
363            if read && let Err(error) = self.read().await {
364                // half-written files are routine while editing; with the file in an
365                // unknown state nothing is written until another read succeeds
366                self.0.ctx.logger().warn(&error);
367                let mut state = self.0.state.lock();
368                if !state.dirty_read {
369                    state.draining = None;
370                    return;
371                }
372                continue;
373            }
374            if write {
375                self.0.state.lock().dirty_write = false;
376                if let Err(error) = self.write().await {
377                    self.0.ctx.logger().log_error(&error);
378                }
379            }
380        }
381    }
382
383    async fn read(&self) -> Result<(), ConfigFileError> {
384        let content = std::fs::read_to_string(&self.0.filename).map_err(|error| ConfigFileError {
385            stage: Stage::Read,
386            path: self.0.filename.clone(),
387            cause: Some(error.to_string()),
388            issues: Vec::new(),
389            not_found: error.kind() == ErrorKind::NotFound,
390        })?;
391        if self.0.state.lock().cache.as_ref().is_some_and(|cache| cache.content == content) {
392            return Ok(());
393        }
394        let (mut data, syntax) = self.parse(&content)?;
395        let mut guard = self.0.state.lock();
396        let state = &mut *guard;
397        self.assign_ids(state, &mut data);
398        if let Some(cache) = &state.cache {
399            let index = apply_patches(&data, &mut state.patches, &|_| {}).index;
400            let (base, theirs) = (flatten(&cache.data), flatten(&data));
401            let conflicts = reconcile(&mut state.journal, &base, &theirs, |id, key| index.file_owned(id, key));
402            for conflict in conflicts {
403                let file = self.0.filename.display();
404                self.0.ctx.logger().error(format_args!(
405                    "config conflict in {file}: entry {} {}; file wins",
406                    conflict.id, conflict.reason
407                ));
408            }
409        }
410        state.cache = Some(Snapshot { content, data, syntax });
411        self.schedule_apply(state);
412        // the file changed while tree-side changes were pending: write the merge
413        if !state.journal.is_empty() {
414            state.dirty_write = true;
415        }
416        Ok(())
417    }
418
419    fn parse(&self, content: &str) -> Result<(Vec<Value>, Syntax), ConfigFileError> {
420        let error = |stage, issues| ConfigFileError {
421            stage,
422            path: self.0.filename.clone(),
423            cause: None,
424            issues,
425            not_found: false,
426        };
427        let parsed = match self.0.kind {
428            Kind::Yaml => {
429                yaml::parse(content).map_err(|e| vec![ConfigIssue { message: e.message, position: e.position }])
430            }
431            Kind::Json => match serde_json::from_str::<Value>(content) {
432                Ok(data) => Ok((data, json_syntax(content))),
433                Err(e) => Err(vec![ConfigIssue {
434                    message: e.to_string().split(" at line").next().unwrap_or_default().to_string(),
435                    position: Position { line: e.line(), column: e.column() },
436                }]),
437            },
438        };
439        let (data, syntax) = parsed.map_err(|issues| error(Stage::Parse, issues))?;
440        // an empty or truncated file (routine mid-edit) is no array either
441        let Value::Array(data) = data else {
442            let position = syntax.locate(&[]).unwrap_or(Position { line: 1, column: 1 });
443            let issue = ConfigIssue { message: "config file must be a top-level array".into(), position };
444            return Err(error(Stage::Validate, vec![issue]));
445        };
446        // ids, patches and the journal all assume an entry is an object
447        let mut issues = Vec::new();
448        find_invalid(&data, &mut Vec::new(), &mut |path| {
449            let position = syntax.locate(path).unwrap_or(Position { line: 1, column: 1 });
450            issues.push(ConfigIssue { message: "entry must be an object".into(), position });
451        });
452        if !issues.is_empty() {
453            return Err(error(Stage::Validate, issues));
454        }
455        Ok((data, syntax))
456    }
457
458    async fn write(&self) -> Result<()> {
459        let expected = {
460            let state = self.0.state.lock();
461            match &state.cache {
462                Some(cache) if !state.journal.is_empty() => cache.content.clone(),
463                _ => return Ok(()),
464            }
465        };
466        let current = match std::fs::read_to_string(&self.0.filename) {
467            Ok(current) => current,
468            Err(error) if error.kind() == ErrorKind::NotFound => {
469                let pending = self.0.state.lock().journal.len();
470                let file = self.0.filename.display();
471                self.0
472                    .ctx
473                    .logger()
474                    .warn(format_args!("config file {file} is missing, {pending} pending change(s) kept in memory"));
475                return Ok(());
476            }
477            Err(error) => return Err(error.into()),
478        };
479        if current != expected {
480            // someone else wrote the file: merge first, then come back
481            let mut state = self.0.state.lock();
482            state.dirty_read = true;
483            state.dirty_write = true;
484            return Ok(());
485        }
486        // snapshot and swap: changes reported meanwhile belong to the next round
487        let (batch, mut data, mut patches) = {
488            let mut state = self.0.state.lock();
489            state.writing = std::mem::take(&mut state.journal);
490            let cache = state.cache.as_ref().expect("checked above");
491            (state.writing.clone(), cache.data.clone(), state.patches.clone())
492        };
493        let warn = |message: String| self.warn(message);
494        // the routed patches take effect together with the written file: the
495        // batch's records are diffs against the old file and the old patches
496        let patched = route_journal(&batch, &mut data, &mut patches, &warn).then_some(patches);
497        let unchanged = self.0.state.lock().cache.as_ref().is_some_and(|cache| cache.data == data);
498        if unchanged {
499            // patch-only changes, or ids assigned to anonymous entries
500            self.commit_batch(None, patched);
501            return Ok(());
502        }
503        let text = self.dump(&data);
504        let read_only = std::fs::metadata(&self.0.filename).map(|m| m.permissions().readonly()).unwrap_or(false);
505        if read_only {
506            let pending = self.restore();
507            let file = self.0.filename.display();
508            self.0
509                .ctx
510                .logger()
511                .warn(format_args!("config file {file} is read-only, {pending} pending change(s) kept in memory"));
512            return Ok(());
513        }
514        if let Err(error) = self.write_text(&text, Some(&expected)).await {
515            let pending = self.restore();
516            if error.is::<StaleWrite>() {
517                let mut state = self.0.state.lock();
518                state.dirty_read = true;
519                state.dirty_write = true;
520                return Ok(());
521            }
522            let file = self.0.filename.display();
523            self.0
524                .ctx
525                .logger()
526                .warn(format_args!("failed to write config file {file}, {pending} pending change(s) kept in memory"));
527            return Err(error);
528        }
529        let syntax = json_syntax(&text);
530        self.commit_batch(Some(Snapshot { content: text, data, syntax }), patched);
531        Ok(())
532    }
533
534    /// Takes in the written batch: the new file content and patches replace
535    /// the batch at once, so no tree sees one without the other.
536    fn commit_batch(&self, cache: Option<Snapshot>, patches: Option<Vec<Value>>) {
537        {
538            let mut state = self.0.state.lock();
539            if let Some(cache) = cache {
540                state.cache = Some(cache);
541            }
542            if let Some(patches) = &patches {
543                state.patches = patches.clone();
544            }
545            state.writing.clear();
546            self.schedule_apply(&mut state);
547        }
548        if let Some(patches) = patches {
549            self.persist_patches(patches);
550        }
551    }
552
553    /// Puts the unwritten batch back in front of the changes reported since.
554    fn restore(&self) -> usize {
555        let mut state = self.0.state.lock();
556        let mut batch = std::mem::take(&mut state.writing);
557        for (id, record) in std::mem::take(&mut state.journal) {
558            merge(&mut batch, &id, record);
559        }
560        state.journal = batch;
561        state.journal.len()
562    }
563
564    /// Changes to patch-owned values are persisted through the include's own
565    /// configuration, i.e. into the parent tree (not awaited: that is the
566    /// tree reconciliation, which the drain loop must not block on).
567    fn persist_patches(&self, patches: Vec<Value>) {
568        let mut config = self.0.ctx.fiber().config();
569        if let Some(map) = config.as_object_mut() {
570            map.insert("patches".into(), Value::Array(patches));
571        }
572        if self.0.loader.entry_of(&self.0.ctx).is_none() {
573            let file = self.0.filename.display();
574            return self.warn(format!("patches of {file} changed at runtime but cannot be persisted"));
575        }
576        match self.0.ctx.fiber().update(config) {
577            Ok(settle) => {
578                let ctx = self.0.ctx.clone();
579                tokio::spawn(async move {
580                    if let Err(error) = settle.await {
581                        ctx.logger().log_error(&error);
582                    }
583                });
584            }
585            Err(error) => self.0.ctx.logger().log_error(&error),
586        }
587    }
588
589    /// Writes through a temp file and a rename, so that no reader sees a
590    /// truncated file. With `expected`, the rename (and every retry of it)
591    /// only goes ahead while the file still holds that content.
592    async fn write_text(&self, text: &str, expected: Option<&str>) -> Result<()> {
593        let name = self.0.filename.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
594        let seq = self.0.seq.fetch_add(1, Ordering::Relaxed);
595        let tmp = self.0.filename.with_file_name(format!(".{name}.{}.{seq}.tmp", std::process::id()));
596        let result = async {
597            std::fs::write(&tmp, text)?;
598            for attempt in 0.. {
599                if let Some(expected) = expected {
600                    let current = match std::fs::read_to_string(&self.0.filename) {
601                        Ok(current) => Some(current),
602                        Err(error) if error.kind() == ErrorKind::NotFound => None,
603                        Err(error) => return Err(error.into()),
604                    };
605                    if current.as_deref() != Some(expected) {
606                        return Err(Error::new(StaleWrite));
607                    }
608                }
609                match (self.0.rename)(&tmp, &self.0.filename) {
610                    Ok(()) => return Ok(()),
611                    Err(error) if attempt < RENAME_RETRIES && is_transient(&error) => {}
612                    Err(error) => return Err(error.into()),
613                }
614                tokio::time::sleep(RENAME_BACKOFF * (attempt + 1)).await;
615            }
616            unreachable!("the loop returns")
617        }
618        .await;
619        if result.is_err() {
620            let _ = std::fs::remove_file(&tmp);
621        }
622        result
623    }
624
625    fn dump(&self, data: &[Value]) -> String {
626        let value = Value::Array(data.to_vec());
627        match self.0.kind {
628            Kind::Yaml => yaml::dump(&value),
629            Kind::Json => serde_json::to_string_pretty(&value).expect("JSON serializes"),
630        }
631    }
632
633    /// Applies `patches` and the unwritten changes to the cached file data,
634    /// and reconciles the tree with the result (latest wins).
635    fn schedule_apply(&self, state: &mut State) {
636        if state.disposed {
637            return;
638        }
639        let Some(cache) = &state.cache else { return };
640        let warn = |message: String| self.warn(message);
641        let Patched { data, index } = apply_patches(&cache.data, &mut state.patches, &warn);
642        let data = apply_journal(data, &state.writing, |_, _| true, &warn);
643        state.pending = Some(apply_journal(data, &state.journal, |_, _| true, &warn));
644        state.index = index;
645        if state.applying.is_some() {
646            return;
647        }
648        let this = self.clone();
649        let task = tokio::spawn(async move {
650            loop {
651                let tree = {
652                    let mut state = this.0.state.lock();
653                    match state.pending.take() {
654                        Some(tree) => tree,
655                        None => {
656                            state.applying = None;
657                            return;
658                        }
659                    }
660                };
661                this.tree().root().update(tree).await;
662            }
663        });
664        state.applying = Some(async move { drop(task.await) }.boxed().shared());
665    }
666
667    /// Entries the file leaves anonymous get an id here, before the loader
668    /// sees them. One that looks exactly like an entry named on the previous
669    /// read keeps that id (unless the file now names it explicitly), so
670    /// editing a neighbor does not restart it.
671    fn assign_ids(&self, state: &mut State, data: &mut [Value]) {
672        let mut used = std::collections::HashSet::new();
673        collect_ids(data, &mut used);
674        for patch in &state.patches {
675            if let Some(Value::Array(insert)) = patch.get("insert") {
676                collect_ids(insert, &mut used);
677            }
678        }
679        let mut previous = std::mem::take(&mut state.anonymous);
680        let store: std::collections::HashSet<String> =
681            self.tree().entries().iter().filter_map(|entry| id_of(&entry.options()).map(String::from)).collect();
682        assign(data, None, &mut used, &mut previous, &mut state.anonymous, &store);
683    }
684
685    /// See [`TreeBackend::locate`]; with `offset`, a char of the expression
686    /// `value`. A value is looked up where its owner writes it: in the file,
687    /// or in a patch in the include's own options.
688    fn locate(&self, id: &str, path: &[PathSegment], value: Option<&Value>, offset: Option<usize>) -> Option<Location> {
689        let in_patch = |index: usize, rest: &[PathSegment]| {
690            let prefix =
691                [PathSegment::Key("config".into()), PathSegment::Key("patches".into()), PathSegment::Index(index)];
692            prefix.into_iter().chain(rest.iter().cloned()).collect::<Vec<_>>()
693        };
694        let path_in_parent = {
695            let state = self.0.state.lock();
696            let cache = state.cache.as_ref()?;
697            let owner = match path.first() {
698                Some(PathSegment::Key(key)) => state.index.key(id, key),
699                _ => state.index.entry(Some(id)),
700            };
701            match owner {
702                Owner::File => {
703                    let mut full = entry_path(&find(&cache.data, id)?);
704                    full.extend_from_slice(path);
705                    let written = match full.split_first() {
706                        Some((PathSegment::Index(index), rest)) => {
707                            cache.data.get(*index).and_then(|v| value_at(v, rest))
708                        }
709                        _ => None,
710                    };
711                    if value.is_some() && written != value {
712                        return None;
713                    }
714                    let position = match offset {
715                        Some(offset) => cache.syntax.locate_expr(&full, offset)?,
716                        None => cache.syntax.locate(&full)?,
717                    };
718                    let Position { line, column } = position;
719                    return Some(Location { file: self.0.filename.clone(), line, column });
720                }
721                Owner::Patch(index) => in_patch(index, path),
722                Owner::Embedded(index, key) => {
723                    let list = state.patches.get(index)?.get(key)?.as_array()?;
724                    let mut rest = vec![PathSegment::Key(key.into())];
725                    rest.extend(entry_path(&find(list, id)?));
726                    rest.extend_from_slice(path);
727                    in_patch(index, &rest)
728                }
729            }
730        };
731        let entry = self.0.loader.entry_of(&self.0.ctx)?;
732        let own = entry.options()["id"].as_str()?.to_string();
733        let tree = entry.parent().tree();
734        match offset {
735            Some(offset) => tree.locate_expr(&own, &path_in_parent, expr_source(value?)?, offset),
736            None => tree.locate(&own, &path_in_parent, value),
737        }
738    }
739
740    fn warn(&self, message: String) {
741        self.0.ctx.root().logger_named("loader").warn(message);
742    }
743}
744
745fn assign(
746    entries: &mut [Value],
747    parent: Option<&str>,
748    used: &mut std::collections::HashSet<String>,
749    previous: &mut Vec<Anonymous>,
750    named: &mut Vec<Anonymous>,
751    store: &std::collections::HashSet<String>,
752) {
753    for options in entries {
754        if id_of(options).is_none() && options.is_object() {
755            let reused = previous.iter().position(|info| {
756                info.parent.as_deref() == parent && !used.contains(&info.id) && info.options == *options
757            });
758            let id = match reused {
759                Some(index) => previous.remove(index).id,
760                None => random_id(&mut |id| used.contains(id) || store.contains(id)),
761            };
762            used.insert(id.clone());
763            named.push(Anonymous { id: id.clone(), parent: parent.map(String::from), options: options.clone() });
764            let map = options.as_object_mut().expect("checked above");
765            let rest = std::mem::take(map);
766            map.insert("id".into(), Value::String(id));
767            map.extend(rest);
768        }
769        let id = id_of(options).map(String::from);
770        if options.get("group") == Some(&Value::Bool(true))
771            && let Some(Value::Array(list)) = options.get_mut("config")
772        {
773            assign(list, id.as_deref(), used, previous, named, store);
774        }
775    }
776}
777
778fn collect_ids(entries: &[Value], used: &mut std::collections::HashSet<String>) {
779    for options in entries {
780        if let Some(id) = id_of(options) {
781            used.insert(id.to_string());
782        }
783        if let Some(list) = group_list(options) {
784            collect_ids(list, used);
785        }
786    }
787}
788
789/// The positions of JSON (and of YAML written by the include itself), which
790/// are YAML too.
791fn json_syntax(content: &str) -> Syntax {
792    yaml::parse(content).map(|(_, syntax)| syntax).unwrap_or_else(|_| yaml::parse("").expect("empty").1)
793}
794
795/// The path of an entry from its index path (see [`find`]).
796fn entry_path(indices: &[usize]) -> Vec<PathSegment> {
797    let mut path = Vec::new();
798    for (depth, index) in indices.iter().enumerate() {
799        if depth > 0 {
800            path.push(PathSegment::Key("config".into()));
801        }
802        path.push(PathSegment::Index(*index));
803    }
804    path
805}
806
807fn find_invalid(entries: &[Value], prefix: &mut Vec<PathSegment>, report: &mut dyn FnMut(&[PathSegment])) {
808    for (index, options) in entries.iter().enumerate() {
809        prefix.push(PathSegment::Index(index));
810        if !options.is_object() {
811            report(prefix);
812        } else if let Some(list) = group_list(options) {
813            prefix.push(PathSegment::Key("config".into()));
814            find_invalid(list, prefix, report);
815            prefix.pop();
816        }
817        prefix.pop();
818    }
819}
820
821/// A rename over a file another process holds open (e.g. a virus scanner)
822/// fails briefly; a bounded retry is cheap.
823fn is_transient(error: &std::io::Error) -> bool {
824    matches!(error.kind(), ErrorKind::PermissionDenied | ErrorKind::ResourceBusy)
825}
826
827struct Backend(Weak<Inner>);
828
829impl TreeBackend for Backend {
830    fn commit(&self, change: &EntryChange) {
831        if let Some(inner) = self.0.upgrade() {
832            Include(inner).commit(change);
833        }
834    }
835
836    fn handle(&self) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
837        Some(self.0.upgrade()?)
838    }
839
840    fn locate(&self, id: &str, path: &[PathSegment], value: Option<&Value>) -> Option<Location> {
841        Include(self.0.upgrade()?).locate(id, path, value, None)
842    }
843
844    fn locate_expr(&self, id: &str, path: &[PathSegment], expr: &str, offset: usize) -> Option<Location> {
845        let value = Value::Object([(EXPR_KEY.to_string(), Value::String(expr.into()))].into_iter().collect());
846        Include(self.0.upgrade()?).locate(id, path, Some(&value), Some(offset))
847    }
848}