| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Syncing an account's GitHub repositories to the hub (section 23), and |
| 5 | //! granting the hub the GitHub access it needs for that (section 2). |
| 6 | //! |
| 7 | //! An account grants access to its private and public repositories |
| 8 | //! ([`SCOPE_PRIVATE`]) or to its public ones only ([`SCOPE_PUBLIC`]), in a |
| 9 | //! browser or with a device flow run through the hub. The hub then lists |
| 10 | //! the repositories the account owns on GitHub, each with what it would |
| 11 | //! become here ([`GithubRepos`]), and imports those asked for in a batch of |
| 12 | //! jobs ([`SyncRequest`], [`SyncStarted`], [`SyncBatch`]), each kept as a |
| 13 | //! mirror that follows GitHub. Times are RFC 3339, in UTC. |
| 14 | |
| 15 | use std::collections::BTreeMap; |
| 16 | |
| 17 | use serde::{Deserialize, Serialize}; |
| 18 | |
| 19 | /// The grant of access to the account's private and public repositories: |
| 20 | /// GitHub's `repo` scope. |
| 21 | pub const SCOPE_PRIVATE: &str = "private"; |
| 22 | |
| 23 | /// The grant of access to the account's public repositories only: |
| 24 | /// GitHub's `public_repo` scope. |
| 25 | pub const SCOPE_PUBLIC: &str = "public"; |
| 26 | |
| 27 | /// A mirror that takes in what is pushed to GitHub by fast-forwarding, or |
| 28 | /// by merging when both sides moved: the default of a sync. |
| 29 | pub const FOLLOW_MERGE: &str = "merge"; |
| 30 | |
| 31 | /// A mirror that takes in what is pushed to GitHub only by fast-forwarding. |
| 32 | pub const FOLLOW_FF_ONLY: &str = "ff-only"; |
| 33 | |
| 34 | /// A mirror the hub only publishes to. |
| 35 | pub const FOLLOW_OFF: &str = "off"; |
| 36 | |
| 37 | /// Why a repository is not imported: the account has no room left for it, |
| 38 | /// in repositories or in bytes. |
| 39 | pub const REASON_QUOTA: &str = "quota"; |
| 40 | |
| 41 | /// Why a repository is not imported: its name is taken here. A retry with |
| 42 | /// another name imports it. |
| 43 | pub const REASON_NAME_TAKEN: &str = "name taken"; |
| 44 | |
| 45 | /// Why a repository is not imported: its name cannot name a repository |
| 46 | /// here. A retry with another name imports it. |
| 47 | pub const REASON_NAME_NOT_ALLOWED: &str = "name not allowed here"; |
| 48 | |
| 49 | /// Why a repository is not imported: a repository here is its mirror |
| 50 | /// already. |
| 51 | pub const REASON_SYNCED: &str = "already synced"; |
| 52 | |
| 53 | /// Why a repository is not imported: it is not one the account owns on |
| 54 | /// GitHub, or not one the access it granted shows. |
| 55 | pub const REASON_NOT_FOUND: &str = "not found"; |
| 56 | |
| 57 | /// A batch whose imports are still under way. |
| 58 | pub const BATCH_RUNNING: &str = "running"; |
| 59 | |
| 60 | /// A batch whose imports all ended. |
| 61 | pub const BATCH_DONE: &str = "done"; |
| 62 | |
| 63 | /// A batch whose imports not started yet were cancelled, and whose others |
| 64 | /// ended. |
| 65 | pub const BATCH_CANCELLED: &str = "cancelled"; |
| 66 | |
| 67 | fn yes() -> bool { |
| 68 | true |
| 69 | } |
| 70 | |
| 71 | fn merge() -> String { |
| 72 | FOLLOW_MERGE.to_owned() |
| 73 | } |
| 74 | |
| 75 | /// `POST /v1/github/access/device`: the access to grant. |
| 76 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 77 | pub struct GrantStart { |
| 78 | /// [`SCOPE_PRIVATE`] or [`SCOPE_PUBLIC`]. |
| 79 | pub scope: String, |
| 80 | } |
| 81 | |
| 82 | /// `POST /v1/github/access/device/poll`: the flow to ask about. |
| 83 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 84 | pub struct GrantPollRequest { |
| 85 | /// What `POST /v1/github/access/device` answered in `poll`. |
| 86 | pub poll: String, |
| 87 | } |
| 88 | |
| 89 | /// The answer of `POST /v1/github/access/device/poll`. |
| 90 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 91 | #[serde(tag = "status", rename_all = "snake_case")] |
| 92 | pub enum GrantPoll { |
| 93 | /// The person has not approved yet. |
| 94 | Pending, |
| 95 | /// Poll less often. |
| 96 | SlowDown { |
| 97 | /// The new interval, in seconds. |
| 98 | interval: u64, |
| 99 | }, |
| 100 | /// The person refused. |
| 101 | Denied, |
| 102 | /// The code expired, or the flow is not known. |
| 103 | Expired, |
| 104 | /// Granted. |
| 105 | Ok { |
| 106 | /// The account. |
| 107 | login: String, |
| 108 | /// The scopes GitHub granted, as it writes them: `repo` or |
| 109 | /// `public_repo`. |
| 110 | scope: String, |
| 111 | }, |
| 112 | } |
| 113 | |
| 114 | /// What the account has room for, as its quotas count it: what it owns |
| 115 | /// and what its jobs are making already. |
| 116 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 117 | pub struct Room { |
| 118 | /// Repositories it may still own. |
| 119 | pub repos_left: u64, |
| 120 | /// Bytes its repositories may still store. |
| 121 | pub bytes_left: u64, |
| 122 | } |
| 123 | |
| 124 | /// A repository the account owns on GitHub, as `GET /v1/github/repos` |
| 125 | /// lists it: what GitHub says of it, and what it would become here. |
| 126 | #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 127 | pub struct GithubRepo { |
| 128 | /// GitHub's id of it, which stays when it is renamed. |
| 129 | pub github_id: u64, |
| 130 | /// `owner/name` on GitHub. |
| 131 | pub full_name: String, |
| 132 | /// Whether it is private on GitHub. |
| 133 | pub private: bool, |
| 134 | /// Whether it is a fork on GitHub. |
| 135 | pub fork: bool, |
| 136 | /// Whether it is archived on GitHub: such a repository is imported |
| 137 | /// without a mirror. |
| 138 | pub archived: bool, |
| 139 | /// Whether it holds nothing yet: such a repository is made empty, with |
| 140 | /// its mirror set. |
| 141 | pub empty: bool, |
| 142 | /// Its size, as GitHub gives it, in KiB. |
| 143 | pub size_kb: u64, |
| 144 | /// Its default branch on GitHub. |
| 145 | #[serde(default)] |
| 146 | pub default_branch: Option<String>, |
| 147 | /// When something was last pushed to it. |
| 148 | #[serde(default)] |
| 149 | pub pushed_at: Option<String>, |
| 150 | /// Whether the account administers it, as a webhook needs. |
| 151 | pub admin: bool, |
| 152 | /// The name it takes here. |
| 153 | pub hub_name: String, |
| 154 | /// The account's repository here that is its mirror already, as |
| 155 | /// `owner/name`, when there is one. |
| 156 | #[serde(default)] |
| 157 | pub synced: Option<String>, |
| 158 | /// Whether it may be imported. |
| 159 | pub eligible: bool, |
| 160 | /// Why it may not be imported, or what its import does differently. |
| 161 | #[serde(default)] |
| 162 | pub reason: Option<String>, |
| 163 | /// About how many bytes of the account's room it takes here: four |
| 164 | /// times its size on GitHub. |
| 165 | pub estimate_bytes: u64, |
| 166 | } |
| 167 | |
| 168 | /// `GET /v1/github/repos`: the repositories the account owns on GitHub, |
| 169 | /// most recently pushed first. |
| 170 | #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 171 | pub struct GithubRepos { |
| 172 | /// The access the account granted: [`SCOPE_PRIVATE`] or |
| 173 | /// [`SCOPE_PUBLIC`]. With the second, private repositories are not |
| 174 | /// listed. |
| 175 | pub scope: String, |
| 176 | /// The repositories. |
| 177 | pub repos: Vec<GithubRepo>, |
| 178 | /// Whether GitHub had more than the hub lists. |
| 179 | pub truncated: bool, |
| 180 | /// What the account has room for. |
| 181 | pub quota: Room, |
| 182 | } |
| 183 | |
| 184 | /// A repository named in a [`SyncRequest`]: GitHub's id of it, or its |
| 185 | /// `owner/name` on GitHub. |
| 186 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 187 | #[serde(untagged)] |
| 188 | pub enum RepoPick { |
| 189 | /// GitHub's id. |
| 190 | Id(u64), |
| 191 | /// `owner/name` on GitHub. |
| 192 | Name(String), |
| 193 | } |
| 194 | |
| 195 | /// `POST /v1/github/sync`: what to import, and how. |
| 196 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 197 | pub struct SyncRequest { |
| 198 | /// Every repository that may be imported, most recently pushed first, |
| 199 | /// as many as the account has room for. |
| 200 | #[serde(default)] |
| 201 | pub all: bool, |
| 202 | /// The repositories to import, when not `all`. |
| 203 | #[serde(default)] |
| 204 | pub repos: Vec<RepoPick>, |
| 205 | /// The names some take here, other than their own: by GitHub's id, in |
| 206 | /// decimal, or by `owner/name` on GitHub. |
| 207 | #[serde(default)] |
| 208 | pub names: BTreeMap<String, String>, |
| 209 | /// Whether public repositories stay public here; `false` imports them |
| 210 | /// all as private. Private ones stay private either way. |
| 211 | #[serde(default = "yes")] |
| 212 | pub keep_public: bool, |
| 213 | /// Whether text and data mining of the imported repositories is |
| 214 | /// reserved; otherwise they take the account's default. |
| 215 | #[serde(default)] |
| 216 | pub reserve_tdm: bool, |
| 217 | /// How each mirror takes in what is pushed to GitHub: |
| 218 | /// [`FOLLOW_MERGE`], [`FOLLOW_FF_ONLY`] or [`FOLLOW_OFF`]. |
| 219 | #[serde(default = "merge")] |
| 220 | pub follow: String, |
| 221 | } |
| 222 | |
| 223 | impl Default for SyncRequest { |
| 224 | fn default() -> Self { |
| 225 | SyncRequest { |
| 226 | all: false, |
| 227 | repos: Vec::new(), |
| 228 | names: BTreeMap::new(), |
| 229 | keep_public: true, |
| 230 | reserve_tdm: false, |
| 231 | follow: merge(), |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | /// A repository a batch queued for import. |
| 237 | #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 238 | pub struct Queued { |
| 239 | /// GitHub's id of it. |
| 240 | pub github_id: u64, |
| 241 | /// `owner/name` on GitHub. |
| 242 | pub full_name: String, |
| 243 | /// The name it takes here. |
| 244 | pub hub_name: String, |
| 245 | /// The job that imports it. |
| 246 | pub job: String, |
| 247 | } |
| 248 | |
| 249 | /// A repository a batch did not queue, and why. |
| 250 | #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 251 | pub struct Skipped { |
| 252 | /// GitHub's id of it, 0 when it named none the account owns. |
| 253 | pub github_id: u64, |
| 254 | /// `owner/name` on GitHub, as listed or as asked for. |
| 255 | pub full_name: String, |
| 256 | /// Why: [`REASON_QUOTA`], [`REASON_NAME_TAKEN`], |
| 257 | /// [`REASON_NAME_NOT_ALLOWED`], [`REASON_SYNCED`] or |
| 258 | /// [`REASON_NOT_FOUND`]. |
| 259 | pub reason: String, |
| 260 | } |
| 261 | |
| 262 | /// The answer of `POST /v1/github/sync` (202) and of a retry: the batch, |
| 263 | /// what it queued and what it did not. |
| 264 | #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 265 | pub struct SyncStarted { |
| 266 | /// The batch's id: `b_` and 26 characters of `a-z 2-7`. |
| 267 | pub batch: String, |
| 268 | /// The repositories queued, each with its job. |
| 269 | pub queued: Vec<Queued>, |
| 270 | /// The repositories not queued, each with why. |
| 271 | pub skipped: Vec<Skipped>, |
| 272 | } |
| 273 | |
| 274 | /// How many repositories of a batch are in each state. |
| 275 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 276 | pub struct BatchCounts { |
| 277 | /// Waiting for their turn. |
| 278 | pub queued: u64, |
| 279 | /// Being imported. |
| 280 | pub running: u64, |
| 281 | /// Waiting for GitHub to let the hub go on. |
| 282 | pub waiting: u64, |
| 283 | /// Imported. |
| 284 | pub done: u64, |
| 285 | /// Not imported: `error` says why. |
| 286 | pub failed: u64, |
| 287 | /// Cancelled before their import started. |
| 288 | pub cancelled: u64, |
| 289 | /// Not queued: `error` says why. |
| 290 | pub skipped: u64, |
| 291 | } |
| 292 | |
| 293 | /// One repository of a batch, and how its import stands. |
| 294 | #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 295 | pub struct BatchItem { |
| 296 | /// GitHub's id of it. |
| 297 | pub github_id: u64, |
| 298 | /// `owner/name` on GitHub. |
| 299 | pub full_name: String, |
| 300 | /// The name it takes here. |
| 301 | pub hub_name: String, |
| 302 | /// `queued`, `running`, `waiting`, `done`, `failed`, `cancelled` or |
| 303 | /// `skipped`. |
| 304 | pub state: String, |
| 305 | /// Why it failed, or was skipped. |
| 306 | #[serde(default)] |
| 307 | pub error: Option<String>, |
| 308 | /// The job that imports it, the last one when it was retried. |
| 309 | #[serde(default)] |
| 310 | pub job: Option<String>, |
| 311 | } |
| 312 | |
| 313 | /// `GET /v1/github/sync`: a batch, and how each of its repositories |
| 314 | /// stands. |
| 315 | #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 316 | pub struct SyncBatch { |
| 317 | /// The batch's id. |
| 318 | pub batch: String, |
| 319 | /// [`BATCH_RUNNING`], [`BATCH_DONE`] or [`BATCH_CANCELLED`]. |
| 320 | pub state: String, |
| 321 | /// How many of its repositories are in each state. |
| 322 | pub counts: BatchCounts, |
| 323 | /// Its repositories, in the order it took them. |
| 324 | pub repos: Vec<BatchItem>, |
| 325 | } |
| 326 | |
| 327 | impl SyncBatch { |
| 328 | /// Whether every repository of it ended, and none failed or was |
| 329 | /// skipped. |
| 330 | pub fn all_done(&self) -> bool { |
| 331 | self.state != BATCH_RUNNING |
| 332 | && self.counts.failed == 0 |
| 333 | && self.counts.skipped == 0 |
| 334 | && self.counts.cancelled == 0 |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | /// `POST /v1/github/sync/{batch}/retry`: a repository of the batch that |
| 339 | /// failed or was skipped, to import again, under another name if given. |
| 340 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 341 | pub struct RetryRequest { |
| 342 | /// GitHub's id of it. |
| 343 | pub github_id: u64, |
| 344 | /// The name it takes here this time. |
| 345 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 346 | pub name: Option<String>, |
| 347 | } |
| 348 | |
| 349 | #[cfg(test)] |
| 350 | mod tests { |
| 351 | use super::*; |
| 352 | |
| 353 | #[test] |
| 354 | fn sync_requests_take_their_defaults() { |
| 355 | let empty: SyncRequest = serde_json::from_str("{}").unwrap(); |
| 356 | assert_eq!(empty, SyncRequest::default()); |
| 357 | assert!(empty.keep_public && !empty.reserve_tdm && !empty.all); |
| 358 | assert_eq!(empty.follow, FOLLOW_MERGE); |
| 359 | let picked: SyncRequest = serde_json::from_str( |
| 360 | r#"{"repos": [7001, "ada/demo"], "names": {"7001": "other"}, "keep_public": false}"#, |
| 361 | ) |
| 362 | .unwrap(); |
| 363 | assert_eq!( |
| 364 | picked.repos, |
| 365 | [RepoPick::Id(7001), RepoPick::Name("ada/demo".into())] |
| 366 | ); |
| 367 | assert_eq!(picked.names["7001"], "other"); |
| 368 | assert!(!picked.keep_public); |
| 369 | } |
| 370 | |
| 371 | #[test] |
| 372 | fn grants_and_batches_on_the_wire() { |
| 373 | let ok = GrantPoll::Ok { |
| 374 | login: "ada".into(), |
| 375 | scope: "repo".into(), |
| 376 | }; |
| 377 | let text = serde_json::to_string(&ok).unwrap(); |
| 378 | assert_eq!(text, r#"{"status":"ok","login":"ada","scope":"repo"}"#); |
| 379 | assert_eq!(serde_json::from_str::<GrantPoll>(&text).unwrap(), ok); |
| 380 | let slow: GrantPoll = |
| 381 | serde_json::from_str(r#"{"status":"slow_down","interval":10}"#).unwrap(); |
| 382 | assert_eq!(slow, GrantPoll::SlowDown { interval: 10 }); |
| 383 | let batch = SyncBatch { |
| 384 | batch: "b_aaaaaaaaaaaaaaaaaaaaaaaaaa".into(), |
| 385 | state: BATCH_DONE.into(), |
| 386 | counts: BatchCounts { |
| 387 | done: 2, |
| 388 | ..BatchCounts::default() |
| 389 | }, |
| 390 | repos: vec![BatchItem { |
| 391 | github_id: 7, |
| 392 | full_name: "ada/demo".into(), |
| 393 | hub_name: "demo".into(), |
| 394 | state: "done".into(), |
| 395 | error: None, |
| 396 | job: Some("j_aaaaaaaaaaaaaaaaaaaaaaaaaa".into()), |
| 397 | }], |
| 398 | }; |
| 399 | let text = serde_json::to_string(&batch).unwrap(); |
| 400 | assert_eq!(serde_json::from_str::<SyncBatch>(&text).unwrap(), batch); |
| 401 | assert!(batch.all_done()); |
| 402 | let skipped = SyncBatch { |
| 403 | counts: BatchCounts { |
| 404 | skipped: 1, |
| 405 | ..batch.counts |
| 406 | }, |
| 407 | ..batch.clone() |
| 408 | }; |
| 409 | assert!(!skipped.all_done()); |
| 410 | let running = SyncBatch { |
| 411 | state: BATCH_RUNNING.into(), |
| 412 | ..batch |
| 413 | }; |
| 414 | assert!(!running.all_done()); |
| 415 | // A short listing, from a hub that says less, still reads. |
| 416 | let repo: GithubRepo = serde_json::from_str( |
| 417 | r#"{"github_id": 1, "full_name": "ada/x", "private": false, "fork": false, |
| 418 | "archived": false, "empty": false, "size_kb": 3, "admin": true, |
| 419 | "hub_name": "x", "eligible": true, "estimate_bytes": 12288}"#, |
| 420 | ) |
| 421 | .unwrap(); |
| 422 | assert_eq!((repo.synced, repo.reason), (None, None)); |
| 423 | } |
| 424 | } |