onevcs_testing/remote.rs
1//! The remote-host side: one implementation of [`RemoteHost`] and [`Hosting`] over
2//! either store.
3//!
4//! What GitHub decides, this decides from what it was seeded with: which change
5//! requests exist, what their checks say, and whether a merge lands. What it does
6//! *not* do is move a commit — a merge here records an outcome and nothing reaches
7//! any origin, which is exactly the boundary the real implementation delegates to
8//! the host and the reason a journey about git drives real git.
9
10use std::path::PathBuf;
11
12use url::Url;
13
14use onevcs::{
15 ArtifactId, ChangeChecks, ChangeId, ChangeRequest, ChangeSpec, Check, CheckSource, Error,
16 Hosting, MergeOutcome, MergePolicy, RemoteHost, Result, Sha,
17};
18
19use crate::events;
20use crate::state::HostState;
21use crate::store::{FileStore, MemoryStore, Store};
22
23/// The host a change request's URL names, matching the one implementation the
24/// crate next door speaks for.
25pub const DEFAULT_HOST: &str = "github.com";
26
27/// The repository a host answers for when it was not addressed at one — which is
28/// the case only when a journey holds it directly rather than through
29/// [`Hosting::for_repo`].
30pub const DEFAULT_SLUG: &str = "onevcs/testing";
31
32/// The remote-host side of a run, over whichever store holds its state.
33///
34/// It is both interfaces at once: a [`RemoteHost`] a journey can call directly, and
35/// the [`Hosting`] factory a run is handed. A host taken from the factory shares
36/// this one's state, so what a publication did is read back through the value the
37/// journey created.
38#[derive(Debug)]
39pub struct Host<T> {
40 store: T,
41 // A slug arrives one way only — `Hosting::for_repo`, which takes the `&str` the
42 // contract fixes — and `named_repository` refuses it there; every other
43 // construction here is `DEFAULT_SLUG`. A newtype would have to be public to be
44 // the parameter's type, and the seam is specified without one, which is the same
45 // reason recorded on `Hosting::for_repo` in the crate next door.
46 // llmlint: ignore[invalid_states_unrepresentable] see the note directly above.
47 slug: String,
48}
49
50/// A host provider that keeps its state in this process.
51pub type MemoryHost = Host<MemoryStore<HostState>>;
52
53/// A host provider that keeps its state in one JSON document, so several `onevcs`
54/// invocations see one another's change requests.
55pub type FileHost = Host<FileStore<HostState>>;
56
57impl MemoryHost {
58 /// A host with nothing opened against it.
59 pub fn new() -> Self {
60 Self::seeded(HostState::default())
61 }
62
63 /// A host that starts from a scenario.
64 pub fn seeded(state: HostState) -> Self {
65 Self {
66 store: MemoryStore::new(state),
67 slug: DEFAULT_SLUG.to_owned(),
68 }
69 }
70
71 /// Everything it knows.
72 pub fn state(&self) -> HostState {
73 self.store
74 .snapshot()
75 .expect("an in-memory store always answers")
76 }
77}
78
79impl Default for MemoryHost {
80 fn default() -> Self {
81 Self::new()
82 }
83}
84
85impl FileHost {
86 /// A host keeping its state at `path`: whatever is already there, or nothing
87 /// opened against it.
88 ///
89 /// Attaching rather than replacing, so a second host over the same path answers
90 /// about the change requests the first one opened.
91 pub fn create(path: impl Into<PathBuf>) -> Result<Self> {
92 Ok(Self {
93 store: FileStore::attach(path, &HostState::default())?,
94 slug: DEFAULT_SLUG.to_owned(),
95 })
96 }
97
98 /// A host that starts from a scenario, keeping its state at `path` and
99 /// replacing whatever was there.
100 pub fn seeded(path: impl Into<PathBuf>, state: HostState) -> Result<Self> {
101 Ok(Self {
102 store: FileStore::replace(path, &state)?,
103 slug: DEFAULT_SLUG.to_owned(),
104 })
105 }
106
107 /// Everything it knows, read back out of its document.
108 pub fn state(&self) -> Result<HostState> {
109 self.store.snapshot()
110 }
111}
112
113impl<T: Store<HostState> + Clone + std::fmt::Debug + Send + Sync + 'static> Hosting for Host<T> {
114 fn for_repo(&self, slug: &str) -> Result<Box<dyn RemoteHost>> {
115 Ok(Box::new(Host {
116 store: self.store.clone(),
117 slug: named_repository(slug)?,
118 }))
119 }
120}
121
122impl<T: Store<HostState>> RemoteHost for Host<T> {
123 fn authenticated_user(&self) -> Result<String> {
124 let login = self.store.snapshot()?.authenticated_user;
125 if login.trim().is_empty() {
126 return Err(Error::Invalid {
127 reason: "the host reported no authenticated user".to_owned(),
128 });
129 }
130 Ok(login)
131 }
132
133 fn open_change(&self, req: ChangeSpec) -> Result<ChangeRequest> {
134 addressable(&req.head, "the head branch")?;
135 addressable(&req.base, "the base branch")?;
136 // The same refusal the real host makes: a change request whose title names
137 // nothing is one it will not open.
138 crate::state::titled(&req.title)?;
139 let slug = self.slug.clone();
140 self.store.with(|state| {
141 // The host numbers its change requests, consecutively from one, so a
142 // journey can seed the checks of a change it has not opened yet.
143 let id = ChangeId((state.changes.len() + 1).to_string());
144 let url = format!("https://{DEFAULT_HOST}/{slug}/pull/{}", id.0);
145 let change = ChangeRequest {
146 head_sha: Sha(events::stable_sha(&[&slug, &req.head, &id.0])),
147 url: Url::parse(&url).map_err(|e| Error::Invalid {
148 reason: format!("{url:?} is not a URL: {e}"),
149 })?,
150 base: req.base.clone(),
151 id: id.clone(),
152 };
153 state.heads.insert(id.clone(), req.head.clone());
154 state.titles.insert(id.clone(), req.title.clone());
155 // Only when there is one: a change request opened with no body records
156 // none, so a journey can tell "nobody drafted one" from "the body is
157 // empty" — which is the distinction the real host draws too.
158 if let Some(body) = req.body.clone() {
159 state.bodies.insert(id, body);
160 }
161 state.changes.push(change.clone());
162 Ok(change)
163 })
164 }
165
166 fn find_changes(&self, head: &str, base: &str) -> Result<Vec<ChangeRequest>> {
167 addressable(head, "the head branch")?;
168 addressable(base, "the base branch")?;
169 let state = self.store.snapshot()?;
170 Ok(state
171 .changes
172 .iter()
173 .filter(|change| {
174 change.base == base
175 && state.heads.get(&change.id).is_some_and(|from| from == head)
176 // Only the open ones: a change the host has already merged is
177 // not one to adopt.
178 && !matches!(state.merges.get(&change.id), Some(MergeOutcome::Merged(_)))
179 })
180 .cloned()
181 .collect())
182 }
183
184 fn change_checks(&self, cr: &ChangeRequest) -> Result<ChangeChecks> {
185 let state = self.store.snapshot()?;
186 let sources = state.check_sources.clone().unwrap_or_else(complete_sources);
187 // The same refusal the real implementation makes when its credential can
188 // read neither the host's check rollup nor its Actions API: what the checks
189 // say is unknown, and answering "none" for "could not look" is what lets a
190 // merge through unguarded.
191 if sources.is_empty() {
192 return Err(Error::Invalid {
193 reason: format!(
194 "this host was seeded with no check source, so what the checks on {} say \
195 cannot be read rather than being empty",
196 cr.url
197 ),
198 });
199 }
200 Ok(ChangeChecks {
201 checks: state.checks.get(&cr.id).cloned().unwrap_or_default(),
202 sources,
203 })
204 }
205
206 fn check_log(&self, cr: &ChangeRequest, check: &Check) -> Result<ArtifactId> {
207 let log = self
208 .store
209 .snapshot()?
210 .check_logs
211 .get(&cr.id)
212 .and_then(|logs| logs.get(&check.name))
213 .cloned()
214 .unwrap_or_else(|| format!("the host log for check {}\n", check.name));
215 events::store_artifact(&artifact_id(&cr.id, &check.name), &log)
216 }
217
218 fn merge(&self, cr: &ChangeRequest, policy: MergePolicy) -> Result<MergeOutcome> {
219 self.store.with(|state| {
220 // A seeded outcome is the host's decision and outranks the policy: it is
221 // how a journey says "this one is queued behind something" or "this one
222 // has already landed".
223 if let Some(decided) = state.merges.get(&cr.id) {
224 return Ok(decided.clone());
225 }
226 let landed = |state: &mut HostState| MergeOutcome::Merged(land(state, cr));
227 Ok(match policy {
228 // Nothing is asked of the host, so nothing is recorded — the same
229 // answer the real implementation gives without a call.
230 MergePolicy::LocalDirect | MergePolicy::ChangeOpen => MergeOutcome::Open,
231 MergePolicy::ChangeAuto => {
232 if required_checks_green(state, &cr.id) {
233 landed(state)
234 } else {
235 // Native auto-merge: the host holds it and lands it when its
236 // own required checks pass, so nothing merges now.
237 state.merges.insert(cr.id.clone(), MergeOutcome::Queued);
238 MergeOutcome::Queued
239 }
240 }
241 MergePolicy::ChangeDirect => landed(state),
242 })
243 })
244 }
245
246 fn merged_at(&self, cr: &ChangeRequest) -> Result<Option<Sha>> {
247 self.store.with(|state| {
248 // Native auto-merge, modelled rather than skipped: a change this host is
249 // holding lands the moment its own required checks are green, on the
250 // host's clock and not on the caller's. Asking is what makes that
251 // observable — which is exactly the shape a publication watching the
252 // real GitHub meets, and the reason a journey can drive a change request
253 // from queued to merged without a second process.
254 if matches!(state.merges.get(&cr.id), Some(MergeOutcome::Queued))
255 && required_checks_green(state, &cr.id)
256 {
257 return Ok(Some(land(state, cr)));
258 }
259 Ok(match state.merges.get(&cr.id) {
260 Some(MergeOutcome::Merged(sha)) => Some(sha.clone()),
261 _ => None,
262 })
263 })
264 }
265}
266
267/// Record this change request as merged, and answer with the commit it merged at.
268///
269/// One place, so the merge a policy performs and the merge the host completes on
270/// its own report the same commit for the same change.
271fn land(state: &mut HostState, cr: &ChangeRequest) -> Sha {
272 let sha = Sha(events::stable_sha(&["merge", &cr.id.0, cr.url.as_str()]));
273 state
274 .merges
275 .insert(cr.id.clone(), MergeOutcome::Merged(sha.clone()));
276 sha
277}
278
279/// What a host that was not told otherwise answers about where its checks came
280/// from: the host's own rollup, which is every check anything posted on the change
281/// request — the answer a credential allowed to read check runs gets.
282fn complete_sources() -> std::collections::BTreeSet<CheckSource> {
283 [CheckSource::StatusChecks].into_iter().collect()
284}
285
286/// Whether every required check on a change request has settled green.
287///
288/// A change with no required checks is not green: nothing has vouched for it, which
289/// is the state auto-merge waits in rather than lands from.
290fn required_checks_green(state: &HostState, id: &ChangeId) -> bool {
291 let checks = match state.checks.get(id) {
292 Some(checks) => checks,
293 None => return false,
294 };
295 let required: Vec<&Check> = checks.iter().filter(|check| check.required).collect();
296 !required.is_empty() && required.iter().all(|check| check.green())
297}
298
299/// The id one check's log is stored under.
300///
301/// Derived from what it is a log *of* rather than minted, so fetching the same
302/// log twice does not leave two artifacts, and a journey can name the id it is
303/// about to assert on.
304fn artifact_id(change: &ChangeId, check: &str) -> String {
305 let safe: String = check
306 .chars()
307 .map(|c| {
308 if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
309 c
310 } else {
311 '-'
312 }
313 })
314 .collect();
315 let number: String = change
316 .0
317 .chars()
318 .filter(|c| c.is_ascii_alphanumeric())
319 .collect();
320 format!("a-testing-{number}-{safe}")
321}
322
323/// One value bound for the host's argument vector, checked before it gets there.
324///
325/// The same refusal the real implementation makes, and for the same reason: a name
326/// shaped like an option or an absent value addresses something other than what it
327/// names, and a provider that accepted one would let a journey pass where the real
328/// host rejects.
329fn addressable(value: &str, what: &str) -> Result<()> {
330 if value.is_empty() || value.starts_with('-') || value.contains(char::is_whitespace) {
331 return Err(Error::Invalid {
332 reason: format!(
333 "{what} {value:?} cannot address anything on the host: it must be non-empty, \
334 must not begin with '-', and must carry no whitespace"
335 ),
336 });
337 }
338 Ok(())
339}
340
341/// A slug that names one repository, as `owner/name`.
342fn named_repository(slug: &str) -> Result<String> {
343 let mut parts = slug.split('/');
344 let named = matches!(
345 (parts.next(), parts.next(), parts.next()),
346 (Some(owner), Some(name), None)
347 if !owner.is_empty()
348 && !name.is_empty()
349 && !slug.starts_with('-')
350 && !slug.contains(char::is_whitespace)
351 );
352 if !named {
353 return Err(Error::Invalid {
354 reason: format!("{slug:?} does not name one repository as owner/name"),
355 });
356 }
357 Ok(slug.to_owned())
358}