Skip to main content

workyard_application/actions/create/
action.rs

1use trine::{InvocationContext, NativePath};
2use workyard_core::{Control, OperationOutcome, ProblemCode};
3use workyard_git::Runner;
4use workyard_state::Store;
5
6use crate::{
7	contracts::Progress,
8	execution::{Events, blocking_action},
9};
10
11use super::{CreateInput, CreateOutcome, contract::ExistingTaskPreview};
12
13/// Establish the task and its participant worktrees.
14pub async fn create(
15	input: CreateInput,
16	context: InvocationContext<Progress>,
17) -> Result<CreateOutcome, CreateOutcome> {
18	blocking_action(run(input, context)).await
19}
20
21async fn run(
22	input: CreateInput,
23	context: InvocationContext<Progress>,
24) -> Result<CreateOutcome, CreateOutcome> {
25	let name = input.task.clone();
26	let rejected = |problem| CreateOutcome::rejected(name.clone(), problem);
27
28	let cancellation = context.cancellation().clone();
29	let control = Control::new({
30		let cancellation = cancellation.clone();
31		move || cancellation.is_cancelled()
32	});
33	control.check().map_err(rejected)?;
34
35	let checkout_hint = super::retry::checkout(&input);
36	let starting_branch_example = super::retry::starting_branch_example(&input);
37	let explicit_workspace = input.workspace.clone();
38	let request = input.prepare(&control).await.map_err(rejected)?;
39	let workspace = request
40		.state_dir
41		.parent()
42		.and_then(|path| NativePath::new(path).ok());
43	let store =
44		Store::open_existing(&request.state_dir, Some(&request.tasks_root)).map_err(rejected)?;
45	let runner = Runner::default();
46
47	let result = workyard_core::create(
48		request,
49		&runner,
50		&control,
51		&Events(context, "create"),
52		&store,
53	)
54	.await;
55	match result {
56		Ok(result) => {
57			let registration =
58				crate::projects::register(&store, &result.task.admitted_roots(None), &control)
59					.await;
60			let mut outcome = CreateOutcome::from_task(result.task, result.record);
61			outcome.explicit_workspace = explicit_workspace;
62			outcome.operation = result.operation.into();
63			outcome.problem = result.problem.map(Into::into);
64			outcome.registration_problem = registration.map(Into::into);
65			if outcome.registration_problem.is_some()
66				|| outcome.operation.outcome == OperationOutcome::Failed
67			{
68				Err(outcome)
69			} else {
70				Ok(outcome)
71			}
72		}
73		Err(problem) if problem.code == ProblemCode::Cancelled => Ok(rejected(problem)),
74		Err(problem) => {
75			let code = problem.code;
76			let mut outcome = rejected(problem);
77			match code {
78				ProblemCode::TaskExists => {
79					outcome.existing_task = Some(ExistingTaskPreview {
80						workspace,
81						cancellation,
82					});
83					outcome.explicit_workspace = explicit_workspace;
84				}
85				ProblemCode::BranchExists => outcome.checkout_hint = checkout_hint,
86				ProblemCode::DefaultBranchUnknown => {
87					outcome.starting_branch_example = starting_branch_example;
88				}
89				_ => {}
90			}
91			Err(outcome)
92		}
93	}
94}
95
96#[cfg(all(test, unix))]
97mod tests {
98	use std::{
99		fs::{self, OpenOptions},
100		io::Write,
101		os::unix::fs::OpenOptionsExt,
102		sync::mpsc,
103		time::{Duration, Instant},
104	};
105
106	#[test]
107	fn blocked_state_work_does_not_block_host_polling() {
108		let workspace = tempfile::tempdir().unwrap();
109		let state = workspace.path().join(".workyard");
110		workyard_state::initialize_workspace(workspace.path(), None).unwrap();
111		let repo = workspace.path().join("api");
112		make_repository(&repo);
113
114		let blocked_record = state.join("tasks/other.json");
115		let path = std::ffi::CString::new(blocked_record.as_os_str().as_encoded_bytes()).unwrap();
116		// A real synchronous state read blocks until the host releases its writer.
117		assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0);
118
119		let (entered, ready) = smol::channel::bounded(1);
120		let (release, wait) = mpsc::channel();
121		let writer = std::thread::spawn(move || {
122			let deadline = Instant::now() + Duration::from_secs(5);
123			let mut pipe = loop {
124				match OpenOptions::new()
125					.write(true)
126					.custom_flags(libc::O_NONBLOCK)
127					.open(&blocked_record)
128				{
129					Ok(pipe) => break pipe,
130					Err(error) if error.raw_os_error() == Some(libc::ENXIO) => {
131						assert!(Instant::now() < deadline, "action never opened state");
132						std::thread::sleep(Duration::from_millis(5));
133					}
134					Err(error) => panic!("open state fixture: {error}"),
135				}
136			};
137			entered.send_blocking(()).unwrap();
138			// Test-only watchdog releases the read even if the host is blocked.
139			let host_responded = wait.recv_timeout(Duration::from_secs(5)).is_ok();
140			pipe.write_all(b"invalid state fixture").unwrap();
141			host_responded
142		});
143
144		let input = crate::create::CreateInput {
145			task: "feat/responsive".into(),
146			projects: vec![],
147			repositories: vec![crate::contracts::RepositoryInput {
148				path: trine::NativePath::new(repo).unwrap(),
149				name: None,
150				remote: None,
151				from: None,
152			}],
153			workspace: Some(trine::NativePath::new(workspace.path()).unwrap()),
154			checkout: false,
155			no_fetch: true,
156			remote: None,
157			from: None,
158		};
159		let context = trine::InvocationContext::unobserved(trine::Cancellation::new());
160		let host = async move {
161			ready.recv().await.unwrap();
162			// A watchdog release can close the receiver before this future polls.
163			let _ = release.send(());
164		};
165		let (result, ()) = smol::block_on(smol::future::zip(
166			crate::create::create(input, context),
167			host,
168		));
169		assert!(writer.join().unwrap(), "state read blocked host polling");
170		assert!(result.is_err(), "fixture must reach the invalid state read");
171	}
172
173	fn make_repository(path: &std::path::Path) {
174		fs::create_dir(path).unwrap();
175		for args in [
176			&["init", "-b", "main"][..],
177			&["commit", "--allow-empty", "-m", "fixture"],
178		] {
179			let result = std::process::Command::new("git")
180				.current_dir(path)
181				.args([
182					"-c",
183					"user.name=Test",
184					"-c",
185					"user.email=test@example.invalid",
186				])
187				.args(args)
188				.output()
189				.unwrap();
190			assert!(result.status.success(), "{result:?}");
191		}
192	}
193}