Skip to main content

workyard_core/amend/
intent.rs

1//! Select the amendment and any removal authority while task admission is held.
2use crate::{
3	AmendRequest, AmendState, OperationKind, OperationOutcome, Problem, ProblemCode,
4	RecoveryRecord, RemovalOptions, TaskLifecycle,
5};
6
7/// Inputs needed to resume an interrupted amendment.
8pub enum AmendRecovery {
9	/// Continue adding or renaming participants.
10	AddOrRename,
11	/// Continue an amendment with explicit removal consent.
12	WithRemovalOptions(RemovalOptions),
13}
14
15pub(super) enum Intent {
16	Apply(AmendRequest),
17	Resume(AmendRecovery),
18}
19
20impl Intent {
21	pub(super) fn resolve<S: AmendState>(
22		self,
23		record: &RecoveryRecord,
24		store: &S,
25		guard: &S::Admission,
26	) -> Result<AmendRequest, Problem> {
27		match self {
28			Self::Apply(request) => {
29				if request.remove.is_empty()
30					&& unfinished_amendment(record)
31					&& store
32						.amend_request(guard)?
33						.is_some_and(|prior| !prior.remove.is_empty())
34				{
35					return Err(removal_decision_required());
36				}
37				Ok(request)
38			}
39			Self::Resume(scope) => {
40				let mut request = store.amend_request(guard)?.ok_or_else(|| {
41					Problem::new(
42						ProblemCode::InvalidInput,
43						"This task has no amendment to resume.",
44					)
45				})?;
46				request.removal_options = scope.authorize(record, &request)?;
47				Ok(request)
48			}
49		}
50	}
51}
52
53impl AmendRecovery {
54	fn authorize(
55		&self,
56		record: &RecoveryRecord,
57		request: &AmendRequest,
58	) -> Result<RemovalOptions, Problem> {
59		if record.task.lifecycle != TaskLifecycle::Active
60			|| record.task.removal.is_some()
61			|| !record.task.operation.is_continuing(OperationKind::Amend)
62		{
63			return Err(Problem::new(
64				ProblemCode::InvalidInput,
65				"This task has no active participant amendment to resume.",
66			));
67		}
68		if let Self::WithRemovalOptions(removal) = self {
69			if (removal.yes || removal.force) && request.remove.is_empty() {
70				return Err(Problem::new(
71					ProblemCode::InvalidInput,
72					"--yes and --force require a pending removal.",
73				));
74			}
75			return Ok(*removal);
76		}
77
78		if !request.remove.is_empty() {
79			return Err(removal_decision_required());
80		}
81		Ok(RemovalOptions::default())
82	}
83}
84
85fn unfinished_amendment(record: &RecoveryRecord) -> bool {
86	record.task.operation.is_continuing(OperationKind::Amend)
87		&& (record.task.operation.outcome != OperationOutcome::Succeeded
88			|| record.pending.is_some()
89			|| record.needs_publication)
90}
91
92fn removal_decision_required() -> Problem {
93	Problem::new(
94		ProblemCode::InvalidInput,
95		"The recorded amendment includes participant removal.",
96	)
97	.remedy(
98		"Inspect the task with status. Repeat the original amendment to continue its selected removals, or use CLI or RPC recovery.",
99	)
100}