Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 7.9 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Forks, jobs and syncing a fork with its upstream (section 20).
5//!
6//! A fork is made by a job: `POST …/forks` answers at once with the job,
7//! and the fork appears whole once the job is done. The list of a
8//! repository's forks is a [`RepoCards`](crate::cards::RepoCards). Ids are
9//! 64 lowercase hex digits; times are RFC 3339, in UTC.
10
11use braid_format::ObjectId;
12use serde::{Deserialize, Serialize};
13
14use crate::cards::RepoRef;
15use crate::hex;
16
17/// A job that makes a fork.
18pub const FORK: &str = "fork";
19
20/// A job that imports a repository from GitHub.
21pub const IMPORT: &str = "import";
22
23/// A job waiting for its turn.
24pub const QUEUED: &str = "queued";
25
26/// A job under way.
27pub const RUNNING: &str = "running";
28
29/// A job that waits for something outside the hub, such as GitHub's rate
30/// limit, before it goes on.
31pub const WAITING: &str = "waiting";
32
33/// A job that did what it was asked.
34pub const DONE: &str = "done";
35
36/// A job that could not do it: `error` says why.
37pub const FAILED: &str = "failed";
38
39/// A job cancelled before it started.
40pub const CANCELLED: &str = "cancelled";
41
42/// A job that had nothing to do: `error` says why.
43pub const SKIPPED: &str = "skipped";
44
45/// Whether a job in `state` has ended, and will not change again.
46pub fn is_finished(state: &str) -> bool {
47 matches!(state, DONE | FAILED | CANCELLED | SKIPPED)
48}
49
50/// A sync that moved the fork's ref to the upstream's head.
51pub const FAST_FORWARD: &str = "fast-forward";
52
53/// A sync that found nothing to bring: the fork has all the upstream has.
54pub const UP_TO_DATE: &str = "up-to-date";
55
56/// A sync that moved nothing: the fork and the upstream each have work the
57/// other has not.
58pub const DIVERGED: &str = "diverged";
59
60/// `POST …/forks`: the fork to make. Both fields are optional: the fork
61/// takes the name and the visibility of the repository it forks.
62#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
63pub struct ForkRequest {
64 /// The fork's name in the caller's account.
65 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub name: Option<String>,
67 /// Whether only those given access can read it. A fork of a private
68 /// repository is private.
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub private: Option<bool>,
71}
72
73/// How far a job got.
74#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
75pub struct JobProgress {
76 /// Objects copied so far.
77 pub objects: u64,
78 /// Bytes copied so far.
79 pub bytes: u64,
80}
81
82/// A job: `GET /v1/jobs/{id}`, and the lists of jobs.
83#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
84pub struct Job {
85 /// Its id: `j_` and 26 characters of `a-z 2-7`.
86 pub id: String,
87 /// What it does: `fork` or `import`.
88 pub kind: String,
89 /// `queued`, `running`, `waiting`, `done`, `failed`, `cancelled` or
90 /// `skipped`.
91 pub state: String,
92 /// How far it got.
93 #[serde(default)]
94 pub progress: JobProgress,
95 /// The repository it makes, `owner/name`.
96 #[serde(default)]
97 pub repo: Option<String>,
98 /// Why it failed, or was skipped.
99 #[serde(default)]
100 pub error: Option<String>,
101 /// When it was asked for.
102 pub created: String,
103 /// When it last started.
104 #[serde(default)]
105 pub started: Option<String>,
106 /// When it ended.
107 #[serde(default)]
108 pub finished: Option<String>,
109}
110
111impl Job {
112 /// Whether it has ended, and will not change again.
113 pub fn is_finished(&self) -> bool {
114 is_finished(&self.state)
115 }
116}
117
118/// `GET /v1/jobs`: a page of the account's jobs, newest first.
119#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
120pub struct Jobs {
121 /// The jobs.
122 pub jobs: Vec<Job>,
123 /// The cursor of the next page, or `None` on the last one.
124 #[serde(default)]
125 pub next: Option<String>,
126}
127
128/// The answer of `POST …/forks` (202): the job that makes the fork, and
129/// where the fork will be.
130#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
131pub struct ForkStarted {
132 /// The job.
133 pub job: Job,
134 /// The fork it makes.
135 pub repo: RepoRef,
136}
137
138/// `POST …/sync-upstream`: which ref to bring up to date.
139#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
140pub struct SyncUpstream {
141 /// The ref, a branch or a tag; the fork's default branch when left
142 /// out. The upstream's ref of the same name is the one brought in.
143 #[serde(default, rename = "ref", skip_serializing_if = "Option::is_none")]
144 pub reference: Option<String>,
145}
146
147/// The answer of `POST …/sync-upstream`.
148#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
149pub struct SyncedUpstream {
150 /// The ref.
151 #[serde(rename = "ref")]
152 pub reference: String,
153 /// `fast-forward`, `up-to-date` or `diverged`.
154 pub outcome: String,
155 /// The fork's head before, `None` when the fork lacked the ref.
156 #[serde(with = "hex::opt_id")]
157 pub head_before: Option<ObjectId>,
158 /// Its head after: the upstream's after a fast-forward, the one before
159 /// otherwise.
160 #[serde(with = "hex::opt_id")]
161 pub head: Option<ObjectId>,
162 /// How many changesets of the upstream's ref the fork still lacks
163 /// after the sync, counted up to [`BEHIND_MOST`]: 0 unless it
164 /// diverged.
165 pub behind: u64,
166 /// Whether there are more than [`BEHIND_MOST`], which `behind` then
167 /// holds.
168 #[serde(default)]
169 pub more: bool,
170}
171
172/// The most changesets a fork is counted behind its upstream.
173pub const BEHIND_MOST: u64 = 1_000;
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178
179 #[test]
180 fn forks_and_jobs_on_the_wire() {
181 // A request that names nothing takes the source's name and
182 // visibility.
183 let empty: ForkRequest = serde_json::from_str("{}").unwrap();
184 assert_eq!(empty, ForkRequest::default());
185 assert_eq!(serde_json::to_string(&empty).unwrap(), "{}");
186 let job = Job {
187 id: "j_aaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
188 kind: FORK.into(),
189 state: QUEUED.into(),
190 repo: Some("bob/demo".into()),
191 created: "2026-01-01T00:00:00Z".into(),
192 ..Job::default()
193 };
194 let started = ForkStarted {
195 job: job.clone(),
196 repo: RepoRef {
197 owner: "bob".into(),
198 name: "demo".into(),
199 },
200 };
201 let text = serde_json::to_string(&started).unwrap();
202 assert_eq!(serde_json::from_str::<ForkStarted>(&text).unwrap(), started);
203 assert!(!job.is_finished());
204 for state in [DONE, FAILED, CANCELLED, SKIPPED] {
205 assert!(is_finished(state), "{state}");
206 }
207 for state in [QUEUED, RUNNING, WAITING, "other"] {
208 assert!(!is_finished(state), "{state}");
209 }
210 // A short job, from a hub that says less, still reads.
211 let short: Job =
212 serde_json::from_str(r#"{"id":"j_x","kind":"fork","state":"done","created":"t"}"#)
213 .unwrap();
214 assert_eq!((short.progress, short.repo), (JobProgress::default(), None));
215 }
216
217 #[test]
218 fn syncs_on_the_wire() {
219 let asked: SyncUpstream = serde_json::from_str(r#"{"ref":"main"}"#).unwrap();
220 assert_eq!(asked.reference.as_deref(), Some("main"));
221 assert_eq!(
222 serde_json::to_string(&SyncUpstream::default()).unwrap(),
223 "{}"
224 );
225 let head = ObjectId::hash(braid_format::Kind::Blob, b"x");
226 let synced = SyncedUpstream {
227 reference: "main".into(),
228 outcome: FAST_FORWARD.into(),
229 head_before: None,
230 head: Some(head),
231 behind: 0,
232 more: false,
233 };
234 let text = serde_json::to_string(&synced).unwrap();
235 assert!(text.contains(r#""ref":"main""#) && text.contains(r#""head_before":null"#));
236 assert_eq!(
237 serde_json::from_str::<SyncedUpstream>(&text).unwrap(),
238 synced
239 );
240 }
241}