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