1pub use crate::adoption::{Boundary, Event};
3use crate::{
4 Error, Manifest, Result,
5 adoption::{self, anchors, canonical, checked_bytes, parent_identity, same},
6 context::HostContext,
7 error::io_error,
8 journal::{self, Phase, Progress},
9 lifecycle_journal::{self as wire, Action, Header, Journal, Mutation, Operation, Role, Watch},
10 observation::{self, Entry, Fingerprint, Kind},
11 planner::{self, Outcome, Plan, Request, UnmanageMode},
12 profiles::selected,
13 state::WriterLock,
14};
15use rustix::fs::{self, Mode, OFlags, RenameFlags};
16use std::{
17 fs::File,
18 path::{Path, PathBuf},
19};
20
21pub struct RemovalAcknowledgement {
23 id: String,
24}
25impl RemovalAcknowledgement {
26 pub fn confirm(id: impl Into<String>) -> Self {
28 Self { id: id.into() }
29 }
30}
31pub struct Approval {
33 plan: Plan,
34 digest: String,
35}
36impl Approval {
37 pub fn from_plan(plan: Plan) -> Result<Self> {
38 Self::approve(plan, None)
39 }
40 pub fn from_removal_plan(plan: Plan, acknowledgement: RemovalAcknowledgement) -> Result<Self> {
41 Self::approve(plan, Some(acknowledgement))
42 }
43 fn approve(plan: Plan, ack: Option<RemovalAcknowledgement>) -> Result<Self> {
44 let valid = match (&plan.inputs.request, ack) {
45 (
46 Request::Apply
47 | Request::Unmanage {
48 mode: UnmanageMode::Keep,
49 ..
50 },
51 None,
52 ) => true,
53 (
54 Request::Unmanage {
55 id,
56 mode: UnmanageMode::Remove,
57 },
58 Some(ack),
59 ) => *id == ack.id,
60 _ => false,
61 };
62 if !valid
63 || plan.has_blockers()
64 || plan.inputs.files.len() > 128
65 || canonical(&plan)? != canonical(&planner::plan(plan.inputs.clone()))?
66 {
67 return Err(Error::Invalid("approval requires an unmodified, unblocked lifecycle plan; removal needs separate matching acknowledgement".into()));
68 }
69 let digest = journal::digest(canonical(&plan)?.as_bytes());
70 Ok(Self { plan, digest })
71 }
72 pub fn sha256(&self) -> &str {
73 &self.digest
74 }
75}
76fn stage_name(id: usize) -> String {
77 format!("op-{id:04}")
78}
79fn stage_path(j: &Journal, id: usize) -> PathBuf {
80 j.directory.path.join(stage_name(id))
81}
82fn inspect(path: &Path, role: Role) -> Result<Entry> {
83 if role == Role::Manifest && observation::inspect(path, false)?.kind == Kind::Regular {
84 observation::read_manifest(path).map(|(_, e)| e)
85 } else {
86 observation::inspect(path, true)
87 }
88}
89fn notify(
90 j: &Journal,
91 boundary: Boundary,
92 observer: &mut impl FnMut(&Event) -> Result<()>,
93) -> Result<()> {
94 observer(&Event {
95 transaction_id: j.record.header.transaction_id.clone(),
96 boundary,
97 sequence: j.record.sequence,
98 })
99}
100fn checkpoint(j: &mut Journal, observer: &mut impl FnMut(&Event) -> Result<()>) -> Result<()> {
101 j.save()?;
102 notify(j, Boundary::Checkpoint, observer)
103}
104fn stage_file(j: &Journal, id: usize, bytes: &[u8], fp: &Fingerprint) -> Result<()> {
105 let name = stage_name(id);
106 j.directory.create(&name, bytes)?;
107 let file = File::from(
108 fs::openat(
109 &j.directory.file,
110 name.as_str(),
111 OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
112 Mode::empty(),
113 )
114 .map_err(|e| io_error("open lifecycle preparation", &j.directory.path, e))?,
115 );
116 fs::fchown(&file, None, Some(rustix::process::Gid::from_raw(fp.gid)))
117 .map_err(|e| io_error("preserve prepared group", &j.directory.path, e))?;
118 fs::fchmod(&file, Mode::from_bits_truncate((fp.mode & 0o777) as _))
119 .map_err(|e| io_error("preserve prepared permissions", &j.directory.path, e))?;
120 file.sync_all()
121 .map_err(|e| io_error("sync lifecycle preparation", &j.directory.path, e))?;
122 j.directory.sync()
123}
124
125pub(crate) fn remove_mapping(
126 bytes: &[u8],
127 id: &str,
128 host: &HostContext,
129 repo: &Path,
130 profiles: &[String],
131) -> Result<Vec<u8>> {
132 let text =
133 std::str::from_utf8(bytes).map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?;
134 let mut old = Manifest::parse(text)?;
135 let index = old
136 .files
137 .iter()
138 .position(|f| f.id == id)
139 .ok_or_else(|| Error::Invalid("missing unmanage mapping".into()))?;
140 let mut doc = text
141 .parse::<toml_edit::DocumentMut>()
142 .map_err(|_| Error::Invalid("cannot edit manifest".into()))?;
143 if let Some(array) = doc["files"].as_array_of_tables_mut() {
144 array.remove(index);
145 } else if let Some(array) = doc["files"].as_array_mut() {
146 let removed = array.remove(index);
149 let prefix = removed
150 .decor()
151 .prefix()
152 .and_then(|s| s.as_str())
153 .unwrap_or_default();
154 if let Some(next) = array.get_mut(index) {
155 let next_prefix = next
156 .decor()
157 .prefix()
158 .and_then(|s| s.as_str())
159 .unwrap_or_default();
160 let combined = format!("{prefix}{next_prefix}");
161 next.decor_mut().set_prefix(combined);
162 } else {
163 let trailing = array.trailing().as_str().unwrap_or_default();
164 array.set_trailing(format!("{prefix}{trailing}"));
165 }
166 } else {
167 return Err(Error::Invalid(
168 "unsupported manifest files representation".into(),
169 ));
170 }
171 let new = doc.to_string();
172 let parsed = Manifest::parse(&new)?;
173 parsed.validate_for_host(host, profiles, Some(repo))?;
174 old.files.remove(index);
175 if journal::encode(&old)? != journal::encode(&parsed)? {
176 return Err(Error::Invalid(
177 "manifest removal changed unrelated declarations".into(),
178 ));
179 }
180 Ok(new.into_bytes())
181}
182
183pub fn execute(
186 host: &HostContext,
187 lock: &WriterLock,
188 approval: Approval,
189 mut observer: impl FnMut(&Event) -> Result<()>,
190) -> Result<Option<String>> {
191 lock.check_context(host)?;
192 journal::ensure_writable(host)?;
193 let inputs = &approval.plan.inputs;
194 if journal::encode(host)? != journal::encode(&inputs.host)? {
195 return Err(Error::Invalid("approval belongs to another host".into()));
196 }
197 let profiles: Vec<_> = inputs.active_profiles.iter().cloned().collect();
198 let fresh = planner::plan(planner::observe(
199 host,
200 &inputs.repository,
201 &profiles,
202 inputs.request.clone(),
203 )?);
204 if fresh.has_blockers() || journal::digest(canonical(&fresh)?.as_bytes()) != approval.digest {
205 return Err(Error::Invalid(
206 "stale or substituted lifecycle plan; observe and approve again".into(),
207 ));
208 }
209 let local = crate::local::LocalConfig::load(host)?;
210 let repo_id = local
211 .repositories
212 .iter()
213 .find(|(_, r)| r.root == inputs.repository)
214 .map(|(id, _)| id.clone())
215 .ok_or_else(|| {
216 Error::Invalid("lifecycle execution requires a registered repository".into())
217 })?;
218 if fresh
219 .files
220 .iter()
221 .all(|f| matches!(f.outcome, Outcome::NoOp))
222 {
223 return Ok(None);
224 }
225 let action = match inputs.request {
226 Request::Apply => Action::Apply,
227 Request::Unmanage {
228 mode: UnmanageMode::Keep,
229 ..
230 } => Action::Keep,
231 Request::Unmanage {
232 mode: UnmanageMode::Remove,
233 ..
234 } => Action::Remove,
235 _ => return Err(Error::Invalid("unsupported lifecycle request".into())),
236 };
237 let watches: Vec<_> = fresh
238 .inputs
239 .files
240 .iter()
241 .map(|f| {
242 Ok(Watch {
243 mapping: f.mapping.clone(),
244 source: f
245 .source
246 .clone()
247 .ok_or_else(|| Error::Invalid("missing lifecycle source snapshot".into()))?,
248 destination: f.destination.clone().ok_or_else(|| {
249 Error::Invalid("missing lifecycle destination snapshot".into())
250 })?,
251 })
252 })
253 .collect::<Result<Vec<_>>>()?;
254 let mut entries = vec![&fresh.inputs.manifest, &fresh.inputs.local_config];
255 for w in &watches {
256 entries.extend([&w.source, &w.destination]);
257 }
258 let mut h = Header {
259 repository_id: repo_id,
260 repository: inputs.repository.clone(),
261 transaction_id: adoption::transaction_id(),
262 approved_plan_sha256: approval.digest,
263 action,
264 removal_acknowledged: action == Action::Remove,
265 profiles,
266 anchors: anchors(&entries),
267 watches,
268 manifest: fresh.inputs.manifest.clone(),
269 local_config: fresh.inputs.local_config.clone(),
270 backups: vec![],
271 };
272 if h.manifest
273 .fingerprint
274 .as_ref()
275 .is_none_or(|f| f.mode & 0o7000 != 0)
276 {
277 return Err(Error::Invalid(
278 "manifest special permission bits refused".into(),
279 ));
280 }
281 h.backups = wire::backup_specs(&h)?;
282 let expected = wire::expected(&h)?;
283 let manifest_bytes = checked_bytes(&h.manifest)?;
285 let new_manifest = if action != Action::Apply {
286 Some(remove_mapping(
287 &manifest_bytes,
288 &h.watches[0].mapping.id,
289 host,
290 &h.repository,
291 &h.profiles,
292 )?)
293 } else {
294 None
295 };
296 let mut backup_bytes = vec![];
297 for b in &h.backups {
298 let e = if b.path == h.manifest.path {
299 &h.manifest
300 } else {
301 &h.watches
302 .iter()
303 .find(|w| w.destination.path == b.path)
304 .ok_or_else(|| Error::Invalid("missing backup destination".into()))?
305 .destination
306 };
307 let bytes = if e.kind == Kind::Symlink {
308 e.link_target
309 .as_ref()
310 .ok_or_else(|| Error::Invalid("missing backup link target".into()))?
311 .to_str()
312 .ok_or_else(|| Error::Invalid("backup link target must be UTF-8".into()))?
313 .as_bytes()
314 .to_vec()
315 } else {
316 checked_bytes(e)?
317 };
318 if journal::digest(&bytes) != b.sha256 {
319 return Err(Error::Invalid("backup input changed".into()));
320 }
321 backup_bytes.push(bytes);
322 }
323 let keep_bytes = if action == Action::Keep {
324 Some(checked_bytes(&h.watches[0].source)?)
325 } else {
326 None
327 };
328 let mut j = Journal::begin(host, h)?;
329 notify(&j, Boundary::Checkpoint, &mut observer)?;
330 for (backup, bytes) in j.record.header.backups.iter().zip(&backup_bytes) {
331 j.directory.create(&backup.name, bytes)?;
332 }
333 j.verify_backups()?;
334 let device = Fingerprint::from_stat(
335 &fs::fstat(&j.directory.file)
336 .map_err(|e| io_error("inspect transaction filesystem", &j.directory.path, e))?,
337 )
338 .device;
339 for entry in std::iter::once(&j.record.header.manifest).chain(
341 j.record
342 .header
343 .watches
344 .iter()
345 .flat_map(|w| [&w.source, &w.destination]),
346 ) {
347 if entry.parents.last().is_none_or(|p| {
348 p.fingerprint.device != device || p.fingerprint.uid != fresh.inputs.user_id
349 }) || entry
350 .fingerprint
351 .as_ref()
352 .is_some_and(|f| f.device != device)
353 {
354 return Err(Error::Invalid(
355 "lifecycle requires owned parents and one filesystem; no cross-device fallback"
356 .into(),
357 ));
358 }
359 }
360 for (id, (role, mutation, path)) in expected.into_iter().enumerate() {
361 let before = match role {
362 Role::Directory => inspect(&path, role)?,
363 Role::Manifest => j.record.header.manifest.clone(),
364 Role::Destination => j
365 .record
366 .header
367 .watches
368 .iter()
369 .find(|w| w.destination.path == path)
370 .ok_or_else(|| Error::Invalid("missing watched destination".into()))?
371 .destination
372 .clone(),
373 };
374 match role {
375 Role::Directory => {
376 fs::mkdirat(
377 &j.directory.file,
378 stage_name(id).as_str(),
379 Mode::from_raw_mode(0o700),
380 )
381 .map_err(|e| io_error("prepare destination parent", &path, e))?;
382 let dir = File::from(
383 fs::openat(
384 &j.directory.file,
385 stage_name(id).as_str(),
386 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
387 Mode::empty(),
388 )
389 .map_err(|e| io_error("open prepared parent", &path, e))?,
390 );
391 dir.sync_all()
392 .map_err(|e| io_error("sync prepared parent", &path, e))?;
393 }
394 Role::Manifest => stage_file(
395 &j,
396 id,
397 new_manifest
398 .as_ref()
399 .ok_or_else(|| Error::Invalid("missing edited manifest".into()))?,
400 before
401 .fingerprint
402 .as_ref()
403 .ok_or_else(|| Error::Invalid("missing manifest fingerprint".into()))?,
404 )?,
405 Role::Destination => match action {
406 Action::Apply => {
407 let w = j
408 .record
409 .header
410 .watches
411 .iter()
412 .find(|w| w.destination.path == path)
413 .ok_or_else(|| Error::Invalid("missing watched destination".into()))?;
414 fs::symlinkat(&w.source.path, &j.directory.file, stage_name(id).as_str())
415 .map_err(|e| io_error("prepare managed link", &path, e))?;
416 }
417 Action::Keep => stage_file(
418 &j,
419 id,
420 keep_bytes
421 .as_ref()
422 .ok_or_else(|| Error::Invalid("missing kept mapping bytes".into()))?,
423 j.record.header.watches[0]
424 .source
425 .fingerprint
426 .as_ref()
427 .ok_or_else(|| Error::Invalid("missing source fingerprint".into()))?,
428 )?,
429 Action::Remove => {}
430 },
431 }
432 j.directory.sync()?;
433 let staged = inspect(&stage_path(&j, id), role)?;
434 j.record.operations.push(Operation {
435 id,
436 role,
437 mutation,
438 before,
439 staged,
440 after: None,
441 progress: Progress::Pending,
442 });
443 }
444 j.record.phase = Phase::Running;
445 checkpoint(&mut j, &mut observer)?;
446 validate_scope(host, &j)?;
447 for id in 0..j.record.operations.len() {
448 validate_layout(host, &j)?;
449 j.record.operations[id].progress = Progress::Intent;
450 checkpoint(&mut j, &mut observer)?;
451 validate_layout(host, &j)?;
452 mutate(&j, id, false)?;
453 notify(&j, Boundary::Mutation, &mut observer)?;
454 let op = &j.record.operations[id];
455 let after = inspect(&op.before.path, op.role)?;
456 let ok = if op.mutation == Mutation::Withdraw {
457 after.kind == Kind::Missing
458 } else {
459 same(&op.staged, &after, false)
460 };
461 if !ok {
462 return Err(Error::Invalid("lifecycle postcondition mismatch".into()));
463 }
464 j.record.operations[id].after = Some(after);
465 j.record.operations[id].progress = Progress::Done;
466 checkpoint(&mut j, &mut observer)?;
467 }
468 j.record.phase = Phase::Verifying;
469 checkpoint(&mut j, &mut observer)?;
470 validate_layout(host, &j)?;
471 j.record.phase = Phase::Completed;
472 checkpoint(&mut j, &mut observer)?;
473 Ok(Some(j.record.header.transaction_id))
474}
475
476fn check_parents(j: &Journal, entry: &Entry) -> Result<()> {
477 for p in &entry.parents {
478 let expected = j
479 .record
480 .header
481 .anchors
482 .iter()
483 .find(|e| e.path == p.path)
484 .map(|e| &e.fingerprint)
485 .or_else(|| {
486 j.record
487 .operations
488 .iter()
489 .find(|o| o.role == Role::Directory && o.before.path == p.path)
490 .and_then(|o| o.staged.fingerprint.as_ref())
491 });
492 if expected.is_none_or(|e| !parent_identity(e, &p.fingerprint)) {
493 return Err(Error::Invalid(
494 "parent identity/permissions changed; lifecycle refused".into(),
495 ));
496 }
497 }
498 Ok(())
499}
500fn applied(j: &Journal, op: &Operation) -> Result<bool> {
501 let live = inspect(&op.before.path, op.role)?;
502 check_parents(j, &live)?;
503 let stage = inspect(&stage_path(j, op.id), op.role)?;
504 let strict = op.progress == Progress::Pending;
505 let before = same(&op.before, &live, strict) && same(&op.staged, &stage, strict);
506 let after = match op.mutation {
507 Mutation::Publish => same(&op.staged, &live, false) && stage.kind == Kind::Missing,
508 Mutation::Exchange => same(&op.staged, &live, false) && same(&op.before, &stage, false),
509 Mutation::Withdraw => live.kind == Kind::Missing && same(&op.before, &stage, false),
510 };
511 match op.progress {
512 Progress::Pending if before => Ok(false),
513 Progress::Intent | Progress::UndoIntent if before => Ok(false),
514 Progress::Intent | Progress::UndoIntent if after => Ok(true),
515 Progress::Done if after && op.after.as_ref().is_some_and(|e| same(e, &live, true)) => {
516 Ok(true)
517 }
518 Progress::Undone if before => Ok(false),
519 _ => Err(Error::Invalid(
520 "lifecycle guard mismatch (file, stage or parent edited); recovery refused".into(),
521 )),
522 }
523}
524fn validate_layout(host: &HostContext, j: &Journal) -> Result<()> {
525 let h = &j.record.header;
526 journal::registered_root(host, &h.repository_id, &h.repository)?;
527 j.verify_backups()?;
528 let config = observation::inspect(&host.local_config_path(), false)?;
529 if !same(&h.local_config, &config, true) {
530 return Err(Error::Invalid(
531 "local configuration changed since approval".into(),
532 ));
533 }
534 check_parents(j, &config)?;
535 for w in &h.watches {
536 let source = observation::inspect(&w.source.path, true)?;
537 if !same(&w.source, &source, true) {
538 return Err(Error::Invalid(
539 "repository source edited; lifecycle/recovery refused".into(),
540 ));
541 }
542 check_parents(j, &source)?;
543 if !wire::changed(h, w) {
544 let current = observation::inspect(&w.destination.path, true)?;
545 if !same(&w.destination, ¤t, true) {
546 return Err(Error::Invalid("unchanged mapping drifted".into()));
547 }
548 check_parents(j, ¤t)?;
549 }
550 }
551 if h.action == Action::Apply {
552 let manifest = observation::read_manifest(&h.manifest.path)?.1;
553 if !same(&h.manifest, &manifest, true) {
554 return Err(Error::Invalid("manifest edited since approval".into()));
555 }
556 check_parents(j, &manifest)?;
557 }
558 let states: Vec<_> = j
559 .record
560 .operations
561 .iter()
562 .map(|o| applied(j, o))
563 .collect::<Result<_>>()?;
564 for op in j
565 .record
566 .operations
567 .iter()
568 .filter(|o| o.role == Role::Directory)
569 {
570 let path = if states[op.id] {
571 op.before.path.clone()
572 } else {
573 stage_path(j, op.id)
574 };
575 let mut expected: Vec<_> = j
576 .record
577 .operations
578 .iter()
579 .filter(|child| {
580 states[op.id]
581 && states[child.id]
582 && child.before.path.parent() == Some(op.before.path.as_path())
583 })
584 .map(|o| {
585 o.before
586 .path
587 .file_name()
588 .map(|name| name.to_owned())
589 .ok_or_else(|| Error::Invalid("missing managed file name".into()))
590 })
591 .collect::<Result<Vec<_>>>()?;
592 expected.sort();
593 if observation::names(&path, 4096)? != expected {
594 return Err(Error::Invalid(
595 "created/prepared destination directory contains unapproved entries".into(),
596 ));
597 }
598 }
599 Ok(())
600}
601fn mutate(j: &Journal, id: usize, undo: bool) -> Result<()> {
602 let op = &j.record.operations[id];
603 let live = observation::parent_handle(&op.before.path)?;
604 if live.missing {
605 return Err(Error::Invalid("operation parent is missing".into()));
606 }
607 let current = inspect(&op.before.path, op.role)?;
608 check_parents(j, ¤t)?;
609 if live.parents.len() != current.parents.len()
610 || live
611 .parents
612 .iter()
613 .zip(¤t.parents)
614 .any(|(a, b)| a.path != b.path || !parent_identity(&a.fingerprint, &b.fingerprint))
615 {
616 return Err(Error::Invalid(
617 "parent substituted during lifecycle mutation".into(),
618 ));
619 }
620 if applied(j, op)? != undo {
621 return Err(Error::Invalid("lifecycle precondition changed".into()));
622 }
623 if undo && op.role == Role::Directory && !observation::names(&op.before.path, 1)?.is_empty() {
624 return Err(Error::Invalid(
625 "created destination parent is not empty".into(),
626 ));
627 }
628 let into_private = match op.mutation {
629 Mutation::Publish => undo,
630 Mutation::Exchange => false,
631 Mutation::Withdraw => !undo,
632 };
633 let flags = if op.mutation == Mutation::Exchange {
634 RenameFlags::EXCHANGE
635 } else {
636 RenameFlags::NOREPLACE
637 };
638 let result = if into_private {
639 fs::renameat_with(
640 &live.directory,
641 &live.name,
642 &j.directory.file,
643 stage_name(id).as_str(),
644 flags,
645 )
646 } else {
647 fs::renameat_with(
648 &j.directory.file,
649 stage_name(id).as_str(),
650 &live.directory,
651 &live.name,
652 flags,
653 )
654 };
655 result.map_err(|e| {
656 io_error(
657 "publish/invert lifecycle rename (no unsafe fallback)",
658 &op.before.path,
659 e,
660 )
661 })?;
662 live.directory
663 .sync_all()
664 .map_err(|e| io_error("sync lifecycle parent", &op.before.path, e))?;
665 j.directory.sync()
666}
667
668fn validate_scope(host: &HostContext, j: &Journal) -> Result<()> {
670 let h = &j.record.header;
671 journal::registered_root(host, &h.repository_id, &h.repository)?;
672 observation::validate_output_path(&h.repository)?;
673 if h.manifest.path != h.repository.join("dort.toml")
674 || h.local_config.path != host.local_config_path()
675 {
676 return Err(Error::Invalid("lifecycle journal scope mismatch".into()));
677 }
678 if j.record.operations.is_empty() {
680 return Ok(());
681 }
682 j.verify_backups()?;
683 let bytes = if h.action == Action::Apply {
684 checked_bytes(&h.manifest)?
685 } else {
686 let b = h
687 .backups
688 .iter()
689 .find(|b| b.path == h.manifest.path)
690 .ok_or_else(|| Error::Invalid("missing manifest backup".into()))?;
691 journal::read_bytes(&j.directory, &b.name)?
692 };
693 let manifest = Manifest::parse(
694 std::str::from_utf8(&bytes).map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?,
695 )?;
696 let active = manifest.validate_for_host(host, &h.profiles, Some(&h.repository))?;
697 let mut mappings: Vec<_> = manifest
698 .files
699 .iter()
700 .filter(|m| {
701 selected(&m.profiles, &active)
702 && (h.action == Action::Apply || m.id == h.watches[0].mapping.id)
703 })
704 .cloned()
705 .collect();
706 mappings.sort_by(|a, b| a.id.cmp(&b.id));
707 if journal::encode(&mappings)?
708 != journal::encode(&h.watches.iter().map(|w| &w.mapping).collect::<Vec<_>>())?
709 {
710 return Err(Error::Invalid(
711 "journal watches do not match original manifest".into(),
712 ));
713 }
714 for w in &h.watches {
715 let source = h.repository.join(
716 w.mapping
717 .overrides
718 .get(&host.platform)
719 .unwrap_or(&w.mapping.source),
720 );
721 if w.source.path != source
722 || w.destination.path != host.target_path(&w.mapping.target, Some(&h.repository))?
723 {
724 return Err(Error::Invalid("journal mapping scope mismatch".into()));
725 }
726 }
727 let snapshot = planner::Snapshot {
728 user_id: rustix::process::geteuid().as_raw(),
729 host: host.clone(),
730 repository: h.repository.clone(),
731 manifest: h.manifest.clone(),
732 local_config: h.local_config.clone(),
733 active_profiles: active,
734 request: match h.action {
735 Action::Apply => Request::Apply,
736 Action::Keep | Action::Remove => Request::Unmanage {
737 id: h.watches[0].mapping.id.clone(),
738 mode: if h.action == Action::Keep {
739 UnmanageMode::Keep
740 } else {
741 UnmanageMode::Remove
742 },
743 },
744 },
745 files: h
746 .watches
747 .iter()
748 .map(|w| planner::FileSnapshot {
749 mapping: w.mapping.clone(),
750 source_path: w.source.path.clone(),
751 target_path: w.destination.path.clone(),
752 source: Some(w.source.clone()),
753 destination: Some(w.destination.clone()),
754 blockers: vec![],
755 })
756 .collect(),
757 };
758 if planner::plan(snapshot).has_blockers() {
759 return Err(Error::Invalid("unsafe lifecycle journal inputs".into()));
760 }
761 let expected = wire::expected(h)?;
762 if j.record.operations.len() != expected.len() {
763 return Err(Error::Invalid("lifecycle operation scope mismatch".into()));
764 }
765 for (op, (role, mutation, path)) in j.record.operations.iter().zip(expected) {
766 if op.role != role
767 || op.mutation != mutation
768 || op.before.path != path
769 || op.staged.path != stage_path(j, op.id)
770 {
771 return Err(Error::Invalid(
772 "lifecycle operation path/order mismatch".into(),
773 ));
774 }
775 }
776 Ok(())
777}
778
779pub(crate) fn rollback_preview(
781 host: &HostContext,
782 repository_id: &str,
783 transaction_id: &str,
784) -> Result<(String, Vec<PathBuf>)> {
785 let j = Journal::open(host, repository_id, transaction_id)?;
786 validate_scope(host, &j)?;
787 if !matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
788 validate_layout(host, &j)?;
789 }
790 let effects = if matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
791 vec![]
792 } else {
793 j.record
794 .operations
795 .iter()
796 .rev()
797 .filter(|o| o.progress != Progress::Undone)
798 .map(|o| o.before.path.clone())
799 .collect()
800 };
801 Ok((
802 journal::digest(journal::encode(&j.record)?.as_bytes()),
803 effects,
804 ))
805}
806
807pub fn rollback(
810 host: &HostContext,
811 lock: &WriterLock,
812 repository_id: &str,
813 transaction_id: &str,
814 mut observer: impl FnMut(&Event) -> Result<()>,
815) -> Result<()> {
816 lock.check_context(host)?;
817 let mut j = Journal::open(host, repository_id, transaction_id)?;
818 validate_scope(host, &j)?;
819 if j.record.phase == Phase::RolledBack {
820 return Ok(());
821 }
822 if j.record.phase == Phase::Preparing {
823 j.record.phase = Phase::RolledBack;
824 return checkpoint(&mut j, &mut observer);
825 }
826 validate_layout(host, &j)?;
827 if j.record.phase != Phase::RollingBack {
828 j.record.phase = Phase::RollingBack;
829 checkpoint(&mut j, &mut observer)?;
830 }
831 for id in (0..j.record.operations.len()).rev() {
832 if j.record.operations[id].progress == Progress::Undone {
833 continue;
834 }
835 validate_layout(host, &j)?;
836 let was_applied = applied(&j, &j.record.operations[id])?;
837 j.record.operations[id].progress = Progress::UndoIntent;
838 checkpoint(&mut j, &mut observer)?;
839 validate_layout(host, &j)?;
840 if was_applied {
841 mutate(&j, id, true)?;
842 notify(&j, Boundary::Mutation, &mut observer)?;
843 }
844 j.record.operations[id].progress = Progress::Undone;
845 checkpoint(&mut j, &mut observer)?;
846 }
847 validate_layout(host, &j)?;
848 j.record.phase = Phase::RolledBack;
849 checkpoint(&mut j, &mut observer)
850}
851
852pub fn history(host: &HostContext) -> Result<Vec<journal::Diagnosis>> {
855 journal::diagnose(host)
856}