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