1use std::collections::HashMap;
15use std::path::{Path, PathBuf};
16use std::thread;
17use std::time::{Duration, Instant};
18
19use crate::access::{self, ReadOnlyKind};
20use crate::adapters::adapter;
21use crate::apply::backup;
22use crate::apply::journal::{FileRecord, Journal, RecordedError};
23use crate::apply::ledger::{EntryKind, Ledger, LedgerEntry, LedgerKey, LedgerSlot, Origin};
24use crate::apply::plan::{
25 self, Action, EntryPlan, EntryState, OpCounts, Plan, PlanOptions, ProjectSelection,
26 ScopeFilter, TargetPlan, read_target,
27};
28use crate::apply::render::{DesiredState, RenderCx};
29use crate::apply::{ApplyEnv, import, placeholder_path, temp_path};
30use crate::error::{CoreError, ErrorCode};
31use crate::formats::{Document, NativeMap, NativeValue};
32use crate::layering::ProjectRepo;
33use crate::model::applied::{AppliedRecord, AppliedTarget, ApplyOutcome, ApplyTrigger};
34use crate::model::ids;
35use crate::model::settings::ApplyMode;
36use crate::model::{SCHEMA_VERSION, TomlDocument};
37use crate::store::{ApplyRef, CommitId, Machine, Operation, Store, Transaction, utc_datetime};
38
39const MAX_REPLANS: u32 = 3;
41const LOCK_RETRY: Duration = Duration::from_secs(2);
43
44#[derive(Debug, Clone)]
46pub struct ApplyRequest {
47 pub options: PlanOptions,
48 pub trigger: ApplyTrigger,
49}
50
51#[derive(Debug, Clone)]
53pub struct TargetResult {
54 pub clients: Vec<&'static str>,
55 pub scope: crate::model::applied::Scope,
56 pub project_id: Option<String>,
58 pub project: Option<PathBuf>,
60 pub file: PathBuf,
61 pub counts: OpCounts,
63 pub outcome: ApplyOutcome,
64 pub error: Option<CoreError>,
66 pub entries: Vec<EntryPlan>,
68 pub written: bool,
69 pub backup: Option<PathBuf>,
70 pub warnings: Vec<CoreError>,
71 pub read_only: Option<ReadOnlyKind>,
75}
76
77impl TargetResult {
78 pub fn unresolved(&self) -> usize {
79 self.entries.iter().filter(|entry| entry.unresolved).count()
80 }
81}
82
83#[derive(Debug, Clone)]
85pub struct ApplyReport {
86 pub apply_id: String,
87 pub trigger: ApplyTrigger,
88 pub outcome: ApplyOutcome,
89 pub targets: Vec<TargetResult>,
90 pub warnings: Vec<CoreError>,
91 pub imported: Vec<String>,
93 pub recorded: bool,
96}
97
98impl ApplyReport {
99 pub fn writes(&self) -> usize {
101 self.targets.iter().filter(|target| target.written).count()
102 }
103
104 pub fn unresolved(&self) -> usize {
106 self.targets.iter().map(TargetResult::unresolved).sum()
107 }
108
109 pub fn status(&self) -> ApplyStatus {
113 status_of(self.targets.iter())
114 }
115
116 pub fn project_status(&self, id: &str) -> ApplyStatus {
120 status_of(
121 self.targets
122 .iter()
123 .filter(|target| target.project_id.as_deref() == Some(id)),
124 )
125 }
126}
127
128fn status_of<'a>(mut targets: impl Iterator<Item = &'a TargetResult> + Clone) -> ApplyStatus {
129 if targets
130 .clone()
131 .any(|target| target.outcome == ApplyOutcome::Failed)
132 {
133 ApplyStatus::FileFailed
134 } else if targets.clone().any(|target| target.unresolved() > 0) {
135 ApplyStatus::NeedsDecision
136 } else if targets
137 .clone()
138 .flat_map(|target| &target.entries)
139 .any(EntryPlan::blocked_by_secret)
140 {
141 ApplyStatus::MissingSecrets
142 } else if targets.any(|target| {
143 target
144 .error
145 .as_ref()
146 .is_some_and(|error| error.code() == ErrorCode::TrustRequired)
147 }) {
148 ApplyStatus::TrustRequired
149 } else {
150 ApplyStatus::Done
151 }
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
156pub enum ApplyStatus {
157 Done,
159 FileFailed,
161 NeedsDecision,
163 MissingSecrets,
165 TrustRequired,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
174pub enum Touched {
175 All,
177 Servers(Vec<String>),
180 Project(PathBuf),
183}
184
185impl Touched {
186 pub fn options(&self) -> PlanOptions {
188 match self {
189 Touched::All => PlanOptions::default(),
190 Touched::Servers(ids) => PlanOptions {
191 servers: Some(ids.clone()),
192 ..PlanOptions::default()
193 },
194 Touched::Project(root) => PlanOptions {
195 scope: ScopeFilter::Project,
196 projects: ProjectSelection::Only(root.clone()),
197 ..PlanOptions::default()
198 },
199 }
200 }
201}
202
203pub fn instant_apply(
208 tx: &mut Transaction<'_>,
209 ax: &ApplyEnv<'_>,
210 touched: &Touched,
211) -> Result<Option<ApplyReport>, CoreError> {
212 if crate::eject::status_at(ax.fs, &ax.home.state_dir())?.is_some_and(|ejected| ejected.all()) {
215 return Ok(None);
216 }
217 let machine = tx.machine().id.clone();
218 let desired = DesiredState::load(tx, Some(&machine))?;
219 if desired.apply_mode() != ApplyMode::Instant {
220 return Ok(None);
221 }
222 let request = ApplyRequest {
223 options: touched.options(),
224 trigger: ApplyTrigger::Instant,
225 };
226 apply_with(tx, ax, &request, Some(desired)).map(Some)
227}
228
229pub fn preview(
232 store: Option<&Store<'_>>,
233 ax: &ApplyEnv<'_>,
234 options: &PlanOptions,
235) -> Result<Plan, CoreError> {
236 let inputs = PlanInputs::load(store, ax)?;
237 plan::plan(
238 &ax.render_cx(inputs.memory),
239 &inputs.desired,
240 &inputs.ledger,
241 &inputs.key,
242 options,
243 )
244}
245
246pub(crate) struct PlanInputs {
249 pub(crate) desired: DesiredState,
250 pub(crate) ledger: Ledger,
251 pub(crate) key: LedgerKey,
252 pub(crate) memory: std::sync::Arc<crate::secrets::scanner::SecretMemory>,
253}
254
255impl PlanInputs {
256 pub(crate) fn load(store: Option<&Store<'_>>, ax: &ApplyEnv<'_>) -> Result<Self, CoreError> {
259 let state_dir = ax.home.state_dir();
260 let machine = Machine::load(ax.fs, &state_dir)?;
261 let desired = match store {
262 Some(store) => DesiredState::load(store, machine.as_ref().map(|m| m.id.as_str()))?,
263 None => DesiredState::empty(),
264 };
265 let ledger = Ledger::load(ax.fs, &state_dir)?;
266 let key = match LedgerKey::load(ax.fs, &state_dir)? {
268 Some(key) => key,
269 None => LedgerKey::from_bytes([0; 32]),
270 };
271 let memory = match store {
272 Some(store) => store.secret_memory().clone(),
273 None => std::sync::Arc::new(crate::secrets::scanner::SecretMemory::new()?),
274 };
275 Ok(Self {
276 desired,
277 ledger,
278 key,
279 memory,
280 })
281 }
282}
283
284pub fn run(
287 store: &Store<'_>,
288 ax: &ApplyEnv<'_>,
289 request: &ApplyRequest,
290) -> Result<(ApplyReport, Option<CommitId>), CoreError> {
291 let operation = Operation::new("apply", "apply");
292 let committed = store.transaction(operation, |tx| apply_in(tx, ax, request))?;
293 Ok((committed.value, committed.commit))
294}
295
296pub fn apply_in(
303 tx: &mut Transaction<'_>,
304 ax: &ApplyEnv<'_>,
305 request: &ApplyRequest,
306) -> Result<ApplyReport, CoreError> {
307 apply_with(tx, ax, request, None)
308}
309
310fn apply_with(
312 tx: &mut Transaction<'_>,
313 ax: &ApplyEnv<'_>,
314 request: &ApplyRequest,
315 desired: Option<DesiredState>,
316) -> Result<ApplyReport, CoreError> {
317 tx.check()?;
318 let state_dir = ax.home.state_dir();
319 let machine = tx.machine().clone();
320 let cx = ax.render_cx(tx.store().secret_memory().clone());
321 let mut ledger = Ledger::load(ax.fs, &state_dir)?;
322 let key = LedgerKey::load_or_create(ax.fs, &state_dir)?;
323
324 let mut desired = match desired {
325 Some(desired) => desired,
326 None => DesiredState::load(tx, Some(&machine.id))?,
327 };
328 let mut plan = plan::plan(&cx, &desired, &ledger, &key, &request.options)?;
329 let mut imported = Vec::new();
330 if plan
331 .targets
332 .iter()
333 .flat_map(|target| &target.entries)
334 .any(import::is_store_resolution)
335 {
336 let resolutions = import::stage_resolutions(tx, &plan, &desired)?;
337 imported = resolutions.changed;
338 desired = DesiredState::load(tx, Some(&machine.id))?;
339 plan = plan::plan(&cx, &desired, &ledger, &key, &request.options)?;
340 for entry in plan
343 .targets
344 .iter_mut()
345 .flat_map(|target| &mut target.entries)
346 {
347 if !import::is_store_resolution(entry) {
348 continue;
349 }
350 let reason = resolutions
351 .failed
352 .iter()
353 .find(|(client, name, _)| {
354 Some(client.as_str()) == entry.client && *name == entry.name
355 })
356 .map(|(_, _, err)| err.clone());
357 let fallback = if entry.action == Action::Release {
358 "the entry is still desired for this client after the release"
359 } else {
360 "the store definition still renders differently after the import"
361 };
362 entry.action = Action::Skip;
363 entry.unresolved = true;
364 entry.problem =
365 Some(reason.unwrap_or_else(|| CoreError::new(ErrorCode::InvalidValue, fallback)));
366 }
367 }
368
369 let base = tx.store().head()?;
370 let now = ax.env.now();
371 let apply_id = ids::new_ulid(now)?;
372 let mut journal = Journal::start(
373 ax.fs,
374 &state_dir,
375 &apply_id,
376 request.trigger,
377 utc_datetime(now).to_string(),
378 )?;
379 let mut executor = Executor {
380 cx: &cx,
381 ax,
382 key: &key,
383 options: &request.options,
384 run_dir: backup::run_dir(ax.home, now, &apply_id),
385 written_at: utc_datetime(now).to_string(),
386 store_commit: base.short().to_owned(),
387 };
388 let mut targets: Vec<TargetResult> = Vec::with_capacity(plan.targets.len());
389 let mut unsaved: Vec<usize> = Vec::new();
393 for target in plan.targets {
394 let (mut result, changed) = executor.execute(target, &mut ledger);
395 let index = targets.len();
396 if changed {
397 unsaved.push(index);
398 }
399 if changed && result.written {
400 if let Err(err) = ledger.save(ax.fs, &state_dir) {
401 for earlier in unsaved.drain(..).filter(|earlier| *earlier != index) {
402 ownership_lost(&mut targets[earlier], &err);
403 journal.files[earlier] = file_record(&targets[earlier]);
404 }
405 ownership_lost(&mut result, &err);
406 }
407 unsaved.clear();
408 }
409 if let Err(err) = journal.record(ax.fs, &state_dir, file_record(&result)) {
410 if !unsaved.is_empty() {
412 let _ = ledger.save(ax.fs, &state_dir);
413 }
414 return Err(err);
415 }
416 targets.push(result);
417 }
418 if !unsaved.is_empty()
419 && let Err(err) = ledger.save(ax.fs, &state_dir)
420 {
421 for index in unsaved {
422 ownership_lost(&mut targets[index], &err);
423 journal.files[index] = file_record(&targets[index]);
424 }
425 }
426 let outcome = run_outcome(&targets);
427 let writes = targets.iter().filter(|target| target.written).count();
428
429 let commits_anyway = tx.has_changes();
430 let recorded = commits_anyway || writes > 0;
431 if recorded {
432 let record = AppliedRecord {
433 schema: SCHEMA_VERSION,
434 machine_id: machine.id.clone(),
435 apply_id: apply_id.clone(),
436 time: utc_datetime(now),
437 store_revision: base.as_str().to_owned(),
438 trigger: request.trigger,
439 outcome,
440 targets: targets
441 .iter()
442 .map(|target| AppliedTarget {
443 client: target.clients[0].to_owned(),
444 scope: target.scope,
445 project_id: target.project_id.clone(),
446 file: placeholder_path(ax.env, &target.file, target.project.as_deref()),
447 create: target.counts.create,
448 update: target.counts.update,
449 remove: target.counts.remove,
450 disable: target.counts.disable,
451 outcome: target.outcome,
452 extra: toml::Table::new(),
453 })
454 .collect(),
455 extra: toml::Table::new(),
456 };
457 let relative = format!("machines/{}.applied.toml", machine.id);
458 tx.write(&relative, TomlDocument::new(record).to_text()?)?;
459 tx.set_apply(ApplyRef {
460 id: apply_id.clone(),
461 outcome,
462 });
463 if !commits_anyway {
464 tx.set_summary(summary(&targets));
465 }
466 }
467 journal.finish(ax.fs, &state_dir, outcome)?;
468 backup::prune(ax.fs, ax.home, now)?;
469 crate::diagnostics::log::event(
470 "apply",
471 &[
472 ("targets", &targets.len()),
473 ("writes", &writes),
474 ("outcome", &format!("{outcome:?}").to_lowercase()),
475 ],
476 );
477
478 Ok(ApplyReport {
479 apply_id,
480 trigger: request.trigger,
481 outcome,
482 targets,
483 warnings: plan.warnings,
484 imported,
485 recorded,
486 })
487}
488
489fn summary(targets: &[TargetResult]) -> String {
491 let written: Vec<&TargetResult> = targets.iter().filter(|target| target.written).collect();
492 let mut clients: Vec<&str> = Vec::new();
493 for target in &written {
494 for client in &target.clients {
495 if !clients.contains(client) {
496 clients.push(client);
497 }
498 }
499 }
500 let files = if written.len() == 1 { "file" } else { "files" };
501 format!("apply: {} {files} ({})", written.len(), clients.join(", "))
502}
503
504fn run_outcome(targets: &[TargetResult]) -> ApplyOutcome {
507 let count = |outcome| targets.iter().filter(|t| t.outcome == outcome).count();
508 let (ok, partial, failed) = (
509 count(ApplyOutcome::Ok),
510 count(ApplyOutcome::Partial),
511 count(ApplyOutcome::Failed),
512 );
513 if ok == targets.len() {
514 ApplyOutcome::Ok
515 } else if ok + partial == 0 && failed > 0 {
516 ApplyOutcome::Failed
517 } else if ok + partial == 0 {
518 ApplyOutcome::Blocked
519 } else {
520 ApplyOutcome::Partial
521 }
522}
523
524fn file_record(result: &TargetResult) -> FileRecord {
525 FileRecord {
526 clients: result.clients.iter().map(|c| (*c).to_owned()).collect(),
527 scope: result.scope,
528 file: result.file.to_string_lossy().into_owned(),
529 outcome: result.outcome,
530 create: result.counts.create,
531 update: result.counts.update,
532 remove: result.counts.remove,
533 disable: result.counts.disable,
534 written: result.written,
535 backup: result
536 .backup
537 .as_ref()
538 .map(|path| path.to_string_lossy().into_owned()),
539 old_values: false,
540 backup_removed: false,
541 error: result.error.as_ref().map(RecordedError::from),
542 }
543}
544
545struct Executor<'a> {
546 cx: &'a RenderCx<'a>,
547 ax: &'a ApplyEnv<'a>,
548 key: &'a LedgerKey,
549 options: &'a PlanOptions,
550 run_dir: PathBuf,
551 written_at: String,
552 store_commit: String,
553}
554
555impl Executor<'_> {
556 fn execute(&mut self, plan: TargetPlan, ledger: &mut Ledger) -> (TargetResult, bool) {
559 let mut plan = plan;
560 let mut replans = 0;
561 loop {
562 let current = match read_target(self.ax.fs, &plan.file) {
563 Ok(bytes) => bytes,
564 Err(err) => return (failed(plan, err), false),
565 };
566 if current != plan.before {
567 replans += 1;
568 if replans > MAX_REPLANS {
569 let err = changed_during_apply(&plan.file);
570 return (failed(plan, err), false);
571 }
572 plan = self.replan(plan, current, ledger);
573 continue;
574 }
575 if let Some(problem) = plan.problem.clone() {
576 return (
577 finished(plan, ApplyOutcome::Blocked, Some(problem), false, None),
578 false,
579 );
580 }
581 if let Err(err) = self.exclude(&plan) {
582 return (failed(plan, err), false);
583 }
584 let Some(after) = plan.after.clone() else {
585 let changed = self.update_ledger(&plan, ledger);
587 let outcome = entry_outcome(&plan, false);
588 return (finished(plan, outcome, None, false, None), changed);
589 };
590 if let Err(err) = self_check(&plan, &after) {
591 return (failed(plan, err), false);
592 }
593 let backup = match ¤t {
594 Some(bytes) => {
595 match backup::save(self.ax.fs, self.ax.home, &self.run_dir, &plan.file, bytes) {
596 Ok(path) => Some(path),
597 Err(err) => return (failed(plan, err), false),
598 }
599 }
600 None => None,
601 };
602 match self.write(&plan, &after) {
603 Ok(true) => {}
604 Ok(false) => {
605 replans += 1;
608 if replans > MAX_REPLANS {
609 let err = changed_during_apply(&plan.file);
610 return (failed(plan, err), false);
611 }
612 let now = match read_target(self.ax.fs, &plan.file) {
613 Ok(bytes) => bytes,
614 Err(err) => return (failed(plan, err), false),
615 };
616 plan = self.replan(plan, now, ledger);
617 continue;
618 }
619 Err(err) => return (failed(plan, err), false),
620 }
621 let changed = self.update_ledger(&plan, ledger);
622 let outcome = entry_outcome(&plan, true);
623 return (finished(plan, outcome, None, true, backup), changed);
624 }
625 }
626
627 fn replan(&self, plan: TargetPlan, bytes: Option<Vec<u8>>, ledger: &Ledger) -> TargetPlan {
628 plan::plan_target(self.cx, plan.input, bytes, ledger, self.key, self.options)
629 }
630
631 fn write(&self, plan: &TargetPlan, after: &[u8]) -> Result<bool, CoreError> {
634 swap_file(self.ax.fs, &plan.file, plan.before.as_deref(), after)
635 }
636
637 fn exclude(&self, plan: &TargetPlan) -> Result<(), CoreError> {
643 let (true, Some(root)) = (plan.input.exclude, plan.project.as_deref()) else {
644 return Ok(());
645 };
646 if let Some(repo) = ProjectRepo::discover(root)? {
647 repo.exclude(self.ax.fs, &plan.file)?;
648 }
649 Ok(())
650 }
651}
652
653pub(crate) fn swap_file(
659 fs: &dyn crate::fs::Fs,
660 file: &Path,
661 expected: Option<&[u8]>,
662 after: &[u8],
663) -> Result<bool, CoreError> {
664 let io = |what: &str, at: &Path, err: std::io::Error| access::write_error(fs, what, at, &err);
665 if let Some(dir) = file.parent() {
666 fs.create_dir_all(dir)
667 .map_err(|err| io("cannot create directory", dir, err))?;
668 }
669 let temp = temp_path(file)?;
670 let like = expected.is_some().then_some(file);
671 fs.write_new(&temp, after, like)
672 .map_err(|err| io("cannot write temp file", &temp, err))?;
673 let discard = || {
674 let _ = fs.remove_file(&temp);
675 };
676 match read_target(fs, file) {
677 Ok(now) if now.as_deref() == expected => {}
678 Ok(_) => {
679 discard();
680 return Ok(false);
681 }
682 Err(err) => {
683 discard();
684 return Err(err);
685 }
686 }
687 let deadline = Instant::now() + LOCK_RETRY;
688 let mut pause = Duration::from_millis(25);
689 loop {
690 match fs.replace(&temp, file) {
691 Ok(()) => return Ok(true),
692 Err(err) if is_sharing_violation(&err) && Instant::now() < deadline => {
693 if let Some(kind) = refused(fs, &err, file) {
700 discard();
701 return Err(access::read_only_target(kind, file));
702 }
703 thread::sleep(pause.min(deadline.saturating_duration_since(Instant::now())));
704 pause = (pause * 2).min(Duration::from_millis(200));
705 }
706 Err(err) if is_sharing_violation(&err) => {
707 discard();
708 return Err(CoreError::new(
709 ErrorCode::FileLocked,
710 format!(
711 "another process kept the file open for {} s: {err}",
712 LOCK_RETRY.as_secs()
713 ),
714 )
715 .with_path(file));
716 }
717 Err(err) => {
718 discard();
719 return Err(io("cannot replace file", file, err));
720 }
721 }
722 }
723}
724
725impl Executor<'_> {
726 fn update_ledger(&self, plan: &TargetPlan, ledger: &mut Ledger) -> bool {
729 let file = plan.file.to_string_lossy().into_owned();
730 let slot = LedgerSlot {
731 scope: plan.scope,
732 project_id: plan.project_id.as_deref(),
733 file: &file,
734 container: &plan.pointer,
735 };
736 let known = ledger.slot_entries(&slot);
737 let mut done: HashMap<String, Option<Option<Origin>>> = HashMap::new();
741 let mut changes: Vec<(String, Option<LedgerEntry>)> = Vec::new();
742 for entry in &plan.entries {
743 let origin = match entry.action {
744 Action::Create => Some(Origin::Created),
745 Action::Adopt | Action::AdoptOverwrite => Some(Origin::Adopted),
746 Action::Update | Action::Disable | Action::Refresh => Some(
747 match done.get(&entry.name) {
748 Some(origin) => origin.flatten(),
749 None => known.get(&entry.name).and_then(|known| known.origin),
750 }
751 .unwrap_or(Origin::Created),
752 ),
753 Action::Remove | Action::Forget | Action::Release => {
754 done.insert(entry.name.clone(), None);
755 changes.push((entry.name.clone(), None));
756 None
757 }
758 Action::None | Action::Import | Action::Skip => None,
759 };
760 let Some(origin) = origin else {
761 continue;
762 };
763 let (Some(client), Some(value)) = (entry.client, &entry.written) else {
764 continue;
765 };
766 let written_hash = match plan.kind {
767 EntryKind::McpEntry => match plan::canonical(client, value) {
768 Some(canonical) => Some(self.key.hash(&canonical)),
769 None => continue,
770 },
771 EntryKind::ListMember => None,
773 };
774 let row = LedgerEntry {
775 kind: plan.kind,
776 client: client.to_owned(),
777 scope: plan.scope,
778 project_id: plan.project_id.clone(),
779 file: file.clone(),
780 container: plan.pointer.clone(),
781 key: entry.name.clone(),
782 server_id: entry.server_id.clone(),
783 origin: Some(origin),
784 written_hash,
785 written_at: Some(self.written_at.clone()),
786 store_commit: Some(self.store_commit.clone()),
787 delivery: entry.delivery.map(str::to_owned),
788 extra: serde_json::Map::new(),
789 };
790 done.insert(entry.name.clone(), Some(Some(origin)));
791 changes.push((entry.name.clone(), Some(row)));
792 }
793 drop(known);
794 ledger.update_slot(&slot, changes)
795 }
796}
797
798fn changed_during_apply(file: &Path) -> CoreError {
799 CoreError::new(
800 ErrorCode::FileChangedDuringApply,
801 format!(
802 "the file kept changing during apply ({MAX_REPLANS} re-plans); it was left as it is"
803 ),
804 )
805 .with_path(file)
806}
807
808fn entry_outcome(plan: &TargetPlan, wrote: bool) -> ApplyOutcome {
811 let stuck = plan
812 .entries
813 .iter()
814 .any(|entry| entry.state == EntryState::Blocked || entry.unresolved);
815 let did = wrote
816 || plan.entries.iter().any(|entry| {
817 matches!(
818 entry.action,
819 Action::Adopt | Action::Refresh | Action::Forget | Action::Release
820 )
821 });
822 match (stuck, did) {
823 (false, _) => ApplyOutcome::Ok,
824 (true, true) => ApplyOutcome::Partial,
825 (true, false) => ApplyOutcome::Blocked,
826 }
827}
828
829fn finished(
830 mut plan: TargetPlan,
831 outcome: ApplyOutcome,
832 error: Option<CoreError>,
833 written: bool,
834 backup: Option<PathBuf>,
835) -> TargetResult {
836 if written {
837 plan.warnings
838 .extend(restart_required(&plan.clients, &plan.file));
839 }
840 TargetResult {
841 counts: if written {
842 plan.counts()
843 } else {
844 OpCounts::default()
845 },
846 clients: plan.clients,
847 scope: plan.scope,
848 project_id: plan.project_id,
849 project: plan.project,
850 file: plan.file,
851 outcome,
852 error,
853 entries: plan.entries,
854 written,
855 backup,
856 warnings: plan.warnings,
857 read_only: plan.read_only,
858 }
859}
860
861fn restart_required(clients: &[&'static str], file: &Path) -> Vec<CoreError> {
864 clients
865 .iter()
866 .filter_map(|&client| adapter(client))
867 .filter(|spec| {
868 spec.mcp
869 .as_ref()
870 .is_some_and(|mcp| mcp.caps.restart_required)
871 })
872 .map(|spec| {
873 CoreError::new(
874 ErrorCode::RestartRequired,
875 format!(
876 "{0} reads this file only at launch: fully quit {0} (also from the system \
877 tray or menu bar) and start it again to load the change",
878 spec.display_name
879 ),
880 )
881 .with_path(file)
882 })
883 .collect()
884}
885
886fn ownership_lost(target: &mut TargetResult, err: &CoreError) {
889 target.outcome = ApplyOutcome::Failed;
890 target.error = Some(err.clone());
891 target.counts = OpCounts::default();
892}
893
894fn failed(mut plan: TargetPlan, err: CoreError) -> TargetResult {
895 if let Some(kind) = err.read_only() {
901 if err.path().is_some_and(|at| own_write(&plan.file, at)) {
902 plan.read_only = Some(kind);
903 }
904 for entry in &mut plan.entries {
905 if entry.action.writes() {
906 entry.state = EntryState::Blocked;
907 entry.action = Action::None;
908 entry.unresolved = false;
909 entry.problem = Some(err.clone());
910 }
911 }
912 return finished(plan, ApplyOutcome::Blocked, Some(err), false, None);
913 }
914 finished(plan, ApplyOutcome::Failed, Some(err), false, None)
915}
916
917fn own_write(file: &Path, at: &Path) -> bool {
920 at == file || at.parent() == file.parent() || file.starts_with(at)
921}
922
923#[cfg(windows)]
928fn refused(fs: &dyn crate::fs::Fs, err: &std::io::Error, file: &Path) -> Option<ReadOnlyKind> {
929 if err.raw_os_error() != Some(5) {
930 return None;
931 }
932 fs.write_probe().and_then(|probe| probe(file).read_only())
933}
934
935#[cfg(not(windows))]
936fn refused(_fs: &dyn crate::fs::Fs, _err: &std::io::Error, _file: &Path) -> Option<ReadOnlyKind> {
937 None
938}
939
940#[cfg(windows)]
941fn is_sharing_violation(err: &std::io::Error) -> bool {
942 matches!(err.raw_os_error(), Some(5 | 32 | 33))
945}
946
947#[cfg(not(windows))]
948fn is_sharing_violation(_err: &std::io::Error) -> bool {
949 false
950}
951
952fn self_check(plan: &TargetPlan, after: &[u8]) -> Result<(), CoreError> {
956 let fail = |detail: String| {
957 Err(CoreError::new(ErrorCode::SelfCheckFailed, detail).with_path(&plan.file))
958 };
959 let format = plan.input.target.format;
960 if plan.kind == EntryKind::ListMember {
961 return self_check_list(plan, after);
962 }
963 let after_doc = match Document::parse(after, format) {
964 Ok(doc) => doc,
965 Err(err) => return fail(format!("the edited file does not parse: {err}")),
966 };
967 let before_doc = match &plan.before {
968 Some(bytes) => Document::parse(bytes, format)?,
969 None => plan.input.target.new_document(),
970 };
971 let container: Vec<&str> = plan.container.iter().map(String::as_str).collect();
972 let mut planned: Vec<&str> = Vec::new();
973 for entry in &plan.entries {
974 planned.push(&entry.name);
975 let got = after_doc.get(&container, &entry.name)?;
976 let ok = match entry.action {
977 Action::Create | Action::Update | Action::AdoptOverwrite | Action::Disable => {
978 match (entry.client, &entry.written, &got) {
979 (Some(client), Some(want), Some(got)) => {
980 plan::canonical(client, got) == plan::canonical(client, want)
981 }
982 _ => false,
983 }
984 }
985 Action::Remove => got.is_none(),
986 _ => got == entry.observed,
987 };
988 if !ok {
989 return fail(format!(
990 "entry {:?} does not read back as planned",
991 entry.name
992 ));
993 }
994 }
995 for name in before_doc.list(&container)? {
996 if !planned.contains(&name.as_str())
997 && before_doc.get(&container, &name)? != after_doc.get(&container, &name)?
998 {
999 return fail(format!("entry {name:?} is not owned but changed"));
1000 }
1001 }
1002 if outside(&before_doc, &container)? != outside(&after_doc, &container)? {
1003 return fail("something outside the server container changed".to_owned());
1004 }
1005 Ok(())
1006}
1007
1008fn self_check_list(plan: &TargetPlan, after: &[u8]) -> Result<(), CoreError> {
1012 let fail = |detail: String| {
1013 Err(CoreError::new(ErrorCode::SelfCheckFailed, detail).with_path(&plan.file))
1014 };
1015 let format = plan.input.target.format;
1016 let after_doc = match Document::parse(after, format) {
1017 Ok(doc) => doc,
1018 Err(err) => return fail(format!("the edited file does not parse: {err}")),
1019 };
1020 let before_doc = match &plan.before {
1021 Some(bytes) => Document::parse(bytes, format)?,
1022 None => plan.input.target.new_document(),
1023 };
1024 let list: Vec<&str> = plan.container.iter().map(String::as_str).collect();
1025 let before = plan::list_members(&before_doc, &list)?;
1026 let after_members = plan::list_members(&after_doc, &list)?;
1027 for entry in &plan.entries {
1028 let want = match entry.action {
1029 Action::Create => true,
1030 Action::Remove => false,
1031 _ => before.contains(&entry.name),
1032 };
1033 if after_members.contains(&entry.name) != want {
1034 return fail(format!(
1035 "list member {:?} does not read back as planned",
1036 entry.name
1037 ));
1038 }
1039 }
1040 let others = |members: &[String]| -> Vec<String> {
1041 members
1042 .iter()
1043 .filter(|member| !plan.entries.iter().any(|entry| entry.name == **member))
1044 .cloned()
1045 .collect()
1046 };
1047 if others(&before) != others(&after_members) {
1048 return fail("a list member that is not owned changed".to_owned());
1049 }
1050 if outside(&before_doc, &list)? != outside(&after_doc, &list)? {
1051 return fail("something outside the list changed".to_owned());
1052 }
1053 Ok(())
1054}
1055
1056fn outside(doc: &Document, path: &[&str]) -> Result<NativeValue, CoreError> {
1063 let mut root = document_value(doc)?;
1064 strip_container(&mut root, path);
1065 Ok(root)
1066}
1067
1068pub(crate) fn document_value(doc: &Document) -> Result<NativeValue, CoreError> {
1070 let mut root = NativeMap::new();
1071 for key in doc.list(&[])? {
1072 if let Some(value) = doc.get(&[], &key)? {
1073 root.insert(key, value);
1074 }
1075 }
1076 Ok(NativeValue::Object(root))
1077}
1078
1079pub(crate) fn strip_container(root: &mut NativeValue, path: &[&str]) {
1082 let keys = crate::formats::mapping_path(path);
1083 let Some(segment) = path.get(keys.len()) else {
1084 remove_path(root, keys);
1085 return;
1086 };
1087 let field = &segment[1..segment.len() - 1];
1088 let empty = match value_at_mut(root, keys) {
1089 Some(NativeValue::Array(items)) => {
1090 let mut seen: Vec<NativeValue> = Vec::new();
1091 items.retain(|item| {
1092 let name = item
1093 .as_object()
1094 .and_then(|entry| entry.get(field))
1095 .filter(|name| !matches!(name, NativeValue::Array(_) | NativeValue::Object(_)));
1096 match name {
1097 Some(name) if !seen.contains(name) => {
1098 seen.push(name.clone());
1099 false
1100 }
1101 _ => true,
1102 }
1103 });
1104 items.is_empty()
1105 }
1106 Some(NativeValue::Object(map)) => map.is_empty(),
1107 Some(NativeValue::Null) => true,
1108 _ => false,
1109 };
1110 if empty {
1111 remove_path(root, keys);
1112 }
1113}
1114
1115fn value_at_mut<'v>(value: &'v mut NativeValue, path: &[&str]) -> Option<&'v mut NativeValue> {
1117 path.iter().try_fold(value, |value, key| match value {
1118 NativeValue::Object(map) => map.get_mut(key),
1119 _ => None,
1120 })
1121}
1122
1123fn remove_path(value: &mut NativeValue, path: &[&str]) -> bool {
1125 let NativeValue::Object(map) = value else {
1126 return false;
1127 };
1128 match path {
1129 [] => false,
1130 [last] => {
1131 map.remove(last);
1132 map.is_empty()
1133 }
1134 [first, rest @ ..] => {
1135 let Some(child) = map.get_mut(first) else {
1136 return false;
1137 };
1138 if remove_path(child, rest) {
1139 map.remove(first);
1140 }
1141 map.is_empty()
1142 }
1143 }
1144}
1145
1146#[cfg(test)]
1149mod tests {
1150 use super::outside;
1151 use crate::formats::{Document, Format};
1152
1153 const CONTINUE: &[&str] = &["mcpServers", "[name]"];
1154
1155 const BEFORE: &str = "name: Local\nmcpServers:\n - name: files\n command: npx\n - uses: owner/block\n - just-text\n - name: files\n command: duplicate\n";
1156
1157 fn same_outside(before: &str, after: &str) -> bool {
1158 let parse = |text: &str| Document::parse(text.as_bytes(), Format::Yaml).unwrap();
1159 outside(&parse(before), CONTINUE).unwrap() == outside(&parse(after), CONTINUE).unwrap()
1160 }
1161
1162 #[test]
1163 fn named_list_items_are_the_only_ones_left_out() {
1164 assert!(same_outside(
1166 BEFORE,
1167 &BEFORE.replace("command: npx", "command: bunx")
1168 ));
1169 assert!(same_outside(
1170 BEFORE,
1171 &format!("{BEFORE} - name: search\n url: https://x.example.com\n")
1172 ));
1173 assert!(same_outside(
1174 "name: Local\n",
1175 "name: Local\nmcpServers:\n - name: a\n"
1176 ));
1177 assert!(same_outside("mcpServers:\n", "mcpServers:\n - name: a\n"));
1178 assert!(!same_outside(
1181 BEFORE,
1182 &BEFORE.replace("owner/block", "owner/other")
1183 ));
1184 assert!(!same_outside(
1185 BEFORE,
1186 &BEFORE.replace("just-text", "other-text")
1187 ));
1188 assert!(!same_outside(
1189 BEFORE,
1190 &BEFORE.replace("duplicate", "changed")
1191 ));
1192 assert!(!same_outside(
1193 BEFORE,
1194 &BEFORE.replace(" - just-text\n", "")
1195 ));
1196 assert!(!same_outside(
1197 BEFORE,
1198 &BEFORE.replace("name: Local", "name: Other")
1199 ));
1200 }
1201}