Skip to main content

onevcs_testing/
state.rs

1//! What a provider knows, in a shape a journey can write down and read back.
2//!
3//! One state type per interface, shared by both flavours of it — the in-memory
4//! provider and the file-backed one differ in where the state lives and in nothing
5//! else, so a scenario seeded for one is the same scenario for the other.
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use serde::{Deserialize, Serialize};
10
11use onevcs::{
12    ChangeId, ChangeRequest, Check, CheckSource, DraftReason, Error, Identity, Landed,
13    MergeOutcome, Recoverable, Result,
14};
15use onevcs::{MergePolicy, Publication, Session, SessionRequest, SessionToken};
16
17use crate::events;
18use crate::store::Checked;
19
20/// The version of the state document this build writes.
21///
22/// A file-backed state outlives the process that wrote it and is read by the next
23/// one, which makes it a stored contract like `onevcs`'s own registry document —
24/// and like that document, the version a document declares decides what is done
25/// with it rather than being guessed at. [`STATE_VERSION`] is the shape the goldens in
26/// `tests/golden/` hold, and those goldens are compared byte for byte, so a change
27/// to the document cannot reach a consumer without the diff saying so.
28///
29/// `2` was what both sides learned when publishing and closing a session came
30/// through the interface: [`VcsState::policy`], [`VcsState::closed_sessions`],
31/// [`VcsState::publications`], and [`HostState::titles`]. `3` is
32/// [`HostState::bodies`], the body a change request was opened with. `4` is the two
33/// fields a `Recoverable` gained inside [`VcsState::preserved`] — the live session
34/// holding a branch, and the lines it would land when it removes more than it adds.
35/// `5` is one more of those: whether the branch's work reached its base, and what
36/// says so. `6` is the two a `Check` gained inside [`HostState::checks`] — the
37/// commit the host attached that check to, and where the check is on the host. `7`
38/// is the two a draft change request needs — [`HostState::drafts`], the reason each
39/// change request was opened as a draft with, and [`HostState::made_ready`], the
40/// `ready_for_review` calls it took. `8` is the two an [`Identity`] inside
41/// [`VcsState::identities`] **lost** — `workflow` and `repo_type`, the registry's
42/// inferences from whether an origin had a host, which every decision they made now
43/// takes from the resolved publication policy instead. `9` is the draft reason inside
44/// [`HostState::drafts`] becoming one of two kinds and saying which — `kind` is
45/// `awaiting-release` or `held` — and [`HostState::described`], the descriptions a
46/// host was handed for a change request after it was opened. `10` is the failure
47/// vocabulary a publication's outcome inside [`VcsState::publications`] may name
48/// widening by one kind, `host-prerequisite` — no field moved, but a document naming
49/// it is one a version 9 build cannot read, and the version is how it says so. `11` is
50/// one more field a `Recoverable` gained inside [`VcsState::preserved`], the same way
51/// `4` and `5` were: where `onevcs preserve` put that branch on its identity's origin,
52/// and the commit the origin carries it at. `12` is the labels a session is opened
53/// with — [`VcsState::session_labels`], keyed by token the way its identity is — and
54/// the two fields a `Recoverable` gained inside [`VcsState::preserved`] to carry them:
55/// the session that answers for the row, and that session's labels.
56///
57/// **Every change to the document is versioned, an added field included.** A field
58/// that only ever appears when it holds something is *compatible* — that is what
59/// [`OLDEST_READABLE_VERSION`] is for — but compatible is not the same as
60/// unremarkable: the version is how a consumer's checked-in scenario says which
61/// shape it was written against, and a document that gained a field without saying
62/// so leaves nothing able to tell "this build wrote no body" from "this document
63/// predates bodies". The two answers differ for exactly the journey this crate
64/// exists to support.
65pub const STATE_VERSION: u32 = 12;
66
67/// The oldest document version this build reads.
68///
69/// Every version from here to [`STATE_VERSION`] is read and carried forward on the
70/// way in, which is how `onevcs`'s own registry document treats its older
71/// versions: what separates a readable older version from a refused one is whether
72/// its every field still means here what it meant there. `2` to `3` added a field
73/// and changed none, so a version 2 document reads as one whose change requests
74/// were opened with no body — which is what they were; `3` to `4` added two the same
75/// way, so a version 3 document reads as one whose preserved rows say nothing about a
76/// hold or a line count, which is what they said. `4` to `5` added one that every row
77/// answers rather than one that appears when it holds something, so a version 4
78/// document's rows are carried forward as the answer that list *was*: preserved work
79/// nobody published, which is work that did not land. `5` to `6` added two that
80/// appear only when they hold something, so a version 5 document's checks read as
81/// checks whose commit and address that build never recorded — which is what they
82/// were, and the one thing that must not be filled in from the change request's own
83/// head. `6` to `7` added two more of that kind, so a version 6 document reads as one
84/// whose change requests were opened before this crate could draft one — which is what
85/// they were: no draft reason recorded for any of them, and no lift ever asked for.
86/// `7` to `8` *removed* two from each identity, and a version 7 document reads past
87/// them: an identity is its origin and its gate here as it is in `onevcs`, and the two
88/// keys beside them are ones this build has no opinion on. `8` to `9` gave every
89/// draft reason a `kind`, and a reason written without one is read as the one kind
90/// there was — `awaiting-release`, whose four fields it carries unchanged — which is
91/// `drafts_of_any_version`'s whole job; the descriptions beside it are absent from a
92/// document written before them, which is the answer, since that build could describe
93/// nothing. `9` to `10` changed no field and no meaning: every failure kind a version 9
94/// document can hold is spelled here as it was there and means what it meant, so it
95/// reads unchanged and needs no carrying forward beyond its version. `10` to `11` added
96/// one that appears only when it holds something, so a version 10 document's preserved
97/// rows read as rows saying nothing about an origin — which is what they said, since
98/// that build had no verb that could put a branch on one. `11` to `12` added the
99/// labels, which appear only where a session was opened with some, and the two row
100/// fields that carry them, which a version 11 row reads as absent: a session nobody
101/// labelled, and a row that names no session — which is what that build's rows said,
102/// since it recorded neither.
103///
104/// `1` is refused rather than read for the opposite reason: it describes a provider
105/// that could not publish, and every session in it would read back as open — a
106/// wrong answer where a journey asserting on a session it had closed needs a
107/// refusal.
108pub const OLDEST_READABLE_VERSION: u32 = 2;
109
110/// Everything the repository side of a run knows about itself.
111///
112/// Every field is public and serializable, so a journey both seeds a scenario and
113/// asserts on what a run left behind. Everything but the version is omitted when
114/// it holds nothing, so a hand-written document names only the part of a scenario
115/// that matters — and a document written by a build that knew fewer fields still
116/// reads here.
117#[derive(Debug, Clone, Serialize, Deserialize)]
118#[serde(default)]
119pub struct VcsState {
120    /// The schema version this state was written at. A document that names none is
121    /// the one this build writes.
122    // llmlint: ignore[boundary_inputs_validated] deciding what to do with a version this
123    // build does not read is the whole of the check — and it is in `Checked::check` below,
124    // where a document is read, rather than here where serde only proves the shape.
125    pub version: u32,
126    /// The repository identities this provider can resolve. A
127    /// [`SessionRequest::repo`] naming none of them is refused, the way an
128    /// unregistered repository is.
129    #[serde(skip_serializing_if = "Vec::is_empty")]
130    pub identities: Vec<Identity>,
131    /// Every session opened or seeded, in the order they were opened.
132    #[serde(skip_serializing_if = "Vec::is_empty")]
133    pub sessions: Vec<Session>,
134    /// Which identity each session belongs to.
135    ///
136    /// Beyond the sketch this crate was specified from, and unavoidable: a
137    /// [`Session`] carries no identity, and a [`Recoverable`] must name one — so
138    /// preserving a session's branch could not answer the question `recoverable`
139    /// asks without this. `open_session` records it; nothing else writes it.
140    // llmlint: ignore[invalid_states_unrepresentable] an identity key is a `String`
141    // everywhere the crate this mirrors spells one — `Recoverable.identity`,
142    // `Identity.origin`, the registry document's own map key — and a newtype here would
143    // make a seeded state disagree with the types it is made of. Every value written to
144    // this map came out of `identity_of`, so it names an identity this provider holds.
145    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
146    pub session_identities: BTreeMap<SessionToken, String>,
147    /// The labels each session was opened with, for the sessions opened with any.
148    ///
149    /// Keyed by token the way [`session_identities`](Self::session_identities) is,
150    /// and for the same reason: a [`Session`] carries no labels, and both `session
151    /// holders` and every `recoverable` row report them. `open_session` records
152    /// them; nothing else writes it.
153    // llmlint: ignore[invalid_states_unrepresentable] keyed by session token, exactly as
154    // `session_identities` above is and for the same reason it gives.
155    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
156    pub session_labels: BTreeMap<SessionToken, BTreeMap<String, String>>,
157    /// Preserved work, newest last, as `recoverable` reports it.
158    ///
159    /// [`Recoverable`] rather than `PreservedBranch` — it *contains* the preserved
160    /// branch and adds the identity, the checkout, why the workstream stopped, and
161    /// the command that lands it, none of which are derivable from the branch
162    /// alone. One list rather than two that could disagree.
163    #[serde(skip_serializing_if = "Vec::is_empty")]
164    pub preserved: Vec<Recoverable>,
165    /// The sessions that have been closed. Every other session here is open.
166    ///
167    /// One way to say closed rather than two, so a scenario written by hand names
168    /// only the sessions whose lifecycle is not the one they were opened in.
169    // llmlint: ignore[invalid_states_unrepresentable] keyed by session token, exactly as
170    // `session_identities` above is and for the same reason: this document is a scenario
171    // somebody writes by hand, and a session is named once under `sessions` with the rest
172    // of the state keyed to it rather than nested inside a shape that could hold only one
173    // arrangement. A token here that names no opened session is refused in
174    // `Checked::check`, where the document is read — the same trust boundary every other
175    // cross-reference in it is checked at.
176    #[serde(skip_serializing_if = "BTreeSet::is_empty")]
177    pub closed_sessions: BTreeSet<SessionToken>,
178    /// The policy this provider publishes under.
179    ///
180    /// The answer a rules file gives the real implementation, which a provider has
181    /// none of — so a journey states it, and unset is the policy the contract's own
182    /// `default:` names ([`DEFAULT_PUBLICATION`](crate::DEFAULT_PUBLICATION)). A
183    /// per-run policy narrows it through [`MergePolicy::narrow`], which is the
184    /// rules system's rule rather than a restatement of it here.
185    #[serde(skip_serializing_if = "Option::is_none")]
186    pub policy: Option<MergePolicy>,
187    /// Every publication this provider performed, in the order it performed them.
188    ///
189    /// Both a record a journey asserts on and the answer to "has this session been
190    /// published already": a second publication of a session that landed has
191    /// nothing the base does not already carry, which is what the real
192    /// implementation reports for the same reason.
193    // llmlint: ignore[invalid_states_unrepresentable] this holds `onevcs::Publication`
194    // verbatim — the value `Vcs::publish` handed back, carrying its own session and branch
195    // — so a journey asserts on exactly what a caller would receive. A shape that made
196    // "this publication is of some other session's branch" unrepresentable could not hold
197    // that type, and would be a second spelling of the answer the crate next door already
198    // has. The cross-reference is checked in `Checked::check` instead, where the document
199    // is read.
200    #[serde(skip_serializing_if = "Vec::is_empty")]
201    pub publications: Vec<Publication>,
202}
203
204/// A repository side that knows nothing, at the version this build writes.
205impl Default for VcsState {
206    fn default() -> Self {
207        Self {
208            version: STATE_VERSION,
209            identities: Vec::new(),
210            sessions: Vec::new(),
211            session_identities: BTreeMap::new(),
212            session_labels: BTreeMap::new(),
213            preserved: Vec::new(),
214            closed_sessions: BTreeSet::new(),
215            policy: None,
216            publications: Vec::new(),
217        }
218    }
219}
220
221/// Everything the remote-host side of a run knows about itself.
222///
223/// Omitted-when-empty and versioned for the same reasons [`VcsState`] is.
224#[derive(Debug, Clone, Serialize, Deserialize)]
225#[serde(default)]
226pub struct HostState {
227    /// The schema version this state was written at. A document that names none is
228    /// the one this build writes.
229    // llmlint: ignore[boundary_inputs_validated] as on `VcsState::version`: the decision
230    // about an unreadable version is made in `Checked::check`, where the document is read.
231    pub version: u32,
232    /// Who the host says is calling. Empty is refused, exactly as a `gh` that
233    /// reports no authenticated user is.
234    // llmlint: ignore[invalid_states_unrepresentable] the interface this satisfies is
235    // `authenticated_user() -> Result<String>`, so the login is a `String` by contract and
236    // the one unusable value — a host that names nobody — is refused where it is read
237    // rather than made unrepresentable in a state a journey writes by hand.
238    pub authenticated_user: String,
239    /// Every change request that has been opened or seeded.
240    #[serde(skip_serializing_if = "Vec::is_empty")]
241    pub changes: Vec<ChangeRequest>,
242    /// The head branch each change request was opened from.
243    ///
244    /// Beyond the sketch, and unavoidable: [`ChangeRequest`] records only the base
245    /// it targets, and `find_changes` matches on the head as well.
246    // llmlint: ignore[invalid_states_unrepresentable] the matching `ChangeSpec.head` and
247    // `ChangeRequest.base` are `String` in the contract this mirrors, and a validated ref
248    // type here would disagree with them. Every value written to this map went through
249    // `addressable` in `open_change` first, which is the same refusal the real
250    // implementation makes at the same point.
251    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
252    pub heads: BTreeMap<ChangeId, String>,
253    /// The title each change request was opened under.
254    ///
255    /// Beyond the sketch, and for the same reason [`heads`](HostState::heads) is:
256    /// [`ChangeRequest`] records neither, and the title is what a publication's
257    /// commit subject becomes — so a journey asserting that the subject it asked
258    /// for is the one the host was given has nowhere else to read it.
259    // llmlint: ignore[invalid_states_unrepresentable] this records the `ChangeSpec.title`
260    // the contract fixes as a `String`, so a validated type here would disagree with the
261    // one it mirrors. `Subject` is not that type: it is `onevcs`'s rule for a *commit
262    // subject*, and a host's own limit is its own — spelling it here would
263    // refuse a seeded title a real host accepts, which is drift in the direction that
264    // looks like rigour. What the host itself refuses is a title that names nothing, and
265    // that is refused below and in `open_change`, at the boundary the value arrives at.
266    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
267    pub titles: BTreeMap<ChangeId, String>,
268    /// The body each change request was opened with, for the change requests that
269    /// were opened with one.
270    ///
271    /// Beside [`titles`](HostState::titles) and for its reason: the body is what a
272    /// caller passes on the `PublishRequest` and nothing else records it, so a
273    /// journey asserting that the body it drafted is the one the host was given has
274    /// nowhere else to read it. A change request with no entry was opened with no
275    /// body at all, which is what a publication nobody gave one does — the two are
276    /// different scenarios, and an empty string is the first rather than the second.
277    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
278    pub bodies: BTreeMap<ChangeId, String>,
279    /// The checks the host reports on each change request. A change with no entry
280    /// has no checks, which is what a repository with no CI reports.
281    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
282    pub checks: BTreeMap<ChangeId, Vec<Check>>,
283    /// The log the host hands over for a check, keyed by change request and then by
284    /// check name. Beyond the sketch: `check_log` is one of the six methods, and
285    /// without this the only log a journey could asssert on is a synthesized one.
286    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
287    pub check_logs: BTreeMap<ChangeId, BTreeMap<String, String>>,
288    /// The reason each change request that was opened as a **draft** was drafted
289    /// with, for the change requests that were.
290    ///
291    /// Beside [`bodies`](HostState::bodies) and for its reason: the reason is what a
292    /// caller passes on the `PublishRequest` and this is where a journey reads back
293    /// that the host was given it. A change with no entry is not a draft, which is
294    /// what every change request opened without one is.
295    ///
296    /// Nothing is refused about the reason itself here. Its shape — that every field
297    /// of it renders as the one line it is printed on — is `onevcs`'s own rule, and
298    /// it is applied where a publication takes one in, before any host is asked.
299    #[serde(
300        skip_serializing_if = "BTreeMap::is_empty",
301        deserialize_with = "drafts_of_any_version"
302    )]
303    pub drafts: BTreeMap<ChangeId, DraftReason>,
304    /// Every `ready_for_review` call this host has taken, in the order it took them
305    /// — the lifts it was asked to perform, never a request for a *reviewer*.
306    ///
307    /// A list rather than a set, and beyond the sketch for a reason a set could not
308    /// serve: lifting a draft is required to be *idempotent*, so what a journey
309    /// asserts is that a second publication asked the host for nothing — and only a
310    /// record of the calls themselves can say that. A change named here is not a
311    /// draft any more, whatever [`drafts`](HostState::drafts) says it was opened as.
312    #[serde(skip_serializing_if = "Vec::is_empty")]
313    pub made_ready: Vec<ChangeId>,
314    /// Every `describe_change` call this host has taken, in the order it took them:
315    /// which change request, the title it was handed when it was handed one, and the
316    /// body.
317    ///
318    /// The calls themselves, for the reason [`made_ready`](HostState::made_ready) is:
319    /// what a journey asks is what a closeout *wrote*, call by call, and the current
320    /// title and body — which each call also writes into
321    /// [`titles`](HostState::titles) and [`bodies`](HostState::bodies), so
322    /// `change_description` answers from the same record `open_change` wrote — can
323    /// only say where the description ended up.
324    #[serde(skip_serializing_if = "Vec::is_empty")]
325    pub described: Vec<Described>,
326    /// Which sources this host answers about its checks from, which is what the
327    /// real implementation reports alongside them.
328    ///
329    /// Unset is a credential allowed to read everything: the whole rollup, exactly
330    /// what a host with nothing to hide reports. A journey states a narrower set to
331    /// be the credential the real one meets in CI — a fine-grained token, which
332    /// cannot read check runs at all and sees GitHub Actions and nothing else — and
333    /// states an *empty* one to be a credential that can read no source at all,
334    /// which is a refusal rather than "no checks". Unset and empty are therefore
335    /// different scenarios, which is why this is an `Option` rather than a set whose
336    /// emptiness means "not stated".
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub check_sources: Option<BTreeSet<CheckSource>>,
339    /// What merging each change request did.
340    ///
341    /// Both a script and a record: an entry seeded here is what `merge` answers,
342    /// whatever the policy asks for — which is how a journey expresses a host that
343    /// queues or refuses — and a merge the policy decided is written back here.
344    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
345    pub merges: BTreeMap<ChangeId, MergeOutcome>,
346}
347
348/// One description a host was handed for a change request after it was opened.
349///
350/// What `RemoteHost::describe_change` was given, verbatim: the title only where the
351/// call carried one, because a call that replaced the body alone left the title as
352/// it was, and a record that filled it in would say the caller wrote a title nobody
353/// wrote.
354// llmlint: ignore[invalid_states_unrepresentable] the title and body are the `&str`s the
355// seam hands over — a host places no shape on prose, and `onevcs`'s own `Subject` rule
356// was applied where the description was composed, before any host was asked.
357#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
358pub struct Described {
359    /// The change request the description was written to.
360    pub id: ChangeId,
361    /// The title the call replaced the change request's with, when it replaced one.
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub title: Option<String>,
364    /// The body the call replaced the change request's with.
365    pub body: String,
366}
367
368/// The `drafts` map of a document at any readable version.
369///
370/// A document written before version 9 spells a draft reason as the four fields of
371/// the one kind there was and no `kind` beside them; this build's reason is one of
372/// two kinds and says which. So a reason arriving without a `kind` is read as
373/// `awaiting-release` — exactly what it was — rather than refused, which is what
374/// keeps a consumer's checked-in scenario readable across the bump. A reason that
375/// *names* a kind is read as it names it, so nothing written by this build is
376/// reinterpreted.
377fn drafts_of_any_version<'de, D>(
378    deserializer: D,
379) -> std::result::Result<BTreeMap<ChangeId, DraftReason>, D::Error>
380where
381    D: serde::Deserializer<'de>,
382{
383    let raw: BTreeMap<ChangeId, serde_json::Map<String, serde_json::Value>> =
384        Deserialize::deserialize(deserializer)?;
385    raw.into_iter()
386        .map(|(id, mut fields)| {
387            fields
388                .entry("kind")
389                .or_insert_with(|| serde_json::Value::from("awaiting-release"));
390            serde_json::from_value::<DraftReason>(serde_json::Value::Object(fields))
391                .map(|reason| (id, reason))
392                .map_err(serde::de::Error::custom)
393        })
394        .collect()
395}
396
397/// Who a host with nothing seeded says is calling.
398///
399/// A host that answers nobody is refused by the real implementation, so a default
400/// state that answered nobody would be a provider that cannot run a publication
401/// until it is configured.
402pub const DEFAULT_AUTHENTICATED_USER: &str = "onevcs-testing";
403
404impl Default for HostState {
405    fn default() -> Self {
406        Self {
407            version: STATE_VERSION,
408            authenticated_user: DEFAULT_AUTHENTICATED_USER.to_owned(),
409            changes: Vec::new(),
410            heads: BTreeMap::new(),
411            titles: BTreeMap::new(),
412            bodies: BTreeMap::new(),
413            drafts: BTreeMap::new(),
414            made_ready: Vec::new(),
415            described: Vec::new(),
416            checks: BTreeMap::new(),
417            check_logs: BTreeMap::new(),
418            check_sources: None,
419            merges: BTreeMap::new(),
420        }
421    }
422}
423
424/// The identity a session request names, or the reason none of them is it.
425///
426/// Three ways to name one, mirroring what the registry accepts: the identity key
427/// itself, the `owner/name` tail of it, or the bare repository name.
428pub(crate) fn identity_of<'a>(state: &'a VcsState, origin_or_path: &str) -> Option<&'a Identity> {
429    let wanted = origin_or_path.trim_end_matches('/');
430    state
431        .identities
432        .iter()
433        .find(|identity| identity.origin == wanted)
434        .or_else(|| {
435            state.identities.iter().find(|identity| {
436                identity
437                    .origin
438                    .rsplit('/')
439                    .next()
440                    .is_some_and(|name| name == wanted)
441                    || identity.origin.ends_with(&format!("/{wanted}"))
442            })
443        })
444}
445
446/// The known identities, as a refusal names them.
447pub(crate) fn known(state: &VcsState) -> String {
448    if state.identities.is_empty() {
449        return "this provider was seeded with no identities".to_owned();
450    }
451    let names: Vec<&str> = state
452        .identities
453        .iter()
454        .map(|identity| identity.origin.as_str())
455        .collect();
456    format!("it knows {}", names.join(", "))
457}
458
459/// The identity a session belongs to, or the reason this provider cannot say.
460///
461/// `open_session` records it and nothing else writes it, so a session that arrived
462/// in a hand-written scenario without one is refused here rather than published
463/// against a repository nobody named.
464pub(crate) fn identity_for(state: &VcsState, token: &SessionToken) -> Result<String> {
465    state
466        .session_identities
467        .get(token)
468        .cloned()
469        .ok_or_else(|| Error::Invalid {
470            reason: format!(
471                "this provider has no record of session {:?}, so it cannot say which identity \
472                 its work belongs to",
473                token.0
474            ),
475        })
476}
477
478/// The session a token names.
479pub(crate) fn session_of<'a>(state: &'a VcsState, token: &SessionToken) -> Option<&'a Session> {
480    state
481        .sessions
482        .iter()
483        .find(|session| session.token == *token)
484}
485
486/// The branch a request asks for, or the one that is derived from the token.
487///
488/// `branch` and `branch_name` are two answers to one question — *continue this* and
489/// *cut one at this* — so a request naming both is refused here as the real
490/// implementation refuses it: that refusal is about the shape of the request rather
491/// than about anything a repository does, and a consumer proving it must meet the
492/// same answer on either side.
493///
494/// **What a provider deliberately does not do to `branch_name` is the rest**, and it
495/// is not approximated: the host's branch prefix is read out of an `onevcs` state
496/// root no provider has, and the first-free suffix is searched against an identity's
497/// checkouts and its origin, which a provider has neither of. So the name is taken as
498/// it was proposed and refused — naming it — where git would refuse it, rather than
499/// being sanitized by a second copy of a grammar that would then have to be held to
500/// the first. A consumer proving what the prefix, the sanitizer and the collision
501/// suffix do drives the real `onevcs`, which is where all three live.
502pub(crate) fn requested_branch(req: &SessionRequest, token: &SessionToken) -> Result<String> {
503    if let (Some(pinned), Some(proposed)) = (&req.branch, &req.branch_name) {
504        return Err(Error::Invalid {
505            reason: format!(
506                "this request names both a branch to continue ({pinned:?}) and a name to cut \
507                 ({proposed:?}), which are two answers to one question"
508            ),
509        });
510    }
511    let name = req
512        .branch
513        .clone()
514        .or_else(|| req.branch_name.clone())
515        .unwrap_or_else(|| format!("onevcs/{}", token.0));
516    named_branch(&name, "the branch")?;
517    Ok(name)
518}
519
520/// A branch name, refused here if git would refuse it.
521///
522/// The real implementation asks `git check-ref-format`, which is the parser that
523/// decides; a provider with no git carries `git-check-ref-format(1)`'s rules
524/// instead. That is a restatement, so it is gated rather than trusted:
525/// `refs.rs` in the suite runs both this and git itself over a table of names
526/// and holds them to each other, because a copy of somebody else's grammar with
527/// no gate is a copy that drifts.
528///
529/// One deliberate difference, and the gate knows about it: a leading `-` is
530/// refused here even though git accepts it as a ref, because such a name reaches
531/// a command line as an option rather than as the branch it spells.
532pub(crate) fn named_branch(value: &str, what: &str) -> Result<()> {
533    // Rule 1 is per slash-separated component; the rest are about the whole name.
534    let components_usable = !value.is_empty()
535        && value.split('/').all(|component| {
536            !component.is_empty() && !component.starts_with('.') && !component.ends_with(".lock")
537        });
538    let usable = components_usable
539        && !value.starts_with('-')
540        && !value.contains("..")
541        && !value.contains("@{")
542        && !value.ends_with('.')
543        && !value.ends_with('/')
544        && !value.chars().any(|c| {
545            c.is_whitespace() || c.is_ascii_control() || c == '\u{7f}' || "~^:?*[\\".contains(c)
546        });
547    if !usable {
548        return Err(Error::Invalid {
549            reason: format!("{what} {value:?} is a name git would not accept"),
550        });
551    }
552    Ok(())
553}
554
555/// A label, refused here where the real implementation refuses one: a key is one or
556/// more of `A-Z`, `a-z`, `0-9`, `_` and `-`, and a value is one line. The same rule
557/// spelled twice on purpose, for the reason [`named_branch`] gives — a provider with
558/// no `onevcs` state root carries the grammar, and the journeys over both providers
559/// hold the two to each other.
560pub(crate) fn label_pair(key: &str, value: &str) -> Result<()> {
561    let key_usable = !key.is_empty()
562        && key
563            .chars()
564            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
565    if !key_usable {
566        return Err(Error::Invalid {
567            reason: format!(
568                "{key:?} is not a label key; a key is one or more of A-Z, a-z, 0-9, `_` and `-`"
569            ),
570        });
571    }
572    if value.contains('\n') {
573        return Err(Error::Invalid {
574            reason: format!(
575                "the value of label {key:?} holds a newline; a label's value is one line"
576            ),
577        });
578    }
579    Ok(())
580}
581
582/// A seeded repository side is refused if it holds a session nothing could act on.
583impl Checked for VcsState {
584    fn check(&self) -> Result<()> {
585        readable_version(self.version)?;
586        for session in &self.sessions {
587            // The token names a file under the state root, and a branch goes on to
588            // spell a ref; both arrive from whoever wrote the document.
589            if !events::is_safe_name(&session.token.0) {
590                return Err(Error::Invalid {
591                    reason: format!("{:?} is not a session token", session.token.0),
592                });
593            }
594            named_branch(&session.branch, "the branch")?;
595            named_branch(&session.base, "the base")?;
596        }
597        for row in &self.preserved {
598            known_identity(self, &row.identity, "preserved work")?;
599            named_branch(&row.branch.branch, "the preserved branch")?;
600            named_branch(&row.branch.base, "the preserved branch's base")?;
601            // The hold names a session, so it is checked like the three below: a row
602            // held by a session nobody opened is the same fiction, and the costly one
603            // — it is the session an operator is told to wait for or close.
604            if let Some(held) = &row.held_by {
605                opened(self, &held.token, "holding preserved work")?;
606            }
607        }
608        // Both of these name a session, so both are checked twice over: the token
609        // has to be a plain name, because it goes on to spell the file its stream is
610        // written in, and it has to name a session this state actually holds. A
611        // document that closes or publishes a session nobody opened describes a run
612        // that could not have happened, and answering `recoverable` or `session`
613        // from it would be answering from a fiction rather than refusing one.
614        for token in &self.closed_sessions {
615            opened(self, token, "closed")?;
616        }
617        for (token, labels) in &self.session_labels {
618            opened(self, token, "labelled")?;
619            for (key, value) in labels {
620                label_pair(key, value)?;
621            }
622        }
623        for (token, origin) in &self.session_identities {
624            opened(self, token, "given an identity")?;
625            // The value as well as the key: this is what `identity_for` answers with,
626            // and it goes on to spell the slug a change request is opened against and
627            // the label every one of that session's events carries. An identity this
628            // provider does not know is one it could not have opened the session for.
629            known_identity(self, origin, &format!("session {:?}", token.0))?;
630        }
631        for publication in &self.publications {
632            let session = opened(self, &publication.session, "published")?;
633            named_branch(&publication.branch, "the published branch")?;
634            // A publication of some other branch than the one the session is on is
635            // the same kind of fiction, and the harder one to spot afterwards: the
636            // branch is what a journey asserts the publication was of.
637            if publication.branch != session.branch {
638                return Err(Error::Invalid {
639                    reason: format!(
640                        "the publication of session {:?} names branch {:?}, but that session is \
641                         on {:?}",
642                        publication.session.0, publication.branch, session.branch
643                    ),
644                });
645            }
646        }
647        Ok(())
648    }
649
650    /// Every field an older readable document could hold means here what it meant
651    /// there, and the two the repository side gained in version 4 are absent from one
652    /// written before them — which is the answer, since that build held no hold and
653    /// counted no lines.
654    ///
655    /// Version 5's field is the exception, and it is carried rather than left at its
656    /// default: a document written before it *listed preserved work nobody had
657    /// published*, which is the `no` this build spells out. Left at the default it
658    /// would read as "nothing here can say", and a consumer's checked-in scenario
659    /// would start reporting work it had always called unpublished as work that may
660    /// have landed.
661    fn carry_forward(&mut self) {
662        if self.version < 5 {
663            for row in &mut self.preserved {
664                row.landed = Landed::No;
665            }
666        }
667        self.version = STATE_VERSION;
668    }
669}
670
671/// Refuse a record kept about a change request this state does not hold.
672fn opened_change(state: &HostState, id: &ChangeId, what: &str) -> Result<()> {
673    if state.changes.iter().any(|change| change.id == *id) {
674        return Ok(());
675    }
676    Err(Error::Invalid {
677        reason: format!(
678            "{what} is recorded for change request {:?}, but no change request by that \
679             identifier was opened",
680            id.0
681        ),
682    })
683}
684
685/// Refuse an identity key this provider was not seeded with.
686fn known_identity(state: &VcsState, origin: &str, what: &str) -> Result<()> {
687    if state
688        .identities
689        .iter()
690        .any(|identity| identity.origin == origin)
691    {
692        return Ok(());
693    }
694    Err(Error::Invalid {
695        reason: format!(
696            "{what} belongs to identity {origin:?}, which this provider does not know; {}",
697            known(state)
698        ),
699    })
700}
701
702/// A change request's title, refused when it names nothing.
703///
704/// The one thing a real host refuses about a title, and the only one this provider
705/// may: how long a title may be is the host's own rule rather than `onevcs`'s
706/// commit-subject rule, and a provider applying the stricter of the two would
707/// refuse what the host it stands in for accepts.
708pub(crate) fn titled(title: &str) -> Result<()> {
709    if title.trim().is_empty() {
710        return Err(Error::Invalid {
711            reason: "a change request's title is blank, so it names no change".to_owned(),
712        });
713    }
714    Ok(())
715}
716
717/// The session a token names, refused when this state does not hold one.
718fn opened<'a>(state: &'a VcsState, token: &SessionToken, what: &str) -> Result<&'a Session> {
719    if !events::is_safe_name(&token.0) {
720        return Err(Error::Invalid {
721            reason: format!("{:?} is not a session token", token.0),
722        });
723    }
724    session_of(state, token).ok_or_else(|| Error::Invalid {
725        reason: format!(
726            "session {:?} is {what} here, but no session by that token was opened",
727            token.0
728        ),
729    })
730}
731
732/// A seeded host side is refused if it holds a change nothing could address.
733impl Checked for HostState {
734    fn check(&self) -> Result<()> {
735        readable_version(self.version)?;
736        for change in &self.changes {
737            named_branch(&change.base, "the base of a seeded change request")?;
738            if change.id.0.is_empty() {
739                return Err(Error::Invalid {
740                    reason: "a seeded change request carries no identifier".to_owned(),
741                });
742            }
743            // The commit a change request's checks are reported against is the whole
744            // evidence that a change reached anything, and the real implementation
745            // refuses a host answer that names none rather than passing a blank one
746            // through. A seeded one is refused for the same reason.
747            if change.head_sha.0.trim().is_empty() {
748                return Err(Error::Invalid {
749                    reason: format!(
750                        "the seeded change request {:?} names no commit its checks are \
751                         reported against",
752                        change.id.0
753                    ),
754                });
755            }
756        }
757        // Both of these are recorded *about* a change request, by `open_change` and
758        // by nothing else, and both are read back by the id they are keyed under. An
759        // entry for a change nobody opened is one no call could ever reach, so it is
760        // refused rather than carried — unlike the checks, logs, and merge outcomes
761        // below it, which a journey deliberately seeds for a change it has not
762        // opened yet.
763        for (id, head) in &self.heads {
764            opened_change(self, id, "a head")?;
765            named_branch(head, "the head of a seeded change request")?;
766        }
767        for (id, title) in &self.titles {
768            opened_change(self, id, "a title")?;
769            // The real host refuses a title that names nothing, so a seeded one is
770            // refused for the same reason.
771            titled(title)?;
772        }
773        for id in self.bodies.keys() {
774            // Nothing is refused about the body itself: a host places no shape on
775            // prose, and a change request opened with an empty one is a scenario.
776            opened_change(self, id, "a body")?;
777        }
778        for (id, reason) in &self.drafts {
779            opened_change(self, id, "a draft reason")?;
780            // The publication rule the crate next door states, applied rather than
781            // restated: a seeded reason no publication could have carried is refused
782            // where the document is read, not answered from later.
783            reason.checked()?;
784        }
785        for id in &self.made_ready {
786            opened_change(self, id, "a lifted draft")?;
787        }
788        for described in &self.described {
789            opened_change(self, &described.id, "a description")?;
790            // The real host refuses a title that names nothing, so a seeded one is
791            // refused for the same reason — and a body is prose, refused for nothing.
792            if let Some(title) = &described.title {
793                titled(title)?;
794            }
795        }
796        Ok(())
797    }
798
799    /// A version 2 document held no bodies, and a version 5 document's checks named
800    /// no commit; each reads as what it was — change requests opened with none, and
801    /// checks whose head that build never recorded. There is nothing to fill in — an
802    /// absent field is already that answer, and a check's commit is the one thing
803    /// that must never be inferred — so this is the version and nothing else. The one
804    /// carry a version 8 document needs, the `kind` its draft reasons lack, is done
805    /// where those are read (`drafts_of_any_version`), because it is a fact about
806    /// one value's shape rather than about the document.
807    fn carry_forward(&mut self) {
808        self.version = STATE_VERSION;
809    }
810}
811
812/// Refuse a document written at a version this build does not read.
813///
814/// Named rather than guessed at: a state whose shape is a later build's reads one
815/// way here and another way where that version is understood, and for a seeded
816/// scenario those two readings are two different tests. The refusal names the
817/// range as well as the version, because "too old" and "too new" are two different
818/// things to do about it — one is a document to re-seed, the other a build to
819/// update.
820fn readable_version(declared: u32) -> Result<()> {
821    if !(OLDEST_READABLE_VERSION..=STATE_VERSION).contains(&declared) {
822        return Err(Error::Invalid {
823            reason: format!(
824                "the document declares version {declared}; this build reads versions \
825                 {OLDEST_READABLE_VERSION} to {STATE_VERSION}"
826            ),
827        });
828    }
829    Ok(())
830}