Forge-core, forge-ci, forge-git and forge-ssh drop dead code, duplicated helpers and redundant tests
Browse files at this commite587be7353fd690b22151a17ef1ff50751fd0ebaParent: 490f099- refactor
- forge-core, forge-ci, forge-git and forge-ssh drop dead code, duplicated helpers and redundant tests
- fixes: streaming log masker no longer leaks a secret whose prefix is another secret, milestone update stores title and folded title the right way round, milestone counts skip pulls, key file is written to a temp file then linked so a crash cannot leave a truncated key, and other verified store fixes
121 changed files +1752 -4049
- crates/forge-ci/src/config.rs +16 -21
- crates/forge-ci/src/error.rs +3 -0
- crates/forge-ci/src/mask.rs +18 -31
- crates/forge-ci/src/steps.rs +25 -8
- crates/forge-core/src/advisories.rs +0 -2
- crates/forge-core/src/alerts.rs +0 -26
- crates/forge-core/src/audit.rs +126 -331
- crates/forge-core/src/authz.rs +1 -14
- crates/forge-core/src/cargo.rs +3 -2
- crates/forge-core/src/ci.rs +18 -36
- crates/forge-core/src/config.rs +20 -22
- crates/forge-core/src/issue_refs.rs +14 -19
- crates/forge-core/src/lib.rs +1 -2
- crates/forge-core/src/mail.rs +0 -55
- crates/forge-core/src/merge_queue.rs +0 -8
- crates/forge-core/src/model.rs +1 -1
- crates/forge-core/src/names.rs +0 -4
- crates/forge-core/src/notifications.rs +2 -2
- crates/forge-core/src/protection.rs +27 -50
- crates/forge-core/src/reactions.rs +0 -9
- crates/forge-core/src/secret.rs +12 -10
- crates/forge-core/src/server_settings.rs +3 -65
- crates/forge-core/src/session.rs +0 -32
- crates/forge-core/src/store/account_tokens.rs +7 -6
- crates/forge-core/src/store/admin_alerts.rs +2 -6
- crates/forge-core/src/store/advisories.rs +10 -23
- crates/forge-core/src/store/audit.rs +1 -10
- crates/forge-core/src/store/backup_runs.rs +8 -25
- crates/forge-core/src/store/ci.rs +151 -238
- crates/forge-core/src/store/contributions.rs +36 -54
- crates/forge-core/src/store/discussions.rs +56 -48
- crates/forge-core/src/store/edit_history_read.rs +29 -17
- crates/forge-core/src/store/health.rs +3 -4
- crates/forge-core/src/store/imports.rs +7 -7
- crates/forge-core/src/store/issues.rs +17 -125
- crates/forge-core/src/store/labels.rs +19 -56
- crates/forge-core/src/store/mail.rs +22 -29
- crates/forge-core/src/store/merge_queue.rs +1 -16
- crates/forge-core/src/store/migrate.rs +34 -137
- crates/forge-core/src/store/mirrors.rs +13 -69
- crates/forge-core/src/store/mod.rs +121 -254
- crates/forge-core/src/store/notifications.rs +55 -217
- crates/forge-core/src/store/oci.rs +5 -14
- crates/forge-core/src/store/orgs.rs +1 -14
- crates/forge-core/src/store/passkeys.rs +17 -28
- crates/forge-core/src/store/pulls.rs +28 -128
- crates/forge-core/src/store/pulls_list_extra.rs +11 -18
- crates/forge-core/src/store/push_recent.rs +6 -6
- crates/forge-core/src/store/reactions.rs +3 -7
- crates/forge-core/src/store/repo_listing.rs +36 -43
- crates/forge-core/src/store/review_requests.rs +17 -26
- crates/forge-core/src/store/reviews.rs +6 -34
- crates/forge-core/src/store/server_settings.rs +16 -15
- crates/forge-core/src/store/snapshot.rs +11 -12
- crates/forge-core/src/store/suggest.rs +15 -35
- crates/forge-core/src/store/suspension.rs +17 -27
- crates/forge-core/src/store/transfers.rs +1 -1
- crates/forge-core/src/store/ui_prefs.rs +44 -77
- crates/forge-core/src/store/user_delete.rs +17 -40
- crates/forge-core/src/store/web_push.rs +2 -2
- crates/forge-core/src/store/webhooks.rs +63 -94
- crates/forge-core/src/suggestions.rs +2 -1
- crates/forge-core/src/time.rs +1 -7
- crates/forge-core/src/token.rs +5 -1
- crates/forge-core/tests/integration/audit_store.rs +0 -1
- crates/forge-core/tests/integration/main.rs +0 -2
- crates/forge-core/tests/integration/read_pool.rs +0 -149
- crates/forge-core/tests/integration/stars_store.rs +4 -14
- crates/forge-core/tests/integration/store_basic.rs +4 -20
- crates/forge-git/src/backup.rs +8 -14
- crates/forge-git/src/blame.rs +1 -3
- crates/forge-git/src/branches.rs +1 -5
- crates/forge-git/src/browse.rs +15 -10
- crates/forge-git/src/command.rs +9 -6
- crates/forge-git/src/history.rs +7 -80
- crates/forge-git/src/mirror.rs +3 -1
- crates/forge-git/src/pulls.rs +23 -139
- crates/forge-git/src/seed.rs +2 -1
- crates/forge-git/src/tags.rs +5 -5
- crates/forge-git/src/trailers.rs +9 -19
- crates/forge-git/src/verify.rs +2 -11
- crates/forge-git/src/version.rs +2 -2
- crates/forge-git/src/wiki.rs +16 -9
- crates/forge-git/tests/integration/browse.rs +0 -2
- crates/forge-git/tests/integration/browse_tools.rs +9 -81
- crates/forge-git/tests/integration/common.rs +66 -0
- crates/forge-git/tests/integration/forge_git.rs +11 -13
- crates/forge-git/tests/integration/history.rs +11 -83
- crates/forge-git/tests/integration/main.rs +0 -1
- crates/forge-ssh/src/backend.rs +4 -5
- crates/forge-ssh/src/lib.rs +5 -5
- crates/forge-ssh/src/parse.rs +22 -19
- crates/forge-ssh/src/server.rs +30 -77
- crates/forge-ssh/tests/ssh_e2e.rs +7 -8
- crates/forge-web-account/src/pages/banner.rs +7 -9
- crates/forge-web-account/src/pages/passkeys.rs +1 -2
- crates/forge-web-app/src/auth.rs +4 -5
- crates/forge-web-app/src/backup/create.rs +16 -19
- crates/forge-web-app/src/ci/api.rs +7 -8
- crates/forge-web-app/src/ci/api_tests.rs +51 -103
- crates/forge-web-app/src/ci/schedule.rs +11 -9
- crates/forge-web-app/src/exporter.rs +1 -2
- crates/forge-web-app/src/mail/worker.rs +8 -8
- crates/forge-web-app/src/merge.rs +2 -2
- crates/forge-web-app/src/release_ops.rs +26 -38
- crates/forge-web-app/src/replication/mod.rs +1 -69
- crates/forge-web-app/src/ssh_backend.rs +13 -19
- crates/forge-web-base/src/accent.rs +1 -1
- crates/forge-web-pages/src/pages/ci_fail.rs +2 -1
- crates/forge-web-pages/src/pages/ci_job.rs +2 -1
- crates/forge-web-pages/src/pages/ci_runs.rs +1 -32
- crates/forge-web-pages/src/pages/edit_history.rs +15 -25
- crates/forge-web-pages/src/pages/issue_parts.rs +13 -24
- crates/forge-web-pages/src/pages/notifications.rs +11 -7
- crates/forge-web-pages/src/pages/repo.rs +2 -34
- crates/forge-web-repo/src/pages/authoring_tests.rs +2 -2
- crates/forge-web-repo/src/pages/branches.rs +3 -2
- crates/forge-web-repo/src/pages/ci_tests.rs +48 -77
- crates/forge-web-repo/src/pages/pulls_merge.rs +3 -3
- crates/forge-web/src/boot.rs +2 -8
- crates/forge-web/src/page_route_tests/repo.rs +17 -33
crates/forge-ci/src/config.rsmodified+16 -21
| @@ -20,28 +20,28 @@ use serde::{Deserialize, Serialize}; | ||
| 20 | 20 | use crate::error::ConfigError; |
| 21 | 21 | |
| 22 | 22 | /// Largest accepted `ci.toml`, in bytes. |
| 23 | -pub const MAX_CONFIG_BYTES: usize = 64 * 1024; | |
| 23 | +const MAX_CONFIG_BYTES: usize = 64 * 1024; | |
| 24 | 24 | /// Largest number of jobs in one workflow. |
| 25 | -pub const MAX_JOBS: usize = 20; | |
| 25 | +const MAX_JOBS: usize = 20; | |
| 26 | 26 | /// Default job timeout. |
| 27 | -pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60; | |
| 27 | +const DEFAULT_TIMEOUT_MINUTES: u32 = 60; | |
| 28 | 28 | /// Smallest and largest allowed job timeout. |
| 29 | -pub const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive<u32> = 1..=360; | |
| 29 | +const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive<u32> = 1..=360; | |
| 30 | 30 | /// Longest workflow `name`, in characters, after trimming. |
| 31 | -pub const MAX_WORKFLOW_NAME_CHARS: usize = 40; | |
| 31 | +const MAX_WORKFLOW_NAME_CHARS: usize = 40; | |
| 32 | 32 | /// Largest number of `cache` entries in one job. |
| 33 | -pub const MAX_CACHE_ENTRIES: usize = 8; | |
| 33 | +const MAX_CACHE_ENTRIES: usize = 8; | |
| 34 | 34 | /// Longest `cache` entry, in characters. |
| 35 | -pub const MAX_CACHE_PATH_CHARS: usize = 200; | |
| 35 | +const MAX_CACHE_PATH_CHARS: usize = 200; | |
| 36 | 36 | /// Largest number of `[release] assets` entries. |
| 37 | -pub const MAX_RELEASE_ASSETS: usize = 32; | |
| 37 | +const MAX_RELEASE_ASSETS: usize = 32; | |
| 38 | 38 | /// Longest `[release] title` template, in characters, after trimming. |
| 39 | -pub const MAX_RELEASE_TITLE_CHARS: usize = 200; | |
| 39 | +const MAX_RELEASE_TITLE_CHARS: usize = 200; | |
| 40 | 40 | |
| 41 | 41 | /// Most `[on] schedule` entries. |
| 42 | -pub const MAX_SCHEDULES: usize = 8; | |
| 42 | +const MAX_SCHEDULES: usize = 8; | |
| 43 | 43 | /// Longest matrix axis value, in characters. |
| 44 | -pub const MAX_MATRIX_VALUE_CHARS: usize = 64; | |
| 44 | +const MAX_MATRIX_VALUE_CHARS: usize = 64; | |
| 45 | 45 | |
| 46 | 46 | /// A parsed and validated workflow. |
| 47 | 47 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| @@ -257,7 +257,7 @@ pub struct MatrixSpec { | ||
| 257 | 257 | } |
| 258 | 258 | |
| 259 | 259 | /// Smallest and largest `memory` a job may declare, in bytes. |
| 260 | -pub const MEMORY_RANGE_BYTES: std::ops::RangeInclusive<u64> = (64 << 20)..=(1024 << 30); | |
| 260 | +const MEMORY_RANGE_BYTES: std::ops::RangeInclusive<u64> = (64 << 20)..=(1024 << 30); | |
| 261 | 261 | |
| 262 | 262 | /// Reads `memory` as a size string (`"4g"`) or as a byte count (what the stored spec holds). |
| 263 | 263 | fn deserialize_memory<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> { |
| @@ -449,9 +449,9 @@ impl CiConfig { | ||
| 449 | 449 | validate_trigger_glob("tag", pattern)?; |
| 450 | 450 | } |
| 451 | 451 | if self.on.schedule.len() > MAX_SCHEDULES { |
| 452 | - return Err(ConfigError::InvalidSchedule { | |
| 453 | - expr: String::new(), | |
| 454 | - reason: format!("at most {MAX_SCHEDULES} schedules are allowed"), | |
| 452 | + return Err(ConfigError::TooManySchedules { | |
| 453 | + count: self.on.schedule.len(), | |
| 454 | + max: MAX_SCHEDULES, | |
| 455 | 455 | }); |
| 456 | 456 | } |
| 457 | 457 | for expr in &self.on.schedule { |
| @@ -746,11 +746,6 @@ fn validate_release_title(title: &str) -> Result<(), ConfigError> { | ||
| 746 | 746 | Ok(()) |
| 747 | 747 | } |
| 748 | 748 | |
| 749 | -/// The job name without its matrix suffix: `test (stable, x86_64)` gives `test`. | |
| 750 | -pub fn base_job_name(name: &str) -> &str { | |
| 751 | - name.split_once(" (").map_or(name, |(base, _)| base) | |
| 752 | -} | |
| 753 | - | |
| 754 | 749 | /// Whether `selected` (a job name from the config) names `job`: the job itself, or any |
| 755 | 750 | /// combination of the matrix job `selected`. |
| 756 | 751 | fn names_job(selected: &str, job: &str) -> bool { |
| @@ -1753,7 +1748,7 @@ artifacts = ["target/release/forge"] | ||
| 1753 | 1748 | } |
| 1754 | 1749 | let many = ["\"0 3 * * *\""; MAX_SCHEDULES + 1].join(", "); |
| 1755 | 1750 | let text = format!("[on]\nschedule = [{many}]\n{}", job_toml("")); |
| 1756 | - assert!(matches!(err_of(&text), ConfigError::InvalidSchedule { .. })); | |
| 1751 | + assert!(matches!(err_of(&text), ConfigError::TooManySchedules { .. })); | |
| 1757 | 1752 | } |
| 1758 | 1753 | |
| 1759 | 1754 | #[test] |
crates/forge-ci/src/error.rsmodified+3 -0
| @@ -32,6 +32,9 @@ pub enum ConfigError { | ||
| 32 | 32 | #[error("invalid schedule {expr:?}: {reason}")] |
| 33 | 33 | InvalidSchedule { expr: String, reason: String }, |
| 34 | 34 | |
| 35 | + #[error("{count} schedules are defined, the limit is {max}")] | |
| 36 | + TooManySchedules { count: usize, max: usize }, | |
| 37 | + | |
| 35 | 38 | #[error("invalid job name {0:?}: must match ^[a-z0-9][a-z0-9_-]{{0,39}}$")] |
| 36 | 39 | InvalidJobName(String), |
| 37 | 40 |
crates/forge-ci/src/mask.rsmodified+18 -31
| @@ -44,17 +44,6 @@ impl Masker { | ||
| 44 | 44 | patterns.sort_by_key(|p| std::cmp::Reverse(p.len())); |
| 45 | 45 | Self { patterns } |
| 46 | 46 | } |
| 47 | - | |
| 48 | - /// Masks every occurrence in `text`. | |
| 49 | - pub fn mask(&self, text: &str) -> String { | |
| 50 | - let (out, _) = scan(&self.patterns, text.as_bytes(), true); | |
| 51 | - bytes_to_string(out) | |
| 52 | - } | |
| 53 | - | |
| 54 | - /// Starts a streaming masker that owns a copy of this masker. | |
| 55 | - pub fn stream(&self) -> MaskStream { | |
| 56 | - MaskStream::new(self.clone()) | |
| 57 | - } | |
| 58 | 47 | } |
| 59 | 48 | |
| 60 | 49 | /// Masks a byte stream that arrives in chunks. |
| @@ -98,11 +87,6 @@ fn scan(patterns: &[Vec<u8>], input: &[u8], last: bool) -> (Vec<u8>, Vec<u8>) { | ||
| 98 | 87 | let mut i = 0; |
| 99 | 88 | while i < input.len() { |
| 100 | 89 | let tail = &input[i..]; |
| 101 | - if let Some(p) = patterns.iter().find(|p| tail.starts_with(p)) { | |
| 102 | - out.extend_from_slice(MASK.as_bytes()); | |
| 103 | - i += p.len(); | |
| 104 | - continue; | |
| 105 | - } | |
| 106 | 90 | if !last |
| 107 | 91 | && patterns |
| 108 | 92 | .iter() |
| @@ -110,19 +94,17 @@ fn scan(patterns: &[Vec<u8>], input: &[u8], last: bool) -> (Vec<u8>, Vec<u8>) { | ||
| 110 | 94 | { |
| 111 | 95 | return (out, tail.to_vec()); |
| 112 | 96 | } |
| 97 | + if let Some(p) = patterns.iter().find(|p| tail.starts_with(p)) { | |
| 98 | + out.extend_from_slice(MASK.as_bytes()); | |
| 99 | + i += p.len(); | |
| 100 | + continue; | |
| 101 | + } | |
| 113 | 102 | out.push(input[i]); |
| 114 | 103 | i += 1; |
| 115 | 104 | } |
| 116 | 105 | (out, Vec::new()) |
| 117 | 106 | } |
| 118 | 107 | |
| 119 | -fn bytes_to_string(bytes: Vec<u8>) -> String { | |
| 120 | - match String::from_utf8(bytes) { | |
| 121 | - Ok(s) => s, | |
| 122 | - Err(e) => String::from_utf8_lossy(e.as_bytes()).into_owned(), | |
| 123 | - } | |
| 124 | -} | |
| 125 | - | |
| 126 | 108 | #[cfg(test)] |
| 127 | 109 | mod tests { |
| 128 | 110 | use super::*; |
| @@ -132,7 +114,7 @@ mod tests { | ||
| 132 | 114 | } |
| 133 | 115 | |
| 134 | 116 | fn stream_all(m: &Masker, chunks: &[&[u8]]) -> String { |
| 135 | - let mut s = m.stream(); | |
| 117 | + let mut s = MaskStream::new(m.clone()); | |
| 136 | 118 | let mut out = Vec::new(); |
| 137 | 119 | for c in chunks { |
| 138 | 120 | out.extend(s.push(c)); |
| @@ -146,31 +128,36 @@ mod tests { | ||
| 146 | 128 | let secret = "hunter2-secret"; |
| 147 | 129 | let encoded = STANDARD.encode(secret.as_bytes()); |
| 148 | 130 | let m = masker(&[secret]); |
| 149 | - assert_eq!(m.mask(&format!("leak: {encoded}")), "leak: ***"); | |
| 131 | + assert_eq!(stream_all(&m, &[format!("leak: {encoded}").as_bytes()]), "leak: ***"); | |
| 150 | 132 | let other = masker(&["abcdefgh"]); |
| 151 | 133 | let enc = STANDARD.encode("abcdefgh"); |
| 152 | - assert_eq!(other.mask(&enc), "***"); | |
| 134 | + assert_eq!(stream_all(&other, &[enc.as_bytes()]), "***"); | |
| 153 | 135 | } |
| 154 | 136 | |
| 155 | 137 | #[test] |
| 156 | 138 | fn short_values_are_ignored() { |
| 157 | 139 | let m = masker(&["abc", "", "ab"]); |
| 158 | - assert_eq!(m.mask("abc ab"), "abc ab"); | |
| 140 | + assert_eq!(stream_all(&m, &[b"abc ab"]), "abc ab"); | |
| 159 | 141 | // 4 chars is the minimum that is masked. |
| 160 | 142 | let m = masker(&["abcd"]); |
| 161 | - assert_eq!(m.mask("xabcdx"), "x***x"); | |
| 143 | + assert_eq!(stream_all(&m, &[b"xabcdx"]), "x***x"); | |
| 162 | 144 | } |
| 163 | 145 | |
| 164 | 146 | #[test] |
| 165 | 147 | fn longest_match_wins() { |
| 166 | 148 | let m = masker(&["secret-value", "secret"]); |
| 167 | - assert_eq!(m.mask("a secret-value b"), "a *** b"); | |
| 149 | + assert_eq!(stream_all(&m, &[b"a secret-value b"]), "a *** b"); | |
| 150 | + } | |
| 151 | + | |
| 152 | + #[test] | |
| 153 | + fn longer_secret_wins_when_shorter_is_its_prefix() { | |
| 154 | + let m = masker(&["hunter", "hunter2-secret"]); | |
| 155 | + assert_eq!(stream_all(&m, &[b"hunter2-sec", b"ret"]), "***"); | |
| 168 | 156 | } |
| 169 | 157 | |
| 170 | 158 | #[test] |
| 171 | 159 | fn empty_secret_set_is_a_no_op() { |
| 172 | 160 | let m = Masker::new(std::iter::empty()); |
| 173 | - assert_eq!(m.mask("anything"), "anything"); | |
| 174 | 161 | assert_eq!(stream_all(&m, &[b"anything"]), "anything"); |
| 175 | 162 | } |
| 176 | 163 | |
| @@ -218,7 +205,7 @@ mod tests { | ||
| 218 | 205 | #[test] |
| 219 | 206 | fn held_bytes_are_bounded() { |
| 220 | 207 | let m = masker(&["0123456789"]); |
| 221 | - let mut s = m.stream(); | |
| 208 | + let mut s = MaskStream::new(m); | |
| 222 | 209 | let out = s.push(b"0123456"); |
| 223 | 210 | assert!(out.is_empty()); |
| 224 | 211 | assert!(s.held.len() <= 9); |
crates/forge-ci/src/steps.rsmodified+25 -8
| @@ -59,19 +59,36 @@ pub fn scan(bytes: &[u8], base_offset: u64, depth: &mut u32) -> Scan { | ||
| 59 | 59 | } |
| 60 | 60 | } |
| 61 | 61 | |
| 62 | -/// Removes ANSI CSI sequences: `ESC [`, any parameter bytes, then one final byte. | |
| 63 | -fn strip_ansi(line: &str) -> String { | |
| 62 | +/// Drops the ANSI escape sequences and the other control characters (a tab stays) of a log line. | |
| 63 | +pub fn strip_ansi(line: &str) -> String { | |
| 64 | 64 | let mut out = String::with_capacity(line.len()); |
| 65 | 65 | let mut chars = line.chars().peekable(); |
| 66 | 66 | while let Some(c) = chars.next() { |
| 67 | - if c == '\u{1b}' && chars.peek() == Some(&'[') { | |
| 68 | - chars.next(); | |
| 69 | - for f in chars.by_ref() { | |
| 70 | - if ('\u{40}'..='\u{7e}').contains(&f) { | |
| 71 | - break; | |
| 67 | + if c == '\u{1b}' { | |
| 68 | + match chars.peek() { | |
| 69 | + Some('[') => { | |
| 70 | + chars.next(); | |
| 71 | + for n in chars.by_ref() { | |
| 72 | + if ('@'..='~').contains(&n) { | |
| 73 | + break; | |
| 74 | + } | |
| 75 | + } | |
| 72 | 76 | } |
| 77 | + Some(']') => { | |
| 78 | + chars.next(); | |
| 79 | + for n in chars.by_ref() { | |
| 80 | + if n == '\u{7}' { | |
| 81 | + break; | |
| 82 | + } | |
| 83 | + if n == '\u{1b}' { | |
| 84 | + chars.next_if_eq(&'\\'); | |
| 85 | + break; | |
| 86 | + } | |
| 87 | + } | |
| 88 | + } | |
| 89 | + _ => {} | |
| 73 | 90 | } |
| 74 | - } else { | |
| 91 | + } else if c == '\t' || !c.is_control() { | |
| 75 | 92 | out.push(c); |
| 76 | 93 | } |
| 77 | 94 | } |
crates/forge-core/src/advisories.rsmodified+0 -2
| @@ -256,7 +256,6 @@ pub fn affects(advisory: &Advisory, version: &str) -> bool { | ||
| 256 | 256 | /// `fixed` (exclusive) or `last_affected` (inclusive). `introduced` of `0` starts at the beginning. |
| 257 | 257 | /// An interval still open at the end runs forever. |
| 258 | 258 | fn range_affects(range: &Range, version: &semver::Version) -> bool { |
| 259 | - // `Some(start)` while an interval is open; `start` is `None` when it began at `0`. | |
| 260 | 259 | let mut open: Option<Option<semver::Version>> = None; |
| 261 | 260 | for event in &range.events { |
| 262 | 261 | match event { |
| @@ -264,7 +263,6 @@ fn range_affects(range: &Range, version: &semver::Version) -> bool { | ||
| 264 | 263 | open = Some(if raw == "0" { |
| 265 | 264 | None |
| 266 | 265 | } else { |
| 267 | - // An unreadable start is treated as "from the beginning": more alerts, never fewer. | |
| 268 | 266 | parse_version(raw) |
| 269 | 267 | }); |
| 270 | 268 | } |
crates/forge-core/src/alerts.rsmodified+0 -26
| @@ -18,32 +18,6 @@ pub enum AlertKind { | ||
| 18 | 18 | Replication, |
| 19 | 19 | } |
| 20 | 20 | |
| 21 | -impl AlertKind { | |
| 22 | - pub const ALL: [AlertKind; 6] = [ | |
| 23 | - AlertKind::RunnerOffline, | |
| 24 | - AlertKind::Backup, | |
| 25 | - AlertKind::Disk, | |
| 26 | - AlertKind::CiKilled, | |
| 27 | - AlertKind::SelfUpdate, | |
| 28 | - AlertKind::Replication, | |
| 29 | - ]; | |
| 30 | - | |
| 31 | - pub fn as_str(self) -> &'static str { | |
| 32 | - match self { | |
| 33 | - AlertKind::RunnerOffline => "runner_offline", | |
| 34 | - AlertKind::Backup => "backup", | |
| 35 | - AlertKind::Disk => "disk", | |
| 36 | - AlertKind::CiKilled => "ci_killed", | |
| 37 | - AlertKind::SelfUpdate => "self_update", | |
| 38 | - AlertKind::Replication => "replication", | |
| 39 | - } | |
| 40 | - } | |
| 41 | - | |
| 42 | - pub fn parse(s: &str) -> Option<AlertKind> { | |
| 43 | - AlertKind::ALL.into_iter().find(|k| k.as_str() == s) | |
| 44 | - } | |
| 45 | -} | |
| 46 | - | |
| 47 | 21 | /// Whether a job's result looks like the process was killed: SIGKILL (`signal: 9`, `SIGKILL`, |
| 48 | 22 | /// `Killed`), the shell's `128 + 9` exit code, or an out-of-memory message. |
| 49 | 23 | pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool { |
crates/forge-core/src/audit.rsmodified+126 -331
| @@ -6,339 +6,135 @@ use ulid::Ulid; | ||
| 6 | 6 | |
| 7 | 7 | use crate::time::now_stamp; |
| 8 | 8 | |
| 9 | -/// Every security-relevant action that is recorded. The `as_str` names are stored and shown. | |
| 10 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 11 | -pub enum AuditAction { | |
| 12 | - LoginSuccess, | |
| 13 | - LoginFailed, | |
| 14 | - Login2faFailed, | |
| 15 | - Logout, | |
| 16 | - PasswordChanged, | |
| 17 | - EmailChanged, | |
| 18 | - PasswordResetByAdmin, | |
| 19 | - TotpEnabled, | |
| 20 | - TotpDisabled, | |
| 21 | - RecoveryCodesRegenerated, | |
| 22 | - SshKeyAdded, | |
| 23 | - SshKeyRemoved, | |
| 24 | - GpgKeyAdded, | |
| 25 | - GpgKeyDeleted, | |
| 26 | - TokenCreated, | |
| 27 | - TokenRevoked, | |
| 28 | - SessionRevoked, | |
| 29 | - UserCreated, | |
| 30 | - UsernameChanged, | |
| 31 | - UserDeleted, | |
| 32 | - RepoCreated, | |
| 33 | - RepoDeleted, | |
| 34 | - RepoRenamed, | |
| 35 | - RepoTransferred, | |
| 36 | - RepoTransferInitiated, | |
| 37 | - RepoTransferAccepted, | |
| 38 | - RepoTransferDeclined, | |
| 39 | - RepoTransferCancelled, | |
| 40 | - RepoVisibilityChanged, | |
| 41 | - CollaboratorAdded, | |
| 42 | - CollaboratorRemoved, | |
| 43 | - CollaboratorRoleChanged, | |
| 44 | - BranchRuleCreated, | |
| 45 | - BranchRuleUpdated, | |
| 46 | - BranchRuleDeleted, | |
| 47 | - RepoArchived, | |
| 48 | - RepoUnarchived, | |
| 49 | - WebhookCreated, | |
| 50 | - WebhookUpdated, | |
| 51 | - WebhookDeleted, | |
| 52 | - MirrorCreated, | |
| 53 | - MirrorUpdated, | |
| 54 | - MirrorDeleted, | |
| 55 | - MirrorSyncFailed, | |
| 56 | - BackupStarted, | |
| 57 | - FsckStarted, | |
| 58 | - ReplicationReconcileStarted, | |
| 59 | - CiSecretSet, | |
| 60 | - CiSecretDeleted, | |
| 61 | - CiRunnerRegistered, | |
| 62 | - CiRunnerDeleted, | |
| 63 | - CiRunnerRestartRequested, | |
| 64 | - CiRunnerConfigChanged, | |
| 65 | - CiRegistrationTokenCreated, | |
| 66 | - AdvisoryAlertDismissed, | |
| 67 | - AdvisoryAlertReopened, | |
| 68 | - UiPrefsChanged, | |
| 69 | - DiscussionsEnabled, | |
| 70 | - DiscussionsDisabled, | |
| 71 | - DiscussionCreated, | |
| 72 | - DiscussionEdited, | |
| 73 | - DiscussionDeleted, | |
| 74 | - DiscussionLocked, | |
| 75 | - DiscussionUnlocked, | |
| 76 | - DiscussionAnswered, | |
| 77 | - DiscussionCommentCreated, | |
| 78 | - DiscussionCommentEdited, | |
| 79 | - DiscussionCommentDeleted, | |
| 80 | - MailSettingsUpdated, | |
| 81 | - MailTestQueued, | |
| 82 | - ServerSettingsUpdated, | |
| 83 | - ServerRestarted, | |
| 84 | - SnippetCreated, | |
| 85 | - SnippetUpdated, | |
| 86 | - SnippetDeleted, | |
| 87 | - WikiPageSaved, | |
| 88 | - WikiEnabled, | |
| 89 | - WikiDisabled, | |
| 90 | - WikiPushed, | |
| 91 | - OrgCreated, | |
| 92 | - OrgDeleted, | |
| 93 | - OrgSettingsUpdated, | |
| 94 | - OrgMemberAdded, | |
| 95 | - OrgMemberRemoved, | |
| 96 | - OrgMemberRoleChanged, | |
| 97 | - TeamCreated, | |
| 98 | - TeamUpdated, | |
| 99 | - TeamDeleted, | |
| 100 | - TeamMemberAdded, | |
| 101 | - TeamMemberRemoved, | |
| 102 | - TeamRepoAdded, | |
| 103 | - TeamRepoRemoved, | |
| 104 | - PasswordResetCompleted, | |
| 105 | - EmailVerified, | |
| 106 | - InviteSent, | |
| 107 | - InviteAccepted, | |
| 108 | - UserSuspended, | |
| 109 | - UserUnsuspended, | |
| 110 | - AdminGranted, | |
| 111 | - AdminRevoked, | |
| 112 | - TotpDisabledByAdmin, | |
| 113 | - PasskeyAdded, | |
| 114 | - PasskeyRenamed, | |
| 115 | - PasskeyDeleted, | |
| 116 | - PasskeysRemovedByAdmin, | |
| 117 | - PasskeyLogin, | |
| 118 | -} | |
| 9 | +macro_rules! audit_actions { | |
| 10 | + ($($variant:ident => $name:literal,)*) => { | |
| 11 | + #[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 12 | + pub enum AuditAction { | |
| 13 | + $($variant,)* | |
| 14 | + } | |
| 119 | 15 | |
| 120 | -impl AuditAction { | |
| 121 | - /// Every action, in declaration order. Used to parse filter values. | |
| 122 | - pub const ALL: &'static [AuditAction] = &[ | |
| 123 | - AuditAction::LoginSuccess, | |
| 124 | - AuditAction::LoginFailed, | |
| 125 | - AuditAction::Login2faFailed, | |
| 126 | - AuditAction::Logout, | |
| 127 | - AuditAction::PasswordChanged, | |
| 128 | - AuditAction::EmailChanged, | |
| 129 | - AuditAction::PasswordResetByAdmin, | |
| 130 | - AuditAction::TotpEnabled, | |
| 131 | - AuditAction::TotpDisabled, | |
| 132 | - AuditAction::RecoveryCodesRegenerated, | |
| 133 | - AuditAction::SshKeyAdded, | |
| 134 | - AuditAction::SshKeyRemoved, | |
| 135 | - AuditAction::GpgKeyAdded, | |
| 136 | - AuditAction::GpgKeyDeleted, | |
| 137 | - AuditAction::TokenCreated, | |
| 138 | - AuditAction::TokenRevoked, | |
| 139 | - AuditAction::SessionRevoked, | |
| 140 | - AuditAction::UserCreated, | |
| 141 | - AuditAction::UsernameChanged, | |
| 142 | - AuditAction::UserDeleted, | |
| 143 | - AuditAction::RepoCreated, | |
| 144 | - AuditAction::RepoDeleted, | |
| 145 | - AuditAction::RepoRenamed, | |
| 146 | - AuditAction::RepoTransferred, | |
| 147 | - AuditAction::RepoTransferInitiated, | |
| 148 | - AuditAction::RepoTransferAccepted, | |
| 149 | - AuditAction::RepoTransferDeclined, | |
| 150 | - AuditAction::RepoTransferCancelled, | |
| 151 | - AuditAction::RepoVisibilityChanged, | |
| 152 | - AuditAction::CollaboratorAdded, | |
| 153 | - AuditAction::CollaboratorRemoved, | |
| 154 | - AuditAction::CollaboratorRoleChanged, | |
| 155 | - AuditAction::BranchRuleCreated, | |
| 156 | - AuditAction::BranchRuleUpdated, | |
| 157 | - AuditAction::BranchRuleDeleted, | |
| 158 | - AuditAction::RepoArchived, | |
| 159 | - AuditAction::RepoUnarchived, | |
| 160 | - AuditAction::WebhookCreated, | |
| 161 | - AuditAction::WebhookUpdated, | |
| 162 | - AuditAction::WebhookDeleted, | |
| 163 | - AuditAction::MirrorCreated, | |
| 164 | - AuditAction::MirrorUpdated, | |
| 165 | - AuditAction::MirrorDeleted, | |
| 166 | - AuditAction::MirrorSyncFailed, | |
| 167 | - AuditAction::BackupStarted, | |
| 168 | - AuditAction::FsckStarted, | |
| 169 | - AuditAction::ReplicationReconcileStarted, | |
| 170 | - AuditAction::CiSecretSet, | |
| 171 | - AuditAction::CiSecretDeleted, | |
| 172 | - AuditAction::CiRunnerRegistered, | |
| 173 | - AuditAction::CiRunnerDeleted, | |
| 174 | - AuditAction::CiRunnerRestartRequested, | |
| 175 | - AuditAction::CiRunnerConfigChanged, | |
| 176 | - AuditAction::CiRegistrationTokenCreated, | |
| 177 | - AuditAction::AdvisoryAlertDismissed, | |
| 178 | - AuditAction::AdvisoryAlertReopened, | |
| 179 | - AuditAction::UiPrefsChanged, | |
| 180 | - AuditAction::DiscussionsEnabled, | |
| 181 | - AuditAction::DiscussionsDisabled, | |
| 182 | - AuditAction::DiscussionCreated, | |
| 183 | - AuditAction::DiscussionEdited, | |
| 184 | - AuditAction::DiscussionDeleted, | |
| 185 | - AuditAction::DiscussionLocked, | |
| 186 | - AuditAction::DiscussionUnlocked, | |
| 187 | - AuditAction::DiscussionAnswered, | |
| 188 | - AuditAction::DiscussionCommentCreated, | |
| 189 | - AuditAction::DiscussionCommentEdited, | |
| 190 | - AuditAction::DiscussionCommentDeleted, | |
| 191 | - AuditAction::MailSettingsUpdated, | |
| 192 | - AuditAction::MailTestQueued, | |
| 193 | - AuditAction::ServerSettingsUpdated, | |
| 194 | - AuditAction::ServerRestarted, | |
| 195 | - AuditAction::SnippetCreated, | |
| 196 | - AuditAction::SnippetUpdated, | |
| 197 | - AuditAction::SnippetDeleted, | |
| 198 | - AuditAction::WikiPageSaved, | |
| 199 | - AuditAction::WikiEnabled, | |
| 200 | - AuditAction::WikiDisabled, | |
| 201 | - AuditAction::WikiPushed, | |
| 202 | - AuditAction::OrgCreated, | |
| 203 | - AuditAction::OrgDeleted, | |
| 204 | - AuditAction::OrgSettingsUpdated, | |
| 205 | - AuditAction::OrgMemberAdded, | |
| 206 | - AuditAction::OrgMemberRemoved, | |
| 207 | - AuditAction::OrgMemberRoleChanged, | |
| 208 | - AuditAction::TeamCreated, | |
| 209 | - AuditAction::TeamUpdated, | |
| 210 | - AuditAction::TeamDeleted, | |
| 211 | - AuditAction::TeamMemberAdded, | |
| 212 | - AuditAction::TeamMemberRemoved, | |
| 213 | - AuditAction::TeamRepoAdded, | |
| 214 | - AuditAction::TeamRepoRemoved, | |
| 215 | - AuditAction::PasswordResetCompleted, | |
| 216 | - AuditAction::EmailVerified, | |
| 217 | - AuditAction::InviteSent, | |
| 218 | - AuditAction::InviteAccepted, | |
| 219 | - AuditAction::UserSuspended, | |
| 220 | - AuditAction::UserUnsuspended, | |
| 221 | - AuditAction::AdminGranted, | |
| 222 | - AuditAction::AdminRevoked, | |
| 223 | - AuditAction::TotpDisabledByAdmin, | |
| 224 | - AuditAction::PasskeyAdded, | |
| 225 | - AuditAction::PasskeyRenamed, | |
| 226 | - AuditAction::PasskeyDeleted, | |
| 227 | - AuditAction::PasskeysRemovedByAdmin, | |
| 228 | - AuditAction::PasskeyLogin, | |
| 229 | - ]; | |
| 16 | + impl AuditAction { | |
| 17 | + pub const ALL: &'static [AuditAction] = &[$(AuditAction::$variant,)*]; | |
| 230 | 18 | |
| 231 | - pub fn as_str(self) -> &'static str { | |
| 232 | - match self { | |
| 233 | - AuditAction::LoginSuccess => "login_success", | |
| 234 | - AuditAction::LoginFailed => "login_failed", | |
| 235 | - AuditAction::Login2faFailed => "login_2fa_failed", | |
| 236 | - AuditAction::Logout => "logout", | |
| 237 | - AuditAction::PasswordChanged => "password_changed", | |
| 238 | - AuditAction::EmailChanged => "email_changed", | |
| 239 | - AuditAction::PasswordResetByAdmin => "password_reset_by_admin", | |
| 240 | - AuditAction::TotpEnabled => "totp_enabled", | |
| 241 | - AuditAction::TotpDisabled => "totp_disabled", | |
| 242 | - AuditAction::RecoveryCodesRegenerated => "recovery_codes_regenerated", | |
| 243 | - AuditAction::SshKeyAdded => "ssh_key_added", | |
| 244 | - AuditAction::SshKeyRemoved => "ssh_key_removed", | |
| 245 | - AuditAction::GpgKeyAdded => "gpg_key_added", | |
| 246 | - AuditAction::GpgKeyDeleted => "gpg_key_deleted", | |
| 247 | - AuditAction::TokenCreated => "token_created", | |
| 248 | - AuditAction::TokenRevoked => "token_revoked", | |
| 249 | - AuditAction::SessionRevoked => "session_revoked", | |
| 250 | - AuditAction::UserCreated => "user_created", | |
| 251 | - AuditAction::UsernameChanged => "username_changed", | |
| 252 | - AuditAction::UserDeleted => "user_deleted", | |
| 253 | - AuditAction::RepoCreated => "repo_created", | |
| 254 | - AuditAction::RepoDeleted => "repo_deleted", | |
| 255 | - AuditAction::RepoRenamed => "repo_renamed", | |
| 256 | - AuditAction::RepoTransferred => "repo_transferred", | |
| 257 | - AuditAction::RepoTransferInitiated => "repo_transfer_initiated", | |
| 258 | - AuditAction::RepoTransferAccepted => "repo_transfer_accepted", | |
| 259 | - AuditAction::RepoTransferDeclined => "repo_transfer_declined", | |
| 260 | - AuditAction::RepoTransferCancelled => "repo_transfer_cancelled", | |
| 261 | - AuditAction::RepoVisibilityChanged => "repo_visibility_changed", | |
| 262 | - AuditAction::CollaboratorAdded => "collaborator_added", | |
| 263 | - AuditAction::CollaboratorRemoved => "collaborator_removed", | |
| 264 | - AuditAction::CollaboratorRoleChanged => "collaborator_role_changed", | |
| 265 | - AuditAction::BranchRuleCreated => "branch_rule_created", | |
| 266 | - AuditAction::BranchRuleUpdated => "branch_rule_updated", | |
| 267 | - AuditAction::BranchRuleDeleted => "branch_rule_deleted", | |
| 268 | - AuditAction::RepoArchived => "repo_archived", | |
| 269 | - AuditAction::RepoUnarchived => "repo_unarchived", | |
| 270 | - AuditAction::WebhookCreated => "webhook_created", | |
| 271 | - AuditAction::WebhookUpdated => "webhook_updated", | |
| 272 | - AuditAction::WebhookDeleted => "webhook_deleted", | |
| 273 | - AuditAction::MirrorCreated => "mirror_created", | |
| 274 | - AuditAction::MirrorUpdated => "mirror_updated", | |
| 275 | - AuditAction::MirrorDeleted => "mirror_deleted", | |
| 276 | - AuditAction::MirrorSyncFailed => "mirror_sync_failed", | |
| 277 | - AuditAction::BackupStarted => "backup_started", | |
| 278 | - AuditAction::FsckStarted => "fsck_started", | |
| 279 | - AuditAction::ReplicationReconcileStarted => "replication_reconcile_started", | |
| 280 | - AuditAction::CiSecretSet => "ci_secret_set", | |
| 281 | - AuditAction::CiSecretDeleted => "ci_secret_deleted", | |
| 282 | - AuditAction::CiRunnerRegistered => "ci_runner_registered", | |
| 283 | - AuditAction::CiRunnerDeleted => "ci_runner_deleted", | |
| 284 | - AuditAction::CiRunnerRestartRequested => "ci_runner_restart_requested", | |
| 285 | - AuditAction::CiRunnerConfigChanged => "ci_runner_config_changed", | |
| 286 | - AuditAction::CiRegistrationTokenCreated => "ci_registration_token_created", | |
| 287 | - AuditAction::AdvisoryAlertDismissed => "advisory_alert_dismissed", | |
| 288 | - AuditAction::AdvisoryAlertReopened => "advisory_alert_reopened", | |
| 289 | - AuditAction::UiPrefsChanged => "ui_prefs_changed", | |
| 290 | - AuditAction::DiscussionsEnabled => "discussions_enabled", | |
| 291 | - AuditAction::DiscussionsDisabled => "discussions_disabled", | |
| 292 | - AuditAction::DiscussionCreated => "discussion_created", | |
| 293 | - AuditAction::DiscussionEdited => "discussion_edited", | |
| 294 | - AuditAction::DiscussionDeleted => "discussion_deleted", | |
| 295 | - AuditAction::DiscussionLocked => "discussion_locked", | |
| 296 | - AuditAction::DiscussionUnlocked => "discussion_unlocked", | |
| 297 | - AuditAction::DiscussionAnswered => "discussion_answered", | |
| 298 | - AuditAction::DiscussionCommentCreated => "discussion_comment_created", | |
| 299 | - AuditAction::DiscussionCommentEdited => "discussion_comment_edited", | |
| 300 | - AuditAction::DiscussionCommentDeleted => "discussion_comment_deleted", | |
| 301 | - AuditAction::MailSettingsUpdated => "mail_settings_updated", | |
| 302 | - AuditAction::MailTestQueued => "mail_test_queued", | |
| 303 | - AuditAction::ServerSettingsUpdated => "server_settings_updated", | |
| 304 | - AuditAction::ServerRestarted => "server_restarted", | |
| 305 | - AuditAction::SnippetCreated => "snippet_created", | |
| 306 | - AuditAction::SnippetUpdated => "snippet_updated", | |
| 307 | - AuditAction::SnippetDeleted => "snippet_deleted", | |
| 308 | - AuditAction::WikiPageSaved => "wiki_page_saved", | |
| 309 | - AuditAction::WikiEnabled => "wiki_enabled", | |
| 310 | - AuditAction::WikiDisabled => "wiki_disabled", | |
| 311 | - AuditAction::WikiPushed => "wiki_pushed", | |
| 312 | - AuditAction::OrgCreated => "org_created", | |
| 313 | - AuditAction::OrgDeleted => "org_deleted", | |
| 314 | - AuditAction::OrgSettingsUpdated => "org_settings_updated", | |
| 315 | - AuditAction::OrgMemberAdded => "org_member_added", | |
| 316 | - AuditAction::OrgMemberRemoved => "org_member_removed", | |
| 317 | - AuditAction::OrgMemberRoleChanged => "org_member_role_changed", | |
| 318 | - AuditAction::TeamCreated => "team_created", | |
| 319 | - AuditAction::TeamUpdated => "team_updated", | |
| 320 | - AuditAction::TeamDeleted => "team_deleted", | |
| 321 | - AuditAction::TeamMemberAdded => "team_member_added", | |
| 322 | - AuditAction::TeamMemberRemoved => "team_member_removed", | |
| 323 | - AuditAction::TeamRepoAdded => "team_repo_added", | |
| 324 | - AuditAction::TeamRepoRemoved => "team_repo_removed", | |
| 325 | - AuditAction::PasswordResetCompleted => "password_reset_completed", | |
| 326 | - AuditAction::EmailVerified => "email_verified", | |
| 327 | - AuditAction::InviteSent => "invite_sent", | |
| 328 | - AuditAction::InviteAccepted => "invite_accepted", | |
| 329 | - AuditAction::UserSuspended => "user_suspended", | |
| 330 | - AuditAction::UserUnsuspended => "user_unsuspended", | |
| 331 | - AuditAction::AdminGranted => "admin_granted", | |
| 332 | - AuditAction::AdminRevoked => "admin_revoked", | |
| 333 | - AuditAction::TotpDisabledByAdmin => "totp_disabled_by_admin", | |
| 334 | - AuditAction::PasskeyAdded => "passkey_added", | |
| 335 | - AuditAction::PasskeyRenamed => "passkey_renamed", | |
| 336 | - AuditAction::PasskeyDeleted => "passkey_deleted", | |
| 337 | - AuditAction::PasskeysRemovedByAdmin => "passkeys_removed_by_admin", | |
| 338 | - AuditAction::PasskeyLogin => "passkey_login", | |
| 19 | + pub fn as_str(self) -> &'static str { | |
| 20 | + match self { | |
| 21 | + $(AuditAction::$variant => $name,)* | |
| 22 | + } | |
| 23 | + } | |
| 339 | 24 | } |
| 340 | - } | |
| 25 | + }; | |
| 26 | +} | |
| 27 | + | |
| 28 | +audit_actions! { | |
| 29 | + LoginSuccess => "login_success", | |
| 30 | + LoginFailed => "login_failed", | |
| 31 | + Login2faFailed => "login_2fa_failed", | |
| 32 | + Logout => "logout", | |
| 33 | + PasswordChanged => "password_changed", | |
| 34 | + EmailChanged => "email_changed", | |
| 35 | + PasswordResetByAdmin => "password_reset_by_admin", | |
| 36 | + TotpEnabled => "totp_enabled", | |
| 37 | + TotpDisabled => "totp_disabled", | |
| 38 | + RecoveryCodesRegenerated => "recovery_codes_regenerated", | |
| 39 | + SshKeyAdded => "ssh_key_added", | |
| 40 | + SshKeyRemoved => "ssh_key_removed", | |
| 41 | + GpgKeyAdded => "gpg_key_added", | |
| 42 | + GpgKeyDeleted => "gpg_key_deleted", | |
| 43 | + TokenCreated => "token_created", | |
| 44 | + TokenRevoked => "token_revoked", | |
| 45 | + SessionRevoked => "session_revoked", | |
| 46 | + UserCreated => "user_created", | |
| 47 | + UsernameChanged => "username_changed", | |
| 48 | + UserDeleted => "user_deleted", | |
| 49 | + RepoCreated => "repo_created", | |
| 50 | + RepoDeleted => "repo_deleted", | |
| 51 | + RepoRenamed => "repo_renamed", | |
| 52 | + RepoTransferred => "repo_transferred", | |
| 53 | + RepoTransferInitiated => "repo_transfer_initiated", | |
| 54 | + RepoTransferAccepted => "repo_transfer_accepted", | |
| 55 | + RepoTransferDeclined => "repo_transfer_declined", | |
| 56 | + RepoTransferCancelled => "repo_transfer_cancelled", | |
| 57 | + RepoVisibilityChanged => "repo_visibility_changed", | |
| 58 | + CollaboratorAdded => "collaborator_added", | |
| 59 | + CollaboratorRemoved => "collaborator_removed", | |
| 60 | + CollaboratorRoleChanged => "collaborator_role_changed", | |
| 61 | + BranchRuleCreated => "branch_rule_created", | |
| 62 | + BranchRuleUpdated => "branch_rule_updated", | |
| 63 | + BranchRuleDeleted => "branch_rule_deleted", | |
| 64 | + RepoArchived => "repo_archived", | |
| 65 | + RepoUnarchived => "repo_unarchived", | |
| 66 | + WebhookCreated => "webhook_created", | |
| 67 | + WebhookUpdated => "webhook_updated", | |
| 68 | + WebhookDeleted => "webhook_deleted", | |
| 69 | + MirrorCreated => "mirror_created", | |
| 70 | + MirrorUpdated => "mirror_updated", | |
| 71 | + MirrorDeleted => "mirror_deleted", | |
| 72 | + MirrorSyncFailed => "mirror_sync_failed", | |
| 73 | + BackupStarted => "backup_started", | |
| 74 | + FsckStarted => "fsck_started", | |
| 75 | + ReplicationReconcileStarted => "replication_reconcile_started", | |
| 76 | + CiSecretSet => "ci_secret_set", | |
| 77 | + CiSecretDeleted => "ci_secret_deleted", | |
| 78 | + CiRunnerRegistered => "ci_runner_registered", | |
| 79 | + CiRunnerDeleted => "ci_runner_deleted", | |
| 80 | + CiRunnerRestartRequested => "ci_runner_restart_requested", | |
| 81 | + CiRunnerConfigChanged => "ci_runner_config_changed", | |
| 82 | + CiRegistrationTokenCreated => "ci_registration_token_created", | |
| 83 | + AdvisoryAlertDismissed => "advisory_alert_dismissed", | |
| 84 | + AdvisoryAlertReopened => "advisory_alert_reopened", | |
| 85 | + UiPrefsChanged => "ui_prefs_changed", | |
| 86 | + DiscussionsEnabled => "discussions_enabled", | |
| 87 | + DiscussionsDisabled => "discussions_disabled", | |
| 88 | + DiscussionCreated => "discussion_created", | |
| 89 | + DiscussionEdited => "discussion_edited", | |
| 90 | + DiscussionDeleted => "discussion_deleted", | |
| 91 | + DiscussionLocked => "discussion_locked", | |
| 92 | + DiscussionUnlocked => "discussion_unlocked", | |
| 93 | + DiscussionAnswered => "discussion_answered", | |
| 94 | + DiscussionCommentCreated => "discussion_comment_created", | |
| 95 | + DiscussionCommentEdited => "discussion_comment_edited", | |
| 96 | + DiscussionCommentDeleted => "discussion_comment_deleted", | |
| 97 | + MailSettingsUpdated => "mail_settings_updated", | |
| 98 | + MailTestQueued => "mail_test_queued", | |
| 99 | + ServerSettingsUpdated => "server_settings_updated", | |
| 100 | + ServerRestarted => "server_restarted", | |
| 101 | + SnippetCreated => "snippet_created", | |
| 102 | + SnippetUpdated => "snippet_updated", | |
| 103 | + SnippetDeleted => "snippet_deleted", | |
| 104 | + WikiPageSaved => "wiki_page_saved", | |
| 105 | + WikiEnabled => "wiki_enabled", | |
| 106 | + WikiDisabled => "wiki_disabled", | |
| 107 | + WikiPushed => "wiki_pushed", | |
| 108 | + OrgCreated => "org_created", | |
| 109 | + OrgDeleted => "org_deleted", | |
| 110 | + OrgSettingsUpdated => "org_settings_updated", | |
| 111 | + OrgMemberAdded => "org_member_added", | |
| 112 | + OrgMemberRemoved => "org_member_removed", | |
| 113 | + OrgMemberRoleChanged => "org_member_role_changed", | |
| 114 | + TeamCreated => "team_created", | |
| 115 | + TeamUpdated => "team_updated", | |
| 116 | + TeamDeleted => "team_deleted", | |
| 117 | + TeamMemberAdded => "team_member_added", | |
| 118 | + TeamMemberRemoved => "team_member_removed", | |
| 119 | + TeamRepoAdded => "team_repo_added", | |
| 120 | + TeamRepoRemoved => "team_repo_removed", | |
| 121 | + PasswordResetCompleted => "password_reset_completed", | |
| 122 | + EmailVerified => "email_verified", | |
| 123 | + InviteSent => "invite_sent", | |
| 124 | + InviteAccepted => "invite_accepted", | |
| 125 | + UserSuspended => "user_suspended", | |
| 126 | + UserUnsuspended => "user_unsuspended", | |
| 127 | + AdminGranted => "admin_granted", | |
| 128 | + AdminRevoked => "admin_revoked", | |
| 129 | + TotpDisabledByAdmin => "totp_disabled_by_admin", | |
| 130 | + PasskeyAdded => "passkey_added", | |
| 131 | + PasskeyRenamed => "passkey_renamed", | |
| 132 | + PasskeyDeleted => "passkey_deleted", | |
| 133 | + PasskeysRemovedByAdmin => "passkeys_removed_by_admin", | |
| 134 | + PasskeyLogin => "passkey_login", | |
| 135 | +} | |
| 341 | 136 | |
| 137 | +impl AuditAction { | |
| 342 | 138 | /// The action with this stored name, if any. |
| 343 | 139 | pub fn parse(name: &str) -> Option<AuditAction> { |
| 344 | 140 | AuditAction::ALL |
| @@ -436,13 +232,12 @@ mod tests { | ||
| 436 | 232 | #[test] |
| 437 | 233 | fn names_are_unique_and_round_trip() { |
| 438 | 234 | let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect(); |
| 439 | - assert_eq!(names.len(), 106); | |
| 440 | 235 | for action in AuditAction::ALL { |
| 441 | 236 | assert_eq!(AuditAction::parse(action.as_str()), Some(*action)); |
| 442 | 237 | } |
| 443 | 238 | names.sort(); |
| 444 | 239 | names.dedup(); |
| 445 | - assert_eq!(names.len(), 106); | |
| 240 | + assert_eq!(names.len(), AuditAction::ALL.len()); | |
| 446 | 241 | assert_eq!(AuditAction::parse("nope"), None); |
| 447 | 242 | } |
| 448 | 243 |
crates/forge-core/src/authz.rsmodified+1 -14
| @@ -23,20 +23,7 @@ pub enum Denied { | ||
| 23 | 23 | |
| 24 | 24 | /// The higher of two optional roles. `Read < Triage < Write < Maintain < Admin`. |
| 25 | 25 | pub fn max_role(a: Option<Role>, b: Option<Role>) -> Option<Role> { |
| 26 | - fn rank(role: Role) -> u8 { | |
| 27 | - match role { | |
| 28 | - Role::Read => 1, | |
| 29 | - Role::Triage => 2, | |
| 30 | - Role::Write => 3, | |
| 31 | - Role::Maintain => 4, | |
| 32 | - Role::Admin => 5, | |
| 33 | - } | |
| 34 | - } | |
| 35 | - match (a, b) { | |
| 36 | - (Some(x), Some(y)) => Some(if rank(y) > rank(x) { y } else { x }), | |
| 37 | - (x, None) => x, | |
| 38 | - (None, y) => y, | |
| 39 | - } | |
| 26 | + a.max(b) | |
| 40 | 27 | } |
| 41 | 28 | |
| 42 | 29 | /// Owner or instance admin: all actions. Public repo: Read for anyone. |
crates/forge-core/src/cargo.rsmodified+3 -2
| @@ -193,8 +193,9 @@ pub fn crate_readme(crate_file: &[u8]) -> Option<String> { | ||
| 193 | 193 | let entry = entry.ok()?; |
| 194 | 194 | let path = entry.path().ok()?.into_owned(); |
| 195 | 195 | let mut parts = path.components(); |
| 196 | - parts.next()?; | |
| 197 | - let file = parts.next()?; | |
| 196 | + let (Some(_), Some(file)) = (parts.next(), parts.next()) else { | |
| 197 | + continue; | |
| 198 | + }; | |
| 198 | 199 | let is_top = parts.next().is_none(); |
| 199 | 200 | let file_name = file.as_os_str().to_string_lossy().to_ascii_lowercase(); |
| 200 | 201 | if is_top && file_name.starts_with("readme") && entry.header().entry_type().is_file() { |
crates/forge-core/src/ci.rsmodified+18 -36
| @@ -2,11 +2,15 @@ | ||
| 2 | 2 | //! migrations/0024_ci.sql; the store functions live in store/ci.rs. |
| 3 | 3 | //! |
| 4 | 4 | //! Job specs are kept as JSON text (`CiJob::spec_json`). The store reads only the `needs` and |
| 5 | -//! `runs_on` arrays out of it, so this crate does not depend on forge-ci. | |
| 5 | +//! `runs_on` arrays out of it. | |
| 6 | 6 | |
| 7 | 7 | use std::collections::BTreeMap; |
| 8 | 8 | use std::str::FromStr; |
| 9 | 9 | |
| 10 | +use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY}; | |
| 11 | + | |
| 12 | +pub use forge_ci::proto::RestartMode; | |
| 13 | + | |
| 10 | 14 | use crate::error::{Error, Result}; |
| 11 | 15 | |
| 12 | 16 | /// State of a run. Stored as the `as_str` name. |
| @@ -142,35 +146,6 @@ pub struct CiRunner { | ||
| 142 | 146 | pub config_overrides: BTreeMap<String, serde_json::Value>, |
| 143 | 147 | } |
| 144 | 148 | |
| 145 | -/// How a runner restarts when an admin asks. | |
| 146 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 147 | -pub enum RestartMode { | |
| 148 | - /// Stop claiming, let the running jobs finish, then restart. | |
| 149 | - Drain, | |
| 150 | - /// Cancel the running jobs and restart at once. | |
| 151 | - Now, | |
| 152 | -} | |
| 153 | - | |
| 154 | -impl RestartMode { | |
| 155 | - pub fn as_str(self) -> &'static str { | |
| 156 | - match self { | |
| 157 | - Self::Drain => "drain", | |
| 158 | - Self::Now => "now", | |
| 159 | - } | |
| 160 | - } | |
| 161 | -} | |
| 162 | - | |
| 163 | -impl std::str::FromStr for RestartMode { | |
| 164 | - type Err = (); | |
| 165 | - fn from_str(s: &str) -> std::result::Result<Self, ()> { | |
| 166 | - match s { | |
| 167 | - "drain" => Ok(Self::Drain), | |
| 168 | - "now" => Ok(Self::Now), | |
| 169 | - _ => Err(()), | |
| 170 | - } | |
| 171 | - } | |
| 172 | -} | |
| 173 | - | |
| 174 | 149 | /// A pending runner restart: asked for, not yet seen to happen. |
| 175 | 150 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 176 | 151 | pub struct RunnerRestart { |
| @@ -319,8 +294,8 @@ pub fn validate_runner_field( | ||
| 319 | 294 | match key { |
| 320 | 295 | "concurrency" => int_in( |
| 321 | 296 | raw, |
| 322 | - i64::from(MIN_RUNNER_CONCURRENCY), | |
| 323 | - i64::from(MAX_RUNNER_CONCURRENCY), | |
| 297 | + i64::from(MIN_CONCURRENCY), | |
| 298 | + i64::from(MAX_CONCURRENCY), | |
| 324 | 299 | "concurrency", |
| 325 | 300 | ), |
| 326 | 301 | "labels" => { |
| @@ -529,10 +504,6 @@ impl CiRunner { | ||
| 529 | 504 | } |
| 530 | 505 | } |
| 531 | 506 | |
| 532 | -/// The smallest and largest concurrency an admin may set. | |
| 533 | -pub const MIN_RUNNER_CONCURRENCY: u32 = 1; | |
| 534 | -pub const MAX_RUNNER_CONCURRENCY: u32 = 64; | |
| 535 | - | |
| 536 | 507 | /// One run of the workflow for a commit. |
| 537 | 508 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 538 | 509 | pub struct CiRun { |
| @@ -673,6 +644,17 @@ pub struct NewJob<'a> { | ||
| 673 | 644 | pub needs: &'a [String], |
| 674 | 645 | } |
| 675 | 646 | |
| 647 | +pub struct NewRun<'a> { | |
| 648 | + pub repo_id: &'a str, | |
| 649 | + pub trigger: &'a str, | |
| 650 | + pub git_ref: &'a str, | |
| 651 | + pub commit_oid: &'a str, | |
| 652 | + pub pull_number: Option<i64>, | |
| 653 | + pub actor_id: &'a str, | |
| 654 | + pub needs_approval: bool, | |
| 655 | + pub config_error: Option<&'a str>, | |
| 656 | +} | |
| 657 | + | |
| 676 | 658 | #[cfg(test)] |
| 677 | 659 | mod memory_tests { |
| 678 | 660 | use super::*; |
crates/forge-core/src/config.rsmodified+20 -22
| @@ -233,30 +233,12 @@ impl BannerConfig { | ||
| 233 | 233 | |
| 234 | 234 | /// Parses `YYYY-MM-DD HH:MM` (UTC) into unix seconds. |
| 235 | 235 | pub fn parse_banner_expiry(raw: &str) -> Option<i64> { |
| 236 | - let raw = raw.trim(); | |
| 237 | - let (date, time) = raw.split_once(' ')?; | |
| 238 | - let mut d = date.split('-'); | |
| 239 | - let (y, m, day): (i64, i64, i64) = ( | |
| 240 | - d.next()?.parse().ok()?, | |
| 241 | - d.next()?.parse().ok()?, | |
| 242 | - d.next()?.parse().ok()?, | |
| 243 | - ); | |
| 244 | - if d.next().is_some() || !(1..=12).contains(&m) || !(1..=31).contains(&day) { | |
| 236 | + let dt = jiff::civil::DateTime::strptime("%Y-%m-%d %H:%M", raw.trim()).ok()?; | |
| 237 | + if dt.year() < 1970 { | |
| 245 | 238 | return None; |
| 246 | 239 | } |
| 247 | - let (hh, mm) = time.split_once(':')?; | |
| 248 | - let (hh, mm): (i64, i64) = (hh.parse().ok()?, mm.parse().ok()?); | |
| 249 | - if !(0..24).contains(&hh) || !(0..60).contains(&mm) || y < 1970 { | |
| 250 | - return None; | |
| 251 | - } | |
| 252 | - // Days from civil (Howard Hinnant). | |
| 253 | - let y2 = if m <= 2 { y - 1 } else { y }; | |
| 254 | - let era = y2 / 400; | |
| 255 | - let yoe = y2 - era * 400; | |
| 256 | - let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day - 1; | |
| 257 | - let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; | |
| 258 | - let days = era * 146_097 + doe - 719_468; | |
| 259 | - Some(days * 86_400 + hh * 3_600 + mm * 60) | |
| 240 | + let zoned = dt.to_zoned_datetime(jiff::tz::TimeZone::UTC).ok()?; | |
| 241 | + Some(zoned.timestamp().as_second()) | |
| 260 | 242 | } |
| 261 | 243 | |
| 262 | 244 | /// Self-update, from the `[self_update]` section. When enabled, a successful push run of `repo` |
| @@ -423,6 +405,21 @@ impl Default for AdvisoriesConfig { | ||
| 423 | 405 | } |
| 424 | 406 | } |
| 425 | 407 | |
| 408 | +impl AdvisoriesConfig { | |
| 409 | + fn validate(&self) -> Result<()> { | |
| 410 | + match self | |
| 411 | + .ecosystems | |
| 412 | + .iter() | |
| 413 | + .find(|name| !crate::advisories::KNOWN_ECOSYSTEMS.contains(&name.as_str())) | |
| 414 | + { | |
| 415 | + Some(name) => Err(Error::Config(format!( | |
| 416 | + "[advisories] unknown ecosystem `{name}`" | |
| 417 | + ))), | |
| 418 | + None => Ok(()), | |
| 419 | + } | |
| 420 | + } | |
| 421 | +} | |
| 422 | + | |
| 426 | 423 | /// Git LFS limits, from the `[lfs]` section. |
| 427 | 424 | #[derive(Debug, Clone, Deserialize)] |
| 428 | 425 | #[serde(deny_unknown_fields, default)] |
| @@ -804,6 +801,7 @@ impl Config { | ||
| 804 | 801 | self.backup.validate()?; |
| 805 | 802 | self.replication.validate()?; |
| 806 | 803 | self.self_update.validate()?; |
| 804 | + self.advisories.validate()?; | |
| 807 | 805 | self.storage.validate()?; |
| 808 | 806 | Ok(()) |
| 809 | 807 | } |
crates/forge-core/src/issue_refs.rsmodified+14 -19
| @@ -11,25 +11,13 @@ const CLOSING_KEYWORDS: [&str; 9] = [ | ||
| 11 | 11 | /// Maximum number of digits in an issue number. |
| 12 | 12 | const MAX_DIGITS: usize = 9; |
| 13 | 13 | |
| 14 | -/// Byte range (including the `#`) and value of every valid `#N` reference in `text`, in order. | |
| 15 | -/// Duplicates are kept. Used to link references in rendered markdown with the same rules. | |
| 16 | -pub fn issue_ref_spans(text: &str) -> Vec<(Range<usize>, i64)> { | |
| 17 | - scan_refs(text) | |
| 18 | -} | |
| 19 | - | |
| 20 | 14 | /// Every `#N` reference in `text`, deduplicated, in order of first appearance. |
| 21 | 15 | /// |
| 22 | 16 | /// A reference is `#` followed by 1 to 9 digits. It is not recognised when the `#` is preceded by |
| 23 | 17 | /// an alphanumeric char, `&` or `/`, or when the digits are followed by an alphanumeric char. |
| 24 | 18 | /// `#0` is not an issue number and is ignored. |
| 25 | 19 | pub fn find_issue_refs(text: &str) -> Vec<i64> { |
| 26 | - let mut out: Vec<i64> = Vec::new(); | |
| 27 | - for (_, n) in scan_refs(text) { | |
| 28 | - if !out.contains(&n) { | |
| 29 | - out.push(n); | |
| 30 | - } | |
| 31 | - } | |
| 32 | - out | |
| 20 | + dedup(issue_ref_spans(text).into_iter().map(|(_, n)| n)) | |
| 33 | 21 | } |
| 34 | 22 | |
| 35 | 23 | /// Issue numbers closed by closing keywords in `text`, deduplicated, in order. |
| @@ -38,11 +26,17 @@ pub fn find_issue_refs(text: &str) -> Vec<i64> { | ||
| 38 | 26 | /// separated by a `:`, with at least one whitespace char between the keyword (or colon) and `#`. |
| 39 | 27 | /// Example: `"Fixes: #3, closes #4"` gives `[3, 4]`; `"unfixes #2"` gives nothing. |
| 40 | 28 | pub fn find_closing_refs(text: &str) -> Vec<i64> { |
| 29 | + dedup( | |
| 30 | + issue_ref_spans(text) | |
| 31 | + .into_iter() | |
| 32 | + .filter(|(range, _)| preceded_by_closing_keyword(&text[..range.start])) | |
| 33 | + .map(|(_, n)| n), | |
| 34 | + ) | |
| 35 | +} | |
| 36 | + | |
| 37 | +fn dedup(values: impl Iterator<Item = i64>) -> Vec<i64> { | |
| 41 | 38 | let mut out: Vec<i64> = Vec::new(); |
| 42 | - for (range, n) in scan_refs(text) { | |
| 43 | - if !preceded_by_closing_keyword(&text[..range.start]) { | |
| 44 | - continue; | |
| 45 | - } | |
| 39 | + for n in values { | |
| 46 | 40 | if !out.contains(&n) { |
| 47 | 41 | out.push(n); |
| 48 | 42 | } |
| @@ -50,8 +44,9 @@ pub fn find_closing_refs(text: &str) -> Vec<i64> { | ||
| 50 | 44 | out |
| 51 | 45 | } |
| 52 | 46 | |
| 53 | -/// Byte range of each valid `#N` reference and its value, in order of appearance. | |
| 54 | -fn scan_refs(text: &str) -> Vec<(Range<usize>, i64)> { | |
| 47 | +/// Byte range (including the `#`) and value of every valid `#N` reference in `text`, in order. | |
| 48 | +/// Duplicates are kept. Used to link references in rendered markdown with the same rules. | |
| 49 | +pub fn issue_ref_spans(text: &str) -> Vec<(Range<usize>, i64)> { | |
| 55 | 50 | let bytes = text.as_bytes(); |
| 56 | 51 | let mut refs = Vec::new(); |
| 57 | 52 | let mut i = 0; |
crates/forge-core/src/lib.rsmodified+1 -2
| @@ -30,7 +30,6 @@ pub mod releases; | ||
| 30 | 30 | pub mod reviews; |
| 31 | 31 | pub mod secret; |
| 32 | 32 | pub mod server_settings; |
| 33 | -pub mod session; | |
| 34 | 33 | pub mod store; |
| 35 | 34 | pub mod suggestions; |
| 36 | 35 | pub mod time; |
| @@ -50,4 +49,4 @@ pub use pulls::*; | ||
| 50 | 49 | pub use reactions::{Reaction, ReactionMap, ReactionSummary, ReactionTarget}; |
| 51 | 50 | pub use reviews::*; |
| 52 | 51 | pub use store::Store; |
| 53 | -pub use store::edit_history_read::EditVersion; | |
| 52 | +pub use store::edit_history_read::{EditTarget, EditVersion}; |
crates/forge-core/src/mail.rsmodified+0 -55
| @@ -271,35 +271,7 @@ pub struct MailStatus { | ||
| 271 | 271 | pub last_error: Option<String>, |
| 272 | 272 | } |
| 273 | 273 | |
| 274 | -/// Where a message stands. | |
| 275 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 276 | -pub enum OutboxStatus { | |
| 277 | - Sent, | |
| 278 | - Queued, | |
| 279 | - GaveUp, | |
| 280 | -} | |
| 281 | - | |
| 282 | -impl OutboxStatus { | |
| 283 | - pub fn label(self) -> &'static str { | |
| 284 | - match self { | |
| 285 | - OutboxStatus::Sent => "sent", | |
| 286 | - OutboxStatus::Queued => "queued", | |
| 287 | - OutboxStatus::GaveUp => "gave up", | |
| 288 | - } | |
| 289 | - } | |
| 290 | -} | |
| 291 | - | |
| 292 | 274 | impl OutboxEntry { |
| 293 | - pub fn status(&self) -> OutboxStatus { | |
| 294 | - if self.sent_at.is_some() { | |
| 295 | - OutboxStatus::Sent | |
| 296 | - } else if self.next_attempt_at.is_some() { | |
| 297 | - OutboxStatus::Queued | |
| 298 | - } else { | |
| 299 | - OutboxStatus::GaveUp | |
| 300 | - } | |
| 301 | - } | |
| 302 | - | |
| 303 | 275 | /// The state of the row at `now` (an RFC 3339-style stamp, compared as text). |
| 304 | 276 | pub fn state_at(&self, now: &str) -> MailState { |
| 305 | 277 | if self.sent_at.is_some() { |
| @@ -527,31 +499,4 @@ mod tests { | ||
| 527 | 499 | entry.sent_at = Some(now.into()); |
| 528 | 500 | assert_eq!(entry.state_at(now), MailState::Sent); |
| 529 | 501 | } |
| 530 | - | |
| 531 | - #[test] | |
| 532 | - fn status_follows_sent_at_and_next_attempt() { | |
| 533 | - let mut entry = OutboxEntry { | |
| 534 | - id: "1".into(), | |
| 535 | - idem_key: "k".into(), | |
| 536 | - to_addr: "a@example.com".into(), | |
| 537 | - subject: "s".into(), | |
| 538 | - body: "b".into(), | |
| 539 | - message_id: None, | |
| 540 | - in_reply_to: None, | |
| 541 | - kind: MailKind::Other, | |
| 542 | - user_id: None, | |
| 543 | - created_at: "t".into(), | |
| 544 | - attempts: 0, | |
| 545 | - next_attempt_at: Some("t".into()), | |
| 546 | - lease_until: None, | |
| 547 | - sent_at: None, | |
| 548 | - discarded_at: None, | |
| 549 | - last_error: None, | |
| 550 | - }; | |
| 551 | - assert_eq!(entry.status(), OutboxStatus::Queued); | |
| 552 | - entry.next_attempt_at = None; | |
| 553 | - assert_eq!(entry.status(), OutboxStatus::GaveUp); | |
| 554 | - entry.sent_at = Some("t".into()); | |
| 555 | - assert_eq!(entry.status(), OutboxStatus::Sent); | |
| 556 | - } | |
| 557 | 502 | } |
crates/forge-core/src/merge_queue.rsmodified+0 -8
| @@ -25,14 +25,6 @@ impl QueueState { | ||
| 25 | 25 | QueueState::Removed => "removed", |
| 26 | 26 | } |
| 27 | 27 | } |
| 28 | - | |
| 29 | - /// Whether the entry still waits for the queue (queued, testing or merging). | |
| 30 | - pub fn is_active(self) -> bool { | |
| 31 | - matches!( | |
| 32 | - self, | |
| 33 | - QueueState::Queued | QueueState::Testing | QueueState::Merging | |
| 34 | - ) | |
| 35 | - } | |
| 36 | 28 | } |
| 37 | 29 | |
| 38 | 30 | impl std::str::FromStr for QueueState { |
crates/forge-core/src/model.rsmodified+1 -1
| @@ -9,7 +9,7 @@ pub enum Visibility { | ||
| 9 | 9 | Private, |
| 10 | 10 | } |
| 11 | 11 | |
| 12 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] | |
| 12 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] | |
| 13 | 13 | #[serde(rename_all = "lowercase")] |
| 14 | 14 | pub enum Role { |
| 15 | 15 | Read, |
crates/forge-core/src/names.rsmodified+0 -4
| @@ -43,10 +43,6 @@ pub const RESERVED: &[&str] = &[ | ||
| 43 | 43 | "favicon.ico", |
| 44 | 44 | "robots.txt", |
| 45 | 45 | "security.txt", |
| 46 | - ".well-known", | |
| 47 | - "-", | |
| 48 | - ".", | |
| 49 | - "..", | |
| 50 | 46 | ]; |
| 51 | 47 | |
| 52 | 48 | /// NFKC normalization plus case fold. |
crates/forge-core/src/notifications.rsmodified+2 -2
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | //! Notification models: repo watch levels, issue subscriptions and inbox entries. |
| 2 | 2 | |
| 3 | +use crate::issues::IssueState; | |
| 3 | 4 | use crate::model::Id; |
| 4 | 5 | |
| 5 | 6 | /// How much activity a user hears about in a repo. A user with no row is `Participating`. |
| @@ -126,8 +127,7 @@ pub struct Notification { | ||
| 126 | 127 | /// True for pull requests (`issues.kind = 'pull'`). |
| 127 | 128 | pub is_pull: bool, |
| 128 | 129 | pub title: String, |
| 129 | - /// `open` or `closed`. | |
| 130 | - pub issue_state: String, | |
| 130 | + pub issue_state: IssueState, | |
| 131 | 131 | pub reason: Reason, |
| 132 | 132 | pub last_activity: String, |
| 133 | 133 | /// `None` when the actor was deleted without a ghost reassignment or the activity had none. |
crates/forge-core/src/protection.rsmodified+27 -50
| @@ -32,7 +32,22 @@ pub struct BranchRule { | ||
| 32 | 32 | pub created_at: String, |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | -/// The settings a rule saves, without its identity. | |
| 35 | +impl BranchRule { | |
| 36 | + pub fn flags(&self) -> RuleFlags { | |
| 37 | + RuleFlags { | |
| 38 | + allow_force_push: self.allow_force_push, | |
| 39 | + allow_deletion: self.allow_deletion, | |
| 40 | + required_approvals: self.required_approvals, | |
| 41 | + block_on_changes_requested: self.block_on_changes_requested, | |
| 42 | + require_up_to_date: self.require_up_to_date, | |
| 43 | + restrict_push: self.restrict_push, | |
| 44 | + require_merge_queue: self.require_merge_queue, | |
| 45 | + required_checks: self.required_checks.clone(), | |
| 46 | + } | |
| 47 | + } | |
| 48 | +} | |
| 49 | + | |
| 50 | +/// The settings a rule saves, without its identity. `Default` is the unprotected branch. | |
| 36 | 51 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 37 | 52 | pub struct RuleFlags { |
| 38 | 53 | pub allow_force_push: bool, |
| @@ -56,19 +71,6 @@ impl RuleFlags { | ||
| 56 | 71 | } |
| 57 | 72 | } |
| 58 | 73 | |
| 59 | -/// The settings that apply to one branch. `Default` is the unprotected branch. | |
| 60 | -#[derive(Debug, Clone, Default, PartialEq, Eq)] | |
| 61 | -pub struct Protection { | |
| 62 | - pub allow_force_push: bool, | |
| 63 | - pub allow_deletion: bool, | |
| 64 | - pub required_approvals: u32, | |
| 65 | - pub block_on_changes_requested: bool, | |
| 66 | - pub require_up_to_date: bool, | |
| 67 | - pub restrict_push: bool, | |
| 68 | - pub require_merge_queue: bool, | |
| 69 | - pub required_checks: Vec<String>, | |
| 70 | -} | |
| 71 | - | |
| 72 | 74 | /// Rejects `required_approvals` above `MAX_REQUIRED_APPROVALS`. |
| 73 | 75 | pub fn validate_required_approvals(n: u32) -> Result<()> { |
| 74 | 76 | if n > MAX_REQUIRED_APPROVALS { |
| @@ -219,7 +221,7 @@ fn is_literal(pattern: &str) -> bool { | ||
| 219 | 221 | /// longest pattern wins, and ties go to the earliest created_at. |
| 220 | 222 | /// 2. Otherwise, if `branch == default_branch`: built-in protection {force_push: false, deletion: false}. |
| 221 | 223 | /// 3. Otherwise: unprotected {force_push: true, deletion: true}. |
| 222 | -pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> Protection { | |
| 224 | +pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> RuleFlags { | |
| 223 | 225 | let best = rules |
| 224 | 226 | .iter() |
| 225 | 227 | .filter(|r| pattern_matches(&r.pattern, branch)) |
| @@ -233,29 +235,12 @@ pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> Pr | ||
| 233 | 235 | .then_with(|| a.pattern.cmp(&b.pattern)) |
| 234 | 236 | }); |
| 235 | 237 | if let Some(rule) = best { |
| 236 | - return Protection { | |
| 237 | - allow_force_push: rule.allow_force_push, | |
| 238 | - allow_deletion: rule.allow_deletion, | |
| 239 | - required_approvals: rule.required_approvals, | |
| 240 | - block_on_changes_requested: rule.block_on_changes_requested, | |
| 241 | - require_up_to_date: rule.require_up_to_date, | |
| 242 | - restrict_push: rule.restrict_push, | |
| 243 | - require_merge_queue: rule.require_merge_queue, | |
| 244 | - required_checks: rule.required_checks.clone(), | |
| 245 | - }; | |
| 238 | + return rule.flags(); | |
| 246 | 239 | } |
| 247 | 240 | if branch == default_branch { |
| 248 | - Protection { | |
| 249 | - allow_force_push: false, | |
| 250 | - allow_deletion: false, | |
| 251 | - ..Protection::default() | |
| 252 | - } | |
| 241 | + RuleFlags::basic(false, false) | |
| 253 | 242 | } else { |
| 254 | - Protection { | |
| 255 | - allow_force_push: true, | |
| 256 | - allow_deletion: true, | |
| 257 | - ..Protection::default() | |
| 258 | - } | |
| 243 | + RuleFlags::basic(true, true) | |
| 259 | 244 | } |
| 260 | 245 | } |
| 261 | 246 | |
| @@ -280,14 +265,6 @@ mod tests { | ||
| 280 | 265 | } |
| 281 | 266 | } |
| 282 | 267 | |
| 283 | - fn flags(force: bool, deletion: bool) -> Protection { | |
| 284 | - Protection { | |
| 285 | - allow_force_push: force, | |
| 286 | - allow_deletion: deletion, | |
| 287 | - ..Protection::default() | |
| 288 | - } | |
| 289 | - } | |
| 290 | - | |
| 291 | 268 | #[test] |
| 292 | 269 | fn pattern_matches_cases() { |
| 293 | 270 | assert!(pattern_matches("main", "main")); |
| @@ -335,27 +312,27 @@ mod tests { | ||
| 335 | 312 | #[test] |
| 336 | 313 | fn effective_without_rules_protects_only_default() { |
| 337 | 314 | let none: &[BranchRule] = &[]; |
| 338 | - assert_eq!(effective(none, "main", "main"), flags(false, false)); | |
| 339 | - assert_eq!(effective(none, "main", "feature"), flags(true, true)); | |
| 315 | + assert_eq!(effective(none, "main", "main"), RuleFlags::basic(false, false)); | |
| 316 | + assert_eq!(effective(none, "main", "feature"), RuleFlags::basic(true, true)); | |
| 340 | 317 | } |
| 341 | 318 | |
| 342 | 319 | #[test] |
| 343 | 320 | fn effective_literal_allows_force_push_on_main() { |
| 344 | 321 | let rules = [rule("main", true, false, "1")]; |
| 345 | - assert_eq!(effective(&rules, "main", "main"), flags(true, false)); | |
| 322 | + assert_eq!(effective(&rules, "main", "main"), RuleFlags::basic(true, false)); | |
| 346 | 323 | } |
| 347 | 324 | |
| 348 | 325 | #[test] |
| 349 | 326 | fn effective_literal_beats_glob() { |
| 350 | 327 | let rules = [rule("*", false, false, "1"), rule("main", true, true, "2")]; |
| 351 | - assert_eq!(effective(&rules, "main", "main"), flags(true, true)); | |
| 328 | + assert_eq!(effective(&rules, "main", "main"), RuleFlags::basic(true, true)); | |
| 352 | 329 | } |
| 353 | 330 | |
| 354 | 331 | #[test] |
| 355 | 332 | fn effective_longer_glob_wins() { |
| 356 | 333 | // Both `*` and `rel*` match `release`; the longer `rel*` wins even though `*` is older. |
| 357 | 334 | let rules = [rule("*", true, true, "0"), rule("rel*", false, false, "1")]; |
| 358 | - assert_eq!(effective(&rules, "main", "release"), flags(false, false)); | |
| 335 | + assert_eq!(effective(&rules, "main", "release"), RuleFlags::basic(false, false)); | |
| 359 | 336 | // `release/**` is longer than `release/*`, so it wins for nested names. |
| 360 | 337 | let rules = [ |
| 361 | 338 | rule("release/*", true, true, "1"), |
| @@ -363,7 +340,7 @@ mod tests { | ||
| 363 | 340 | ]; |
| 364 | 341 | assert_eq!( |
| 365 | 342 | effective(&rules, "main", "release/a/b"), |
| 366 | - flags(false, false) | |
| 343 | + RuleFlags::basic(false, false) | |
| 367 | 344 | ); |
| 368 | 345 | } |
| 369 | 346 | |
| @@ -377,7 +354,7 @@ mod tests { | ||
| 377 | 354 | let rules = [gated]; |
| 378 | 355 | assert_eq!( |
| 379 | 356 | effective(&rules, "main", "main"), |
| 380 | - Protection { | |
| 357 | + RuleFlags { | |
| 381 | 358 | allow_force_push: false, |
| 382 | 359 | allow_deletion: false, |
| 383 | 360 | required_approvals: 2, |
crates/forge-core/src/reactions.rsmodified+0 -9
| @@ -1,7 +1,6 @@ | ||
| 1 | 1 | //! Emoji reactions: the fixed set a user can put on an issue, a pull request or a comment, and |
| 2 | 2 | //! the summaries the pages show. Stored as the short name (`+1`, `heart`, ...). |
| 3 | 3 | |
| 4 | -use crate::error::{Error, Result}; | |
| 5 | 4 | use crate::model::Id; |
| 6 | 5 | |
| 7 | 6 | /// The fixed reaction set, in the order the pages list them. |
| @@ -64,14 +63,6 @@ impl Reaction { | ||
| 64 | 63 | } |
| 65 | 64 | } |
| 66 | 65 | |
| 67 | -impl std::str::FromStr for Reaction { | |
| 68 | - type Err = Error; | |
| 69 | - | |
| 70 | - fn from_str(s: &str) -> Result<Self> { | |
| 71 | - Reaction::parse(s).ok_or_else(|| Error::Invalid(format!("unknown reaction: {s}"))) | |
| 72 | - } | |
| 73 | -} | |
| 74 | - | |
| 75 | 66 | /// What a reaction is attached to. Pull requests are issue rows, so they use `Issue`. |
| 76 | 67 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 77 | 68 | pub enum ReactionTarget { |
crates/forge-core/src/secret.rsmodified+12 -10
| @@ -24,8 +24,6 @@ pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> { | ||
| 24 | 24 | } |
| 25 | 25 | |
| 26 | 26 | fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { |
| 27 | - use std::io::Write; | |
| 28 | - | |
| 29 | 27 | use rand::TryRng; |
| 30 | 28 | |
| 31 | 29 | let mut key = [0u8; 32]; |
| @@ -33,6 +31,16 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { | ||
| 33 | 31 | .try_fill_bytes(&mut key) |
| 34 | 32 | .map_err(std::io::Error::other)?; |
| 35 | 33 | |
| 34 | + let tmp = path.with_extension(format!("{}.tmp", std::process::id())); | |
| 35 | + let _ = std::fs::remove_file(&tmp); | |
| 36 | + let linked = write_private(&tmp, &key).and_then(|()| std::fs::hard_link(&tmp, path)); | |
| 37 | + let _ = std::fs::remove_file(&tmp); | |
| 38 | + linked.map(|()| key) | |
| 39 | +} | |
| 40 | + | |
| 41 | +fn write_private(path: &Path, key: &[u8; 32]) -> std::io::Result<()> { | |
| 42 | + use std::io::Write; | |
| 43 | + | |
| 36 | 44 | let mut options = std::fs::OpenOptions::new(); |
| 37 | 45 | options.write(true).create_new(true); |
| 38 | 46 | #[cfg(unix)] |
| @@ -41,14 +49,8 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { | ||
| 41 | 49 | options.mode(0o600); |
| 42 | 50 | } |
| 43 | 51 | let mut file = options.open(path)?; |
| 44 | - let written = file.write_all(&key).and_then(|()| file.sync_all()); | |
| 45 | - if let Err(e) = written { | |
| 46 | - // Do not leave a truncated key behind; the next start would reject it. | |
| 47 | - drop(file); | |
| 48 | - let _ = std::fs::remove_file(path); | |
| 49 | - return Err(e); | |
| 50 | - } | |
| 51 | - Ok(key) | |
| 52 | + file.write_all(key)?; | |
| 53 | + file.sync_all() | |
| 52 | 54 | } |
| 53 | 55 | |
| 54 | 56 | fn read_key(path: &Path) -> Result<[u8; 32]> { |
crates/forge-core/src/server_settings.rsmodified+3 -65
| @@ -1,29 +1,13 @@ | ||
| 1 | -//! Admin-editable server settings, layered on the config file. | |
| 2 | -//! | |
| 3 | -//! Precedence per field: a UI override (table `server_settings`), then the config file, then the | |
| 4 | -//! built-in default. The config file is never rewritten. Every field has a [`Kind`]: | |
| 5 | -//! | |
| 6 | -//! - `Live`: applied to the running process at once. Consumers read [`Live::current`]. | |
| 7 | -//! - `Restart`: saved and shown as pending until the process restarts. Boot layers the stored | |
| 8 | -//! overrides on the file config, so they take effect then. | |
| 9 | -//! - `ReadOnly`: shown, never editable (listen addresses, database path, data dir). | |
| 10 | -//! | |
| 11 | -//! A secret field is write-only: the page shows whether it is set, never the value, and the stored | |
| 12 | -//! value is sealed with the instance key. | |
| 13 | -//! | |
| 14 | -//! Values travel as canonical strings (`true`, `42`, `a, b`) so one table holds every field and a | |
| 15 | -//! new field needs no migration. [`get`] and [`set`] convert between those strings and [`Config`]. | |
| 16 | - | |
| 17 | 1 | use std::collections::{BTreeMap, BTreeSet}; |
| 18 | 2 | use std::net::IpAddr; |
| 19 | 3 | use std::sync::{Arc, RwLock}; |
| 20 | 4 | |
| 21 | 5 | use ipnet::IpNet; |
| 22 | 6 | |
| 7 | +use crate::advisories::KNOWN_ECOSYSTEMS; | |
| 23 | 8 | use crate::config::{Config, MailTransport, OrgCreation, Registration, StorageBackend}; |
| 24 | 9 | use crate::error::{Error, Result}; |
| 25 | 10 | |
| 26 | -/// How a field reaches the running process. | |
| 27 | 11 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 28 | 12 | pub enum Kind { |
| 29 | 13 | Live, |
| @@ -31,7 +15,6 @@ pub enum Kind { | ||
| 31 | 15 | ReadOnly, |
| 32 | 16 | } |
| 33 | 17 | |
| 34 | -/// The page tab a field belongs to. | |
| 35 | 18 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 36 | 19 | pub enum Group { |
| 37 | 20 | General, |
| @@ -68,21 +51,15 @@ impl Group { | ||
| 68 | 51 | } |
| 69 | 52 | } |
| 70 | 53 | |
| 71 | -/// The value type of a field, which decides the input and the server-side check. | |
| 72 | 54 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 73 | 55 | pub enum Ty { |
| 74 | 56 | Bool, |
| 75 | - /// Whole number in `min..=max`. | |
| 76 | 57 | Uint(u64, u64), |
| 77 | 58 | Text, |
| 78 | - /// A filesystem path. Empty is allowed and usually means "off". | |
| 79 | 59 | Path, |
| 80 | 60 | Choice(&'static [&'static str]), |
| 81 | - /// Comma separated entries. | |
| 82 | 61 | List, |
| 83 | - /// Write-only text. | |
| 84 | 62 | Secret, |
| 85 | - /// Socket address (read-only fields only). | |
| 86 | 63 | Addr, |
| 87 | 64 | } |
| 88 | 65 | |
| @@ -132,7 +109,6 @@ const JURISDICTION: &[&str] = &["", "eu", "fedramp"]; | ||
| 132 | 109 | const MB: Ty = Ty::Uint(1, 1_048_576); |
| 133 | 110 | const PORT: Ty = Ty::Uint(1, 65_535); |
| 134 | 111 | |
| 135 | -/// Every setting, in display order. | |
| 136 | 112 | pub static FIELDS: &[Field] = &[ |
| 137 | 113 | f( |
| 138 | 114 | "registration", |
| @@ -723,7 +699,6 @@ pub static FIELDS: &[Field] = &[ | ||
| 723 | 699 | ), |
| 724 | 700 | ]; |
| 725 | 701 | |
| 726 | -/// The field for a dotted key. | |
| 727 | 702 | pub fn field(key: &str) -> Option<&'static Field> { |
| 728 | 703 | FIELDS.iter().find(|f| f.key == key) |
| 729 | 704 | } |
| @@ -740,7 +715,6 @@ fn split_list(raw: &str) -> Vec<String> { | ||
| 740 | 715 | .collect() |
| 741 | 716 | } |
| 742 | 717 | |
| 743 | -/// Checks `raw` against the field's type and returns its canonical string. | |
| 744 | 718 | pub fn normalize(field: &Field, raw: &str) -> Result<String> { |
| 745 | 719 | let raw = raw.trim(); |
| 746 | 720 | match field.ty { |
| @@ -807,7 +781,7 @@ pub fn normalize(field: &Field, raw: &str) -> Result<String> { | ||
| 807 | 781 | } |
| 808 | 782 | if field.key == "advisories.ecosystems" { |
| 809 | 783 | for item in &items { |
| 810 | - if !matches!(item.as_str(), "crates.io" | "npm" | "Go") { | |
| 784 | + if !KNOWN_ECOSYSTEMS.contains(&item.as_str()) { | |
| 811 | 785 | return Err(invalid(field, &format!("unknown ecosystem `{item}`"))); |
| 812 | 786 | } |
| 813 | 787 | } |
| @@ -840,8 +814,6 @@ fn backend_name(b: StorageBackend) -> &'static str { | ||
| 840 | 814 | } |
| 841 | 815 | } |
| 842 | 816 | |
| 843 | -/// The canonical string of a field's value in `cfg`. Secrets return their real value, so callers | |
| 844 | -/// that render must not call this for a secret field. | |
| 845 | 817 | pub fn get(cfg: &Config, key: &str) -> String { |
| 846 | 818 | let path = |p: &std::path::Path| p.to_string_lossy().into_owned(); |
| 847 | 819 | let list = |v: &[String]| v.join(", "); |
| @@ -944,7 +916,6 @@ pub fn get(cfg: &Config, key: &str) -> String { | ||
| 944 | 916 | } |
| 945 | 917 | } |
| 946 | 918 | |
| 947 | -/// Checks `raw` and stores it into `cfg`. A read-only or unknown key is refused. | |
| 948 | 919 | pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { |
| 949 | 920 | let field = field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?; |
| 950 | 921 | if field.kind == Kind::ReadOnly { |
| @@ -1072,8 +1043,6 @@ pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { | ||
| 1072 | 1043 | Ok(()) |
| 1073 | 1044 | } |
| 1074 | 1045 | |
| 1075 | -/// `file` with every override applied. Read-only keys in `overrides` are ignored. Does not | |
| 1076 | -/// validate the result; see [`Config::validate`]. | |
| 1077 | 1046 | pub fn apply(file: &Config, overrides: &BTreeMap<String, String>) -> Result<Config> { |
| 1078 | 1047 | let mut cfg = file.clone(); |
| 1079 | 1048 | for (key, value) in overrides { |
| @@ -1084,9 +1053,6 @@ pub fn apply(file: &Config, overrides: &BTreeMap<String, String>) -> Result<Conf | ||
| 1084 | 1053 | Ok(cfg) |
| 1085 | 1054 | } |
| 1086 | 1055 | |
| 1087 | -/// The config boot runs with: the file plus every stored override. If that combination no longer | |
| 1088 | -/// validates (say the file changed under an override), the overrides are dropped and the error is | |
| 1089 | -/// returned beside the file config so the caller can log it. | |
| 1090 | 1056 | pub fn boot_config(file: &Config, overrides: &BTreeMap<String, String>) -> (Config, Option<Error>) { |
| 1091 | 1057 | match apply(file, overrides).and_then(|c| c.validate().map(|()| c)) { |
| 1092 | 1058 | Ok(config) => (config, None), |
| @@ -1094,17 +1060,14 @@ pub fn boot_config(file: &Config, overrides: &BTreeMap<String, String>) -> (Conf | ||
| 1094 | 1060 | } |
| 1095 | 1061 | } |
| 1096 | 1062 | |
| 1097 | -/// `boot` with the `Live` fields taken from `pending`: what the running process uses. | |
| 1098 | 1063 | pub fn live_view(boot: &Config, pending: &Config) -> Config { |
| 1099 | 1064 | let mut cfg = boot.clone(); |
| 1100 | 1065 | for f in FIELDS.iter().filter(|f| f.kind == Kind::Live) { |
| 1101 | - // Values from `get` always pass `normalize`, so this cannot fail. | |
| 1102 | 1066 | let _ = set(&mut cfg, f.key, &get(pending, f.key)); |
| 1103 | 1067 | } |
| 1104 | 1068 | cfg |
| 1105 | 1069 | } |
| 1106 | 1070 | |
| 1107 | -/// Where a field's effective value comes from. | |
| 1108 | 1071 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1109 | 1072 | pub enum Source { |
| 1110 | 1073 | Default, |
| @@ -1112,23 +1075,16 @@ pub enum Source { | ||
| 1112 | 1075 | Ui, |
| 1113 | 1076 | } |
| 1114 | 1077 | |
| 1115 | -/// One field as the page shows it. | |
| 1116 | 1078 | #[derive(Debug, Clone)] |
| 1117 | 1079 | pub struct FieldView { |
| 1118 | 1080 | pub field: &'static Field, |
| 1119 | - /// Effective value. Empty for a secret. | |
| 1120 | 1081 | pub value: String, |
| 1121 | - /// The value the file (or default) gives. Empty for a secret. | |
| 1122 | 1082 | pub file_value: String, |
| 1123 | 1083 | pub source: Source, |
| 1124 | - /// For a secret: whether a value is set. | |
| 1125 | 1084 | pub secret_set: bool, |
| 1126 | - /// Saved but not yet running: a restart field whose value differs from the running one. | |
| 1127 | 1085 | pub restart_pending: bool, |
| 1128 | 1086 | } |
| 1129 | 1087 | |
| 1130 | -/// The process-wide settings handle: the file config, the config boot ran with, and the live view | |
| 1131 | -/// consumers read. | |
| 1132 | 1088 | pub struct Live { |
| 1133 | 1089 | file: Arc<Config>, |
| 1134 | 1090 | file_keys: BTreeSet<String>, |
| @@ -1146,7 +1102,6 @@ impl Live { | ||
| 1146 | 1102 | } |
| 1147 | 1103 | } |
| 1148 | 1104 | |
| 1149 | - /// The config the running process uses right now. | |
| 1150 | 1105 | pub fn current(&self) -> Arc<Config> { |
| 1151 | 1106 | self.current |
| 1152 | 1107 | .read() |
| @@ -1154,15 +1109,6 @@ impl Live { | ||
| 1154 | 1109 | .clone() |
| 1155 | 1110 | } |
| 1156 | 1111 | |
| 1157 | - pub fn file(&self) -> &Config { | |
| 1158 | - &self.file | |
| 1159 | - } | |
| 1160 | - | |
| 1161 | - pub fn boot(&self) -> &Config { | |
| 1162 | - &self.boot | |
| 1163 | - } | |
| 1164 | - | |
| 1165 | - /// Validates `file + overrides`, then publishes its live fields. Nothing changes on error. | |
| 1166 | 1112 | pub fn publish(&self, overrides: &BTreeMap<String, String>) -> Result<()> { |
| 1167 | 1113 | let pending = apply(&self.file, overrides)?; |
| 1168 | 1114 | pending.validate()?; |
| @@ -1174,7 +1120,6 @@ impl Live { | ||
| 1174 | 1120 | Ok(()) |
| 1175 | 1121 | } |
| 1176 | 1122 | |
| 1177 | - /// Every field with its effective value and source. | |
| 1178 | 1123 | pub fn views(&self, overrides: &BTreeMap<String, String>) -> Vec<FieldView> { |
| 1179 | 1124 | let pending = apply(&self.file, overrides).unwrap_or_else(|_| (*self.file).clone()); |
| 1180 | 1125 | FIELDS |
| @@ -1210,9 +1155,6 @@ impl Live { | ||
| 1210 | 1155 | .collect() |
| 1211 | 1156 | } |
| 1212 | 1157 | |
| 1213 | - /// Plans a save of one tab. `submitted` maps key to the raw form value. Returns the keys to | |
| 1214 | - /// store, the keys to clear (submitted equal to the file value), and the validated result. | |
| 1215 | - /// A blank secret keeps what is stored. Nothing is stored on error. | |
| 1216 | 1158 | pub fn plan_save( |
| 1217 | 1159 | &self, |
| 1218 | 1160 | existing: &BTreeMap<String, String>, |
| @@ -1262,7 +1204,6 @@ impl Live { | ||
| 1262 | 1204 | }) |
| 1263 | 1205 | } |
| 1264 | 1206 | |
| 1265 | - /// The overrides after dropping `key`, validated. | |
| 1266 | 1207 | pub fn plan_reset( |
| 1267 | 1208 | &self, |
| 1268 | 1209 | existing: &BTreeMap<String, String>, |
| @@ -1276,12 +1217,10 @@ impl Live { | ||
| 1276 | 1217 | } |
| 1277 | 1218 | } |
| 1278 | 1219 | |
| 1279 | -/// The outcome of [`Live::plan_save`]. | |
| 1280 | 1220 | #[derive(Debug)] |
| 1281 | 1221 | pub struct SavePlan { |
| 1282 | 1222 | pub sets: Vec<(String, String)>, |
| 1283 | 1223 | pub clears: Vec<String>, |
| 1284 | - /// All overrides once the plan is applied. | |
| 1285 | 1224 | pub overrides: BTreeMap<String, String>, |
| 1286 | 1225 | } |
| 1287 | 1226 | |
| @@ -1379,7 +1318,7 @@ max_log_mb = 20 | ||
| 1379 | 1318 | let v = live.views(&over); |
| 1380 | 1319 | let v = v.iter().find(|v| v.field.key == "base_url").unwrap(); |
| 1381 | 1320 | assert!(v.restart_pending); |
| 1382 | - let (boot, err) = boot_config(live.file(), &over); | |
| 1321 | + let (boot, err) = boot_config(&base(), &over); | |
| 1383 | 1322 | assert!(err.is_none()); |
| 1384 | 1323 | assert_eq!(boot.base_url, "https://new.example"); |
| 1385 | 1324 | let after = Live::new(Arc::new(base()), Default::default(), Arc::new(boot)); |
| @@ -1402,7 +1341,6 @@ max_log_mb = 20 | ||
| 1402 | 1341 | let mut cfg = base(); |
| 1403 | 1342 | assert!(set(&mut cfg, key, value).is_err(), "{key}={value}"); |
| 1404 | 1343 | } |
| 1405 | - // Cross-field loader rules apply to a whole save. | |
| 1406 | 1344 | let group_form = form(&[("storage.backend", "r2")]); |
| 1407 | 1345 | assert!( |
| 1408 | 1346 | live.plan_save(&BTreeMap::new(), Group::Storage, &group_form) |
crates/forge-core/src/session.rsdeleted+0 -32
| @@ -1,32 +0,0 @@ | ||
| 1 | -//! Session and CSRF token generation. | |
| 2 | - | |
| 3 | -use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; | |
| 4 | - | |
| 5 | -use crate::token::random_32; | |
| 6 | - | |
| 7 | -/// base64url(32 random bytes), used as the cookie value. The DB stores its sha256. | |
| 8 | -pub fn new_session_token() -> String { | |
| 9 | - BASE64_URL_SAFE_NO_PAD.encode(random_32()) | |
| 10 | -} | |
| 11 | - | |
| 12 | -pub fn new_csrf_token() -> String { | |
| 13 | - BASE64_URL_SAFE_NO_PAD.encode(random_32()) | |
| 14 | -} | |
| 15 | - | |
| 16 | -#[cfg(test)] | |
| 17 | -mod tests { | |
| 18 | - use super::*; | |
| 19 | - | |
| 20 | - #[test] | |
| 21 | - fn tokens_are_unique_base64url_of_32_bytes() { | |
| 22 | - let a = new_session_token(); | |
| 23 | - let b = new_csrf_token(); | |
| 24 | - assert_eq!(a.len(), 43); | |
| 25 | - assert_eq!(b.len(), 43); | |
| 26 | - assert_ne!(a, b); | |
| 27 | - assert!( | |
| 28 | - a.bytes() | |
| 29 | - .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') | |
| 30 | - ); | |
| 31 | - } | |
| 32 | -} |
crates/forge-core/src/store/account_tokens.rsmodified+7 -6
| @@ -5,9 +5,10 @@ | ||
| 5 | 5 | |
| 6 | 6 | use std::time::Duration; |
| 7 | 7 | |
| 8 | -use super::issues::finish; | |
| 8 | +use super::finish; | |
| 9 | 9 | use super::{ |
| 10 | - Store, col_int, col_opt_text, col_text, db_err, fetch_opt, insert_err, map_user, new_id, | |
| 10 | + USER_COLS, Store, col_int, col_opt_text, col_text, db_err, fetch_opt, insert_err, map_user, | |
| 11 | + new_id, | |
| 11 | 12 | }; |
| 12 | 13 | use crate::error::{Error, Result}; |
| 13 | 14 | use crate::model::{AccountKind, User}; |
| @@ -98,10 +99,10 @@ impl Store { | ||
| 98 | 99 | let conn = self.read_conn().await; |
| 99 | 100 | fetch_opt( |
| 100 | 101 | &conn, |
| 101 | - "SELECT id, username, email, password_hash, is_admin, created_at, about, timezone, \ | |
| 102 | - (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ | |
| 103 | - theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark, sidebar_side FROM users WHERE LOWER(email) = LOWER(?1) \ | |
| 104 | - AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1", | |
| 102 | + &format!( | |
| 103 | + "SELECT {USER_COLS} FROM users WHERE LOWER(email) = LOWER(?1) \ | |
| 104 | + AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1" | |
| 105 | + ), | |
| 105 | 106 | (email.to_owned(),), |
| 106 | 107 | map_user, |
| 107 | 108 | ) |
crates/forge-core/src/store/admin_alerts.rsmodified+2 -6
| @@ -6,8 +6,8 @@ | ||
| 6 | 6 | |
| 7 | 7 | use turso::{Row, Value}; |
| 8 | 8 | |
| 9 | -use super::issues::finish; | |
| 10 | -use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id}; | |
| 9 | +use super::finish; | |
| 10 | +use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id, text}; | |
| 11 | 11 | use crate::error::Result; |
| 12 | 12 | use crate::time::now_stamp; |
| 13 | 13 | |
| @@ -59,10 +59,6 @@ fn map_notice(row: &Row) -> Result<AdminNotice> { | ||
| 59 | 59 | }) |
| 60 | 60 | } |
| 61 | 61 | |
| 62 | -fn text(s: &str) -> Value { | |
| 63 | - Value::Text(s.to_owned()) | |
| 64 | -} | |
| 65 | - | |
| 66 | 62 | impl Store { |
| 67 | 63 | /// Marks the condition `key` active. Returns true when it was not active before, which is |
| 68 | 64 | /// when the admins are told. An alert already active keeps its first `raised_at`; only its |
crates/forge-core/src/store/advisories.rsmodified+10 -23
| @@ -302,7 +302,7 @@ impl Store { | ||
| 302 | 302 | outcome.opened += 1; |
| 303 | 303 | } |
| 304 | 304 | Some(AlertState::Fixed) => { |
| 305 | - set_state(&tx, &rid, key, AlertState::Open, &now).await?; | |
| 305 | + set_state(&tx, &rid, key, AlertState::Fixed, AlertState::Open, &now).await?; | |
| 306 | 306 | outcome.opened += 1; |
| 307 | 307 | } |
| 308 | 308 | Some(AlertState::Open | AlertState::Dismissed) => {} |
| @@ -310,7 +310,7 @@ impl Store { | ||
| 310 | 310 | } |
| 311 | 311 | for (key, state) in &existing { |
| 312 | 312 | if *state == AlertState::Open && !matched.contains(key) { |
| 313 | - set_state(&tx, &rid, key, AlertState::Fixed, &now).await?; | |
| 313 | + set_state(&tx, &rid, key, AlertState::Open, AlertState::Fixed, &now).await?; | |
| 314 | 314 | outcome.fixed += 1; |
| 315 | 315 | } |
| 316 | 316 | } |
| @@ -333,21 +333,7 @@ impl Store { | ||
| 333 | 333 | let rid = repo_id.to_string(); |
| 334 | 334 | let now = now_stamp(); |
| 335 | 335 | let outcome: Result<bool> = async { |
| 336 | - let mut params = key_params(&rid, key); | |
| 337 | - params.extend([ | |
| 338 | - Value::Text(to.as_str().to_string()), | |
| 339 | - Value::Text(now.clone()), | |
| 340 | - Value::Text(from.as_str().to_string()), | |
| 341 | - ]); | |
| 342 | - let changed = tx | |
| 343 | - .execute( | |
| 344 | - "UPDATE repo_alerts SET state = ?6, updated_at = ?7 WHERE repo_id = ?1 AND \ | |
| 345 | - advisory_id = ?2 AND ecosystem = ?3 AND package = ?4 AND version = ?5 AND \ | |
| 346 | - state = ?8", | |
| 347 | - params, | |
| 348 | - ) | |
| 349 | - .await | |
| 350 | - .map_err(db_err)?; | |
| 336 | + let changed = set_state(&tx, &rid, key, from, to, &now).await?; | |
| 351 | 337 | Ok(changed > 0) |
| 352 | 338 | } |
| 353 | 339 | .await; |
| @@ -531,22 +517,23 @@ async fn set_state( | ||
| 531 | 517 | tx: &turso::transaction::Transaction<'_>, |
| 532 | 518 | repo_id: &str, |
| 533 | 519 | key: &AlertKey, |
| 534 | - state: AlertState, | |
| 520 | + from: AlertState, | |
| 521 | + to: AlertState, | |
| 535 | 522 | now: &str, |
| 536 | -) -> Result<()> { | |
| 523 | +) -> Result<u64> { | |
| 537 | 524 | let mut params = key_params(repo_id, key); |
| 538 | 525 | params.extend([ |
| 539 | - Value::Text(state.as_str().to_string()), | |
| 526 | + Value::Text(to.as_str().to_string()), | |
| 540 | 527 | Value::Text(now.to_string()), |
| 528 | + Value::Text(from.as_str().to_string()), | |
| 541 | 529 | ]); |
| 542 | 530 | tx.execute( |
| 543 | 531 | "UPDATE repo_alerts SET state = ?6, updated_at = ?7 WHERE repo_id = ?1 AND advisory_id = ?2 \ |
| 544 | - AND ecosystem = ?3 AND package = ?4 AND version = ?5", | |
| 532 | + AND ecosystem = ?3 AND package = ?4 AND version = ?5 AND state = ?8", | |
| 545 | 533 | params, |
| 546 | 534 | ) |
| 547 | 535 | .await |
| 548 | - .map_err(db_err)?; | |
| 549 | - Ok(()) | |
| 536 | + .map_err(db_err) | |
| 550 | 537 | } |
| 551 | 538 | |
| 552 | 539 | #[cfg(test)] |
crates/forge-core/src/store/audit.rsmodified+1 -10
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | use turso::{Row, Value}; |
| 4 | 4 | |
| 5 | -use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt}; | |
| 5 | +use super::{Store, col_opt_text, col_text, db_err, fetch_all}; | |
| 6 | 6 | use crate::audit::{AuditAction, AuditCursor, AuditEntry, AuditFilter}; |
| 7 | 7 | use crate::error::{Error, Result}; |
| 8 | 8 | |
| @@ -142,15 +142,6 @@ impl Store { | ||
| 142 | 142 | fetch_all(&conn, &sql, params, map_audit).await |
| 143 | 143 | } |
| 144 | 144 | |
| 145 | - /// How many entries match `filter`, for the page count. | |
| 146 | - pub async fn count_audit(&self, filter: &AuditFilter) -> Result<u64> { | |
| 147 | - let (where_sql, params) = audit_where(filter, None); | |
| 148 | - let sql = format!("SELECT COUNT(*) FROM audit_log {where_sql}"); | |
| 149 | - let conn = self.read_conn().await; | |
| 150 | - let count = fetch_opt(&conn, &sql, params, |row| col_int(row, 0)).await?; | |
| 151 | - Ok(count.unwrap_or(0).max(0) as u64) | |
| 152 | - } | |
| 153 | - | |
| 154 | 145 | /// Retention: deletes entries stamped before `cutoff` (an RFC 3339 UTC stamp). Returns the |
| 155 | 146 | /// number of entries removed. This is the only delete on the audit log. |
| 156 | 147 | pub async fn purge_audit_before(&self, cutoff: &str) -> Result<u64> { |
crates/forge-core/src/store/backup_runs.rsmodified+8 -25
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | |
| 4 | 4 | use turso::{Row, Value}; |
| 5 | 5 | |
| 6 | -use super::{Store, col_text, db_err, fetch_all, new_id}; | |
| 6 | +use super::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all, new_id}; | |
| 7 | 7 | use crate::error::{Error, Result}; |
| 8 | 8 | use crate::time::now_stamp; |
| 9 | 9 | |
| @@ -76,29 +76,12 @@ pub struct BackupRun { | ||
| 76 | 76 | pub error: Option<String>, |
| 77 | 77 | } |
| 78 | 78 | |
| 79 | -fn opt_int(row: &Row, i: usize) -> Result<Option<i64>> { | |
| 80 | - match row.get_value(i).map_err(db_err)? { | |
| 81 | - Value::Integer(n) => Ok(Some(n)), | |
| 82 | - Value::Null => Ok(None), | |
| 83 | - _ => Err(Error::Database(format!("column {i} is not an integer"))), | |
| 84 | - } | |
| 85 | -} | |
| 86 | - | |
| 87 | -fn opt_text(row: &Row, i: usize) -> Result<Option<String>> { | |
| 88 | - match row.get_value(i).map_err(db_err)? { | |
| 89 | - Value::Text(s) => Ok(Some(s)), | |
| 90 | - Value::Null => Ok(None), | |
| 91 | - _ => Err(Error::Database(format!("column {i} is not text"))), | |
| 92 | - } | |
| 93 | -} | |
| 94 | - | |
| 95 | 79 | fn map_run(row: &Row) -> Result<BackupRun> { |
| 96 | 80 | let kind = col_text(row, 1)?; |
| 97 | 81 | let trigger = col_text(row, 8)?; |
| 98 | - let bytes = match opt_int(row, 6)? { | |
| 99 | - Some(n) => Some(u64::try_from(n).map_err(|_| Error::Database("negative run size".into()))?), | |
| 100 | - None => None, | |
| 101 | - }; | |
| 82 | + let bytes = col_opt_int(row, 6)? | |
| 83 | + .map(|n| u64::try_from(n).map_err(|_| Error::Database("negative run size".into()))) | |
| 84 | + .transpose()?; | |
| 102 | 85 | Ok(BackupRun { |
| 103 | 86 | id: col_text(row, 0)?, |
| 104 | 87 | kind: RunKind::parse(&kind) |
| @@ -106,11 +89,11 @@ fn map_run(row: &Row) -> Result<BackupRun> { | ||
| 106 | 89 | trigger: RunTrigger::parse(&trigger) |
| 107 | 90 | .ok_or_else(|| Error::Database(format!("unknown run trigger {trigger:?}")))?, |
| 108 | 91 | started_at: col_text(row, 2)?, |
| 109 | - finished_at: opt_text(row, 3)?, | |
| 110 | - ok: opt_int(row, 4)?.map(|n| n != 0), | |
| 111 | - path: opt_text(row, 5)?, | |
| 92 | + finished_at: col_opt_text(row, 3)?, | |
| 93 | + ok: col_opt_int(row, 4)?.map(|n| n != 0), | |
| 94 | + path: col_opt_text(row, 5)?, | |
| 112 | 95 | bytes, |
| 113 | - error: opt_text(row, 7)?, | |
| 96 | + error: col_opt_text(row, 7)?, | |
| 114 | 97 | }) |
| 115 | 98 | } |
| 116 | 99 |
crates/forge-core/src/store/ci.rsmodified+151 -238
| @@ -10,19 +10,19 @@ use std::time::Duration; | ||
| 10 | 10 | use turso::{Connection, Row, Value}; |
| 11 | 11 | |
| 12 | 12 | use super::{ |
| 13 | - Store, col_blob, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, | |
| 14 | - finish, insert_err, missing_row, new_id, | |
| 13 | + Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, | |
| 14 | + fetch_opt, finish, insert_err, missing_row, new_id, opt_int_value, opt_text, text, | |
| 15 | 15 | }; |
| 16 | 16 | use crate::ci::{ |
| 17 | 17 | CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, JobStep, |
| 18 | - MAX_RUNNER_CONCURRENCY, MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, | |
| 19 | - RunState, RunnerJob, RunnerReport, RunnerRestart, STARVE_AFTER_SECS, StepSample, | |
| 20 | - pick_by_memory, validate_runner_field, | |
| 18 | + MemoryOffer, NewJob, NewRun, QueueSkips, RestartMode, RunState, RunnerJob, RunnerReport, | |
| 19 | + RunnerRestart, STARVE_AFTER_SECS, StepSample, pick_by_memory, validate_runner_field, | |
| 21 | 20 | }; |
| 22 | 21 | use crate::error::{Error, Result}; |
| 23 | 22 | use crate::secret; |
| 24 | 23 | use crate::time::{now_stamp, stamp_after, stamp_to_unix}; |
| 25 | 24 | use crate::token::{generate_token, hash_token}; |
| 25 | +use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY}; | |
| 26 | 26 | use forge_ci::steps::{MAX_STEPS, StepMark}; |
| 27 | 27 | |
| 28 | 28 | const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, message, queued_at, \ |
| @@ -50,27 +50,6 @@ const MAX_LABEL: usize = 64; | ||
| 50 | 50 | /// Longest page `list_runs` returns. |
| 51 | 51 | const MAX_PER_PAGE: u32 = 100; |
| 52 | 52 | |
| 53 | -fn text(s: &str) -> Value { | |
| 54 | - Value::Text(s.to_string()) | |
| 55 | -} | |
| 56 | - | |
| 57 | -fn opt_text(v: Option<&str>) -> Value { | |
| 58 | - v.map_or(Value::Null, text) | |
| 59 | -} | |
| 60 | - | |
| 61 | -fn opt_int_value(v: Option<i64>) -> Value { | |
| 62 | - v.map_or(Value::Null, Value::Integer) | |
| 63 | -} | |
| 64 | - | |
| 65 | -/// An integer column that may be NULL. | |
| 66 | -fn opt_int(row: &Row, i: usize) -> Result<Option<i64>> { | |
| 67 | - match row.get_value(i).map_err(db_err)? { | |
| 68 | - Value::Integer(n) => Ok(Some(n)), | |
| 69 | - Value::Null => Ok(None), | |
| 70 | - _ => Err(Error::Database(format!("column {i} is not an integer"))), | |
| 71 | - } | |
| 72 | -} | |
| 73 | - | |
| 74 | 53 | fn map_runner(row: &Row) -> Result<CiRunner> { |
| 75 | 54 | let labels = serde_json::from_str::<Vec<String>>(&col_text(row, 2)?) |
| 76 | 55 | .map_err(|e| Error::Database(format!("runner labels are not a string list: {e}")))?; |
| @@ -86,7 +65,7 @@ fn map_runner(row: &Row) -> Result<CiRunner> { | ||
| 86 | 65 | concurrency: opt_u32(row, 7)?, |
| 87 | 66 | version: col_opt_text(row, 8)?, |
| 88 | 67 | cpus: opt_u32(row, 9)?, |
| 89 | - memory_bytes: opt_int(row, 10)?.and_then(|n| u64::try_from(n).ok()), | |
| 68 | + memory_bytes: col_opt_int(row, 10)?.and_then(|n| u64::try_from(n).ok()), | |
| 90 | 69 | build: col_opt_text(row, 14)?, |
| 91 | 70 | boot_id: col_opt_text(row, 15)?, |
| 92 | 71 | capabilities: col_opt_text(row, 18)? |
| @@ -97,15 +76,14 @@ fn map_runner(row: &Row) -> Result<CiRunner> { | ||
| 97 | 76 | .collect() |
| 98 | 77 | }) |
| 99 | 78 | .unwrap_or_default(), |
| 100 | - memory_budget: opt_int(row, 19)?.and_then(|n| u64::try_from(n).ok()), | |
| 101 | - memory_free: opt_int(row, 20)?.and_then(|n| u64::try_from(n).ok()), | |
| 102 | - memory_reserve: opt_int(row, 21)?.and_then(|n| u64::try_from(n).ok()), | |
| 79 | + memory_budget: col_opt_int(row, 19)?.and_then(|n| u64::try_from(n).ok()), | |
| 80 | + memory_free: col_opt_int(row, 20)?.and_then(|n| u64::try_from(n).ok()), | |
| 81 | + memory_reserve: col_opt_int(row, 21)?.and_then(|n| u64::try_from(n).ok()), | |
| 103 | 82 | }, |
| 104 | 83 | restart: match (col_opt_text(row, 16)?, col_opt_text(row, 17)?) { |
| 105 | - (Some(mode), Some(requested_at)) => mode | |
| 106 | - .parse::<RestartMode>() | |
| 107 | - .ok() | |
| 108 | - .map(|mode| RunnerRestart { mode, requested_at }), | |
| 84 | + (Some(mode), Some(requested_at)) => { | |
| 85 | + RestartMode::parse(&mode).map(|mode| RunnerRestart { mode, requested_at }) | |
| 86 | + } | |
| 109 | 87 | _ => None, |
| 110 | 88 | }, |
| 111 | 89 | running_jobs: opt_u32(row, 13)?.unwrap_or(0), |
| @@ -123,7 +101,7 @@ fn json_map(row: &Row, i: usize) -> Result<BTreeMap<String, serde_json::Value>> | ||
| 123 | 101 | |
| 124 | 102 | /// A NULL-able integer column that holds a count. |
| 125 | 103 | fn opt_u32(row: &Row, i: usize) -> Result<Option<u32>> { |
| 126 | - Ok(opt_int(row, i)?.and_then(|n| u32::try_from(n).ok())) | |
| 104 | + Ok(col_opt_int(row, i)?.and_then(|n| u32::try_from(n).ok())) | |
| 127 | 105 | } |
| 128 | 106 | |
| 129 | 107 | fn map_run(row: &Row) -> Result<CiRun> { |
| @@ -134,7 +112,7 @@ fn map_run(row: &Row) -> Result<CiRun> { | ||
| 134 | 112 | trigger: col_text(row, 3)?, |
| 135 | 113 | git_ref: col_text(row, 4)?, |
| 136 | 114 | commit_oid: col_text(row, 5)?, |
| 137 | - pull_number: opt_int(row, 6)?, | |
| 115 | + pull_number: col_opt_int(row, 6)?, | |
| 138 | 116 | actor_id: col_text(row, 7)?, |
| 139 | 117 | state: col_text(row, 8)?.parse::<RunState>()?, |
| 140 | 118 | config_error: col_opt_text(row, 9)?, |
| @@ -151,7 +129,7 @@ fn map_job(row: &Row) -> Result<CiJob> { | ||
| 151 | 129 | spec_json: col_text(row, 3)?, |
| 152 | 130 | state: col_text(row, 4)?.parse::<JobState>()?, |
| 153 | 131 | runner_id: col_opt_text(row, 5)?, |
| 154 | - exit_code: opt_int(row, 6)?, | |
| 132 | + exit_code: col_opt_int(row, 6)?, | |
| 155 | 133 | message: col_opt_text(row, 7)?, |
| 156 | 134 | queued_at: col_opt_text(row, 8)?, |
| 157 | 135 | started_at: col_opt_text(row, 9)?, |
| @@ -411,14 +389,54 @@ async fn recompute_run(conn: &Connection, run_id: &str, now: &str) -> Result<()> | ||
| 411 | 389 | Ok(()) |
| 412 | 390 | } |
| 413 | 391 | |
| 392 | +const DONE_RUNS: &str = "WITH done AS ( \ | |
| 393 | + SELECT id, git_ref, \ | |
| 394 | + ROW_NUMBER() OVER (PARTITION BY git_ref ORDER BY number DESC) AS branch_rank, \ | |
| 395 | + ROW_NUMBER() OVER (ORDER BY number DESC) AS repo_rank \ | |
| 396 | + FROM ci_runs WHERE repo_id = ?1 AND state = 'success' \ | |
| 397 | + )"; | |
| 398 | + | |
| 399 | +fn recent_done_scope(repo_id: &str, git_refs: &[String]) -> (Vec<Value>, String) { | |
| 400 | + let mut params = vec![text(repo_id)]; | |
| 401 | + params.extend(git_refs.iter().map(|git_ref| text(git_ref))); | |
| 402 | + let scope = if git_refs.is_empty() { | |
| 403 | + "done.repo_rank <= 5".to_owned() | |
| 404 | + } else { | |
| 405 | + let marks: Vec<String> = (2..=git_refs.len() + 1).map(|i| format!("?{i}")).collect(); | |
| 406 | + format!( | |
| 407 | + "(done.branch_rank <= 5 AND done.git_ref IN ({})) OR done.repo_rank <= 5", | |
| 408 | + marks.join(", ") | |
| 409 | + ) | |
| 410 | + }; | |
| 411 | + (params, scope) | |
| 412 | +} | |
| 413 | + | |
| 414 | +fn waited_secs(queued_at: Option<&str>, now: i64) -> u64 { | |
| 415 | + queued_at | |
| 416 | + .and_then(stamp_to_unix) | |
| 417 | + .map_or(0, |at| u64::try_from(now - at).unwrap_or(0)) | |
| 418 | +} | |
| 419 | + | |
| 420 | +async fn cancel_open_jobs(conn: &Connection, run_id: &str, now: &str) -> Result<()> { | |
| 421 | + conn.execute( | |
| 422 | + "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \ | |
| 423 | + WHERE run_id = ?1 AND state IN ('queued', 'blocked')", | |
| 424 | + (run_id.to_string(), now.to_string()), | |
| 425 | + ) | |
| 426 | + .await | |
| 427 | + .map_err(db_err)?; | |
| 428 | + conn.execute( | |
| 429 | + "UPDATE ci_jobs SET cancel_requested = 1 WHERE run_id = ?1 AND state = 'running'", | |
| 430 | + (run_id.to_string(),), | |
| 431 | + ) | |
| 432 | + .await | |
| 433 | + .map_err(db_err)?; | |
| 434 | + Ok(()) | |
| 435 | +} | |
| 436 | + | |
| 414 | 437 | impl Store { |
| 415 | 438 | fn seal_ci_secret(&self, plain: &[u8]) -> Result<Vec<u8>> { |
| 416 | - let key = self | |
| 417 | - .inner | |
| 418 | - .secret_key | |
| 419 | - .get() | |
| 420 | - .ok_or_else(|| Error::Crypto("instance secret key is not set".into()))?; | |
| 421 | - Ok(secret::seal(key, plain)?.into_bytes()) | |
| 439 | + Ok(secret::seal(self.secret_key()?, plain)?.into_bytes()) | |
| 422 | 440 | } |
| 423 | 441 | |
| 424 | 442 | /// Creates a single-use registration token valid for `ttl_hours`. Returns the plaintext, |
| @@ -457,8 +475,9 @@ impl Store { | ||
| 457 | 475 | let conn = self.inner.conn.lock().await; |
| 458 | 476 | let mut rows = conn |
| 459 | 477 | .query( |
| 460 | - "SELECT 1 FROM ci_registration_tokens WHERE token_hash = ?1 AND used_at IS NULL", | |
| 461 | - vec![text(token_hash)], | |
| 478 | + "SELECT 1 FROM ci_registration_tokens \ | |
| 479 | + WHERE token_hash = ?1 AND used_at IS NULL AND expires_at > ?2", | |
| 480 | + vec![text(token_hash), text(&now_stamp())], | |
| 462 | 481 | ) |
| 463 | 482 | .await |
| 464 | 483 | .map_err(db_err)?; |
| @@ -655,10 +674,10 @@ impl Store { | ||
| 655 | 674 | /// must be 1 to 64, else `Invalid`. `NotFound` if the runner does not exist. |
| 656 | 675 | pub async fn set_runner_concurrency(&self, id: &str, value: Option<u32>) -> Result<()> { |
| 657 | 676 | if let Some(n) = value |
| 658 | - && !(MIN_RUNNER_CONCURRENCY..=MAX_RUNNER_CONCURRENCY).contains(&n) | |
| 677 | + && !(MIN_CONCURRENCY..=MAX_CONCURRENCY).contains(&n) | |
| 659 | 678 | { |
| 660 | 679 | return Err(Error::Invalid(format!( |
| 661 | - "concurrency must be {MIN_RUNNER_CONCURRENCY} to {MAX_RUNNER_CONCURRENCY}" | |
| 680 | + "concurrency must be {MIN_CONCURRENCY} to {MAX_CONCURRENCY}" | |
| 662 | 681 | ))); |
| 663 | 682 | } |
| 664 | 683 | let conn = self.inner.conn.lock().await; |
| @@ -695,14 +714,7 @@ impl Store { | ||
| 695 | 714 | .await; |
| 696 | 715 | } |
| 697 | 716 | let conn = self.inner.conn.lock().await; |
| 698 | - let mut runner = fetch_opt( | |
| 699 | - &conn, | |
| 700 | - &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"), | |
| 701 | - (id.to_string(),), | |
| 702 | - map_runner, | |
| 703 | - ) | |
| 704 | - .await? | |
| 705 | - .ok_or(Error::NotFound)?; | |
| 717 | + let mut runner = load_runner(&conn, id).await?.ok_or(Error::NotFound)?; | |
| 706 | 718 | match parsed { |
| 707 | 719 | Some(v) => { |
| 708 | 720 | runner.config_overrides.insert(key.to_owned(), v); |
| @@ -719,7 +731,6 @@ impl Store { | ||
| 719 | 731 | .map_err(|e| Error::Database(e.to_string()))?, |
| 720 | 732 | ) |
| 721 | 733 | }; |
| 722 | - // The forge claims with the labels it stores, so a labels override is live at once. | |
| 723 | 734 | let labels = if key == "labels" { |
| 724 | 735 | let chosen = runner |
| 725 | 736 | .config_overrides |
| @@ -762,14 +773,7 @@ impl Store { | ||
| 762 | 773 | config: &BTreeMap<String, serde_json::Value>, |
| 763 | 774 | ) -> Result<bool> { |
| 764 | 775 | let conn = self.inner.conn.lock().await; |
| 765 | - let current = fetch_opt( | |
| 766 | - &conn, | |
| 767 | - &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"), | |
| 768 | - (id.to_string(),), | |
| 769 | - map_runner, | |
| 770 | - ) | |
| 771 | - .await?; | |
| 772 | - let Some(current) = current else { | |
| 776 | + let Some(current) = load_runner(&conn, id).await? else { | |
| 773 | 777 | return Ok(false); |
| 774 | 778 | }; |
| 775 | 779 | if ¤t.reported_config == config { |
| @@ -831,14 +835,7 @@ impl Store { | ||
| 831 | 835 | /// value. Returns true when a stored value changed, so the caller can tell live pages. |
| 832 | 836 | pub async fn record_runner_report(&self, id: &str, report: &RunnerReport) -> Result<bool> { |
| 833 | 837 | let conn = self.inner.conn.lock().await; |
| 834 | - let current = fetch_opt( | |
| 835 | - &conn, | |
| 836 | - &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"), | |
| 837 | - (id.to_string(),), | |
| 838 | - map_runner, | |
| 839 | - ) | |
| 840 | - .await?; | |
| 841 | - let Some(current) = current else { | |
| 838 | + let Some(current) = load_runner(&conn, id).await? else { | |
| 842 | 839 | return Ok(false); |
| 843 | 840 | }; |
| 844 | 841 | let merged = RunnerReport { |
| @@ -860,7 +857,6 @@ impl Store { | ||
| 860 | 857 | if merged == current.reported { |
| 861 | 858 | return Ok(false); |
| 862 | 859 | } |
| 863 | - // A new boot id while a restart is pending means the runner came back. | |
| 864 | 860 | if merged.boot_id != current.reported.boot_id && current.restart.is_some() { |
| 865 | 861 | conn.execute( |
| 866 | 862 | "UPDATE ci_runners SET restart_mode = NULL, restart_requested_at = NULL \ |
| @@ -924,7 +920,7 @@ impl Store { | ||
| 924 | 920 | |row| col_opt_text(row, 0), |
| 925 | 921 | ) |
| 926 | 922 | .await?; |
| 927 | - Ok(found.flatten().and_then(|m| m.parse().ok())) | |
| 923 | + Ok(found.flatten().and_then(|m| RestartMode::parse(&m))) | |
| 928 | 924 | } |
| 929 | 925 | |
| 930 | 926 | /// Removes a runner. `NotFound` if it does not exist. |
| @@ -947,18 +943,17 @@ impl Store { | ||
| 947 | 943 | /// `Blocked` until `approve_run`. Otherwise need-less jobs are `Queued` and the run is |
| 948 | 944 | /// `Queued`. Jobs with needs are always `Blocked` at first. |
| 949 | 945 | #[allow(clippy::too_many_arguments)] |
| 950 | - pub async fn create_run( | |
| 951 | - &self, | |
| 952 | - repo_id: &str, | |
| 953 | - trigger: &str, | |
| 954 | - git_ref: &str, | |
| 955 | - commit_oid: &str, | |
| 956 | - pull_number: Option<i64>, | |
| 957 | - actor_id: &str, | |
| 958 | - needs_approval: bool, | |
| 959 | - jobs: &[NewJob<'_>], | |
| 960 | - config_error: Option<&str>, | |
| 961 | - ) -> Result<CiRun> { | |
| 946 | + pub async fn create_run(&self, run: &NewRun<'_>, jobs: &[NewJob<'_>]) -> Result<CiRun> { | |
| 947 | + let NewRun { | |
| 948 | + repo_id, | |
| 949 | + trigger, | |
| 950 | + git_ref, | |
| 951 | + commit_oid, | |
| 952 | + pull_number, | |
| 953 | + actor_id, | |
| 954 | + needs_approval, | |
| 955 | + config_error, | |
| 956 | + } = *run; | |
| 962 | 957 | let id = new_id(); |
| 963 | 958 | let now = now_stamp(); |
| 964 | 959 | let conn = self.inner.conn.lock().await; |
| @@ -1099,11 +1094,10 @@ impl Store { | ||
| 1099 | 1094 | let candidates: Vec<(Option<u64>, u64)> = compatible |
| 1100 | 1095 | .iter() |
| 1101 | 1096 | .map(|(_, spec, queued_at)| { |
| 1102 | - let waited = queued_at | |
| 1103 | - .as_deref() | |
| 1104 | - .and_then(stamp_to_unix) | |
| 1105 | - .map_or(0, |at| u64::try_from(now - at).unwrap_or(0)); | |
| 1106 | - (declared_memory(spec), waited) | |
| 1097 | + ( | |
| 1098 | + declared_memory(spec), | |
| 1099 | + waited_secs(queued_at.as_deref(), now), | |
| 1100 | + ) | |
| 1107 | 1101 | }) |
| 1108 | 1102 | .collect(); |
| 1109 | 1103 | compatible = pick_by_memory(&candidates, &offer, STARVE_AFTER_SECS) |
| @@ -1168,7 +1162,6 @@ impl Store { | ||
| 1168 | 1162 | ..QueueSkips::default() |
| 1169 | 1163 | }; |
| 1170 | 1164 | let mut missing = BTreeSet::new(); |
| 1171 | - // The same walk as `pick_by_memory`, oldest first, counting instead of picking. | |
| 1172 | 1165 | for (spec, queued_at) in &queued { |
| 1173 | 1166 | if !runs_on_covered(spec, &runner.labels) { |
| 1174 | 1167 | skips.lacking_labels += 1; |
| @@ -1191,11 +1184,7 @@ impl Store { | ||
| 1191 | 1184 | let need = offer.reservation(declared); |
| 1192 | 1185 | skips.too_big += 1; |
| 1193 | 1186 | skips.smallest_need = Some(skips.smallest_need.map_or(need, |n| n.min(need))); |
| 1194 | - let waited = queued_at | |
| 1195 | - .as_deref() | |
| 1196 | - .and_then(stamp_to_unix) | |
| 1197 | - .map_or(0, |at| u64::try_from(now - at).unwrap_or(0)); | |
| 1198 | - if waited >= STARVE_AFTER_SECS { | |
| 1187 | + if waited_secs(queued_at.as_deref(), now) >= STARVE_AFTER_SECS { | |
| 1199 | 1188 | skips.starved_need = Some(need); |
| 1200 | 1189 | } |
| 1201 | 1190 | } |
| @@ -1280,7 +1269,8 @@ impl Store { | ||
| 1280 | 1269 | |
| 1281 | 1270 | /// Finishes a job with a terminal state. Dependants are then unblocked or skipped, and the |
| 1282 | 1271 | /// run state is recomputed. A `Failure` or `Error` fails the run fast: the run's queued and |
| 1283 | - /// blocked jobs are cancelled and its running jobs get `cancel_requested`. Returns the run. `Conflict` if the job already finished. | |
| 1272 | + /// blocked jobs are cancelled and its running jobs get `cancel_requested`. Returns the run. | |
| 1273 | + /// `Conflict` if the job already finished. | |
| 1284 | 1274 | pub async fn finish_job( |
| 1285 | 1275 | &self, |
| 1286 | 1276 | job_id: &str, |
| @@ -1316,21 +1306,7 @@ impl Store { | ||
| 1316 | 1306 | .map_err(db_err)?; |
| 1317 | 1307 | propagate(&tx, &job.run_id, &now).await?; |
| 1318 | 1308 | if matches!(state, JobState::Failure | JobState::Error) { |
| 1319 | - // Fail fast: the run cannot succeed any more, so stop the sibling jobs now. | |
| 1320 | - tx.execute( | |
| 1321 | - "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \ | |
| 1322 | - WHERE run_id = ?1 AND state IN ('queued', 'blocked')", | |
| 1323 | - (job.run_id.clone(), now.clone()), | |
| 1324 | - ) | |
| 1325 | - .await | |
| 1326 | - .map_err(db_err)?; | |
| 1327 | - tx.execute( | |
| 1328 | - "UPDATE ci_jobs SET cancel_requested = 1 \ | |
| 1329 | - WHERE run_id = ?1 AND state = 'running'", | |
| 1330 | - (job.run_id.clone(),), | |
| 1331 | - ) | |
| 1332 | - .await | |
| 1333 | - .map_err(db_err)?; | |
| 1309 | + cancel_open_jobs(&tx, &job.run_id, &now).await?; | |
| 1334 | 1310 | } |
| 1335 | 1311 | recompute_run(&tx, &job.run_id, &now).await?; |
| 1336 | 1312 | load_run(&tx, &job.run_id).await?.ok_or_else(missing_row) |
| @@ -1388,19 +1364,7 @@ impl Store { | ||
| 1388 | 1364 | if run.state.is_terminal() { |
| 1389 | 1365 | return Ok(()); |
| 1390 | 1366 | } |
| 1391 | - tx.execute( | |
| 1392 | - "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \ | |
| 1393 | - WHERE run_id = ?1 AND state IN ('queued', 'blocked')", | |
| 1394 | - (run_id.to_string(), now.clone()), | |
| 1395 | - ) | |
| 1396 | - .await | |
| 1397 | - .map_err(db_err)?; | |
| 1398 | - tx.execute( | |
| 1399 | - "UPDATE ci_jobs SET cancel_requested = 1 WHERE run_id = ?1 AND state = 'running'", | |
| 1400 | - (run_id.to_string(),), | |
| 1401 | - ) | |
| 1402 | - .await | |
| 1403 | - .map_err(db_err)?; | |
| 1367 | + cancel_open_jobs(&tx, run_id, &now).await?; | |
| 1404 | 1368 | recompute_run(&tx, run_id, &now).await |
| 1405 | 1369 | } |
| 1406 | 1370 | .await; |
| @@ -1507,15 +1471,17 @@ impl Store { | ||
| 1507 | 1471 | .collect(); |
| 1508 | 1472 | let created = self |
| 1509 | 1473 | .create_run( |
| 1510 | - &run.repo_id, | |
| 1511 | - &run.trigger, | |
| 1512 | - &run.git_ref, | |
| 1513 | - &run.commit_oid, | |
| 1514 | - run.pull_number, | |
| 1515 | - actor_id, | |
| 1516 | - false, | |
| 1474 | + &NewRun { | |
| 1475 | + repo_id: &run.repo_id, | |
| 1476 | + trigger: &run.trigger, | |
| 1477 | + git_ref: &run.git_ref, | |
| 1478 | + commit_oid: &run.commit_oid, | |
| 1479 | + pull_number: run.pull_number, | |
| 1480 | + actor_id, | |
| 1481 | + needs_approval: false, | |
| 1482 | + config_error: run.config_error.as_deref(), | |
| 1483 | + }, | |
| 1517 | 1484 | &new_jobs, |
| 1518 | - run.config_error.as_deref(), | |
| 1519 | 1485 | ) |
| 1520 | 1486 | .await?; |
| 1521 | 1487 | let warnings = self.run_warnings(&run.id).await?; |
| @@ -1527,7 +1493,11 @@ impl Store { | ||
| 1527 | 1493 | |
| 1528 | 1494 | /// Stores the config warnings of a run, replacing any earlier ones. |
| 1529 | 1495 | pub async fn set_run_warnings(&self, run_id: &str, warnings: &[String]) -> Result<()> { |
| 1530 | - let joined = (!warnings.is_empty()).then(|| warnings.join("\n")); | |
| 1496 | + let lines: Vec<String> = warnings | |
| 1497 | + .iter() | |
| 1498 | + .map(|w| w.replace(['\n', '\r'], " ")) | |
| 1499 | + .collect(); | |
| 1500 | + let joined = (!lines.is_empty()).then(|| lines.join("\n")); | |
| 1531 | 1501 | let conn = self.inner.conn.lock().await; |
| 1532 | 1502 | conn.execute( |
| 1533 | 1503 | "UPDATE ci_runs SET config_warnings = ?2 WHERE id = ?1", |
| @@ -1599,6 +1569,7 @@ impl Store { | ||
| 1599 | 1569 | ) |
| 1600 | 1570 | .await?; |
| 1601 | 1571 | let mut runs: Vec<String> = Vec::new(); |
| 1572 | + let mut failed_runs: Vec<String> = Vec::new(); | |
| 1602 | 1573 | for job in &lost { |
| 1603 | 1574 | tx.execute( |
| 1604 | 1575 | "UPDATE ci_jobs SET \ |
| @@ -1613,9 +1584,15 @@ impl Store { | ||
| 1613 | 1584 | if !runs.contains(&job.run_id) { |
| 1614 | 1585 | runs.push(job.run_id.clone()); |
| 1615 | 1586 | } |
| 1587 | + if !job.cancel_requested && !failed_runs.contains(&job.run_id) { | |
| 1588 | + failed_runs.push(job.run_id.clone()); | |
| 1589 | + } | |
| 1616 | 1590 | } |
| 1617 | 1591 | for run_id in &runs { |
| 1618 | 1592 | propagate(&tx, run_id, &now).await?; |
| 1593 | + if failed_runs.contains(run_id) { | |
| 1594 | + cancel_open_jobs(&tx, run_id, &now).await?; | |
| 1595 | + } | |
| 1619 | 1596 | recompute_run(&tx, run_id, &now).await?; |
| 1620 | 1597 | } |
| 1621 | 1598 | let mut out = Vec::with_capacity(lost.len()); |
| @@ -1708,27 +1685,10 @@ impl Store { | ||
| 1708 | 1685 | repo_id: &str, |
| 1709 | 1686 | git_refs: &[String], |
| 1710 | 1687 | ) -> Result<Vec<JobSample>> { |
| 1711 | - let mut params: Vec<Value> = Vec::with_capacity(git_refs.len() + 1); | |
| 1712 | - params.push(Value::Text(repo_id.to_string())); | |
| 1713 | - params.extend(git_refs.iter().map(|git_ref| Value::Text(git_ref.clone()))); | |
| 1714 | - let scope = if git_refs.is_empty() { | |
| 1715 | - "done.repo_rank <= 5".to_owned() | |
| 1716 | - } else { | |
| 1717 | - let marks: Vec<String> = (2..=git_refs.len() + 1).map(|i| format!("?{i}")).collect(); | |
| 1718 | - format!( | |
| 1719 | - "(done.branch_rank <= 5 AND done.git_ref IN ({})) OR done.repo_rank <= 5", | |
| 1720 | - marks.join(", ") | |
| 1721 | - ) | |
| 1722 | - }; | |
| 1688 | + let (params, scope) = recent_done_scope(repo_id, git_refs); | |
| 1723 | 1689 | let sql = format!( |
| 1724 | - "WITH done AS ( \ | |
| 1725 | - SELECT id, git_ref, \ | |
| 1726 | - ROW_NUMBER() OVER (PARTITION BY git_ref ORDER BY number DESC) AS branch_rank, \ | |
| 1727 | - ROW_NUMBER() OVER (ORDER BY number DESC) AS repo_rank \ | |
| 1728 | - FROM ci_runs WHERE repo_id = ?1 AND state = 'success' \ | |
| 1729 | - ) \ | |
| 1730 | - SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, j.started_at, \ | |
| 1731 | - j.finished_at \ | |
| 1690 | + "{DONE_RUNS} SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, \ | |
| 1691 | + j.started_at, j.finished_at \ | |
| 1732 | 1692 | FROM done JOIN ci_jobs j ON j.run_id = done.id \ |
| 1733 | 1693 | WHERE ({scope}) \ |
| 1734 | 1694 | AND j.state = 'success' AND j.started_at IS NOT NULL AND j.finished_at IS NOT NULL" |
| @@ -1868,26 +1828,9 @@ impl Store { | ||
| 1868 | 1828 | repo_id: &str, |
| 1869 | 1829 | git_refs: &[String], |
| 1870 | 1830 | ) -> Result<Vec<StepSample>> { |
| 1871 | - let mut params: Vec<Value> = Vec::with_capacity(git_refs.len() + 1); | |
| 1872 | - params.push(Value::Text(repo_id.to_string())); | |
| 1873 | - params.extend(git_refs.iter().map(|git_ref| Value::Text(git_ref.clone()))); | |
| 1874 | - let scope = if git_refs.is_empty() { | |
| 1875 | - "done.repo_rank <= 5".to_owned() | |
| 1876 | - } else { | |
| 1877 | - let marks: Vec<String> = (2..=git_refs.len() + 1).map(|i| format!("?{i}")).collect(); | |
| 1878 | - format!( | |
| 1879 | - "(done.branch_rank <= 5 AND done.git_ref IN ({})) OR done.repo_rank <= 5", | |
| 1880 | - marks.join(", ") | |
| 1881 | - ) | |
| 1882 | - }; | |
| 1831 | + let (params, scope) = recent_done_scope(repo_id, git_refs); | |
| 1883 | 1832 | let sql = format!( |
| 1884 | - "WITH done AS ( \ | |
| 1885 | - SELECT id, git_ref, \ | |
| 1886 | - ROW_NUMBER() OVER (PARTITION BY git_ref ORDER BY number DESC) AS branch_rank, \ | |
| 1887 | - ROW_NUMBER() OVER (ORDER BY number DESC) AS repo_rank \ | |
| 1888 | - FROM ci_runs WHERE repo_id = ?1 AND state = 'success' \ | |
| 1889 | - ) \ | |
| 1890 | - SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, s.name, \ | |
| 1833 | + "{DONE_RUNS} SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, s.name, \ | |
| 1891 | 1834 | s.started_at, s.finished_at \ |
| 1892 | 1835 | FROM done JOIN ci_jobs j ON j.run_id = done.id \ |
| 1893 | 1836 | JOIN ci_job_steps s ON s.job_id = j.id \ |
| @@ -2031,7 +1974,6 @@ impl Store { | ||
| 2031 | 1974 | let conn = self.inner.conn.lock().await; |
| 2032 | 1975 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 2033 | 1976 | let outcome: Result<(Vec<String>, Vec<String>, Vec<String>)> = async { |
| 2034 | - // Which run owns each artifact, read before the rows go. | |
| 2035 | 1977 | let owners: BTreeMap<String, String> = fetch_all( |
| 2036 | 1978 | &tx, |
| 2037 | 1979 | "SELECT a.id, j.run_id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id", |
| @@ -2073,14 +2015,13 @@ impl Store { | ||
| 2073 | 2015 | .await |
| 2074 | 2016 | .map_err(db_err)?; |
| 2075 | 2017 | |
| 2076 | - // Keep only the newest `keep_runs` runs (per repo) that still have artifacts. | |
| 2077 | 2018 | if keep_runs > 0 { |
| 2078 | 2019 | let old = fetch_all( |
| 2079 | 2020 | &tx, |
| 2080 | 2021 | "SELECT a.id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id \ |
| 2081 | 2022 | WHERE j.run_id NOT IN ( \ |
| 2082 | 2023 | SELECT id FROM ( \ |
| 2083 | - SELECT r.id, ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY r.id DESC) \ | |
| 2024 | + SELECT r.id, ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY r.number DESC) \ | |
| 2084 | 2025 | AS rn \ |
| 2085 | 2026 | FROM ci_runs r \ |
| 2086 | 2027 | WHERE EXISTS (SELECT 1 FROM ci_artifacts a2 JOIN ci_jobs j2 \ |
| @@ -2099,10 +2040,8 @@ impl Store { | ||
| 2099 | 2040 | artifact_ids.extend(old); |
| 2100 | 2041 | } |
| 2101 | 2042 | |
| 2102 | - // Over the disk limit: drop the oldest runs' artifacts, one whole run at a time. | |
| 2103 | 2043 | if max_total_bytes > 0 { |
| 2104 | 2044 | let limit = i64::try_from(max_total_bytes).unwrap_or(i64::MAX); |
| 2105 | - // (artifact id, run id, size), oldest run first. | |
| 2106 | 2045 | let rows = fetch_all( |
| 2107 | 2046 | &tx, |
| 2108 | 2047 | "SELECT a.id, j.run_id, a.size FROM ci_artifacts a \ |
| @@ -2215,14 +2154,9 @@ impl Store { | ||
| 2215 | 2154 | if !names.contains(&name) { |
| 2216 | 2155 | continue; |
| 2217 | 2156 | } |
| 2218 | - let key = self | |
| 2219 | - .inner | |
| 2220 | - .secret_key | |
| 2221 | - .get() | |
| 2222 | - .ok_or_else(|| Error::Crypto("instance secret key is not set".into()))?; | |
| 2223 | 2157 | let sealed = String::from_utf8(sealed) |
| 2224 | 2158 | .map_err(|_| Error::Crypto("sealed CI secret is not UTF-8".into()))?; |
| 2225 | - let plain = secret::open(key, &sealed)?; | |
| 2159 | + let plain = secret::open(self.secret_key()?, &sealed)?; | |
| 2226 | 2160 | let value = String::from_utf8(plain) |
| 2227 | 2161 | .map_err(|_| Error::Crypto("CI secret is not UTF-8".into()))?; |
| 2228 | 2162 | out.insert(name, value); |
| @@ -2305,15 +2239,17 @@ mod tests { | ||
| 2305 | 2239 | .collect(); |
| 2306 | 2240 | store |
| 2307 | 2241 | .create_run( |
| 2308 | - repo_id, | |
| 2309 | - "push", | |
| 2310 | - "refs/heads/main", | |
| 2311 | - "abc123", | |
| 2312 | - None, | |
| 2313 | - actor, | |
| 2314 | - approval, | |
| 2242 | + &NewRun { | |
| 2243 | + repo_id, | |
| 2244 | + trigger: "push", | |
| 2245 | + git_ref: "refs/heads/main", | |
| 2246 | + commit_oid: "abc123", | |
| 2247 | + pull_number: None, | |
| 2248 | + actor_id: actor, | |
| 2249 | + needs_approval: approval, | |
| 2250 | + config_error: None, | |
| 2251 | + }, | |
| 2315 | 2252 | &new, |
| 2316 | - None, | |
| 2317 | 2253 | ) |
| 2318 | 2254 | .await |
| 2319 | 2255 | .unwrap() |
| @@ -2363,7 +2299,6 @@ mod tests { | ||
| 2363 | 2299 | .create_registration_token(&fx.tahinli.id, 1) |
| 2364 | 2300 | .await |
| 2365 | 2301 | .unwrap(); |
| 2366 | - // Only the hash is stored. | |
| 2367 | 2302 | { |
| 2368 | 2303 | let conn = fx.store.inner.conn.lock().await; |
| 2369 | 2304 | let n = fetch_opt( |
| @@ -2511,7 +2446,6 @@ mod tests { | ||
| 2511 | 2446 | assert_eq!(found.config_overrides["limits.memory"], "8g"); |
| 2512 | 2447 | assert_eq!(found.reported_config["limits.memory"], "4g"); |
| 2513 | 2448 | |
| 2514 | - // Labels are claimed with at once, and a reset restores what the runner reported. | |
| 2515 | 2449 | fx.store |
| 2516 | 2450 | .set_runner_field(&runner.id, "labels", Some("linux, arm")) |
| 2517 | 2451 | .await |
| @@ -2530,7 +2464,6 @@ mod tests { | ||
| 2530 | 2464 | assert_eq!(after.labels, vec!["linux".to_string()]); |
| 2531 | 2465 | assert!(after.config_overrides.is_empty()); |
| 2532 | 2466 | |
| 2533 | - // Concurrency goes through the same entry point. | |
| 2534 | 2467 | fx.store |
| 2535 | 2468 | .set_runner_field(&runner.id, "concurrency", Some("6")) |
| 2536 | 2469 | .await |
| @@ -2566,7 +2499,6 @@ mod tests { | ||
| 2566 | 2499 | .await, |
| 2567 | 2500 | Err(Error::Invalid(_)) |
| 2568 | 2501 | )); |
| 2569 | - // A boot id alone is not enough, the version is the same for every build. | |
| 2570 | 2502 | fx.store |
| 2571 | 2503 | .record_runner_report(&runner.id, &boot_report("b1", &[])) |
| 2572 | 2504 | .await |
| @@ -2606,13 +2538,11 @@ mod tests { | ||
| 2606 | 2538 | assert_eq!(listed.restart.as_ref().unwrap().mode, RestartMode::Drain); |
| 2607 | 2539 | assert!(listed.supports_restart()); |
| 2608 | 2540 | |
| 2609 | - // The same process reporting again changes nothing. | |
| 2610 | 2541 | fx.store |
| 2611 | 2542 | .record_runner_report(&runner.id, &boot_report("b1", &["restart"])) |
| 2612 | 2543 | .await |
| 2613 | 2544 | .unwrap(); |
| 2614 | 2545 | assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some()); |
| 2615 | - // A heartbeat without a boot id changes nothing either. | |
| 2616 | 2546 | let beat = RunnerReport { |
| 2617 | 2547 | concurrency: Some(2), |
| 2618 | 2548 | ..RunnerReport::default() |
| @@ -2623,7 +2553,6 @@ mod tests { | ||
| 2623 | 2553 | .unwrap(); |
| 2624 | 2554 | assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some()); |
| 2625 | 2555 | |
| 2626 | - // "Restart now" replaces the pending drain. | |
| 2627 | 2556 | fx.store |
| 2628 | 2557 | .request_runner_restart(&runner.id, RestartMode::Now) |
| 2629 | 2558 | .await |
| @@ -2633,7 +2562,6 @@ mod tests { | ||
| 2633 | 2562 | Some(RestartMode::Now) |
| 2634 | 2563 | ); |
| 2635 | 2564 | |
| 2636 | - // The runner comes back with a new boot id: the request is cleared, capability kept. | |
| 2637 | 2565 | assert!( |
| 2638 | 2566 | fx.store |
| 2639 | 2567 | .record_runner_report(&runner.id, &boot_report("b2", &["restart"])) |
| @@ -2678,7 +2606,6 @@ mod tests { | ||
| 2678 | 2606 | .unwrap(), |
| 2679 | 2607 | "an identical report is not a change" |
| 2680 | 2608 | ); |
| 2681 | - // A heartbeat reports only the concurrency and keeps the host facts. | |
| 2682 | 2609 | let beat = RunnerReport { |
| 2683 | 2610 | concurrency: Some(3), |
| 2684 | 2611 | ..RunnerReport::default() |
| @@ -2699,7 +2626,6 @@ mod tests { | ||
| 2699 | 2626 | ); |
| 2700 | 2627 | assert_eq!(listed.running_jobs, 0); |
| 2701 | 2628 | |
| 2702 | - // The running count comes from the job table, and drops when the job finishes. | |
| 2703 | 2629 | create( |
| 2704 | 2630 | &fx.store, |
| 2705 | 2631 | &fx.repo.id, |
| @@ -2801,15 +2727,17 @@ mod tests { | ||
| 2801 | 2727 | let broken = fx |
| 2802 | 2728 | .store |
| 2803 | 2729 | .create_run( |
| 2804 | - &repo.id, | |
| 2805 | - "push", | |
| 2806 | - "refs/heads/main", | |
| 2807 | - "abc123", | |
| 2808 | - None, | |
| 2809 | - &fx.tahinli.id, | |
| 2810 | - false, | |
| 2730 | + &NewRun { | |
| 2731 | + repo_id: &repo.id, | |
| 2732 | + trigger: "push", | |
| 2733 | + git_ref: "refs/heads/main", | |
| 2734 | + commit_oid: "abc123", | |
| 2735 | + pull_number: None, | |
| 2736 | + actor_id: &fx.tahinli.id, | |
| 2737 | + needs_approval: false, | |
| 2738 | + config_error: Some("line 3: unknown key"), | |
| 2739 | + }, | |
| 2811 | 2740 | &[], |
| 2812 | - Some("line 3: unknown key"), | |
| 2813 | 2741 | ) |
| 2814 | 2742 | .await |
| 2815 | 2743 | .unwrap(); |
| @@ -2842,15 +2770,17 @@ mod tests { | ||
| 2842 | 2770 | let dev = fx |
| 2843 | 2771 | .store |
| 2844 | 2772 | .create_run( |
| 2845 | - &repo.id, | |
| 2846 | - "push", | |
| 2847 | - "refs/heads/dev", | |
| 2848 | - "abc123", | |
| 2849 | - None, | |
| 2850 | - &fx.tahinli.id, | |
| 2851 | - false, | |
| 2773 | + &NewRun { | |
| 2774 | + repo_id: &repo.id, | |
| 2775 | + trigger: "push", | |
| 2776 | + git_ref: "refs/heads/dev", | |
| 2777 | + commit_oid: "abc123", | |
| 2778 | + pull_number: None, | |
| 2779 | + actor_id: &fx.tahinli.id, | |
| 2780 | + needs_approval: false, | |
| 2781 | + config_error: Some("broken"), | |
| 2782 | + }, | |
| 2852 | 2783 | &[], |
| 2853 | - Some("broken"), | |
| 2854 | 2784 | ) |
| 2855 | 2785 | .await |
| 2856 | 2786 | .unwrap(); |
| @@ -2922,7 +2852,7 @@ mod tests { | ||
| 2922 | 2852 | let run = create(store, repo_id, actor, jobs, approval).await; |
| 2923 | 2853 | let conn = store.inner.conn.lock().await; |
| 2924 | 2854 | for (i, j) in jobs.iter().enumerate() { |
| 2925 | - let at = crate::time::stamp_before(Duration::from_secs(10 - i as u64)); | |
| 2855 | + let at = crate::time::stamp_ago(Duration::from_secs(10 - i as u64)); | |
| 2926 | 2856 | conn.execute( |
| 2927 | 2857 | "UPDATE ci_jobs SET queued_at = ?1 WHERE name = ?2", |
| 2928 | 2858 | (at, j.name.clone()), |
| @@ -2971,7 +2901,6 @@ mod tests { | ||
| 2971 | 2901 | ) |
| 2972 | 2902 | .await; |
| 2973 | 2903 | let runner = bare_runner(&["linux"]); |
| 2974 | - // 2 GiB free: the 4 GiB job is skipped (it is young), the 1 GiB one runs. | |
| 2975 | 2904 | let first = fx |
| 2976 | 2905 | .store |
| 2977 | 2906 | .claim_job_fitting(&runner, offer(2)) |
| @@ -2979,7 +2908,6 @@ mod tests { | ||
| 2979 | 2908 | .unwrap() |
| 2980 | 2909 | .unwrap(); |
| 2981 | 2910 | assert_eq!(first.0.name, "small"); |
| 2982 | - // 1 GiB left: a job with no memory reserves the default 1 GiB and fits. | |
| 2983 | 2911 | let second = fx |
| 2984 | 2912 | .store |
| 2985 | 2913 | .claim_job_fitting(&runner, offer(1)) |
| @@ -2987,7 +2915,6 @@ mod tests { | ||
| 2987 | 2915 | .unwrap() |
| 2988 | 2916 | .unwrap(); |
| 2989 | 2917 | assert_eq!(second.0.name, "plain"); |
| 2990 | - // Nothing fits in 0 GiB, and the big job is still queued. | |
| 2991 | 2918 | assert!( |
| 2992 | 2919 | fx.store |
| 2993 | 2920 | .claim_job_fitting(&runner, offer(0)) |
| @@ -2995,7 +2922,6 @@ mod tests { | ||
| 2995 | 2922 | .unwrap() |
| 2996 | 2923 | .is_none() |
| 2997 | 2924 | ); |
| 2998 | - // An idle runner takes it. | |
| 2999 | 2925 | let big = fx |
| 3000 | 2926 | .store |
| 3001 | 2927 | .claim_job_fitting(&runner, offer(6)) |
| @@ -3068,7 +2994,7 @@ mod tests { | ||
| 3068 | 2994 | false, |
| 3069 | 2995 | ) |
| 3070 | 2996 | .await; |
| 3071 | - let old = crate::time::stamp_before(Duration::from_secs(STARVE_AFTER_SECS + 60)); | |
| 2997 | + let old = crate::time::stamp_ago(Duration::from_secs(STARVE_AFTER_SECS + 60)); | |
| 3072 | 2998 | { |
| 3073 | 2999 | let conn = fx.store.inner.conn.lock().await; |
| 3074 | 3000 | conn.execute( |
| @@ -3087,7 +3013,6 @@ mod tests { | ||
| 3087 | 3013 | .is_none(), |
| 3088 | 3014 | "the old big job holds the line" |
| 3089 | 3015 | ); |
| 3090 | - // Once enough memory is free the big job goes first. | |
| 3091 | 3016 | let claimed = fx |
| 3092 | 3017 | .store |
| 3093 | 3018 | .claim_job_fitting(&runner, offer(5)) |
| @@ -3128,7 +3053,6 @@ mod tests { | ||
| 3128 | 3053 | assert_eq!(back.oom_kills, None); |
| 3129 | 3054 | let run = fx.store.run_by_id(&run.id).await.unwrap().unwrap(); |
| 3130 | 3055 | assert_eq!(run.state, RunState::Running); |
| 3131 | - // The old token no longer matches, and only a running job can be requeued. | |
| 3132 | 3056 | assert!(!fx.store.requeue_job(&claimed.id).await.unwrap()); |
| 3133 | 3057 | assert!(!fx.store.requeue_job("missing").await.unwrap()); |
| 3134 | 3058 | let (again, _, token) = fx |
| @@ -3292,7 +3216,6 @@ mod tests { | ||
| 3292 | 3216 | second.0.id.clone() |
| 3293 | 3217 | }; |
| 3294 | 3218 | |
| 3295 | - // Success unblocks b; c still waits on b. | |
| 3296 | 3219 | let after_a = fx |
| 3297 | 3220 | .store |
| 3298 | 3221 | .finish_job(&a_id, JobState::Success, Some(0), None) |
| @@ -3308,7 +3231,6 @@ mod tests { | ||
| 3308 | 3231 | JobState::Blocked |
| 3309 | 3232 | ); |
| 3310 | 3233 | |
| 3311 | - // Failure of b skips c transitively once b is done. | |
| 3312 | 3234 | let b_claim = fx.store.claim_job(&runner).await.unwrap().unwrap(); |
| 3313 | 3235 | assert_eq!(b_claim.0.name, "b"); |
| 3314 | 3236 | fx.store |
| @@ -3467,7 +3389,6 @@ mod tests { | ||
| 3467 | 3389 | .unwrap(); |
| 3468 | 3390 | assert_eq!(done.state, RunState::Cancelled); |
| 3469 | 3391 | assert!(done.finished_at.is_some()); |
| 3470 | - // A finished run does not change again. | |
| 3471 | 3392 | fx.store.request_cancel(&run.id).await.unwrap(); |
| 3472 | 3393 | assert_eq!( |
| 3473 | 3394 | fx.store.run_by_id(&run.id).await.unwrap().unwrap().state, |
| @@ -3528,7 +3449,6 @@ mod tests { | ||
| 3528 | 3449 | .finish_job(&b.id, JobState::Failure, Some(1), None) |
| 3529 | 3450 | .await |
| 3530 | 3451 | .unwrap(); |
| 3531 | - // Fail fast cancels the queued `d` and skips `c`. | |
| 3532 | 3452 | let done = fx.store.run_by_id(&first.id).await.unwrap().unwrap(); |
| 3533 | 3453 | assert_eq!(done.state, RunState::Failure); |
| 3534 | 3454 | assert_eq!( |
| @@ -3557,7 +3477,6 @@ mod tests { | ||
| 3557 | 3477 | assert_eq!(c2.state, JobState::Blocked); |
| 3558 | 3478 | assert_eq!(spec_needs(&c2.spec_json), ["b"]); |
| 3559 | 3479 | |
| 3560 | - // One finished job brings its dependants; a live one is refused. | |
| 3561 | 3480 | let single = fx |
| 3562 | 3481 | .store |
| 3563 | 3482 | .rerun_job(&first.id, &a.id, &fx.tahinli.id) |
| @@ -3628,7 +3547,6 @@ mod tests { | ||
| 3628 | 3547 | .await |
| 3629 | 3548 | .unwrap() |
| 3630 | 3549 | .unwrap(); |
| 3631 | - // Nothing is older than the epoch. | |
| 3632 | 3550 | assert!(fx.store.reap_lost_jobs(DAWN).await.unwrap().is_empty()); |
| 3633 | 3551 | let future = stamp_after(Duration::from_secs(3600)); |
| 3634 | 3552 | let reaped = fx.store.reap_lost_jobs(&future).await.unwrap(); |
| @@ -3739,13 +3657,10 @@ mod tests { | ||
| 3739 | 3657 | .await |
| 3740 | 3658 | .unwrap(); |
| 3741 | 3659 | artifacts.push(made.id); |
| 3742 | - // ULIDs made in the same millisecond do not sort by creation order. | |
| 3743 | 3660 | tokio::time::sleep(Duration::from_millis(2)).await; |
| 3744 | 3661 | } |
| 3745 | - // Keep the newest two runs: the oldest run's artifact goes. | |
| 3746 | 3662 | let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap(); |
| 3747 | 3663 | assert_eq!(deleted, vec![artifacts[0].clone()]); |
| 3748 | - // 20 + 30 bytes left against a 35 byte limit: the older run (20 bytes) goes. | |
| 3749 | 3664 | let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); |
| 3750 | 3665 | assert_eq!(deleted, vec![artifacts[1].clone()]); |
| 3751 | 3666 | let (_, again, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); |
| @@ -3795,7 +3710,6 @@ mod tests { | ||
| 3795 | 3710 | .await |
| 3796 | 3711 | .unwrap(); |
| 3797 | 3712 | |
| 3798 | - // Raw storage is sealed, not plaintext. | |
| 3799 | 3713 | { |
| 3800 | 3714 | let conn = fx.store.inner.conn.lock().await; |
| 3801 | 3715 | let raw = fetch_opt( |
| @@ -3827,7 +3741,6 @@ mod tests { | ||
| 3827 | 3741 | assert_eq!(values.len(), 1); |
| 3828 | 3742 | assert_eq!(values.get("DEPLOY_KEY").map(String::as_str), Some(plain)); |
| 3829 | 3743 | |
| 3830 | - // Replacing keeps one row. | |
| 3831 | 3744 | fx.store |
| 3832 | 3745 | .set_ci_secret(&repo.id, "DEPLOY_KEY", b"rotated") |
| 3833 | 3746 | .await |
crates/forge-core/src/store/contributions.rsmodified+36 -54
| @@ -13,6 +13,27 @@ use crate::tz::local_date; | ||
| 13 | 13 | /// Most contributions `contributions_between` returns for one day. |
| 14 | 14 | const DAY_LIMIT: u32 = 200; |
| 15 | 15 | |
| 16 | +fn activity_sql() -> String { | |
| 17 | + format!( | |
| 18 | + "SELECT 'push' AS kind, actor_id AS user_id, repo_id, created_at, ref_name, \ | |
| 19 | + 0 AS number, '' AS title, '' AS commit_oid FROM push_events \ | |
| 20 | + WHERE new_oid NOT IN ('{ZERO_OID_SHA1}', '{ZERO_OID_SHA256}') \ | |
| 21 | + AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ | |
| 22 | + UNION ALL \ | |
| 23 | + SELECT kind, author_id, repo_id, created_at, '', number, title, '' FROM issues \ | |
| 24 | + WHERE kind IN ('issue', 'pull') \ | |
| 25 | + AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ | |
| 26 | + UNION ALL \ | |
| 27 | + SELECT 'comment', c.author_id, i.repo_id, c.created_at, '', i.number, i.title, '' \ | |
| 28 | + FROM comments c JOIN issues i ON i.id = c.issue_id \ | |
| 29 | + WHERE i.repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ | |
| 30 | + UNION ALL \ | |
| 31 | + SELECT 'coauthored', user_id, repo_id, created_at, '', 0, summary, commit_oid \ | |
| 32 | + FROM coauthored_commits \ | |
| 33 | + WHERE repo_id IN (SELECT id FROM repos WHERE visibility = 'public')" | |
| 34 | + ) | |
| 35 | +} | |
| 36 | + | |
| 16 | 37 | /// What a contribution was: a branch push, an issue, pull request or comment the user wrote, or |
| 17 | 38 | /// a commit the user was credited with as a co-author. |
| 18 | 39 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| @@ -81,35 +102,21 @@ impl Store { | ||
| 81 | 102 | since: &str, |
| 82 | 103 | tz: &str, |
| 83 | 104 | ) -> Result<Vec<(String, u32)>> { |
| 84 | - // Parameters: ?1 user, ?2 since, ?3 and ?4 zero oids. | |
| 85 | - let sql = "SELECT minute, COUNT(*) FROM ( \ | |
| 86 | - SELECT substr(created_at, 1, 16) AS minute FROM push_events \ | |
| 87 | - WHERE actor_id = ?1 AND created_at >= ?2 AND new_oid NOT IN (?3, ?4) \ | |
| 88 | - AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ | |
| 89 | - UNION ALL \ | |
| 90 | - SELECT substr(created_at, 1, 16) FROM issues \ | |
| 91 | - WHERE author_id = ?1 AND created_at >= ?2 AND kind IN ('issue', 'pull') \ | |
| 92 | - AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ | |
| 93 | - UNION ALL \ | |
| 94 | - SELECT substr(c.created_at, 1, 16) FROM comments c JOIN issues i ON i.id = c.issue_id \ | |
| 95 | - WHERE c.author_id = ?1 AND c.created_at >= ?2 AND i.repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ | |
| 96 | - UNION ALL \ | |
| 97 | - SELECT substr(created_at, 1, 16) FROM coauthored_commits \ | |
| 98 | - WHERE user_id = ?1 AND created_at >= ?2 AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ | |
| 99 | - ) GROUP BY minute"; | |
| 105 | + let sql = format!( | |
| 106 | + "SELECT substr(created_at, 1, 16) AS minute, COUNT(*) FROM ({}) \ | |
| 107 | + WHERE user_id = ?1 AND created_at >= ?2 GROUP BY minute", | |
| 108 | + activity_sql() | |
| 109 | + ); | |
| 100 | 110 | let params = vec![ |
| 101 | 111 | Value::Text(user_id.to_string()), |
| 102 | 112 | Value::Text(since.to_string()), |
| 103 | - Value::Text(ZERO_OID_SHA1.to_string()), | |
| 104 | - Value::Text(ZERO_OID_SHA256.to_string()), | |
| 105 | 113 | ]; |
| 106 | 114 | |
| 107 | 115 | let conn = self.read_conn().await; |
| 108 | - let rows = fetch_all(&conn, sql, params, |row| { | |
| 116 | + let rows = fetch_all(&conn, &sql, params, |row| { | |
| 109 | 117 | Ok((col_text(row, 0)?, col_int(row, 1)?)) |
| 110 | 118 | }) |
| 111 | 119 | .await?; |
| 112 | - // `minute` is `YYYY-MM-DDTHH:MM` in UTC; the stamp is completed with seconds to parse. | |
| 113 | 120 | let mut days: BTreeMap<String, u32> = BTreeMap::new(); |
| 114 | 121 | for (minute, count) in rows { |
| 115 | 122 | let Ok(ts) = format!("{minute}:00Z").parse::<Timestamp>() else { |
| @@ -131,41 +138,23 @@ impl Store { | ||
| 131 | 138 | from: &str, |
| 132 | 139 | to: &str, |
| 133 | 140 | ) -> Result<Vec<ContributionItem>> { |
| 134 | - // Parameters: ?1 user, ?2 from, ?3 to, ?4 and ?5 zero oids. | |
| 135 | - let sql = "SELECT 'push' AS created_kind, o.username, r.name, p.created_at, p.ref_name, \ | |
| 136 | - 0, '', '' FROM push_events p \ | |
| 137 | - JOIN repos r ON r.id = p.repo_id JOIN users o ON o.id = r.owner_id \ | |
| 138 | - WHERE p.actor_id = ?1 AND p.created_at >= ?2 AND p.created_at < ?3 \ | |
| 139 | - AND p.new_oid NOT IN (?4, ?5) AND r.visibility = 'public' \ | |
| 140 | - UNION ALL \ | |
| 141 | - SELECT i.kind, o.username, r.name, i.created_at, '', i.number, i.title, '' FROM issues i \ | |
| 142 | - JOIN repos r ON r.id = i.repo_id JOIN users o ON o.id = r.owner_id \ | |
| 143 | - WHERE i.author_id = ?1 AND i.created_at >= ?2 AND i.created_at < ?3 \ | |
| 144 | - AND i.kind IN ('issue', 'pull') AND r.visibility = 'public' \ | |
| 145 | - UNION ALL \ | |
| 146 | - SELECT 'comment', o.username, r.name, c.created_at, '', i.number, i.title, '' \ | |
| 147 | - FROM comments c JOIN issues i ON i.id = c.issue_id \ | |
| 148 | - JOIN repos r ON r.id = i.repo_id JOIN users o ON o.id = r.owner_id \ | |
| 149 | - WHERE c.author_id = ?1 AND c.created_at >= ?2 AND c.created_at < ?3 \ | |
| 150 | - AND r.visibility = 'public' \ | |
| 151 | - UNION ALL \ | |
| 152 | - SELECT 'coauthored', o.username, r.name, k.created_at, '', 0, k.summary, k.commit_oid \ | |
| 153 | - FROM coauthored_commits k \ | |
| 154 | - JOIN repos r ON r.id = k.repo_id JOIN users o ON o.id = r.owner_id \ | |
| 155 | - WHERE k.user_id = ?1 AND k.created_at >= ?2 AND k.created_at < ?3 \ | |
| 156 | - AND r.visibility = 'public' \ | |
| 157 | - ORDER BY created_at DESC LIMIT ?6"; | |
| 141 | + let sql = format!( | |
| 142 | + "SELECT a.kind, o.username, r.name, a.created_at, a.ref_name, a.number, a.title, \ | |
| 143 | + a.commit_oid FROM ({}) a \ | |
| 144 | + JOIN repos r ON r.id = a.repo_id JOIN users o ON o.id = r.owner_id \ | |
| 145 | + WHERE a.user_id = ?1 AND a.created_at >= ?2 AND a.created_at < ?3 \ | |
| 146 | + ORDER BY a.created_at DESC LIMIT ?4", | |
| 147 | + activity_sql() | |
| 148 | + ); | |
| 158 | 149 | let params = vec![ |
| 159 | 150 | Value::Text(user_id.to_string()), |
| 160 | 151 | Value::Text(from.to_string()), |
| 161 | 152 | Value::Text(to.to_string()), |
| 162 | - Value::Text(ZERO_OID_SHA1.to_string()), | |
| 163 | - Value::Text(ZERO_OID_SHA256.to_string()), | |
| 164 | 153 | Value::Integer(i64::from(DAY_LIMIT)), |
| 165 | 154 | ]; |
| 166 | 155 | |
| 167 | 156 | let conn = self.read_conn().await; |
| 168 | - fetch_all(&conn, sql, params, map_item).await | |
| 157 | + fetch_all(&conn, &sql, params, map_item).await | |
| 169 | 158 | } |
| 170 | 159 | |
| 171 | 160 | /// Credits `user_id` with a co-authored commit in `repo_id`. A commit is recorded once per |
| @@ -311,7 +300,6 @@ mod tests { | ||
| 311 | 300 | .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at) |
| 312 | 301 | .await |
| 313 | 302 | .unwrap(); |
| 314 | - // A repeat of the same commit is ignored. | |
| 315 | 303 | store |
| 316 | 304 | .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at) |
| 317 | 305 | .await |
| @@ -349,7 +337,6 @@ mod tests { | ||
| 349 | 337 | .await |
| 350 | 338 | .unwrap(); |
| 351 | 339 | |
| 352 | - // Day one: a push and an issue. | |
| 353 | 340 | let day1 = "2026-03-01T10:00:00.000000000Z"; |
| 354 | 341 | let day2 = "2026-03-02T10:00:00.000000000Z"; |
| 355 | 342 | let before = "2026-02-28T10:00:00.000000000Z"; |
| @@ -363,7 +350,6 @@ mod tests { | ||
| 363 | 350 | .unwrap(); |
| 364 | 351 | set_created_at(&store, "issues", &issue.id, day1).await; |
| 365 | 352 | |
| 366 | - // Day two: a branch update, a deletion (not counted), a pull request, a comment. | |
| 367 | 353 | store |
| 368 | 354 | .record_push_event_at(&demo.id, &tahinli.id, "refs/heads/main", OID, OID, day2) |
| 369 | 355 | .await |
| @@ -393,7 +379,6 @@ mod tests { | ||
| 393 | 379 | .unwrap(); |
| 394 | 380 | set_created_at(&store, "comments", &comment.id, day2).await; |
| 395 | 381 | |
| 396 | - // Before `since`, and someone else's activity: left out. | |
| 397 | 382 | store |
| 398 | 383 | .record_push_event_at(&demo.id, &tahinli.id, "refs/heads/main", OID, OID, before) |
| 399 | 384 | .await |
| @@ -413,8 +398,6 @@ mod tests { | ||
| 413 | 398 | vec![("2026-03-01".to_string(), 2), ("2026-03-02".to_string(), 3)] |
| 414 | 399 | ); |
| 415 | 400 | |
| 416 | - // `since` filters out the first day. In Kiritimati (+14) the 10:00 UTC events fall on | |
| 417 | - // the next local day. | |
| 418 | 401 | let later = store |
| 419 | 402 | .contribution_counts( |
| 420 | 403 | &tahinli.id, |
| @@ -425,7 +408,6 @@ mod tests { | ||
| 425 | 408 | .unwrap(); |
| 426 | 409 | assert_eq!(later, vec![("2026-03-03".to_string(), 3)]); |
| 427 | 410 | |
| 428 | - // A user with nothing in range gets an empty list. | |
| 429 | 411 | assert!( |
| 430 | 412 | store |
| 431 | 413 | .contribution_counts(&bob.id, "2026-03-03T00:00:00.000000000Z", "UTC") |
crates/forge-core/src/store/discussions.rsmodified+56 -48
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | use turso::transaction::Transaction; |
| 6 | 6 | use turso::{Connection, Row, Value}; |
| 7 | 7 | |
| 8 | -use super::issues::finish; | |
| 8 | +use super::finish; | |
| 9 | 9 | use super::{ |
| 10 | 10 | Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id, |
| 11 | 11 | }; |
| @@ -452,23 +452,16 @@ impl Store { | ||
| 452 | 452 | .await |
| 453 | 453 | .map_err(db_err)?; |
| 454 | 454 | if discussion.author_id != author_id { |
| 455 | - tx.execute( | |
| 456 | - "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \ | |
| 457 | - last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, 'reply', ?4, 1, ?5) \ | |
| 458 | - ON CONFLICT (user_id, discussion_id) DO UPDATE SET \ | |
| 459 | - reason = CASE WHEN discussion_notifications.reason = 'mention' THEN 'mention' \ | |
| 460 | - ELSE 'reply' END, last_actor_id = excluded.last_actor_id, unread = 1, \ | |
| 461 | - updated_at = excluded.updated_at", | |
| 462 | - ( | |
| 463 | - discussion.author_id.clone(), | |
| 464 | - discussion_id.to_string(), | |
| 465 | - discussion.repo_id.clone(), | |
| 466 | - author_id.to_string(), | |
| 467 | - now, | |
| 468 | - ), | |
| 455 | + upsert_discussion_notification( | |
| 456 | + &tx, | |
| 457 | + &discussion.author_id, | |
| 458 | + &discussion.repo_id, | |
| 459 | + discussion_id, | |
| 460 | + "reply", | |
| 461 | + author_id, | |
| 462 | + &now, | |
| 469 | 463 | ) |
| 470 | - .await | |
| 471 | - .map_err(db_err)?; | |
| 464 | + .await?; | |
| 472 | 465 | } |
| 473 | 466 | Ok(comment) |
| 474 | 467 | } |
| @@ -598,21 +591,16 @@ impl Store { | ||
| 598 | 591 | let conn = self.inner.conn.lock().await; |
| 599 | 592 | let now = now_stamp(); |
| 600 | 593 | for user_id in user_ids { |
| 601 | - conn.execute( | |
| 602 | - "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \ | |
| 603 | - last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, 'mention', ?4, 1, ?5) \ | |
| 604 | - ON CONFLICT (user_id, discussion_id) DO UPDATE SET reason = 'mention', \ | |
| 605 | - last_actor_id = excluded.last_actor_id, unread = 1, updated_at = excluded.updated_at", | |
| 606 | - ( | |
| 607 | - user_id.clone(), | |
| 608 | - discussion_id.to_string(), | |
| 609 | - repo_id.to_string(), | |
| 610 | - actor_id.to_string(), | |
| 611 | - now.clone(), | |
| 612 | - ), | |
| 594 | + upsert_discussion_notification( | |
| 595 | + &conn, | |
| 596 | + user_id, | |
| 597 | + repo_id, | |
| 598 | + discussion_id, | |
| 599 | + "mention", | |
| 600 | + actor_id, | |
| 601 | + &now, | |
| 613 | 602 | ) |
| 614 | - .await | |
| 615 | - .map_err(db_err)?; | |
| 603 | + .await?; | |
| 616 | 604 | } |
| 617 | 605 | Ok(()) |
| 618 | 606 | } |
| @@ -696,27 +684,47 @@ impl Store { | ||
| 696 | 684 | repo_id: Option<&str>, |
| 697 | 685 | ) -> Result<()> { |
| 698 | 686 | let conn = self.inner.conn.lock().await; |
| 699 | - let result = match repo_id { | |
| 700 | - Some(repo) => { | |
| 701 | - conn.execute( | |
| 702 | - "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND repo_id = ?2 AND unread = 1", | |
| 703 | - (user_id.to_string(), repo.to_string()), | |
| 704 | - ) | |
| 705 | - .await | |
| 706 | - } | |
| 707 | - None => { | |
| 708 | - conn.execute( | |
| 709 | - "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1", | |
| 710 | - (user_id.to_string(),), | |
| 711 | - ) | |
| 712 | - .await | |
| 713 | - } | |
| 714 | - }; | |
| 715 | - result.map_err(db_err)?; | |
| 687 | + conn.execute( | |
| 688 | + "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1 \ | |
| 689 | + AND (?2 IS NULL OR repo_id = ?2)", | |
| 690 | + (user_id.to_string(), repo_id.map(str::to_string)), | |
| 691 | + ) | |
| 692 | + .await | |
| 693 | + .map_err(db_err)?; | |
| 716 | 694 | Ok(()) |
| 717 | 695 | } |
| 718 | 696 | } |
| 719 | 697 | |
| 698 | +async fn upsert_discussion_notification( | |
| 699 | + conn: &Connection, | |
| 700 | + user_id: &str, | |
| 701 | + repo_id: &str, | |
| 702 | + discussion_id: &str, | |
| 703 | + reason: &str, | |
| 704 | + actor_id: &str, | |
| 705 | + now: &str, | |
| 706 | +) -> Result<()> { | |
| 707 | + conn.execute( | |
| 708 | + "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \ | |
| 709 | + last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, 1, ?6) \ | |
| 710 | + ON CONFLICT (user_id, discussion_id) DO UPDATE SET \ | |
| 711 | + reason = CASE WHEN excluded.reason = 'mention' OR discussion_notifications.reason = 'mention' \ | |
| 712 | + THEN 'mention' ELSE 'reply' END, last_actor_id = excluded.last_actor_id, unread = 1, \ | |
| 713 | + updated_at = excluded.updated_at", | |
| 714 | + ( | |
| 715 | + user_id.to_string(), | |
| 716 | + discussion_id.to_string(), | |
| 717 | + repo_id.to_string(), | |
| 718 | + reason.to_string(), | |
| 719 | + actor_id.to_string(), | |
| 720 | + now.to_string(), | |
| 721 | + ), | |
| 722 | + ) | |
| 723 | + .await | |
| 724 | + .map_err(db_err)?; | |
| 725 | + Ok(()) | |
| 726 | +} | |
| 727 | + | |
| 720 | 728 | #[cfg(test)] |
| 721 | 729 | mod tests { |
| 722 | 730 | use super::*; |
crates/forge-core/src/store/edit_history_read.rsmodified+29 -17
| @@ -4,11 +4,26 @@ | ||
| 4 | 4 | |
| 5 | 5 | use std::collections::HashMap; |
| 6 | 6 | |
| 7 | -use super::{Store, col_int, col_opt_text, col_text, fetch_all, fetch_opt}; | |
| 7 | +use super::{IN_CHUNK, Store, col_int, col_opt_text, col_text, fetch_all, fetch_opt, placeholders}; | |
| 8 | 8 | use crate::error::Result; |
| 9 | 9 | |
| 10 | -/// Longest id list sent in one `IN (...)` query. | |
| 11 | -const CHUNK: usize = 500; | |
| 10 | +/// The kinds of target that have edit history. `as_str` is the stored text. | |
| 11 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 12 | +pub enum EditTarget { | |
| 13 | + Issue, | |
| 14 | + Comment, | |
| 15 | + ReviewComment, | |
| 16 | +} | |
| 17 | + | |
| 18 | +impl EditTarget { | |
| 19 | + pub fn as_str(self) -> &'static str { | |
| 20 | + match self { | |
| 21 | + Self::Issue => "issue", | |
| 22 | + Self::Comment => "comment", | |
| 23 | + Self::ReviewComment => "review_comment", | |
| 24 | + } | |
| 25 | + } | |
| 26 | +} | |
| 12 | 27 | |
| 13 | 28 | /// One previous version of an issue, pull request, comment or review comment. |
| 14 | 29 | #[derive(Debug, Clone, PartialEq)] |
| @@ -22,15 +37,11 @@ pub struct EditVersion { | ||
| 22 | 37 | pub old_body: String, |
| 23 | 38 | } |
| 24 | 39 | |
| 25 | -fn placeholders(n: usize) -> String { | |
| 26 | - vec!["?"; n].join(",") | |
| 27 | -} | |
| 28 | - | |
| 29 | 40 | impl Store { |
| 30 | 41 | /// The previous versions of one target, newest first. |
| 31 | 42 | pub async fn edit_history( |
| 32 | 43 | &self, |
| 33 | - target_kind: &str, | |
| 44 | + target_kind: EditTarget, | |
| 34 | 45 | target_id: &str, |
| 35 | 46 | ) -> Result<Vec<EditVersion>> { |
| 36 | 47 | let conn = self.read_conn().await; |
| @@ -40,7 +51,7 @@ impl Store { | ||
| 40 | 51 | FROM edit_history h JOIN users u ON u.id = h.editor_id \ |
| 41 | 52 | WHERE h.target_kind = ?1 AND h.target_id = ?2 \ |
| 42 | 53 | ORDER BY h.edited_at DESC, h.id DESC", |
| 43 | - (target_kind.to_string(), target_id.to_string()), | |
| 54 | + (target_kind.as_str().to_string(), target_id.to_string()), | |
| 44 | 55 | |row| { |
| 45 | 56 | Ok(EditVersion { |
| 46 | 57 | id: col_text(row, 0)?, |
| @@ -58,7 +69,7 @@ impl Store { | ||
| 58 | 69 | /// absent from the map. One query per 500 ids. |
| 59 | 70 | pub async fn edit_count( |
| 60 | 71 | &self, |
| 61 | - target_kind: &str, | |
| 72 | + target_kind: EditTarget, | |
| 62 | 73 | target_ids: &[&str], |
| 63 | 74 | ) -> Result<HashMap<String, u64>> { |
| 64 | 75 | let mut out = HashMap::new(); |
| @@ -66,14 +77,14 @@ impl Store { | ||
| 66 | 77 | return Ok(out); |
| 67 | 78 | } |
| 68 | 79 | let conn = self.read_conn().await; |
| 69 | - for chunk in target_ids.chunks(CHUNK) { | |
| 80 | + for chunk in target_ids.chunks(IN_CHUNK) { | |
| 70 | 81 | let sql = format!( |
| 71 | 82 | "SELECT target_id, COUNT(*) FROM edit_history \ |
| 72 | 83 | WHERE target_kind = ?1 AND target_id IN ({}) GROUP BY target_id", |
| 73 | 84 | placeholders(chunk.len()) |
| 74 | 85 | ); |
| 75 | 86 | let mut params: Vec<turso::Value> = Vec::with_capacity(chunk.len() + 1); |
| 76 | - params.push(turso::Value::Text(target_kind.to_string())); | |
| 87 | + params.push(turso::Value::Text(target_kind.as_str().to_string())); | |
| 77 | 88 | params.extend(chunk.iter().map(|id| turso::Value::Text((*id).to_string()))); |
| 78 | 89 | let rows = fetch_all(&conn, &sql, params, |row| { |
| 79 | 90 | let count = u64::try_from(col_int(row, 1)?).unwrap_or(0); |
| @@ -89,14 +100,15 @@ impl Store { | ||
| 89 | 100 | /// target does not exist (a deleted comment has no history either). |
| 90 | 101 | pub async fn edit_target_issue( |
| 91 | 102 | &self, |
| 92 | - target_kind: &str, | |
| 103 | + target_kind: EditTarget, | |
| 93 | 104 | target_id: &str, |
| 94 | 105 | ) -> Result<Option<String>> { |
| 95 | 106 | let sql = match target_kind { |
| 96 | - "issue" => "SELECT id FROM issues WHERE id = ?1 LIMIT 1", | |
| 97 | - "comment" => "SELECT issue_id FROM comments WHERE id = ?1 LIMIT 1", | |
| 98 | - "review_comment" => "SELECT issue_id FROM review_comments WHERE id = ?1 LIMIT 1", | |
| 99 | - _ => return Ok(None), | |
| 107 | + EditTarget::Issue => "SELECT id FROM issues WHERE id = ?1 LIMIT 1", | |
| 108 | + EditTarget::Comment => "SELECT issue_id FROM comments WHERE id = ?1 LIMIT 1", | |
| 109 | + EditTarget::ReviewComment => { | |
| 110 | + "SELECT issue_id FROM review_comments WHERE id = ?1 LIMIT 1" | |
| 111 | + } | |
| 100 | 112 | }; |
| 101 | 113 | let conn = self.read_conn().await; |
| 102 | 114 | fetch_opt(&conn, sql, (target_id.to_string(),), |row| col_text(row, 0)).await |
crates/forge-core/src/store/health.rsmodified+3 -4
| @@ -5,17 +5,16 @@ use crate::error::{Error, Result}; | ||
| 5 | 5 | use crate::time::{stamp_ago, stamp_to_unix}; |
| 6 | 6 | |
| 7 | 7 | /// Window in which a runner's last report counts as online. |
| 8 | -pub const RUNNER_ONLINE_SECS: u64 = 90; | |
| 8 | +pub const RUNNER_ONLINE_SECS: i64 = 90; | |
| 9 | 9 | |
| 10 | 10 | /// Whether a runner counts as online at `now_unix`: enabled, and its last report within |
| 11 | 11 | /// [`RUNNER_ONLINE_SECS`]. The runners page dot and the live signal of the runners page both use |
| 12 | 12 | /// this one rule. |
| 13 | 13 | pub fn runner_is_online(disabled: bool, last_seen_at: Option<&str>, now_unix: i64) -> bool { |
| 14 | - let limit = i64::try_from(RUNNER_ONLINE_SECS).unwrap_or(i64::MAX); | |
| 15 | 14 | !disabled |
| 16 | 15 | && last_seen_at |
| 17 | 16 | .and_then(stamp_to_unix) |
| 18 | - .is_some_and(|seen| now_unix.saturating_sub(seen) <= limit) | |
| 17 | + .is_some_and(|seen| now_unix.saturating_sub(seen) <= RUNNER_ONLINE_SECS) | |
| 19 | 18 | } |
| 20 | 19 | |
| 21 | 20 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| @@ -31,7 +30,7 @@ impl Store { | ||
| 31 | 30 | /// Counts of repos, users, queued CI jobs and runners. Five indexed `COUNT(*)` queries. |
| 32 | 31 | pub async fn health_counts(&self) -> Result<HealthCounts> { |
| 33 | 32 | let conn = self.read_conn().await; |
| 34 | - let since = stamp_ago(std::time::Duration::from_secs(RUNNER_ONLINE_SECS)); | |
| 33 | + let since = stamp_ago(std::time::Duration::from_secs(RUNNER_ONLINE_SECS.unsigned_abs())); | |
| 35 | 34 | let plain = |sql: &'static str| { |
| 36 | 35 | let conn = &conn; |
| 37 | 36 | async move { |
crates/forge-core/src/store/imports.rsmodified+7 -7
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | |
| 4 | 4 | use turso::{Row, Value}; |
| 5 | 5 | |
| 6 | -use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; | |
| 6 | +use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id, text}; | |
| 7 | 7 | use crate::error::{Error, Result}; |
| 8 | 8 | use crate::time::now_stamp; |
| 9 | 9 | |
| @@ -100,10 +100,6 @@ fn map_job(row: &Row) -> Result<ImportJob> { | ||
| 100 | 100 | }) |
| 101 | 101 | } |
| 102 | 102 | |
| 103 | -fn text(s: &str) -> Value { | |
| 104 | - Value::Text(s.to_owned()) | |
| 105 | -} | |
| 106 | - | |
| 107 | 103 | impl Store { |
| 108 | 104 | /// Creates a queued job. `source_ref` must not hold a credential. |
| 109 | 105 | pub async fn create_import_job( |
| @@ -186,7 +182,11 @@ impl Store { | ||
| 186 | 182 | error: Option<&str>, |
| 187 | 183 | ) -> Result<()> { |
| 188 | 184 | let now = now_stamp(); |
| 189 | - let finished = state.is_finished().then(|| now.clone()); | |
| 185 | + let finished = if state.is_finished() { | |
| 186 | + text(&now) | |
| 187 | + } else { | |
| 188 | + Value::Null | |
| 189 | + }; | |
| 190 | 190 | let conn = self.inner.conn.lock().await; |
| 191 | 191 | conn.execute( |
| 192 | 192 | "UPDATE import_jobs SET state = ?2, error = ?3, updated_at = ?4, finished_at = ?5 \ |
| @@ -196,7 +196,7 @@ impl Store { | ||
| 196 | 196 | text(state.as_str()), |
| 197 | 197 | error.map_or(Value::Null, text), |
| 198 | 198 | text(&now), |
| 199 | - finished.as_deref().map_or(Value::Null, text), | |
| 199 | + finished, | |
| 200 | 200 | ], |
| 201 | 201 | ) |
| 202 | 202 | .await |
crates/forge-core/src/store/issues.rsmodified+17 -125
| @@ -1,6 +1,3 @@ | ||
| 1 | -//! Issues, comments, timeline events and milestones. Every multi-row write runs in one | |
| 2 | -//! transaction. Numbers come from `repos.next_issue_number` in the same transaction as the insert. | |
| 3 | - | |
| 4 | 1 | use std::collections::HashMap; |
| 5 | 2 | |
| 6 | 3 | use serde_json::{Map, Value as Json}; |
| @@ -8,8 +5,8 @@ use turso::transaction::Transaction; | ||
| 8 | 5 | use turso::{Connection, Row, Value}; |
| 9 | 6 | |
| 10 | 7 | use super::{ |
| 11 | - Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, missing_row, | |
| 12 | - new_id, | |
| 8 | + IN_CHUNK, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, | |
| 9 | + insert_err, missing_row, new_id, placeholders, | |
| 13 | 10 | }; |
| 14 | 11 | use crate::error::{Error, Result}; |
| 15 | 12 | use crate::issues::{ |
| @@ -19,7 +16,6 @@ use crate::issues::{ | ||
| 19 | 16 | use crate::names::normalize_name; |
| 20 | 17 | use crate::time::now_stamp; |
| 21 | 18 | |
| 22 | -/// Event kinds the timeline knows. Anything else is rejected by `add_event`. | |
| 23 | 19 | const EVENT_KINDS: &[&str] = &[ |
| 24 | 20 | "closed", |
| 25 | 21 | "reopened", |
| @@ -33,7 +29,6 @@ const EVENT_KINDS: &[&str] = &[ | ||
| 33 | 29 | "referenced", |
| 34 | 30 | "locked", |
| 35 | 31 | "unlocked", |
| 36 | - // Pull requests (store/pulls.rs). | |
| 37 | 32 | "merged", |
| 38 | 33 | "head_updated", |
| 39 | 34 | "base_changed", |
| @@ -44,11 +39,9 @@ const EVENT_KINDS: &[&str] = &[ | ||
| 44 | 39 | "converted_to_draft", |
| 45 | 40 | "auto_merge_enabled", |
| 46 | 41 | "auto_merge_disabled", |
| 47 | - // Pull request reviews (store/reviews.rs). | |
| 48 | 42 | "review_dismissed", |
| 49 | 43 | "thread_resolved", |
| 50 | 44 | "thread_unresolved", |
| 51 | - // Pinned issues (store/pinned.rs). | |
| 52 | 45 | "pinned", |
| 53 | 46 | "unpinned", |
| 54 | 47 | ]; |
| @@ -59,15 +52,11 @@ pub(super) const ISSUE_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, | ||
| 59 | 52 | const COMMENT_COLS: &str = "id, issue_id, author_id, body, created_at, updated_at, edited"; |
| 60 | 53 | const LABEL_COLS: &str = "l.id, l.repo_id, l.name, l.color, l.description"; |
| 61 | 54 | |
| 62 | -/// Caps the number of placeholders in one `IN (...)` list. | |
| 63 | -const IN_CHUNK: usize = 500; | |
| 64 | - | |
| 65 | 55 | pub(super) fn parse_db<T: std::str::FromStr<Err = Error>>(s: &str) -> Result<T> { |
| 66 | 56 | s.parse::<T>() |
| 67 | 57 | .map_err(|e| Error::Database(format!("stored value {s:?}: {e}"))) |
| 68 | 58 | } |
| 69 | 59 | |
| 70 | -/// Reads `ISSUE_COLS` (columns 0 to 14). | |
| 71 | 60 | pub(super) fn map_issue(row: &Row) -> Result<Issue> { |
| 72 | 61 | Ok(Issue { |
| 73 | 62 | id: col_text(row, 0)?, |
| @@ -117,7 +106,6 @@ fn map_event(row: &Row) -> Result<IssueEvent> { | ||
| 117 | 106 | }) |
| 118 | 107 | } |
| 119 | 108 | |
| 120 | -/// A label read from `LABEL_COLS` (or any five columns) starting at `base`. | |
| 121 | 109 | fn map_label(row: &Row, base: usize) -> Result<Label> { |
| 122 | 110 | Ok(Label { |
| 123 | 111 | id: col_text(row, base)?, |
| @@ -128,10 +116,6 @@ fn map_label(row: &Row, base: usize) -> Result<Label> { | ||
| 128 | 116 | }) |
| 129 | 117 | } |
| 130 | 118 | |
| 131 | -fn placeholders(n: usize) -> String { | |
| 132 | - vec!["?"; n].join(",") | |
| 133 | -} | |
| 134 | - | |
| 135 | 119 | pub(crate) fn like_pattern(query: &str) -> String { |
| 136 | 120 | let mut out = String::with_capacity(query.len() + 2); |
| 137 | 121 | out.push('%'); |
| @@ -145,32 +129,16 @@ pub(crate) fn like_pattern(query: &str) -> String { | ||
| 145 | 129 | out |
| 146 | 130 | } |
| 147 | 131 | |
| 148 | -/// Validates a `YYYY-MM-DD` due date. | |
| 149 | -pub fn validate_due_on(due_on: &str) -> Result<()> { | |
| 150 | - let format = time::macros::format_description!("[year]-[month]-[day]"); | |
| 151 | - match time::Date::parse(due_on, &format) { | |
| 152 | - Ok(_) => Ok(()), | |
| 153 | - Err(_) => Err(Error::Invalid(format!( | |
| 154 | - "due date {due_on:?} is not YYYY-MM-DD" | |
| 155 | - ))), | |
| 156 | - } | |
| 157 | -} | |
| 158 | - | |
| 159 | -/// Runs `outcome` inside `tx`: commits on success, rolls back on error. | |
| 160 | -pub(super) async fn finish<T>(tx: Transaction<'_>, outcome: Result<T>) -> Result<T> { | |
| 161 | - match outcome { | |
| 162 | - Ok(value) => { | |
| 163 | - tx.commit().await.map_err(db_err)?; | |
| 164 | - Ok(value) | |
| 165 | - } | |
| 166 | - Err(e) => { | |
| 167 | - let _ = tx.rollback().await; | |
| 168 | - Err(e) | |
| 169 | - } | |
| 132 | +fn event_data(data: Json) -> Result<Map<String, Json>> { | |
| 133 | + match data { | |
| 134 | + Json::Object(map) => Ok(map), | |
| 135 | + Json::Null => Ok(Map::new()), | |
| 136 | + _ => Err(Error::Invalid( | |
| 137 | + "event data must be a JSON object".to_string(), | |
| 138 | + )), | |
| 170 | 139 | } |
| 171 | 140 | } |
| 172 | 141 | |
| 173 | -/// Inserts a timeline event. `data` must be a JSON object or null (stored as `{}`). | |
| 174 | 142 | pub(super) async fn insert_event( |
| 175 | 143 | conn: &Connection, |
| 176 | 144 | issue_id: &str, |
| @@ -195,9 +163,6 @@ pub(super) async fn insert_event( | ||
| 195 | 163 | Ok(()) |
| 196 | 164 | } |
| 197 | 165 | |
| 198 | -/// The issue or pull request row by id, or `NotFound`. Pull requests share the issue write paths | |
| 199 | -/// (comments, edits, state, events), so both kinds are accepted here. Lookups by number stay | |
| 200 | -/// kind-specific. | |
| 201 | 166 | pub(super) async fn load_issue(conn: &Connection, issue_id: &str) -> Result<Issue> { |
| 202 | 167 | fetch_opt( |
| 203 | 168 | conn, |
| @@ -209,7 +174,6 @@ pub(super) async fn load_issue(conn: &Connection, issue_id: &str) -> Result<Issu | ||
| 209 | 174 | .ok_or(Error::NotFound) |
| 210 | 175 | } |
| 211 | 176 | |
| 212 | -/// Labels of an issue, read through `issue_labels`, keyed by issue id. | |
| 213 | 177 | async fn labels_for_issues( |
| 214 | 178 | conn: &Connection, |
| 215 | 179 | issue_ids: &[String], |
| @@ -233,7 +197,6 @@ async fn labels_for_issues( | ||
| 233 | 197 | Ok(out) |
| 234 | 198 | } |
| 235 | 199 | |
| 236 | -/// Display usernames of assignees, keyed by issue id. | |
| 237 | 200 | async fn assignees_for_issues( |
| 238 | 201 | conn: &Connection, |
| 239 | 202 | issue_ids: &[String], |
| @@ -257,10 +220,7 @@ async fn assignees_for_issues( | ||
| 257 | 220 | Ok(out) |
| 258 | 221 | } |
| 259 | 222 | |
| 260 | -// issues | |
| 261 | 223 | impl Store { |
| 262 | - /// Creates an issue with the next number of the repo. The read of the counter, the insert | |
| 263 | - /// and the increment run in one transaction, so numbers are unique and never reused. | |
| 264 | 224 | pub async fn create_issue( |
| 265 | 225 | &self, |
| 266 | 226 | repo_id: &str, |
| @@ -341,8 +301,6 @@ impl Store { | ||
| 341 | 301 | .await |
| 342 | 302 | } |
| 343 | 303 | |
| 344 | - /// One page of issues matching `f`, plus the total number of matches. | |
| 345 | - /// Every user value is a bound parameter. The clauses and the ORDER BY are fixed strings. | |
| 346 | 304 | pub async fn list_issues( |
| 347 | 305 | &self, |
| 348 | 306 | repo_id: &str, |
| @@ -351,7 +309,6 @@ impl Store { | ||
| 351 | 309 | self.list_of_kind(repo_id, f, "issue").await |
| 352 | 310 | } |
| 353 | 311 | |
| 354 | - /// `list_issues` for any `kind` ('issue' or 'pull'). Pull request listing shares it. | |
| 355 | 312 | pub(super) async fn list_of_kind( |
| 356 | 313 | &self, |
| 357 | 314 | repo_id: &str, |
| @@ -401,18 +358,15 @@ impl Store { | ||
| 401 | 358 | params.push(Value::Text(normalize_name(reviewer))); |
| 402 | 359 | } |
| 403 | 360 | if let Some(query) = non_empty(f.query.as_deref()) { |
| 404 | - // Escape the LIKE wildcards and the escape character itself. | |
| 405 | 361 | clauses.push("i.title LIKE ? ESCAPE '\\'"); |
| 406 | 362 | params.push(Value::Text(like_pattern(query))); |
| 407 | 363 | } |
| 408 | - if let (true, Some(draft)) = (kind == "pull", f.draft) { | |
| 409 | - { | |
| 410 | - clauses.push(if draft { | |
| 411 | - "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 1)" | |
| 412 | - } else { | |
| 413 | - "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 0)" | |
| 414 | - }); | |
| 415 | - } | |
| 364 | + if kind == "pull" && let Some(draft) = f.draft { | |
| 365 | + clauses.push(if draft { | |
| 366 | + "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 1)" | |
| 367 | + } else { | |
| 368 | + "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 0)" | |
| 369 | + }); | |
| 416 | 370 | } |
| 417 | 371 | let where_sql = clauses.join(" AND "); |
| 418 | 372 | let order = match f.sort { |
| @@ -468,12 +422,10 @@ impl Store { | ||
| 468 | 422 | Ok((items, total)) |
| 469 | 423 | } |
| 470 | 424 | |
| 471 | - /// Open and closed issue counts of the repo (issues only, not pulls). | |
| 472 | 425 | pub async fn issue_counts(&self, repo_id: &str) -> Result<(u64, u64)> { |
| 473 | 426 | self.counts_of_kind(repo_id, "issue").await |
| 474 | 427 | } |
| 475 | 428 | |
| 476 | - /// Open and closed counts for one `kind` ('issue' or 'pull'). | |
| 477 | 429 | pub(super) async fn counts_of_kind(&self, repo_id: &str, kind: &str) -> Result<(u64, u64)> { |
| 478 | 430 | let conn = self.read_conn().await; |
| 479 | 431 | let row = fetch_opt( |
| @@ -492,8 +444,6 @@ impl Store { | ||
| 492 | 444 | )) |
| 493 | 445 | } |
| 494 | 446 | |
| 495 | - /// Saves the previous title and body to the edit history. A title change also records a | |
| 496 | - /// `renamed` event with `{"from", "to"}`. | |
| 497 | 447 | pub async fn edit_issue( |
| 498 | 448 | &self, |
| 499 | 449 | issue_id: &str, |
| @@ -543,9 +493,6 @@ impl Store { | ||
| 543 | 493 | finish(tx, outcome).await |
| 544 | 494 | } |
| 545 | 495 | |
| 546 | - /// Sets the state. Returns `false` and changes nothing if the issue is already in `state`. | |
| 547 | - /// Closing sets `closed_at` and `state_reason`; reopening clears both. The closed or | |
| 548 | - /// reopened event carries `data`, plus `"reason"` when closing with one. | |
| 549 | 496 | pub async fn set_issue_state( |
| 550 | 497 | &self, |
| 551 | 498 | issue_id: &str, |
| @@ -554,15 +501,7 @@ impl Store { | ||
| 554 | 501 | reason: Option<StateReason>, |
| 555 | 502 | data: Json, |
| 556 | 503 | ) -> Result<bool> { |
| 557 | - let mut data = match data { | |
| 558 | - Json::Object(map) => map, | |
| 559 | - Json::Null => Map::new(), | |
| 560 | - _ => { | |
| 561 | - return Err(Error::Invalid( | |
| 562 | - "event data must be a JSON object".to_string(), | |
| 563 | - )); | |
| 564 | - } | |
| 565 | - }; | |
| 504 | + let mut data = event_data(data)?; | |
| 566 | 505 | let conn = self.inner.conn.lock().await; |
| 567 | 506 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 568 | 507 | let outcome: Result<bool> = async { |
| @@ -604,9 +543,6 @@ impl Store { | ||
| 604 | 543 | finish(tx, outcome).await |
| 605 | 544 | } |
| 606 | 545 | |
| 607 | - /// Locks or unlocks a conversation. `reason` must be one of `LOCK_REASONS` or `None`, and is | |
| 608 | - /// dropped on unlock. Returns `false` and changes nothing when the lock state and reason | |
| 609 | - /// already match. The `locked` or `unlocked` event carries `"reason"` when one is given. | |
| 610 | 546 | pub async fn set_issue_locked( |
| 611 | 547 | &self, |
| 612 | 548 | issue_id: &str, |
| @@ -653,10 +589,6 @@ impl Store { | ||
| 653 | 589 | finish(tx, outcome).await |
| 654 | 590 | } |
| 655 | 591 | |
| 656 | - // comments | |
| 657 | - | |
| 658 | - /// Adds a comment, bumps the issue's `comment_count` and `updated_at`. Blank bodies are | |
| 659 | - /// rejected. | |
| 660 | 592 | pub async fn add_comment( |
| 661 | 593 | &self, |
| 662 | 594 | issue_id: &str, |
| @@ -718,7 +650,6 @@ impl Store { | ||
| 718 | 650 | .await |
| 719 | 651 | } |
| 720 | 652 | |
| 721 | - /// Saves the previous body to the edit history and marks the comment edited. | |
| 722 | 653 | pub async fn edit_comment(&self, comment_id: &str, editor_id: &str, body: &str) -> Result<()> { |
| 723 | 654 | validate_body(body)?; |
| 724 | 655 | if body.trim().is_empty() { |
| @@ -761,7 +692,6 @@ impl Store { | ||
| 761 | 692 | finish(tx, outcome).await |
| 762 | 693 | } |
| 763 | 694 | |
| 764 | - /// Deletes the comment with its edit history and decrements the issue's `comment_count`. | |
| 765 | 695 | pub async fn delete_comment(&self, comment_id: &str) -> Result<()> { |
| 766 | 696 | let conn = self.inner.conn.lock().await; |
| 767 | 697 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| @@ -817,8 +747,6 @@ impl Store { | ||
| 817 | 747 | .await |
| 818 | 748 | } |
| 819 | 749 | |
| 820 | - // events | |
| 821 | - | |
| 822 | 750 | pub async fn list_events(&self, issue_id: &str) -> Result<Vec<IssueEvent>> { |
| 823 | 751 | let conn = self.read_conn().await; |
| 824 | 752 | fetch_all( |
| @@ -831,8 +759,6 @@ impl Store { | ||
| 831 | 759 | .await |
| 832 | 760 | } |
| 833 | 761 | |
| 834 | - /// Records a timeline event. `kind` must be one of the known event kinds, and `data` a JSON | |
| 835 | - /// object or null. | |
| 836 | 762 | pub async fn add_event( |
| 837 | 763 | &self, |
| 838 | 764 | issue_id: &str, |
| @@ -843,23 +769,12 @@ impl Store { | ||
| 843 | 769 | if !EVENT_KINDS.contains(&kind) { |
| 844 | 770 | return Err(Error::Invalid(format!("event kind {kind:?}"))); |
| 845 | 771 | } |
| 846 | - let data = match data { | |
| 847 | - Json::Object(_) => data, | |
| 848 | - Json::Null => Json::Object(Map::new()), | |
| 849 | - _ => { | |
| 850 | - return Err(Error::Invalid( | |
| 851 | - "event data must be a JSON object".to_string(), | |
| 852 | - )); | |
| 853 | - } | |
| 854 | - }; | |
| 772 | + let data = Json::Object(event_data(data)?); | |
| 855 | 773 | let conn = self.inner.conn.lock().await; |
| 856 | 774 | load_issue(&conn, issue_id).await?; |
| 857 | 775 | insert_event(&conn, issue_id, actor_id, kind, &data).await |
| 858 | 776 | } |
| 859 | 777 | |
| 860 | - // users | |
| 861 | - | |
| 862 | - /// Display name and avatar hash for each id that exists. Unknown ids are left out. | |
| 863 | 778 | pub async fn usernames_by_ids( |
| 864 | 779 | &self, |
| 865 | 780 | ids: &[String], |
| @@ -895,7 +810,6 @@ impl Store { | ||
| 895 | 810 | } |
| 896 | 811 | } |
| 897 | 812 | |
| 898 | -/// Repo deletion for the M3 tables. Called from `Store::delete_repo` inside its transaction. | |
| 899 | 813 | pub(super) async fn delete_repo_issue_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> { |
| 900 | 814 | let id = repo_id.to_string(); |
| 901 | 815 | for sql in [ |
| @@ -954,7 +868,6 @@ mod tests { | ||
| 954 | 868 | } |
| 955 | 869 | } |
| 956 | 870 | |
| 957 | - /// A repo of its own, so issue numbers and repo-wide counts start clean per scenario. | |
| 958 | 871 | async fn fresh_repo(store: &Store, owner: &str, name: &str) -> String { |
| 959 | 872 | store |
| 960 | 873 | .create_repo(owner, name, "", Visibility::Public, "main") |
| @@ -975,13 +888,11 @@ mod tests { | ||
| 975 | 888 | items.into_iter().map(|i| i.issue.title).collect() |
| 976 | 889 | } |
| 977 | 890 | |
| 978 | - // Creating, filtering, paging and counting issues. Each scenario has its own repo. | |
| 979 | 891 | #[tokio::test] |
| 980 | 892 | async fn issue_create_and_list_rules_hold_in_each_scenario() { |
| 981 | 893 | let fx = fixture().await; |
| 982 | 894 | let s = &fx.store; |
| 983 | 895 | |
| 984 | - // Scenario 1: numbers start at one and advance; lookup by number. | |
| 985 | 896 | let repo = fresh_repo(s, &fx.tahinli.id, "numbers").await; |
| 986 | 897 | let a = s |
| 987 | 898 | .create_issue(&repo, &fx.tahinli.id, " First ", "body") |
| @@ -1002,7 +913,6 @@ mod tests { | ||
| 1002 | 913 | "numbers: no third issue" |
| 1003 | 914 | ); |
| 1004 | 915 | |
| 1005 | - // Scenario 2: invalid input and missing repos are refused without taking a number. | |
| 1006 | 916 | let repo = fresh_repo(s, &fx.tahinli.id, "validate").await; |
| 1007 | 917 | assert!( |
| 1008 | 918 | matches!( |
| @@ -1032,7 +942,6 @@ mod tests { | ||
| 1032 | 942 | .unwrap(); |
| 1033 | 943 | assert_eq!(ok.number, 1, "validate: failed creates kept no number"); |
| 1034 | 944 | |
| 1035 | - // Scenario 3: concurrent creates still get unique numbers one to twenty. | |
| 1036 | 945 | let repo = fresh_repo(s, &fx.tahinli.id, "concurrent").await; |
| 1037 | 946 | let mut handles = Vec::new(); |
| 1038 | 947 | for i in 0..20 { |
| @@ -1061,7 +970,6 @@ mod tests { | ||
| 1061 | 970 | "concurrent: all open" |
| 1062 | 971 | ); |
| 1063 | 972 | |
| 1064 | - // Scenario 4: state, author and text filters. | |
| 1065 | 973 | let repo = fresh_repo(s, &fx.tahinli.id, "filters").await; |
| 1066 | 974 | let a = s |
| 1067 | 975 | .create_issue(&repo, &fx.tahinli.id, "Crash on start", "") |
| @@ -1080,7 +988,6 @@ mod tests { | ||
| 1080 | 988 | .await |
| 1081 | 989 | .unwrap(); |
| 1082 | 990 | |
| 1083 | - // Default filter (open only). | |
| 1084 | 991 | assert_eq!( |
| 1085 | 992 | titles(s, &repo, &IssueFilter::default()).await, |
| 1086 | 993 | vec!["Typo in docs"], |
| @@ -1116,7 +1023,6 @@ mod tests { | ||
| 1116 | 1023 | "filters: text is case-insensitive" |
| 1117 | 1024 | ); |
| 1118 | 1025 | |
| 1119 | - // Scenario 5: wildcards in the text query are literal. | |
| 1120 | 1026 | let repo = fresh_repo(s, &fx.tahinli.id, "wildcards").await; |
| 1121 | 1027 | for t in [ |
| 1122 | 1028 | "100% done", |
| @@ -1158,7 +1064,6 @@ mod tests { | ||
| 1158 | 1064 | "wildcards: blank query matches everything" |
| 1159 | 1065 | ); |
| 1160 | 1066 | |
| 1161 | - // Scenario 6: paging and clamping. | |
| 1162 | 1067 | let repo = fresh_repo(s, &fx.tahinli.id, "pages").await; |
| 1163 | 1068 | for i in 0..30 { |
| 1164 | 1069 | s.create_issue(&repo, &fx.tahinli.id, &format!("issue {i}"), "") |
| @@ -1176,14 +1081,12 @@ mod tests { | ||
| 1176 | 1081 | let (second, _) = s.list_issues(&repo, &page(2, 25)).await.unwrap(); |
| 1177 | 1082 | assert_eq!(second.len(), 5, "pages: second page size"); |
| 1178 | 1083 | assert_eq!(second[4].issue.number, 1, "pages: oldest last"); |
| 1179 | - // per_page clamps to 1..=100, page to 1..=1000. | |
| 1180 | 1084 | let (one, _) = s.list_issues(&repo, &page(0, 0)).await.unwrap(); |
| 1181 | 1085 | assert_eq!(one.len(), 1, "pages: per_page and page clamp up"); |
| 1182 | 1086 | assert_eq!(one[0].issue.number, 30, "pages: clamped to first page"); |
| 1183 | 1087 | let (big, _) = s.list_issues(&repo, &page(5000, 1000)).await.unwrap(); |
| 1184 | 1088 | assert!(big.is_empty(), "pages: far past the end"); |
| 1185 | 1089 | |
| 1186 | - // Scenario 7: sorting by number and by last update. | |
| 1187 | 1090 | let repo = fresh_repo(s, &fx.tahinli.id, "sorts").await; |
| 1188 | 1091 | let first = s |
| 1189 | 1092 | .create_issue(&repo, &fx.tahinli.id, "one", "") |
| @@ -1212,7 +1115,6 @@ mod tests { | ||
| 1212 | 1115 | "sorts: recently updated" |
| 1213 | 1116 | ); |
| 1214 | 1117 | |
| 1215 | - // Scenario 8: labels and assignees are attached, and filterable by name. | |
| 1216 | 1118 | let repo = fresh_repo(s, &fx.tahinli.id, "labels").await; |
| 1217 | 1119 | let issue = s |
| 1218 | 1120 | .create_issue(&repo, &fx.tahinli.id, "labelled", "") |
| @@ -1264,7 +1166,6 @@ mod tests { | ||
| 1264 | 1166 | "labels: filter by assignee" |
| 1265 | 1167 | ); |
| 1266 | 1168 | |
| 1267 | - // Scenario 9: counts split open and closed. | |
| 1268 | 1169 | let repo = fresh_repo(s, &fx.tahinli.id, "counts").await; |
| 1269 | 1170 | let a = s |
| 1270 | 1171 | .create_issue(&repo, &fx.tahinli.id, "a", "") |
| @@ -1283,13 +1184,11 @@ mod tests { | ||
| 1283 | 1184 | ); |
| 1284 | 1185 | } |
| 1285 | 1186 | |
| 1286 | - // Editing, locking, state, comments, events and usernames. Each scenario has its own repo. | |
| 1287 | 1187 | #[tokio::test] |
| 1288 | 1188 | async fn issue_edit_and_thread_rules_hold_in_each_scenario() { |
| 1289 | 1189 | let fx = fixture().await; |
| 1290 | 1190 | let s = &fx.store; |
| 1291 | 1191 | |
| 1292 | - // Scenario 1: an edit saves history and records a rename, body-only edits do not. | |
| 1293 | 1192 | let repo = fresh_repo(s, &fx.tahinli.id, "edit").await; |
| 1294 | 1193 | let issue = s |
| 1295 | 1194 | .create_issue(&repo, &fx.tahinli.id, "old", "old body") |
| @@ -1339,7 +1238,6 @@ mod tests { | ||
| 1339 | 1238 | "edit: rename actor" |
| 1340 | 1239 | ); |
| 1341 | 1240 | |
| 1342 | - // Body-only edit: history yes, no rename event. | |
| 1343 | 1241 | s.edit_issue(&issue.id, &fx.bob.id, "new", "newer") |
| 1344 | 1242 | .await |
| 1345 | 1243 | .unwrap(); |
| @@ -1356,7 +1254,6 @@ mod tests { | ||
| 1356 | 1254 | "edit: unknown issue" |
| 1357 | 1255 | ); |
| 1358 | 1256 | |
| 1359 | - // Scenario 2: locking toggles the reason and records events. | |
| 1360 | 1257 | let repo = fresh_repo(s, &fx.tahinli.id, "locks").await; |
| 1361 | 1258 | let issue = s |
| 1362 | 1259 | .create_issue(&repo, &fx.tahinli.id, "t", "") |
| @@ -1414,7 +1311,6 @@ mod tests { | ||
| 1414 | 1311 | .collect(); |
| 1415 | 1312 | assert_eq!(kinds, vec!["locked", "unlocked"], "lock: events"); |
| 1416 | 1313 | |
| 1417 | - // Scenario 3: closing and reopening record events and stamps. | |
| 1418 | 1314 | let repo = fresh_repo(s, &fx.tahinli.id, "state").await; |
| 1419 | 1315 | let issue = s |
| 1420 | 1316 | .create_issue(&repo, &fx.tahinli.id, "t", "") |
| @@ -1504,7 +1400,6 @@ mod tests { | ||
| 1504 | 1400 | "state: payload must be an object" |
| 1505 | 1401 | ); |
| 1506 | 1402 | |
| 1507 | - // Scenario 4: comments keep the count, timestamps and ordering in step. | |
| 1508 | 1403 | let repo = fresh_repo(s, &fx.tahinli.id, "comments").await; |
| 1509 | 1404 | let issue = s |
| 1510 | 1405 | .create_issue(&repo, &fx.tahinli.id, "t", "") |
| @@ -1580,7 +1475,6 @@ mod tests { | ||
| 1580 | 1475 | "comments: delete twice" |
| 1581 | 1476 | ); |
| 1582 | 1477 | |
| 1583 | - // Scenario 5: events validate their kind and their issue. | |
| 1584 | 1478 | let repo = fresh_repo(s, &fx.tahinli.id, "events").await; |
| 1585 | 1479 | let issue = s |
| 1586 | 1480 | .create_issue(&repo, &fx.tahinli.id, "t", "") |
| @@ -1632,7 +1526,6 @@ mod tests { | ||
| 1632 | 1526 | "events: unknown issue" |
| 1633 | 1527 | ); |
| 1634 | 1528 | |
| 1635 | - // Scenario 6: usernames are batched and unknown ids are skipped. | |
| 1636 | 1529 | let ids = vec![ |
| 1637 | 1530 | fx.tahinli.id.clone(), |
| 1638 | 1531 | fx.bob.id.clone(), |
| @@ -1648,7 +1541,6 @@ mod tests { | ||
| 1648 | 1541 | ); |
| 1649 | 1542 | } |
| 1650 | 1543 | |
| 1651 | - // Kept on its own store: it counts rows in whole tables, so other repos must not exist. | |
| 1652 | 1544 | #[tokio::test] |
| 1653 | 1545 | async fn delete_repo_leaves_no_m3_rows() { |
| 1654 | 1546 | let fx = fixture().await; |
crates/forge-core/src/store/labels.rsmodified+19 -56
| @@ -4,22 +4,23 @@ | ||
| 4 | 4 | use std::collections::{BTreeMap, BTreeSet}; |
| 5 | 5 | |
| 6 | 6 | use jiff::civil::Date; |
| 7 | -use serde_json::{Value, json}; | |
| 8 | -use turso::transaction::Transaction; | |
| 7 | +use serde_json::json; | |
| 9 | 8 | use turso::{Connection, Row}; |
| 10 | 9 | |
| 10 | +use super::issues::insert_event; | |
| 11 | 11 | use super::{ |
| 12 | - Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id, | |
| 12 | + Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, insert_err, | |
| 13 | + new_id, | |
| 13 | 14 | }; |
| 14 | 15 | use crate::authz::{Action, authorize}; |
| 15 | 16 | use crate::error::{Error, Result}; |
| 16 | -use crate::issues::{IssueState, Label, Milestone, validate_body, validate_label, validate_title}; | |
| 17 | +use crate::issues::{ | |
| 18 | + IssueState, Label, MAX_ASSIGNEES, Milestone, validate_body, validate_label, validate_title, | |
| 19 | +}; | |
| 17 | 20 | use crate::model::User; |
| 18 | 21 | use crate::names::normalize_name; |
| 19 | 22 | use crate::time::now_stamp; |
| 20 | 23 | |
| 21 | -/// Most assignees one issue can have. | |
| 22 | -pub const MAX_ASSIGNEES: usize = 10; | |
| 23 | 24 | /// Most labels one repo can have. |
| 24 | 25 | pub const MAX_LABELS: i64 = 500; |
| 25 | 26 | |
| @@ -53,7 +54,8 @@ const LABEL_COLS: &str = "id, repo_id, name, color, description"; | ||
| 53 | 54 | const MILESTONE_SELECT: &str = "SELECT m.id, m.repo_id, m.title, m.description, m.due_on, m.state, \ |
| 54 | 55 | m.created_at, m.closed_at, \ |
| 55 | 56 | COUNT(CASE WHEN i.state = 'open' THEN 1 END), COUNT(CASE WHEN i.state = 'closed' THEN 1 END) \ |
| 56 | - FROM milestones m LEFT JOIN issues i ON i.repo_id = m.repo_id AND i.milestone_id = m.id"; | |
| 57 | + FROM milestones m LEFT JOIN issues i ON i.repo_id = m.repo_id AND i.milestone_id = m.id \ | |
| 58 | + AND i.kind = 'issue'"; | |
| 57 | 59 | |
| 58 | 60 | // labels |
| 59 | 61 | |
| @@ -206,7 +208,7 @@ impl Store { | ||
| 206 | 208 | Ok(()) |
| 207 | 209 | } |
| 208 | 210 | .await; |
| 209 | - commit_or_rollback(tx, outcome).await | |
| 211 | + finish(tx, outcome).await | |
| 210 | 212 | } |
| 211 | 213 | |
| 212 | 214 | /// The labels on one issue, ordered by case-folded name. |
| @@ -309,7 +311,7 @@ impl Store { | ||
| 309 | 311 | Ok(()) |
| 310 | 312 | } |
| 311 | 313 | .await; |
| 312 | - commit_or_rollback(tx, outcome).await | |
| 314 | + finish(tx, outcome).await | |
| 313 | 315 | } |
| 314 | 316 | |
| 315 | 317 | /// The issue's assignees as `(user id, display username)`, ordered by name. |
| @@ -426,7 +428,7 @@ impl Store { | ||
| 426 | 428 | Ok(()) |
| 427 | 429 | } |
| 428 | 430 | .await; |
| 429 | - commit_or_rollback(tx, outcome).await | |
| 431 | + finish(tx, outcome).await | |
| 430 | 432 | } |
| 431 | 433 | |
| 432 | 434 | // milestones |
| @@ -528,8 +530,8 @@ impl Store { | ||
| 528 | 530 | ( |
| 529 | 531 | id.to_string(), |
| 530 | 532 | repo_id.to_string(), |
| 533 | + title.clone(), | |
| 531 | 534 | normalize_name(&title), |
| 532 | - title, | |
| 533 | 535 | description.to_string(), |
| 534 | 536 | due_on.map(str::to_owned), |
| 535 | 537 | state.as_str().to_string(), |
| @@ -569,7 +571,7 @@ impl Store { | ||
| 569 | 571 | Ok(()) |
| 570 | 572 | } |
| 571 | 573 | .await; |
| 572 | - commit_or_rollback(tx, outcome).await | |
| 574 | + finish(tx, outcome).await | |
| 573 | 575 | } |
| 574 | 576 | |
| 575 | 577 | /// Sets or clears the issue's milestone. The milestone must belong to the issue's repo |
| @@ -646,7 +648,7 @@ impl Store { | ||
| 646 | 648 | Ok(()) |
| 647 | 649 | } |
| 648 | 650 | .await; |
| 649 | - commit_or_rollback(tx, outcome).await | |
| 651 | + finish(tx, outcome).await | |
| 650 | 652 | } |
| 651 | 653 | } |
| 652 | 654 | |
| @@ -710,49 +712,10 @@ async fn issue_repo_id(conn: &Connection, issue_id: &str) -> Result<String> { | ||
| 710 | 712 | .ok_or(Error::NotFound) |
| 711 | 713 | } |
| 712 | 714 | |
| 713 | -/// Inserts an issue event on the given connection or transaction. Used inside transactions, | |
| 714 | -/// where `Store::add_event` would deadlock on the connection lock. | |
| 715 | -async fn insert_event( | |
| 716 | - conn: &Connection, | |
| 717 | - issue_id: &str, | |
| 718 | - actor_id: Option<&str>, | |
| 719 | - kind: &str, | |
| 720 | - data: &Value, | |
| 721 | -) -> Result<()> { | |
| 722 | - conn.execute( | |
| 723 | - "INSERT INTO issue_events (id, issue_id, actor_id, kind, data, created_at) \ | |
| 724 | - VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | |
| 725 | - ( | |
| 726 | - new_id(), | |
| 727 | - issue_id.to_string(), | |
| 728 | - actor_id.map(str::to_owned), | |
| 729 | - kind.to_string(), | |
| 730 | - data.to_string(), | |
| 731 | - now_stamp(), | |
| 732 | - ), | |
| 733 | - ) | |
| 734 | - .await | |
| 735 | - .map_err(db_err)?; | |
| 736 | - Ok(()) | |
| 737 | -} | |
| 738 | - | |
| 739 | -/// Commits when the work succeeded, otherwise rolls back and returns the error. | |
| 740 | -async fn commit_or_rollback<T>(tx: Transaction<'_>, outcome: Result<T>) -> Result<T> { | |
| 741 | - match outcome { | |
| 742 | - Ok(value) => { | |
| 743 | - tx.commit().await.map_err(db_err)?; | |
| 744 | - Ok(value) | |
| 745 | - } | |
| 746 | - Err(e) => { | |
| 747 | - let _ = tx.rollback().await; | |
| 748 | - Err(e) | |
| 749 | - } | |
| 750 | - } | |
| 751 | -} | |
| 752 | - | |
| 753 | 715 | #[cfg(test)] |
| 754 | 716 | mod tests { |
| 755 | 717 | use super::*; |
| 718 | + use serde_json::Value; | |
| 756 | 719 | use crate::issues::{IssueEvent, StateReason}; |
| 757 | 720 | use crate::model::{Role, Visibility}; |
| 758 | 721 | |
| @@ -1259,17 +1222,17 @@ mod tests { | ||
| 1259 | 1222 | ), |
| 1260 | 1223 | "update: other repo refused" |
| 1261 | 1224 | ); |
| 1262 | - s.update_milestone(&repo, &v1.id, "v1.0", "done", None, IssueState::Closed) | |
| 1225 | + s.update_milestone(&repo, &v1.id, "V1.0", "done", None, IssueState::Closed) | |
| 1263 | 1226 | .await |
| 1264 | 1227 | .unwrap(); |
| 1265 | 1228 | let closed = s.milestone_by_id(&repo, &v1.id).await.unwrap().unwrap(); |
| 1266 | - assert_eq!(closed.title, "v1.0", "update: title"); | |
| 1229 | + assert_eq!(closed.title, "V1.0", "update: title"); | |
| 1267 | 1230 | assert_eq!(closed.description, "done", "update: description"); |
| 1268 | 1231 | assert!(closed.due_on.is_none(), "update: due date cleared"); |
| 1269 | 1232 | assert!(matches!(closed.state, IssueState::Closed), "update: closed"); |
| 1270 | 1233 | assert!(closed.closed_at.is_some(), "update: closed stamp set"); |
| 1271 | 1234 | |
| 1272 | - s.update_milestone(&repo, &v1.id, "v1.0", "done", None, IssueState::Open) | |
| 1235 | + s.update_milestone(&repo, &v1.id, "V1.0", "done", None, IssueState::Open) | |
| 1273 | 1236 | .await |
| 1274 | 1237 | .unwrap(); |
| 1275 | 1238 | let reopened = s.milestone_by_id(&repo, &v1.id).await.unwrap().unwrap(); |
crates/forge-core/src/store/mail.rsmodified+22 -29
| @@ -106,12 +106,7 @@ impl Store { | ||
| 106 | 106 | validate_settings(update)?; |
| 107 | 107 | let sealed = match update.password { |
| 108 | 108 | Some(password) => { |
| 109 | - let key = self | |
| 110 | - .inner | |
| 111 | - .secret_key | |
| 112 | - .get() | |
| 113 | - .ok_or_else(|| Error::Crypto("the instance key is not set".into()))?; | |
| 114 | - Some(secret::seal(key, password.as_bytes())?.into_bytes()) | |
| 109 | + Some(secret::seal(self.secret_key()?, password.as_bytes())?.into_bytes()) | |
| 115 | 110 | } |
| 116 | 111 | None => None, |
| 117 | 112 | }; |
| @@ -161,11 +156,7 @@ impl Store { | ||
| 161 | 156 | let Some(bytes) = sealed else { |
| 162 | 157 | return Ok(None); |
| 163 | 158 | }; |
| 164 | - let key = self | |
| 165 | - .inner | |
| 166 | - .secret_key | |
| 167 | - .get() | |
| 168 | - .ok_or_else(|| Error::Crypto("the instance key is not set".into()))?; | |
| 159 | + let key = self.secret_key()?; | |
| 169 | 160 | let text = String::from_utf8(bytes) |
| 170 | 161 | .map_err(|_| Error::Crypto("sealed mail password is not text".into()))?; |
| 171 | 162 | let plain = secret::open(key, &text)?; |
| @@ -317,20 +308,22 @@ impl Store { | ||
| 317 | 308 | /// How many outbox rows stand in each state at `now`, in `MailState::ALL` order. |
| 318 | 309 | pub async fn mail_state_counts(&self, now: &str) -> Result<Vec<(MailState, u32)>> { |
| 319 | 310 | let conn = self.read_conn().await; |
| 320 | - let mut counts = Vec::with_capacity(MailState::ALL.len()); | |
| 321 | - for state in MailState::ALL { | |
| 322 | - let clause = state_clause(state); | |
| 323 | - let sql = format!("SELECT COUNT(*) FROM mail_outbox WHERE {clause}"); | |
| 324 | - // A clause without `?1` must be bound with no parameters at all. | |
| 325 | - let n = if clause.contains("?1") { | |
| 326 | - fetch_opt(&conn, &sql, (now.to_owned(),), |row| col_int(row, 0)).await? | |
| 327 | - } else { | |
| 328 | - fetch_opt(&conn, &sql, (), |row| col_int(row, 0)).await? | |
| 329 | - } | |
| 330 | - .unwrap_or(0); | |
| 331 | - counts.push((state, u32::try_from(n).unwrap_or(u32::MAX))); | |
| 332 | - } | |
| 333 | - Ok(counts) | |
| 311 | + let columns = MailState::ALL | |
| 312 | + .map(|state| format!("COUNT(CASE WHEN {} THEN 1 END)", state_clause(state))) | |
| 313 | + .join(", "); | |
| 314 | + let sql = format!("SELECT {columns} FROM mail_outbox"); | |
| 315 | + let counts = fetch_opt(&conn, &sql, (now.to_owned(),), |row| { | |
| 316 | + MailState::ALL | |
| 317 | + .into_iter() | |
| 318 | + .enumerate() | |
| 319 | + .map(|(i, state)| { | |
| 320 | + let n = col_int(row, i)?; | |
| 321 | + Ok((state, u32::try_from(n).unwrap_or(u32::MAX))) | |
| 322 | + }) | |
| 323 | + .collect::<Result<Vec<_>>>() | |
| 324 | + }) | |
| 325 | + .await?; | |
| 326 | + Ok(counts.unwrap_or_default()) | |
| 334 | 327 | } |
| 335 | 328 | |
| 336 | 329 | /// Gives a failed message a fresh set of tries, due at `now`. Returns `false` when the row is |
| @@ -426,7 +419,7 @@ mod tests { | ||
| 426 | 419 | use std::time::Duration; |
| 427 | 420 | |
| 428 | 421 | use super::*; |
| 429 | - use crate::mail::OutboxStatus; | |
| 422 | + use crate::mail::MailState; | |
| 430 | 423 | use crate::time::{now_stamp, stamp_after}; |
| 431 | 424 | |
| 432 | 425 | const KEY: [u8; 32] = [7u8; 32]; |
| @@ -562,7 +555,7 @@ mod tests { | ||
| 562 | 555 | .is_empty() |
| 563 | 556 | ); |
| 564 | 557 | let rows = store.recent_mail(10).await.expect("rows"); |
| 565 | - assert_eq!(rows[0].status(), OutboxStatus::Sent); | |
| 558 | + assert_eq!(rows[0].state_at(&now_stamp()), MailState::Sent); | |
| 566 | 559 | assert_eq!(rows[0].attempts, 1); |
| 567 | 560 | } |
| 568 | 561 | |
| @@ -598,14 +591,14 @@ mod tests { | ||
| 598 | 591 | let row = store.recent_mail(10).await.expect("rows").remove(0); |
| 599 | 592 | assert_eq!(row.attempts, 1); |
| 600 | 593 | assert_eq!(row.last_error.as_deref(), Some("timeout")); |
| 601 | - assert_eq!(row.status(), OutboxStatus::Queued); | |
| 594 | + assert_eq!(row.state_at(&now), MailState::Retrying); | |
| 602 | 595 | |
| 603 | 596 | store |
| 604 | 597 | .mark_mail_failed(&row.id, "gone", None) |
| 605 | 598 | .await |
| 606 | 599 | .expect("gave up"); |
| 607 | 600 | let row = store.recent_mail(10).await.expect("rows").remove(0); |
| 608 | - assert_eq!(row.status(), OutboxStatus::GaveUp); | |
| 601 | + assert_eq!(row.state_at(&now), MailState::Failed); | |
| 609 | 602 | assert_eq!(store.next_mail_due().await.expect("none"), None); |
| 610 | 603 | } |
| 611 | 604 |
crates/forge-core/src/store/merge_queue.rsmodified+1 -16
| @@ -3,8 +3,7 @@ | ||
| 3 | 3 | |
| 4 | 4 | use turso::Value; |
| 5 | 5 | |
| 6 | -use super::issues::finish; | |
| 7 | -use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; | |
| 6 | +use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; | |
| 8 | 7 | use crate::error::{Error, Result}; |
| 9 | 8 | use crate::merge_queue::{QueueEntry, QueueState}; |
| 10 | 9 | use crate::pulls::MergeStyle; |
| @@ -178,20 +177,6 @@ impl Store { | ||
| 178 | 177 | .await |
| 179 | 178 | } |
| 180 | 179 | |
| 181 | - /// Records the CI run that tests the entry's candidate. | |
| 182 | - pub async fn queue_attach_run(&self, id: &str, run_id: &str) -> Result<()> { | |
| 183 | - self.queue_update( | |
| 184 | - "UPDATE merge_queue SET run_id = ?2, updated_at = ?3 WHERE id = ?1 AND finished_at IS NULL", | |
| 185 | - vec![ | |
| 186 | - Value::Text(id.to_string()), | |
| 187 | - Value::Text(run_id.to_string()), | |
| 188 | - Value::Text(now_stamp()), | |
| 189 | - ], | |
| 190 | - ) | |
| 191 | - .await?; | |
| 192 | - Ok(()) | |
| 193 | - } | |
| 194 | - | |
| 195 | 180 | /// Moves a tested entry to `merging`. False when another event already took it. |
| 196 | 181 | pub async fn queue_set_merging(&self, id: &str) -> Result<bool> { |
| 197 | 182 | self.queue_update( |
crates/forge-core/src/store/migrate.rsmodified+34 -137
| @@ -192,9 +192,7 @@ async fn applied_versions(conn: &Connection) -> Result<Vec<i64>> { | ||
| 192 | 192 | mod tests { |
| 193 | 193 | use super::*; |
| 194 | 194 | |
| 195 | - #[tokio::test] | |
| 196 | - async fn database_at_0001_gains_profile_columns_with_defaults() { | |
| 197 | - let dir = tempfile::tempdir().unwrap(); | |
| 195 | + async fn open_at(dir: &tempfile::TempDir, version: u32) -> (turso::Database, Connection) { | |
| 198 | 196 | let path = dir.path().join("old.db"); |
| 199 | 197 | let db = turso::Builder::new_local(path.to_str().unwrap()) |
| 200 | 198 | .build() |
| @@ -206,16 +204,32 @@ mod tests { | ||
| 206 | 204 | ) |
| 207 | 205 | .await |
| 208 | 206 | .unwrap(); |
| 209 | - conn.execute_batch(MIGRATIONS[0].1).await.unwrap(); | |
| 207 | + for &(v, sql) in MIGRATIONS.iter().filter(|(v, _)| *v <= version) { | |
| 208 | + conn.execute_batch(sql).await.unwrap(); | |
| 209 | + conn.execute( | |
| 210 | + "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, 'then')", | |
| 211 | + (i64::from(v),), | |
| 212 | + ) | |
| 213 | + .await | |
| 214 | + .unwrap(); | |
| 215 | + } | |
| 216 | + (db, conn) | |
| 217 | + } | |
| 218 | + | |
| 219 | + #[tokio::test] | |
| 220 | + async fn database_at_0001_gains_all_later_schema() { | |
| 221 | + let dir = tempfile::tempdir().unwrap(); | |
| 222 | + let (_db, conn) = open_at(&dir, 1).await; | |
| 210 | 223 | conn.execute( |
| 211 | - "INSERT INTO schema_migrations (version, applied_at) VALUES (1, 'then')", | |
| 224 | + "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \ | |
| 225 | + VALUES ('u1', 'Old', 'old', 'h', 0, 'then')", | |
| 212 | 226 | (), |
| 213 | 227 | ) |
| 214 | 228 | .await |
| 215 | 229 | .unwrap(); |
| 216 | 230 | conn.execute( |
| 217 | - "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \ | |
| 218 | - VALUES ('u1', 'Old', 'old', 'h', 0, 'then')", | |
| 231 | + "INSERT INTO repos (id, owner_id, name, name_folded, description, visibility, default_branch, archived, created_at) \ | |
| 232 | + VALUES ('r1', 'u1', 'proj', 'proj', '', 'public', 'main', 0, 'then')", | |
| 219 | 233 | (), |
| 220 | 234 | ) |
| 221 | 235 | .await |
| @@ -230,6 +244,7 @@ mod tests { | ||
| 230 | 244 | let row = rows.next().await.unwrap().expect("user row"); |
| 231 | 245 | assert_eq!(row.get_value(0).unwrap(), turso::Value::Text(String::new())); |
| 232 | 246 | assert_eq!(row.get_value(1).unwrap(), turso::Value::Text("UTC".into())); |
| 247 | + drop(rows); | |
| 233 | 248 | let mut rows = conn |
| 234 | 249 | .query("SELECT version FROM schema_migrations ORDER BY version", ()) |
| 235 | 250 | .await |
| @@ -243,102 +258,7 @@ mod tests { | ||
| 243 | 258 | .map(|(v, _)| turso::Value::Integer(i64::from(*v))) |
| 244 | 259 | .collect(); |
| 245 | 260 | assert_eq!(versions, expected); |
| 246 | - } | |
| 247 | - | |
| 248 | - #[tokio::test] | |
| 249 | - async fn database_at_0002_gains_branch_protections() { | |
| 250 | - let dir = tempfile::tempdir().unwrap(); | |
| 251 | - let path = dir.path().join("v2.db"); | |
| 252 | - let db = turso::Builder::new_local(path.to_str().unwrap()) | |
| 253 | - .build() | |
| 254 | - .await | |
| 255 | - .unwrap(); | |
| 256 | - let conn = db.connect().unwrap(); | |
| 257 | - conn.execute_batch( | |
| 258 | - "CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)", | |
| 259 | - ) | |
| 260 | - .await | |
| 261 | - .unwrap(); | |
| 262 | - for (version, sql) in &MIGRATIONS[..2] { | |
| 263 | - conn.execute_batch(sql).await.unwrap(); | |
| 264 | - conn.execute( | |
| 265 | - "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, 'then')", | |
| 266 | - (i64::from(*version),), | |
| 267 | - ) | |
| 268 | - .await | |
| 269 | - .unwrap(); | |
| 270 | - } | |
| 271 | - conn.execute( | |
| 272 | - "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \ | |
| 273 | - VALUES ('u1', 'Old', 'old', 'h', 0, 'then')", | |
| 274 | - (), | |
| 275 | - ) | |
| 276 | - .await | |
| 277 | - .unwrap(); | |
| 278 | - conn.execute( | |
| 279 | - "INSERT INTO repos (id, owner_id, name, name_folded, description, visibility, default_branch, archived, created_at) \ | |
| 280 | - VALUES ('r1', 'u1', 'proj', 'proj', '', 'public', 'main', 0, 'then')", | |
| 281 | - (), | |
| 282 | - ) | |
| 283 | - .await | |
| 284 | - .unwrap(); | |
| 285 | - | |
| 286 | - migrate(&conn).await.unwrap(); | |
| 287 | - | |
| 288 | - conn.execute( | |
| 289 | - "INSERT INTO branch_protections (id, repo_id, pattern, allow_force_push, allow_deletion, created_at) \ | |
| 290 | - VALUES ('b1', 'r1', 'main', 1, 0, 'then')", | |
| 291 | - (), | |
| 292 | - ) | |
| 293 | - .await | |
| 294 | - .unwrap(); | |
| 295 | - let mut rows = conn | |
| 296 | - .query("SELECT COUNT(*) FROM branch_protections", ()) | |
| 297 | - .await | |
| 298 | - .unwrap(); | |
| 299 | - let row = rows.next().await.unwrap().expect("count row"); | |
| 300 | - assert_eq!(row.get_value(0).unwrap(), turso::Value::Integer(1)); | |
| 301 | - } | |
| 302 | - | |
| 303 | - #[tokio::test] | |
| 304 | - async fn database_at_0003_gains_issue_tables_and_counter() { | |
| 305 | - let dir = tempfile::tempdir().unwrap(); | |
| 306 | - let path = dir.path().join("v3.db"); | |
| 307 | - let db = turso::Builder::new_local(path.to_str().unwrap()) | |
| 308 | - .build() | |
| 309 | - .await | |
| 310 | - .unwrap(); | |
| 311 | - let conn = db.connect().unwrap(); | |
| 312 | - conn.execute_batch( | |
| 313 | - "CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)", | |
| 314 | - ) | |
| 315 | - .await | |
| 316 | - .unwrap(); | |
| 317 | - for (version, sql) in &MIGRATIONS[..3] { | |
| 318 | - conn.execute_batch(sql).await.unwrap(); | |
| 319 | - conn.execute( | |
| 320 | - "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, 'then')", | |
| 321 | - (i64::from(*version),), | |
| 322 | - ) | |
| 323 | - .await | |
| 324 | - .unwrap(); | |
| 325 | - } | |
| 326 | - conn.execute( | |
| 327 | - "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \ | |
| 328 | - VALUES ('u1', 'Old', 'old', 'h', 0, 'then')", | |
| 329 | - (), | |
| 330 | - ) | |
| 331 | - .await | |
| 332 | - .unwrap(); | |
| 333 | - conn.execute( | |
| 334 | - "INSERT INTO repos (id, owner_id, name, name_folded, description, visibility, default_branch, archived, created_at) \ | |
| 335 | - VALUES ('r1', 'u1', 'proj', 'proj', '', 'public', 'main', 0, 'then')", | |
| 336 | - (), | |
| 337 | - ) | |
| 338 | - .await | |
| 339 | - .unwrap(); | |
| 340 | - | |
| 341 | - migrate(&conn).await.unwrap(); | |
| 261 | + drop(rows); | |
| 342 | 262 | |
| 343 | 263 | let mut rows = conn |
| 344 | 264 | .query("SELECT next_issue_number FROM repos WHERE id = 'r1'", ()) |
| @@ -361,44 +281,14 @@ mod tests { | ||
| 361 | 281 | ) |
| 362 | 282 | .await |
| 363 | 283 | .unwrap(); |
| 364 | - } | |
| 365 | - | |
| 366 | - /// A database that stopped at 0004 (as before the TOTP work) gains the 2FA columns and the | |
| 367 | - /// recovery table, with safe defaults for existing users. Applies every migration below 6 | |
| 368 | - /// from the list, so once 0005 lands it is applied here too. | |
| 369 | - #[tokio::test] | |
| 370 | - async fn database_at_0004_gains_totp_columns_and_recovery_table() { | |
| 371 | - let dir = tempfile::tempdir().unwrap(); | |
| 372 | - let path = dir.path().join("v4.db"); | |
| 373 | - let db = turso::Builder::new_local(path.to_str().unwrap()) | |
| 374 | - .build() | |
| 375 | - .await | |
| 376 | - .unwrap(); | |
| 377 | - let conn = db.connect().unwrap(); | |
| 378 | - conn.execute_batch( | |
| 379 | - "CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)", | |
| 380 | - ) | |
| 381 | - .await | |
| 382 | - .unwrap(); | |
| 383 | - for &(version, sql) in MIGRATIONS.iter().filter(|(v, _)| *v < 6) { | |
| 384 | - conn.execute_batch(sql).await.unwrap(); | |
| 385 | - conn.execute( | |
| 386 | - "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, 'then')", | |
| 387 | - (i64::from(version),), | |
| 388 | - ) | |
| 389 | - .await | |
| 390 | - .unwrap(); | |
| 391 | - } | |
| 392 | 284 | conn.execute( |
| 393 | - "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \ | |
| 394 | - VALUES ('u1', 'Old', 'old', 'h', 0, 'then')", | |
| 285 | + "INSERT INTO branch_protections (id, repo_id, pattern, allow_force_push, allow_deletion, created_at) \ | |
| 286 | + VALUES ('b1', 'r1', 'main', 1, 0, 'then')", | |
| 395 | 287 | (), |
| 396 | 288 | ) |
| 397 | 289 | .await |
| 398 | 290 | .unwrap(); |
| 399 | 291 | |
| 400 | - migrate(&conn).await.unwrap(); | |
| 401 | - | |
| 402 | 292 | let mut rows = conn |
| 403 | 293 | .query( |
| 404 | 294 | "SELECT totp_secret_sealed, totp_enabled, totp_last_step FROM users WHERE id = 'u1'", |
| @@ -413,7 +303,14 @@ mod tests { | ||
| 413 | 303 | drop(rows); |
| 414 | 304 | |
| 415 | 305 | conn.execute( |
| 416 | - "INSERT INTO recovery_codes (id, user_id, code_hash) VALUES ('r1', 'u1', 'h')", | |
| 306 | + "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \ | |
| 307 | + VALUES ('u2', 'Other', 'other', 'h', 0, 'then')", | |
| 308 | + (), | |
| 309 | + ) | |
| 310 | + .await | |
| 311 | + .unwrap(); | |
| 312 | + conn.execute( | |
| 313 | + "INSERT INTO recovery_codes (id, user_id, code_hash) VALUES ('c1', 'u2', 'h')", | |
| 417 | 314 | (), |
| 418 | 315 | ) |
| 419 | 316 | .await |
| @@ -421,7 +318,7 @@ mod tests { | ||
| 421 | 318 | conn.execute_batch("PRAGMA foreign_keys = ON") |
| 422 | 319 | .await |
| 423 | 320 | .unwrap(); |
| 424 | - conn.execute("DELETE FROM users WHERE id = 'u1'", ()) | |
| 321 | + conn.execute("DELETE FROM users WHERE id = 'u2'", ()) | |
| 425 | 322 | .await |
| 426 | 323 | .unwrap(); |
| 427 | 324 | let mut rows = conn |
crates/forge-core/src/store/mirrors.rsmodified+13 -69
| @@ -7,8 +7,8 @@ | ||
| 7 | 7 | use turso::{Row, Value}; |
| 8 | 8 | |
| 9 | 9 | use super::{ |
| 10 | - Store, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, | |
| 11 | - insert_err, missing_row, new_id, | |
| 10 | + Store, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, | |
| 11 | + finish, insert_err, missing_row, new_id, opt_text, | |
| 12 | 12 | }; |
| 13 | 13 | use crate::error::{Error, Result}; |
| 14 | 14 | use crate::mirrors::{ |
| @@ -38,29 +38,12 @@ fn map_mirror(row: &Row) -> Result<Mirror> { | ||
| 38 | 38 | enabled: col_bool(row, 7)?, |
| 39 | 39 | next_sync_at: col_text(row, 8)?, |
| 40 | 40 | last_sync_at: col_opt_text(row, 9)?, |
| 41 | - last_ok: opt_int(row, 10)?.map(|n| n != 0), | |
| 41 | + last_ok: col_opt_int(row, 10)?.map(|n| n != 0), | |
| 42 | 42 | last_error: col_opt_text(row, 11)?, |
| 43 | 43 | created_at: col_text(row, 12)?, |
| 44 | 44 | }) |
| 45 | 45 | } |
| 46 | 46 | |
| 47 | -/// An integer column that may be NULL. | |
| 48 | -fn opt_int(row: &Row, i: usize) -> Result<Option<i64>> { | |
| 49 | - match row.get_value(i).map_err(db_err)? { | |
| 50 | - Value::Integer(n) => Ok(Some(n)), | |
| 51 | - Value::Null => Ok(None), | |
| 52 | - _ => Err(Error::Database(format!("column {i} is not an integer"))), | |
| 53 | - } | |
| 54 | -} | |
| 55 | - | |
| 56 | -fn opt_text(v: Option<&str>) -> Value { | |
| 57 | - v.map_or(Value::Null, |s| Value::Text(s.to_string())) | |
| 58 | -} | |
| 59 | - | |
| 60 | -fn opt_int_value(v: Option<bool>) -> Value { | |
| 61 | - v.map_or(Value::Null, |b| Value::Integer(i64::from(b))) | |
| 62 | -} | |
| 63 | - | |
| 64 | 47 | /// Rejects an interval that is neither `0` (manual only) nor at least the minimum. |
| 65 | 48 | fn validate_interval(minutes: u32) -> Result<()> { |
| 66 | 49 | if minutes != 0 && minutes < MIN_INTERVAL_MINUTES { |
| @@ -74,12 +57,7 @@ fn validate_interval(minutes: u32) -> Result<()> { | ||
| 74 | 57 | impl Store { |
| 75 | 58 | /// Seals a plaintext mirror secret with the instance key. |
| 76 | 59 | fn seal_mirror_secret(&self, plain: &[u8]) -> Result<Vec<u8>> { |
| 77 | - let key = self | |
| 78 | - .inner | |
| 79 | - .secret_key | |
| 80 | - .get() | |
| 81 | - .ok_or_else(|| Error::Crypto("mirror secret key is not set".into()))?; | |
| 82 | - Ok(secret::seal(key, plain)?.into_bytes()) | |
| 60 | + Ok(secret::seal(self.secret_key()?, plain)?.into_bytes()) | |
| 83 | 61 | } |
| 84 | 62 | |
| 85 | 63 | /// Creates a mirror. The repo has at most one pull mirror (`Conflict` for a second) and at |
| @@ -263,12 +241,7 @@ impl Store { | ||
| 263 | 241 | }; |
| 264 | 242 | let sealed = String::from_utf8(sealed) |
| 265 | 243 | .map_err(|_| Error::Crypto("sealed mirror secret is not UTF-8".into()))?; |
| 266 | - let key = self | |
| 267 | - .inner | |
| 268 | - .secret_key | |
| 269 | - .get() | |
| 270 | - .ok_or_else(|| Error::Crypto("mirror secret key is not set".into()))?; | |
| 271 | - Ok(Some(secret::open(key, &sealed)?)) | |
| 244 | + Ok(Some(secret::open(self.secret_key()?, &sealed)?)) | |
| 272 | 245 | } |
| 273 | 246 | |
| 274 | 247 | /// Enabled mirrors due at or before `now`, earliest first, at most `limit` (capped at 200). |
| @@ -328,7 +301,7 @@ impl Store { | ||
| 328 | 301 | let params = vec![ |
| 329 | 302 | Value::Text(id.to_string()), |
| 330 | 303 | Value::Text(now_stamp()), |
| 331 | - opt_int_value(Some(ok)), | |
| 304 | + Value::Integer(i64::from(ok)), | |
| 332 | 305 | opt_text(error), |
| 333 | 306 | Value::Text(next_sync_at.to_string()), |
| 334 | 307 | ]; |
| @@ -389,41 +362,6 @@ mod tests { | ||
| 389 | 362 | } |
| 390 | 363 | } |
| 391 | 364 | |
| 392 | - #[tokio::test] | |
| 393 | - async fn next_mirror_due_is_the_earliest_enabled_mirror() { | |
| 394 | - let (store, _tahinli, repo, _dir) = setup().await; | |
| 395 | - assert_eq!(store.next_mirror_due().await.unwrap(), None); | |
| 396 | - let m = store | |
| 397 | - .create_mirror(&push(&repo, "https://c.example/z.git")) | |
| 398 | - .await | |
| 399 | - .unwrap(); | |
| 400 | - let later = stamp_after(Duration::from_secs(3600)); | |
| 401 | - store.schedule_mirror(&m.id, &later).await.unwrap(); | |
| 402 | - assert_eq!( | |
| 403 | - store.next_mirror_due().await.unwrap().as_deref(), | |
| 404 | - Some(later.as_str()) | |
| 405 | - ); | |
| 406 | - let soon = stamp_after(Duration::from_secs(10)); | |
| 407 | - let m2 = store | |
| 408 | - .create_mirror(&push(&repo, "https://d.example/w.git")) | |
| 409 | - .await | |
| 410 | - .unwrap(); | |
| 411 | - store.schedule_mirror(&m2.id, &soon).await.unwrap(); | |
| 412 | - assert_eq!( | |
| 413 | - store.next_mirror_due().await.unwrap().as_deref(), | |
| 414 | - Some(soon.as_str()) | |
| 415 | - ); | |
| 416 | - store | |
| 417 | - .update_mirror(&m2.id, &m2.url, "", SecretUpdate::Keep, 480, false) | |
| 418 | - .await | |
| 419 | - .unwrap(); | |
| 420 | - assert_eq!( | |
| 421 | - store.next_mirror_due().await.unwrap().as_deref(), | |
| 422 | - Some(later.as_str()), | |
| 423 | - "a disabled mirror is ignored" | |
| 424 | - ); | |
| 425 | - } | |
| 426 | - | |
| 427 | 365 | async fn add_repo(store: &Store, owner: &User, name: &str) -> Repo { |
| 428 | 366 | store |
| 429 | 367 | .create_repo(&owner.id, name, "", Visibility::Public, "main") |
| @@ -653,6 +591,7 @@ mod tests { | ||
| 653 | 591 | #[tokio::test] |
| 654 | 592 | async fn due_mirrors_are_earliest_first_and_skip_disabled() { |
| 655 | 593 | let (store, _tahinli, repo, _dir) = setup().await; |
| 594 | + assert_eq!(store.next_mirror_due().await.unwrap(), None); | |
| 656 | 595 | let late = store |
| 657 | 596 | .create_mirror(&push(&repo, "https://late.example/r.git")) |
| 658 | 597 | .await |
| @@ -678,7 +617,7 @@ mod tests { | ||
| 678 | 617 | .await |
| 679 | 618 | .unwrap(); |
| 680 | 619 | store |
| 681 | - .schedule_mirror(&off.id, "2020-01-01T00:00:00.000000000Z") | |
| 620 | + .schedule_mirror(&off.id, "2019-12-31T00:00:00.000000000Z") | |
| 682 | 621 | .await |
| 683 | 622 | .unwrap(); |
| 684 | 623 | store |
| @@ -696,6 +635,11 @@ mod tests { | ||
| 696 | 635 | ) |
| 697 | 636 | .await |
| 698 | 637 | .unwrap(); |
| 638 | + assert_eq!( | |
| 639 | + store.next_mirror_due().await.unwrap().as_deref(), | |
| 640 | + Some("2020-01-01T00:00:00.000000000Z"), | |
| 641 | + "a disabled mirror is ignored" | |
| 642 | + ); | |
| 699 | 643 | |
| 700 | 644 | let now = now_stamp(); |
| 701 | 645 | let due: Vec<String> = store |
crates/forge-core/src/store/mod.rsmodified+121 -254
| @@ -71,6 +71,8 @@ use crate::protection::{BranchRule, RuleFlags, validate_required_approvals}; | ||
| 71 | 71 | use crate::time::now_stamp; |
| 72 | 72 | |
| 73 | 73 | const BUSY_TIMEOUT: Duration = Duration::from_millis(5000); |
| 74 | + | |
| 75 | +const IN_CHUNK: usize = 500; | |
| 74 | 76 | /// Longest accepted `about` text, in characters. |
| 75 | 77 | pub const MAX_ABOUT_CHARS: usize = 2000; |
| 76 | 78 | /// Longest accepted display name, in characters. |
| @@ -152,13 +154,12 @@ impl Store { | ||
| 152 | 154 | let conn = db.connect().map_err(db_err)?; |
| 153 | 155 | apply_pragmas(&conn).await; |
| 154 | 156 | migrate::migrate(&conn).await?; |
| 155 | - // Readers are opened after migrations so their schema view is current. | |
| 156 | 157 | let mut readers = Vec::with_capacity(READER_COUNT); |
| 157 | 158 | for _ in 0..READER_COUNT { |
| 158 | 159 | let reader = db.connect().map_err(db_err)?; |
| 159 | 160 | apply_pragmas(&reader).await; |
| 160 | - apply_query_only(&reader).await?; | |
| 161 | - apply_reader_cache_size(&reader).await?; | |
| 161 | + run_pragma(&reader, "PRAGMA query_only = 1").await.map_err(db_err)?; | |
| 162 | + run_pragma(&reader, "PRAGMA cache_size = -2048").await.map_err(db_err)?; | |
| 162 | 163 | readers.push(Mutex::new(reader)); |
| 163 | 164 | } |
| 164 | 165 | Ok(Store { |
| @@ -193,7 +194,13 @@ impl Store { | ||
| 193 | 194 | let _ = self.inner.secret_key.set(key); |
| 194 | 195 | } |
| 195 | 196 | |
| 196 | - // users | |
| 197 | + fn secret_key(&self) -> Result<&[u8; 32]> { | |
| 198 | + self.inner | |
| 199 | + .secret_key | |
| 200 | + .get() | |
| 201 | + .ok_or_else(|| Error::Crypto("the instance key is not set".into())) | |
| 202 | + } | |
| 203 | + | |
| 197 | 204 | pub async fn user_count(&self) -> Result<u64> { |
| 198 | 205 | let conn = self.read_conn().await; |
| 199 | 206 | let mut rows = conn |
| @@ -212,27 +219,7 @@ impl Store { | ||
| 212 | 219 | password_hash: &str, |
| 213 | 220 | is_admin: bool, |
| 214 | 221 | ) -> Result<User> { |
| 215 | - let user = User { | |
| 216 | - id: new_id(), | |
| 217 | - username: username.to_string(), | |
| 218 | - email: email.map(str::to_owned), | |
| 219 | - password_hash: password_hash.to_string(), | |
| 220 | - is_admin, | |
| 221 | - created_at: now_stamp(), | |
| 222 | - about: String::new(), | |
| 223 | - display_name: None, | |
| 224 | - timezone: "UTC".to_string(), | |
| 225 | - avatar_hash: None, | |
| 226 | - theme: "light".into(), | |
| 227 | - language: "auto".into(), | |
| 228 | - accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | |
| 229 | - accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | |
| 230 | - base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), | |
| 231 | - base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), | |
| 232 | - sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(), | |
| 233 | - kind: AccountKind::User, | |
| 234 | - email_notifications: true, | |
| 235 | - }; | |
| 222 | + let user = new_user(username, email, password_hash, is_admin); | |
| 236 | 223 | let conn = self.inner.conn.lock().await; |
| 237 | 224 | conn.execute( |
| 238 | 225 | "INSERT INTO users (id, username, username_folded, email, password_hash, is_admin, created_at, theme) \ |
| @@ -260,27 +247,7 @@ impl Store { | ||
| 260 | 247 | email: Option<&str>, |
| 261 | 248 | password_hash: &str, |
| 262 | 249 | ) -> Result<Option<User>> { |
| 263 | - let user = User { | |
| 264 | - id: new_id(), | |
| 265 | - username: username.to_string(), | |
| 266 | - email: email.map(str::to_owned), | |
| 267 | - password_hash: password_hash.to_string(), | |
| 268 | - is_admin: true, | |
| 269 | - created_at: now_stamp(), | |
| 270 | - about: String::new(), | |
| 271 | - display_name: None, | |
| 272 | - timezone: "UTC".to_string(), | |
| 273 | - avatar_hash: None, | |
| 274 | - theme: "light".into(), | |
| 275 | - language: "auto".into(), | |
| 276 | - accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | |
| 277 | - accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | |
| 278 | - base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), | |
| 279 | - base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), | |
| 280 | - sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(), | |
| 281 | - kind: AccountKind::User, | |
| 282 | - email_notifications: true, | |
| 283 | - }; | |
| 250 | + let user = new_user(username, email, password_hash, true); | |
| 284 | 251 | let conn = self.inner.conn.lock().await; |
| 285 | 252 | let inserted = conn |
| 286 | 253 | .execute( |
| @@ -334,7 +301,6 @@ impl Store { | ||
| 334 | 301 | .await |
| 335 | 302 | } |
| 336 | 303 | |
| 337 | - // sessions | |
| 338 | 304 | /// Changes only the display casing of a username. `display` must validate and fold to the |
| 339 | 305 | /// user's current `username_folded`; anything else is rejected and nothing is written. |
| 340 | 306 | pub async fn set_username_display(&self, user_id: &str, display: &str) -> Result<()> { |
| @@ -454,7 +420,6 @@ impl Store { | ||
| 454 | 420 | .await |
| 455 | 421 | } |
| 456 | 422 | |
| 457 | - // ssh keys | |
| 458 | 423 | pub async fn add_ssh_key( |
| 459 | 424 | &self, |
| 460 | 425 | user_id: &str, |
| @@ -479,7 +444,7 @@ impl Store { | ||
| 479 | 444 | "SELECT COUNT(*) FROM ssh_keys WHERE user_id = ?1", |
| 480 | 445 | user_id, |
| 481 | 446 | MAX_SSH_KEYS, |
| 482 | - "an account can have at most 100 SSH keys", | |
| 447 | + &format!("an account can have at most {MAX_SSH_KEYS} SSH keys"), | |
| 483 | 448 | ) |
| 484 | 449 | .await?; |
| 485 | 450 | conn.execute( |
| @@ -549,7 +514,6 @@ impl Store { | ||
| 549 | 514 | Ok(()) |
| 550 | 515 | } |
| 551 | 516 | |
| 552 | - // tokens | |
| 553 | 517 | pub async fn create_token( |
| 554 | 518 | &self, |
| 555 | 519 | user_id: &str, |
| @@ -575,7 +539,7 @@ impl Store { | ||
| 575 | 539 | "SELECT COUNT(*) FROM access_tokens WHERE user_id = ?1", |
| 576 | 540 | user_id, |
| 577 | 541 | MAX_TOKENS, |
| 578 | - "an account can have at most 100 access tokens", | |
| 542 | + &format!("an account can have at most {MAX_TOKENS} access tokens"), | |
| 579 | 543 | ) |
| 580 | 544 | .await?; |
| 581 | 545 | conn.execute( |
| @@ -648,7 +612,6 @@ impl Store { | ||
| 648 | 612 | Ok(()) |
| 649 | 613 | } |
| 650 | 614 | |
| 651 | - // repos | |
| 652 | 615 | pub async fn create_repo( |
| 653 | 616 | &self, |
| 654 | 617 | owner_id: &str, |
| @@ -683,7 +646,6 @@ impl Store { | ||
| 683 | 646 | let conn = self.inner.conn.lock().await; |
| 684 | 647 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 685 | 648 | let outcome: Result<Option<Repo>> = async { |
| 686 | - // A new repo takes over an old name, so any redirect for it is dropped. | |
| 687 | 649 | tx.execute( |
| 688 | 650 | "DELETE FROM repo_redirects WHERE owner_folded = (SELECT username_folded FROM users WHERE id = ?1) AND name_folded = ?2", |
| 689 | 651 | (owner_id.to_string(), normalize_name(name)), |
| @@ -716,20 +678,7 @@ impl Store { | ||
| 716 | 678 | .await |
| 717 | 679 | } |
| 718 | 680 | .await; |
| 719 | - match outcome { | |
| 720 | - Ok(Some(repo)) => { | |
| 721 | - tx.commit().await.map_err(db_err)?; | |
| 722 | - Ok(repo) | |
| 723 | - } | |
| 724 | - Ok(None) => { | |
| 725 | - let _ = tx.rollback().await; | |
| 726 | - Err(missing_row()) | |
| 727 | - } | |
| 728 | - Err(e) => { | |
| 729 | - let _ = tx.rollback().await; | |
| 730 | - Err(e) | |
| 731 | - } | |
| 732 | - } | |
| 681 | + finish(tx, outcome.and_then(|repo| repo.ok_or_else(missing_row))).await | |
| 733 | 682 | } |
| 734 | 683 | |
| 735 | 684 | /// Normalized. The caller strips a trailing ".git" from `name`. |
| @@ -778,10 +727,7 @@ impl Store { | ||
| 778 | 727 | ) |
| 779 | 728 | .await |
| 780 | 729 | .map_err(db_err)?; |
| 781 | - if n == 0 { | |
| 782 | - return Err(Error::NotFound); | |
| 783 | - } | |
| 784 | - Ok(()) | |
| 730 | + affected(n) | |
| 785 | 731 | } |
| 786 | 732 | |
| 787 | 733 | pub async fn collaborator_role(&self, repo_id: &str, user_id: &str) -> Result<Option<Role>> { |
| @@ -811,7 +757,6 @@ impl Store { | ||
| 811 | 757 | Ok(()) |
| 812 | 758 | } |
| 813 | 759 | |
| 814 | - // events | |
| 815 | 760 | pub async fn record_push_event( |
| 816 | 761 | &self, |
| 817 | 762 | repo_id: &str, |
| @@ -840,7 +785,7 @@ impl Store { | ||
| 840 | 785 | .map_err(db_err)?; |
| 841 | 786 | Ok(()) |
| 842 | 787 | } |
| 843 | - // profile | |
| 788 | + | |
| 844 | 789 | /// Sets the about text and timezone. `about` is at most 2000 characters and `timezone` |
| 845 | 790 | /// must be a known IANA name; anything else is rejected and nothing is written. |
| 846 | 791 | pub async fn set_profile(&self, user_id: &str, about: &str, timezone: &str) -> Result<()> { |
| @@ -858,10 +803,7 @@ impl Store { | ||
| 858 | 803 | ) |
| 859 | 804 | .await |
| 860 | 805 | .map_err(db_err)?; |
| 861 | - if n == 0 { | |
| 862 | - return Err(Error::NotFound); | |
| 863 | - } | |
| 864 | - Ok(()) | |
| 806 | + affected(n) | |
| 865 | 807 | } |
| 866 | 808 | |
| 867 | 809 | /// Sets the display name. `name` goes through `validate_display_name`; an empty name clears |
| @@ -879,10 +821,7 @@ impl Store { | ||
| 879 | 821 | ) |
| 880 | 822 | .await |
| 881 | 823 | .map_err(db_err)?; |
| 882 | - if n == 0 { | |
| 883 | - return Err(Error::NotFound); | |
| 884 | - } | |
| 885 | - Ok(()) | |
| 824 | + affected(n) | |
| 886 | 825 | } |
| 887 | 826 | |
| 888 | 827 | /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest. |
| @@ -940,16 +879,57 @@ impl Store { | ||
| 940 | 879 | } |
| 941 | 880 | } |
| 942 | 881 | |
| 943 | -// ---- helpers ---- | |
| 944 | - | |
| 945 | 882 | fn new_id() -> String { |
| 946 | 883 | Ulid::generate().to_string() |
| 947 | 884 | } |
| 948 | 885 | |
| 886 | +fn new_user(username: &str, email: Option<&str>, password_hash: &str, is_admin: bool) -> User { | |
| 887 | + User { | |
| 888 | + id: new_id(), | |
| 889 | + username: username.to_string(), | |
| 890 | + email: email.map(str::to_owned), | |
| 891 | + password_hash: password_hash.to_string(), | |
| 892 | + is_admin, | |
| 893 | + created_at: now_stamp(), | |
| 894 | + about: String::new(), | |
| 895 | + display_name: None, | |
| 896 | + timezone: "UTC".to_string(), | |
| 897 | + avatar_hash: None, | |
| 898 | + theme: "light".into(), | |
| 899 | + language: "auto".into(), | |
| 900 | + accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | |
| 901 | + accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | |
| 902 | + base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), | |
| 903 | + base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), | |
| 904 | + sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(), | |
| 905 | + kind: AccountKind::User, | |
| 906 | + email_notifications: true, | |
| 907 | + } | |
| 908 | +} | |
| 909 | + | |
| 910 | +fn text(s: &str) -> Value { | |
| 911 | + Value::Text(s.to_string()) | |
| 912 | +} | |
| 913 | + | |
| 914 | +fn opt_text(v: Option<&str>) -> Value { | |
| 915 | + v.map_or(Value::Null, text) | |
| 916 | +} | |
| 917 | + | |
| 918 | +fn opt_int_value(v: Option<i64>) -> Value { | |
| 919 | + v.map_or(Value::Null, Value::Integer) | |
| 920 | +} | |
| 921 | + | |
| 949 | 922 | fn db_err(e: turso::Error) -> Error { |
| 950 | 923 | Error::Database(e.to_string()) |
| 951 | 924 | } |
| 952 | 925 | |
| 926 | +fn affected(n: u64) -> Result<()> { | |
| 927 | + if n == 0 { | |
| 928 | + return Err(Error::NotFound); | |
| 929 | + } | |
| 930 | + Ok(()) | |
| 931 | +} | |
| 932 | + | |
| 953 | 933 | fn missing_row() -> Error { |
| 954 | 934 | Error::Database("expected a row that is not there".into()) |
| 955 | 935 | } |
| @@ -964,25 +944,9 @@ fn insert_err(e: turso::Error, conflict_msg: &str) -> Error { | ||
| 964 | 944 | } |
| 965 | 945 | } |
| 966 | 946 | |
| 967 | -/// Makes a connection refuse writes. Turso takes `1`, not `ON`. Failure is fatal, because a | |
| 968 | -/// reader that can write would break the pool's rule. | |
| 969 | -async fn apply_query_only(conn: &Connection) -> Result<()> { | |
| 970 | - let mut rows = conn | |
| 971 | - .query("PRAGMA query_only = 1", ()) | |
| 972 | - .await | |
| 973 | - .map_err(db_err)?; | |
| 974 | - while rows.next().await.map_err(db_err)?.is_some() {} | |
| 975 | - Ok(()) | |
| 976 | -} | |
| 977 | - | |
| 978 | -/// Caps each reader's page cache at 2 MiB (negative means KiB). Turso gives every connection | |
| 979 | -/// its own cache, so the default 2000 pages (~8 MB) per reader adds up across the pool. | |
| 980 | -async fn apply_reader_cache_size(conn: &Connection) -> Result<()> { | |
| 981 | - let mut rows = conn | |
| 982 | - .query("PRAGMA cache_size = -2048", ()) | |
| 983 | - .await | |
| 984 | - .map_err(db_err)?; | |
| 985 | - while rows.next().await.map_err(db_err)?.is_some() {} | |
| 947 | +async fn run_pragma(conn: &Connection, sql: &str) -> std::result::Result<(), turso::Error> { | |
| 948 | + let mut rows = conn.query(sql, ()).await?; | |
| 949 | + while rows.next().await?.is_some() {} | |
| 986 | 950 | Ok(()) |
| 987 | 951 | } |
| 988 | 952 | |
| @@ -994,13 +958,7 @@ async fn apply_pragmas(conn: &Connection) { | ||
| 994 | 958 | "PRAGMA synchronous = FULL", |
| 995 | 959 | "PRAGMA foreign_keys = ON", |
| 996 | 960 | ] { |
| 997 | - let applied = async { | |
| 998 | - let mut rows = conn.query(sql, ()).await?; | |
| 999 | - while rows.next().await?.is_some() {} | |
| 1000 | - Ok::<(), turso::Error>(()) | |
| 1001 | - } | |
| 1002 | - .await; | |
| 1003 | - if let Err(e) = applied { | |
| 961 | + if let Err(e) = run_pragma(conn, sql).await { | |
| 1004 | 962 | tracing::warn!(pragma = sql, error = %e, "database pragma not applied"); |
| 1005 | 963 | } |
| 1006 | 964 | } |
| @@ -1085,6 +1043,14 @@ fn col_opt_text(row: &Row, i: usize) -> Result<Option<String>> { | ||
| 1085 | 1043 | } |
| 1086 | 1044 | } |
| 1087 | 1045 | |
| 1046 | +fn col_opt_int(row: &Row, i: usize) -> Result<Option<i64>> { | |
| 1047 | + match row.get_value(i).map_err(db_err)? { | |
| 1048 | + Value::Integer(n) => Ok(Some(n)), | |
| 1049 | + Value::Null => Ok(None), | |
| 1050 | + _ => Err(Error::Database(format!("column {i} is not an integer"))), | |
| 1051 | + } | |
| 1052 | +} | |
| 1053 | + | |
| 1088 | 1054 | fn col_blob(row: &Row, i: usize) -> Result<Vec<u8>> { |
| 1089 | 1055 | match row.get_value(i).map_err(db_err)? { |
| 1090 | 1056 | Value::Blob(b) => Ok(b), |
| @@ -1092,6 +1058,10 @@ fn col_blob(row: &Row, i: usize) -> Result<Vec<u8>> { | ||
| 1092 | 1058 | } |
| 1093 | 1059 | } |
| 1094 | 1060 | |
| 1061 | +pub(crate) fn placeholders(n: usize) -> String { | |
| 1062 | + vec!["?"; n].join(",") | |
| 1063 | +} | |
| 1064 | + | |
| 1095 | 1065 | pub(crate) fn col_int(row: &Row, i: usize) -> Result<i64> { |
| 1096 | 1066 | match row.get_value(i).map_err(db_err)? { |
| 1097 | 1067 | Value::Integer(n) => Ok(n), |
| @@ -1238,7 +1208,6 @@ fn parse_role(s: &str) -> Result<Role> { | ||
| 1238 | 1208 | } |
| 1239 | 1209 | } |
| 1240 | 1210 | |
| 1241 | -/// Repo deletion. Lives in its own impl block so the existing store code stays untouched. | |
| 1242 | 1211 | impl Store { |
| 1243 | 1212 | /// Deletes a repo row and every row that references it (webhooks and their deliveries, issues and their children, labels, |
| 1244 | 1213 | /// milestones, pull requests, notifications, watches and issue subscriptions, redirects, collaborators, push events, |
| @@ -1252,8 +1221,6 @@ impl Store { | ||
| 1252 | 1221 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 1253 | 1222 | let id = repo_id.to_string(); |
| 1254 | 1223 | let outcome: Result<u64> = async { |
| 1255 | - // Review rows and pull request rows of this repo's issues go first, then the M3 rows, | |
| 1256 | - // child tables before parents. | |
| 1257 | 1224 | notifications::delete_repo_notification_rows(&tx, &id).await?; |
| 1258 | 1225 | reviews::delete_repo_review_rows(&tx, &id).await?; |
| 1259 | 1226 | pulls::delete_repo_pull_rows(&tx, &id).await?; |
| @@ -1261,7 +1228,6 @@ impl Store { | ||
| 1261 | 1228 | discussions::delete_repo_discussion_rows(&tx, &id).await?; |
| 1262 | 1229 | releases::delete_repo_release_rows(&tx, &id).await?; |
| 1263 | 1230 | for sql in [ |
| 1264 | - // Deliveries before hooks, hooks before the repo. | |
| 1265 | 1231 | "DELETE FROM webhook_deliveries WHERE hook_id IN (SELECT id FROM webhooks WHERE repo_id = ?1)", |
| 1266 | 1232 | "DELETE FROM webhooks WHERE repo_id = ?1", |
| 1267 | 1233 | "DELETE FROM repo_mirrors WHERE repo_id = ?1", |
| @@ -1279,13 +1245,11 @@ impl Store { | ||
| 1279 | 1245 | "DELETE FROM advisory_notifications WHERE repo_id = ?1", |
| 1280 | 1246 | "DELETE FROM repo_alerts WHERE repo_id = ?1", |
| 1281 | 1247 | "DELETE FROM repo_dependencies WHERE repo_id = ?1", |
| 1282 | - // CI: artifacts and jobs before runs, runs before the repo. | |
| 1283 | 1248 | "DELETE FROM ci_artifacts WHERE job_id IN (SELECT ci_jobs.id FROM ci_jobs \ |
| 1284 | 1249 | JOIN ci_runs ON ci_runs.id = ci_jobs.run_id WHERE ci_runs.repo_id = ?1)", |
| 1285 | 1250 | "DELETE FROM ci_jobs WHERE run_id IN (SELECT id FROM ci_runs WHERE repo_id = ?1)", |
| 1286 | 1251 | "DELETE FROM ci_runs WHERE repo_id = ?1", |
| 1287 | 1252 | "DELETE FROM ci_secrets WHERE repo_id = ?1", |
| 1288 | - // Forks of this repo stay, detached from it. | |
| 1289 | 1253 | "UPDATE repos SET fork_of = NULL WHERE fork_of = ?1", |
| 1290 | 1254 | ] { |
| 1291 | 1255 | tx.execute(sql, (id.clone(),)).await.map_err(db_err)?; |
| @@ -1295,20 +1259,11 @@ impl Store { | ||
| 1295 | 1259 | .map_err(db_err) |
| 1296 | 1260 | } |
| 1297 | 1261 | .await; |
| 1298 | - match outcome { | |
| 1299 | - Ok(1) => { | |
| 1300 | - tx.commit().await.map_err(db_err)?; | |
| 1301 | - Ok(()) | |
| 1302 | - } | |
| 1303 | - Ok(_) => { | |
| 1304 | - let _ = tx.rollback().await; | |
| 1305 | - Err(Error::NotFound) | |
| 1306 | - } | |
| 1307 | - Err(e) => { | |
| 1308 | - let _ = tx.rollback().await; | |
| 1309 | - Err(e) | |
| 1310 | - } | |
| 1311 | - } | |
| 1262 | + finish( | |
| 1263 | + tx, | |
| 1264 | + outcome.and_then(|n| if n == 1 { Ok(()) } else { Err(Error::NotFound) }), | |
| 1265 | + ) | |
| 1266 | + .await | |
| 1312 | 1267 | } |
| 1313 | 1268 | } |
| 1314 | 1269 | |
| @@ -1316,7 +1271,6 @@ const BRANCH_RULE_COLS: &str = "id, repo_id, pattern, allow_force_push, allow_de | ||
| 1316 | 1271 | required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks, \ |
| 1317 | 1272 | require_merge_queue"; |
| 1318 | 1273 | |
| 1319 | -// branch protection | |
| 1320 | 1274 | impl Store { |
| 1321 | 1275 | /// The repo's branch rules, ordered by pattern. |
| 1322 | 1276 | pub async fn list_branch_rules(&self, repo_id: &str) -> Result<Vec<BranchRule>> { |
| @@ -1395,10 +1349,7 @@ impl Store { | ||
| 1395 | 1349 | ) |
| 1396 | 1350 | .await |
| 1397 | 1351 | .map_err(db_err)?; |
| 1398 | - if n == 0 { | |
| 1399 | - return Err(Error::NotFound); | |
| 1400 | - } | |
| 1401 | - Ok(()) | |
| 1352 | + affected(n) | |
| 1402 | 1353 | } |
| 1403 | 1354 | } |
| 1404 | 1355 | |
| @@ -1421,7 +1372,6 @@ fn map_branch_rule(row: &Row) -> Result<BranchRule> { | ||
| 1421 | 1372 | }) |
| 1422 | 1373 | } |
| 1423 | 1374 | |
| 1424 | -// repo renames, transfers and redirects | |
| 1425 | 1375 | impl Store { |
| 1426 | 1376 | /// The repo a past owner/name points at (both folded). Chains work because a redirect always |
| 1427 | 1377 | /// points at the repo id, not at an intermediate name. |
| @@ -1443,65 +1393,60 @@ impl Store { | ||
| 1443 | 1393 | /// Renames a repo under its current owner. The old name keeps working through a redirect. |
| 1444 | 1394 | /// A name taken by another repo of the same owner gives `Conflict`. |
| 1445 | 1395 | pub async fn rename_repo(&self, repo_id: &str, new_name: &str) -> Result<()> { |
| 1446 | - let folded = validate_name(new_name)?; | |
| 1447 | - let owner_id = self.repo_owner_id(repo_id).await?.ok_or(Error::NotFound)?; | |
| 1448 | - self.move_repo(repo_id, &owner_id, new_name, &folded).await | |
| 1396 | + validate_name(new_name)?; | |
| 1397 | + self.move_repo(repo_id, None, Some(new_name)).await | |
| 1449 | 1398 | } |
| 1450 | 1399 | |
| 1451 | 1400 | /// Moves a repo to another owner under the same name. The old owner/name keeps working through |
| 1452 | 1401 | /// a redirect. Collaborator rows stay, except the new owner's, which is removed. A name taken |
| 1453 | 1402 | /// by the new owner gives `Conflict`. |
| 1454 | 1403 | pub async fn transfer_repo(&self, repo_id: &str, new_owner_id: &str) -> Result<()> { |
| 1455 | - let repo = self.repo_by_id(repo_id).await?.ok_or(Error::NotFound)?; | |
| 1456 | - self.move_repo( | |
| 1457 | - repo_id, | |
| 1458 | - new_owner_id, | |
| 1459 | - &repo.name, | |
| 1460 | - &normalize_name(&repo.name), | |
| 1461 | - ) | |
| 1462 | - .await | |
| 1404 | + self.move_repo(repo_id, Some(new_owner_id), None).await | |
| 1463 | 1405 | } |
| 1464 | 1406 | |
| 1465 | - /// The owner id of a repo, or `None` if it does not exist. | |
| 1466 | - async fn repo_owner_id(&self, repo_id: &str) -> Result<Option<String>> { | |
| 1467 | - let conn = self.read_conn().await; | |
| 1468 | - fetch_opt( | |
| 1469 | - &conn, | |
| 1470 | - "SELECT owner_id FROM repos WHERE id = ?1", | |
| 1471 | - (repo_id.to_string(),), | |
| 1472 | - |row| col_text(row, 0), | |
| 1473 | - ) | |
| 1474 | - .await | |
| 1475 | - } | |
| 1476 | - | |
| 1477 | - /// Shared body of rename and transfer, in one transaction: updates owner, name and folded | |
| 1478 | - /// name, records a redirect from the old owner/name to this repo, drops any redirect for the | |
| 1479 | - /// new owner/name, and removes the new owner's collaborator row when the owner changes. | |
| 1407 | + /// Shared body of rename and transfer, in one transaction. `None` keeps the current owner or | |
| 1408 | + /// name, which is read here under the writer lock so a concurrent move is not written back. | |
| 1409 | + /// Updates owner, name and folded name, records a redirect from the old owner/name to this | |
| 1410 | + /// repo, drops any redirect for the new owner/name, and removes the new owner's collaborator | |
| 1411 | + /// row when the owner changes. | |
| 1480 | 1412 | async fn move_repo( |
| 1481 | 1413 | &self, |
| 1482 | 1414 | repo_id: &str, |
| 1483 | - new_owner_id: &str, | |
| 1484 | - new_name: &str, | |
| 1485 | - new_folded: &str, | |
| 1415 | + new_owner_id: Option<&str>, | |
| 1416 | + new_name: Option<&str>, | |
| 1486 | 1417 | ) -> Result<()> { |
| 1487 | 1418 | let conn = self.inner.conn.lock().await; |
| 1488 | 1419 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 1489 | 1420 | let id = repo_id.to_string(); |
| 1490 | 1421 | let outcome: Result<()> = async { |
| 1491 | - // Old owner folded, old owner id, and old folded name. | |
| 1492 | - let (old_owner_id, old_owner_folded, old_folded): (String, String, String) = fetch_opt( | |
| 1422 | + let (old_owner_id, old_owner_folded, old_name, old_folded): ( | |
| 1423 | + String, | |
| 1424 | + String, | |
| 1425 | + String, | |
| 1426 | + String, | |
| 1427 | + ) = fetch_opt( | |
| 1493 | 1428 | &tx, |
| 1494 | - "SELECT r.owner_id, u.username_folded, r.name_folded FROM repos r \ | |
| 1429 | + "SELECT r.owner_id, u.username_folded, r.name, r.name_folded FROM repos r \ | |
| 1495 | 1430 | JOIN users u ON u.id = r.owner_id WHERE r.id = ?1", |
| 1496 | 1431 | (id.clone(),), |
| 1497 | - |row| Ok((col_text(row, 0)?, col_text(row, 1)?, col_text(row, 2)?)), | |
| 1432 | + |row| { | |
| 1433 | + Ok(( | |
| 1434 | + col_text(row, 0)?, | |
| 1435 | + col_text(row, 1)?, | |
| 1436 | + col_text(row, 2)?, | |
| 1437 | + col_text(row, 3)?, | |
| 1438 | + )) | |
| 1439 | + }, | |
| 1498 | 1440 | ) |
| 1499 | 1441 | .await? |
| 1500 | 1442 | .ok_or(Error::NotFound)?; |
| 1443 | + let new_owner_id = new_owner_id.map_or(old_owner_id.clone(), str::to_owned); | |
| 1444 | + let new_name = new_name.map_or(old_name, str::to_owned); | |
| 1445 | + let new_folded = normalize_name(&new_name); | |
| 1501 | 1446 | let new_owner_folded: String = fetch_opt( |
| 1502 | 1447 | &tx, |
| 1503 | 1448 | "SELECT username_folded FROM users WHERE id = ?1", |
| 1504 | - (new_owner_id.to_string(),), | |
| 1449 | + (new_owner_id.clone(),), | |
| 1505 | 1450 | |row| col_text(row, 0), |
| 1506 | 1451 | ) |
| 1507 | 1452 | .await? |
| @@ -1519,7 +1464,6 @@ impl Store { | ||
| 1519 | 1464 | .await |
| 1520 | 1465 | .map_err(|e| insert_err(e, "a repository with this name already exists"))?; |
| 1521 | 1466 | |
| 1522 | - // The new owner/name is live now, so no redirect may point at it. | |
| 1523 | 1467 | tx.execute( |
| 1524 | 1468 | "DELETE FROM repo_redirects WHERE owner_folded = ?1 AND name_folded = ?2", |
| 1525 | 1469 | (new_owner_folded.clone(), new_folded.to_string()), |
| @@ -1550,8 +1494,6 @@ impl Store { | ||
| 1550 | 1494 | ) |
| 1551 | 1495 | .await |
| 1552 | 1496 | .map_err(db_err)?; |
| 1553 | - // A transfer the old owner offered is void once the repo has moved: its target | |
| 1554 | - // must not be able to accept it later and take the repo from the new owner. | |
| 1555 | 1497 | tx.execute( |
| 1556 | 1498 | "DELETE FROM repo_transfers WHERE repo_id = ?1", |
| 1557 | 1499 | (id.clone(),), |
| @@ -1562,21 +1504,10 @@ impl Store { | ||
| 1562 | 1504 | Ok(()) |
| 1563 | 1505 | } |
| 1564 | 1506 | .await; |
| 1565 | - match outcome { | |
| 1566 | - Ok(()) => { | |
| 1567 | - tx.commit().await.map_err(db_err)?; | |
| 1568 | - Ok(()) | |
| 1569 | - } | |
| 1570 | - Err(e) => { | |
| 1571 | - let _ = tx.rollback().await; | |
| 1572 | - Err(e) | |
| 1573 | - } | |
| 1574 | - } | |
| 1507 | + finish(tx, outcome).await | |
| 1575 | 1508 | } |
| 1576 | 1509 | } |
| 1577 | 1510 | |
| 1578 | -// ---- account security: email, password, two-factor ---- | |
| 1579 | - | |
| 1580 | 1511 | /// The two-factor state of a user. |
| 1581 | 1512 | #[derive(Debug, Clone, PartialEq)] |
| 1582 | 1513 | pub struct TotpState { |
| @@ -1623,10 +1554,7 @@ impl Store { | ||
| 1623 | 1554 | ) |
| 1624 | 1555 | .await |
| 1625 | 1556 | .map_err(db_err)?; |
| 1626 | - if n == 0 { | |
| 1627 | - return Err(Error::NotFound); | |
| 1628 | - } | |
| 1629 | - Ok(()) | |
| 1557 | + affected(n) | |
| 1630 | 1558 | } |
| 1631 | 1559 | |
| 1632 | 1560 | /// Replaces the stored password hash. The caller hashes the password. |
| @@ -1639,10 +1567,7 @@ impl Store { | ||
| 1639 | 1567 | ) |
| 1640 | 1568 | .await |
| 1641 | 1569 | .map_err(db_err)?; |
| 1642 | - if n == 0 { | |
| 1643 | - return Err(Error::NotFound); | |
| 1644 | - } | |
| 1645 | - Ok(()) | |
| 1570 | + affected(n) | |
| 1646 | 1571 | } |
| 1647 | 1572 | |
| 1648 | 1573 | /// Deletes every session of the user except `keep_session_id`. Returns how many were removed. |
| @@ -1703,10 +1628,7 @@ impl Store { | ||
| 1703 | 1628 | ) |
| 1704 | 1629 | .await |
| 1705 | 1630 | .map_err(db_err)?; |
| 1706 | - if n == 0 { | |
| 1707 | - return Err(Error::NotFound); | |
| 1708 | - } | |
| 1709 | - Ok(()) | |
| 1631 | + affected(n) | |
| 1710 | 1632 | } |
| 1711 | 1633 | |
| 1712 | 1634 | /// Turns two-factor on after a confirmed code, and replaces the recovery codes with |
| @@ -1733,9 +1655,7 @@ impl Store { | ||
| 1733 | 1655 | ) |
| 1734 | 1656 | .await |
| 1735 | 1657 | .map_err(db_err)?; |
| 1736 | - if n == 0 { | |
| 1737 | - return Err(Error::NotFound); | |
| 1738 | - } | |
| 1658 | + affected(n)?; | |
| 1739 | 1659 | replace_codes_in(&tx, &uid, code_hashes).await |
| 1740 | 1660 | } |
| 1741 | 1661 | .await; |
| @@ -1908,14 +1828,12 @@ mod tests { | ||
| 1908 | 1828 | let dir = tempfile::tempdir().unwrap(); |
| 1909 | 1829 | let (store, user) = store_with_user(&dir).await; |
| 1910 | 1830 | |
| 1911 | - // Scenario: a new user has an empty bio and UTC. | |
| 1912 | 1831 | assert_eq!(user.about, ""); |
| 1913 | 1832 | assert_eq!(user.timezone, "UTC"); |
| 1914 | 1833 | let fetched = store.user_by_id(&user.id).await.unwrap().unwrap(); |
| 1915 | 1834 | assert_eq!(fetched.about, ""); |
| 1916 | 1835 | assert_eq!(fetched.timezone, "UTC"); |
| 1917 | 1836 | |
| 1918 | - // Scenario: a valid profile is saved; invalid input is refused and changes nothing. | |
| 1919 | 1837 | store |
| 1920 | 1838 | .set_profile(&user.id, "Hello *world*", "Europe/Istanbul") |
| 1921 | 1839 | .await |
| @@ -1949,7 +1867,6 @@ mod tests { | ||
| 1949 | 1867 | validate_display_name(" Ahmet Kaan Gümüş ").unwrap(), |
| 1950 | 1868 | Some("Ahmet Kaan Gümüş".to_string()) |
| 1951 | 1869 | ); |
| 1952 | - // The limit counts characters: 80 two-byte letters fit, 81 do not. | |
| 1953 | 1870 | assert!(validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS)).is_ok()); |
| 1954 | 1871 | assert!(matches!( |
| 1955 | 1872 | validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS + 1)), |
| @@ -1982,12 +1899,10 @@ mod tests { | ||
| 1982 | 1899 | let fetched = store.user_by_id(&user.id).await.unwrap().unwrap(); |
| 1983 | 1900 | assert_eq!(fetched.display_name.as_deref(), Some("Ahmet Kaan Gümüş")); |
| 1984 | 1901 | |
| 1985 | - // Blank input clears the name back to NULL. | |
| 1986 | 1902 | store.set_display_name(&user.id, " ").await.unwrap(); |
| 1987 | 1903 | let cleared = store.user_by_id(&user.id).await.unwrap().unwrap(); |
| 1988 | 1904 | assert_eq!(cleared.display_name, None); |
| 1989 | 1905 | |
| 1990 | - // A rejected name leaves the stored value alone. | |
| 1991 | 1906 | store.set_display_name(&user.id, "Kept").await.unwrap(); |
| 1992 | 1907 | let long = "x".repeat(MAX_DISPLAY_NAME_CHARS + 1); |
| 1993 | 1908 | assert!(matches!( |
| @@ -2007,7 +1922,6 @@ mod tests { | ||
| 2007 | 1922 | let dir = tempfile::tempdir().unwrap(); |
| 2008 | 1923 | let (store, user) = store_with_user(&dir).await; |
| 2009 | 1924 | |
| 2010 | - // Scenario: upsert replaces the image and its hash; delete is idempotent. | |
| 2011 | 1925 | assert_eq!(store.avatar(&user.id).await.unwrap(), None); |
| 2012 | 1926 | assert_eq!(store.avatar_hash(&user.id).await.unwrap(), None); |
| 2013 | 1927 | store.set_avatar(&user.id, b"png-1", "aaaa").await.unwrap(); |
| @@ -2024,7 +1938,6 @@ mod tests { | ||
| 2024 | 1938 | store.delete_avatar(&user.id).await.unwrap(); |
| 2025 | 1939 | assert_eq!(store.avatar(&user.id).await.unwrap(), None); |
| 2026 | 1940 | |
| 2027 | - // Scenario: deleting the user row removes its avatar with it. | |
| 2028 | 1941 | let doomed = store |
| 2029 | 1942 | .create_user("Doomed", None, "hash", false) |
| 2030 | 1943 | .await |
| @@ -2045,8 +1958,6 @@ mod tests { | ||
| 2045 | 1958 | let (store, tahinli) = store_with_user(&dir).await; |
| 2046 | 1959 | let bob = store.create_user("Bob", None, "hash", false).await.unwrap(); |
| 2047 | 1960 | |
| 2048 | - // Scenario: deleting a repo removes its collaborators, push events and branch | |
| 2049 | - // rules atomically, and leaves the other repo and its rows untouched. | |
| 2050 | 1961 | let keep = store |
| 2051 | 1962 | .create_repo(&tahinli.id, "keep", "", Visibility::Public, "main") |
| 2052 | 1963 | .await |
| @@ -2107,7 +2018,6 @@ mod tests { | ||
| 2107 | 2018 | assert_eq!(col_int(&row, 0).unwrap(), 1); |
| 2108 | 2019 | } |
| 2109 | 2020 | |
| 2110 | - // Scenario: a missing id is NotFound; deleting twice reports NotFound the second time. | |
| 2111 | 2021 | let later = store |
| 2112 | 2022 | .create_repo(&tahinli.id, "later", "", Visibility::Public, "main") |
| 2113 | 2023 | .await |
| @@ -2129,8 +2039,6 @@ mod tests { | ||
| 2129 | 2039 | let dir = tempfile::tempdir().unwrap(); |
| 2130 | 2040 | let (store, owner) = store_with_user(&dir).await; |
| 2131 | 2041 | |
| 2132 | - // Scenario: required checks are trimmed, de-duplicated and blanks dropped; | |
| 2133 | - // saving without checks clears them; a control character is refused. | |
| 2134 | 2042 | { |
| 2135 | 2043 | let repo = store |
| 2136 | 2044 | .create_repo(&owner.id, "checks", "", Visibility::Public, "main") |
| @@ -2169,7 +2077,6 @@ mod tests { | ||
| 2169 | 2077 | )); |
| 2170 | 2078 | } |
| 2171 | 2079 | |
| 2172 | - // Scenario: listing, upserting the same pattern updates in place, bad patterns refused. | |
| 2173 | 2080 | { |
| 2174 | 2081 | let repo = store |
| 2175 | 2082 | .create_repo(&owner.id, "list", "", Visibility::Public, "main") |
| @@ -2189,7 +2096,6 @@ mod tests { | ||
| 2189 | 2096 | let patterns: Vec<&str> = rules.iter().map(|r| r.pattern.as_str()).collect(); |
| 2190 | 2097 | assert_eq!(patterns, ["main", "release/*"]); |
| 2191 | 2098 | |
| 2192 | - // Same pattern updates the flags in place and keeps the id and created_at. | |
| 2193 | 2099 | let updated = store |
| 2194 | 2100 | .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(true, true)) |
| 2195 | 2101 | .await |
| @@ -2209,7 +2115,6 @@ mod tests { | ||
| 2209 | 2115 | )); |
| 2210 | 2116 | } |
| 2211 | 2117 | |
| 2212 | - // Scenario: merge and push fields round-trip; an out-of-range value is refused. | |
| 2213 | 2118 | { |
| 2214 | 2119 | let repo = store |
| 2215 | 2120 | .create_repo(&owner.id, "fields", "", Visibility::Public, "main") |
| @@ -2238,7 +2143,6 @@ mod tests { | ||
| 2238 | 2143 | vec![saved] |
| 2239 | 2144 | ); |
| 2240 | 2145 | |
| 2241 | - // Out of range is refused and stores nothing new. | |
| 2242 | 2146 | let too_many = RuleFlags { |
| 2243 | 2147 | required_approvals: 21, |
| 2244 | 2148 | ..flags |
| @@ -2251,7 +2155,6 @@ mod tests { | ||
| 2251 | 2155 | assert_eq!(rules[0].required_approvals, 20); |
| 2252 | 2156 | } |
| 2253 | 2157 | |
| 2254 | - // Scenario: deleting a rule is scoped to its own repo. | |
| 2255 | 2158 | { |
| 2256 | 2159 | let a = store |
| 2257 | 2160 | .create_repo(&owner.id, "scope-a", "", Visibility::Public, "main") |
| @@ -2322,7 +2225,6 @@ mod tests { | ||
| 2322 | 2225 | } |
| 2323 | 2226 | } |
| 2324 | 2227 | |
| 2325 | -// collaborators (settings page) | |
| 2326 | 2228 | impl Store { |
| 2327 | 2229 | /// Every collaborator on a repo with their role, ordered by username (case-insensitive). |
| 2328 | 2230 | pub async fn list_collaborators(&self, repo_id: &str) -> Result<Vec<(User, Role)>> { |
| @@ -2357,7 +2259,6 @@ impl Store { | ||
| 2357 | 2259 | /// Longest accepted repo description, in characters. |
| 2358 | 2260 | pub const MAX_DESCRIPTION_CHARS: usize = 350; |
| 2359 | 2261 | |
| 2360 | -// general repo settings (description, default branch, visibility) | |
| 2361 | 2262 | impl Store { |
| 2362 | 2263 | /// Saves the description and the default branch in one statement. The description must be at |
| 2363 | 2264 | /// most `MAX_DESCRIPTION_CHARS` characters with no control characters. The branch is not checked |
| @@ -2393,10 +2294,7 @@ impl Store { | ||
| 2393 | 2294 | ) |
| 2394 | 2295 | .await |
| 2395 | 2296 | .map_err(db_err)?; |
| 2396 | - if n == 0 { | |
| 2397 | - return Err(Error::NotFound); | |
| 2398 | - } | |
| 2399 | - Ok(()) | |
| 2297 | + affected(n) | |
| 2400 | 2298 | } |
| 2401 | 2299 | |
| 2402 | 2300 | /// Sets the repo's visibility. `NotFound` when the repo is gone. |
| @@ -2409,10 +2307,7 @@ impl Store { | ||
| 2409 | 2307 | ) |
| 2410 | 2308 | .await |
| 2411 | 2309 | .map_err(db_err)?; |
| 2412 | - if n == 0 { | |
| 2413 | - return Err(Error::NotFound); | |
| 2414 | - } | |
| 2415 | - Ok(()) | |
| 2310 | + affected(n) | |
| 2416 | 2311 | } |
| 2417 | 2312 | } |
| 2418 | 2313 | |
| @@ -2444,7 +2339,6 @@ mod collaborator_tests { | ||
| 2444 | 2339 | .set_collaborator(&repo.id, &amy.id, Role::Write) |
| 2445 | 2340 | .await |
| 2446 | 2341 | .unwrap(); |
| 2447 | - // Setting an existing collaborator again replaces the role. | |
| 2448 | 2342 | store |
| 2449 | 2343 | .set_collaborator(&repo.id, &zed.id, Role::Triage) |
| 2450 | 2344 | .await |
| @@ -2462,7 +2356,6 @@ mod collaborator_tests { | ||
| 2462 | 2356 | "ordered by username, one row per user" |
| 2463 | 2357 | ); |
| 2464 | 2358 | |
| 2465 | - // Push rights follow the role through authorize. | |
| 2466 | 2359 | assert!(authorize(Some(&amy), &repo, Some(Role::Write), None, Action::Write).is_ok()); |
| 2467 | 2360 | assert_eq!( |
| 2468 | 2361 | authorize(Some(&zed), &repo, Some(Role::Read), None, Action::Write), |
| @@ -2493,7 +2386,6 @@ pub enum RepoSort { | ||
| 2493 | 2386 | /// A row of the public listing: the repo, its star count and its last activity time. |
| 2494 | 2387 | pub type ListedRepo = (Repo, u64, String); |
| 2495 | 2388 | |
| 2496 | -// stars and the public repo listing | |
| 2497 | 2389 | impl Store { |
| 2498 | 2390 | /// Stars a repo for a user. Starring a repo twice changes nothing. |
| 2499 | 2391 | pub async fn star(&self, user_id: &str, repo_id: &str) -> Result<()> { |
| @@ -2546,23 +2438,6 @@ impl Store { | ||
| 2546 | 2438 | Ok(u64::try_from(n).unwrap_or(0)) |
| 2547 | 2439 | } |
| 2548 | 2440 | |
| 2549 | - /// Every repo the user has starred, newest star first. The result is not filtered by | |
| 2550 | - /// visibility; callers must check what the viewer may read. | |
| 2551 | - pub async fn starred_repos(&self, user_id: &str) -> Result<Vec<Repo>> { | |
| 2552 | - let conn = self.read_conn().await; | |
| 2553 | - fetch_all( | |
| 2554 | - &conn, | |
| 2555 | - &format!( | |
| 2556 | - "SELECT {REPO_COLS} FROM stars s JOIN repos r ON r.id = s.repo_id \ | |
| 2557 | - JOIN users u ON u.id = r.owner_id \ | |
| 2558 | - WHERE s.user_id = ?1 ORDER BY s.created_at DESC, r.id" | |
| 2559 | - ), | |
| 2560 | - (user_id.to_string(),), | |
| 2561 | - map_repo, | |
| 2562 | - ) | |
| 2563 | - .await | |
| 2564 | - } | |
| 2565 | - | |
| 2566 | 2441 | /// One page of public repos, optionally filtered by `query`. The query matches the repo name |
| 2567 | 2442 | /// or description, case-insensitively, as a plain substring: `%`, `_` and `\` are literal. |
| 2568 | 2443 | /// Each row carries the star count and the last activity time (the latest push, or the |
| @@ -2633,7 +2508,6 @@ mod security_tests { | ||
| 2633 | 2508 | async fn account_email_password_and_session_scenarios() { |
| 2634 | 2509 | let (store, user, _dir) = store_with_user().await; |
| 2635 | 2510 | |
| 2636 | - // Scenario: email and password hash persist; a bad email and a missing user are refused. | |
| 2637 | 2511 | store |
| 2638 | 2512 | .set_email(&user.id, "tahinli@example.com") |
| 2639 | 2513 | .await |
| @@ -2648,7 +2522,6 @@ mod security_tests { | ||
| 2648 | 2522 | Err(Error::NotFound) |
| 2649 | 2523 | )); |
| 2650 | 2524 | |
| 2651 | - // Scenario: deleting sessions except one keeps only the named session. | |
| 2652 | 2525 | let expiry = crate::time::stamp_after(std::time::Duration::from_secs(3600)); |
| 2653 | 2526 | let keep = store |
| 2654 | 2527 | .create_session(&user.id, "h1", "c1", &expiry, None, None) |
| @@ -2678,12 +2551,10 @@ mod security_tests { | ||
| 2678 | 2551 | async fn totp_scenarios() { |
| 2679 | 2552 | let (store, user, _dir) = store_with_user().await; |
| 2680 | 2553 | |
| 2681 | - // Scenario: enabling without a secret is refused and leaves TOTP off. | |
| 2682 | 2554 | let err = store.enable_totp(&user.id, 1, &[]).await; |
| 2683 | 2555 | assert!(matches!(err, Err(Error::NotFound))); |
| 2684 | 2556 | assert!(!store.totp_state(&user.id).await.unwrap().unwrap().enabled); |
| 2685 | 2557 | |
| 2686 | - // Scenario: enrollment, then replay and recovery-code rules. | |
| 2687 | 2558 | let fresh = store.totp_state(&user.id).await.unwrap().unwrap(); |
| 2688 | 2559 | assert_eq!(fresh.sealed_secret, None); |
| 2689 | 2560 | assert!(!fresh.enabled); |
| @@ -2700,7 +2571,6 @@ mod security_tests { | ||
| 2700 | 2571 | assert_eq!(on.last_step, 100); |
| 2701 | 2572 | assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 2); |
| 2702 | 2573 | |
| 2703 | - // Steps must strictly increase: 100 was used, so 100 and older are refused. | |
| 2704 | 2574 | assert!(!store.accept_totp_step(&user.id, 100).await.unwrap()); |
| 2705 | 2575 | assert!(!store.accept_totp_step(&user.id, 99).await.unwrap()); |
| 2706 | 2576 | assert!(store.accept_totp_step(&user.id, 101).await.unwrap()); |
| @@ -2738,7 +2608,6 @@ mod security_tests { | ||
| 2738 | 2608 | assert_eq!(off.last_step, 0); |
| 2739 | 2609 | assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 0); |
| 2740 | 2610 | |
| 2741 | - // Scenario: device fields (added, last used, name) on a second user. | |
| 2742 | 2611 | let device = store |
| 2743 | 2612 | .create_user("device-owner", None, "h", false) |
| 2744 | 2613 | .await |
| @@ -2775,14 +2644,12 @@ mod security_tests { | ||
| 2775 | 2644 | Some("Work phone") |
| 2776 | 2645 | ); |
| 2777 | 2646 | |
| 2778 | - // Stamps have nanosecond precision and sort as text, so a later use compares greater. | |
| 2779 | 2647 | std::thread::sleep(std::time::Duration::from_millis(5)); |
| 2780 | 2648 | assert!(store.accept_totp_step(&device.id, 101).await.unwrap()); |
| 2781 | 2649 | let used = store.totp_state(&device.id).await.unwrap().unwrap(); |
| 2782 | 2650 | assert!(used.last_used_at.as_deref().unwrap() > added.as_str()); |
| 2783 | 2651 | assert_eq!(used.created_at.as_deref(), Some(added.as_str())); |
| 2784 | 2652 | |
| 2785 | - // A replayed step is refused and leaves the last use alone. | |
| 2786 | 2653 | std::thread::sleep(std::time::Duration::from_millis(5)); |
| 2787 | 2654 | assert!(!store.accept_totp_step(&device.id, 101).await.unwrap()); |
| 2788 | 2655 | assert_eq!( |
crates/forge-core/src/store/notifications.rsmodified+55 -217
| @@ -3,9 +3,8 @@ | ||
| 3 | 3 | use turso::transaction::Transaction; |
| 4 | 4 | use turso::{Row, Value}; |
| 5 | 5 | |
| 6 | -use super::issues::finish; | |
| 7 | -use super::repo_listing::READABLE_BY_VIEWER; | |
| 8 | -use super::{Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, map_user, new_id}; | |
| 6 | +use super::repo_listing::VIEWER_ACCESS; | |
| 7 | +use super::{Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, finish, map_user, new_id}; | |
| 9 | 8 | use crate::error::{Error, Result}; |
| 10 | 9 | use crate::model::{Id, User}; |
| 11 | 10 | use crate::notifications::{Notification, Reason, SubState, WatchLevel}; |
| @@ -19,7 +18,7 @@ const MAX_NOTIFICATION_PAGE: u32 = 200; | ||
| 19 | 18 | /// from, drops out of the inbox, the dashboard and the unread count at once. |
| 20 | 19 | pub(super) fn readable_repo() -> String { |
| 21 | 20 | format!( |
| 22 | - "({READABLE_BY_VIEWER} OR EXISTS (SELECT 1 FROM users ua WHERE ua.id = ? AND ua.is_admin = 1))" | |
| 21 | + "((r.visibility = 'public' OR {VIEWER_ACCESS}) OR EXISTS (SELECT 1 FROM users ua WHERE ua.id = ? AND ua.is_admin = 1))" | |
| 23 | 22 | ) |
| 24 | 23 | } |
| 25 | 24 | |
| @@ -61,7 +60,7 @@ fn map_notification(row: &Row) -> Result<Notification> { | ||
| 61 | 60 | number: col_int(row, 5)?, |
| 62 | 61 | is_pull: kind == "pull", |
| 63 | 62 | title: col_text(row, 7)?, |
| 64 | - issue_state: col_text(row, 8)?, | |
| 63 | + issue_state: col_text(row, 8)?.parse()?, | |
| 65 | 64 | reason: reason_from(&col_text(row, 9)?)?, |
| 66 | 65 | last_activity: col_text(row, 10)?, |
| 67 | 66 | last_actor_name: match row.get_value(11).map_err(db_err)? { |
| @@ -91,6 +90,14 @@ pub(super) async fn delete_repo_notification_rows( | ||
| 91 | 90 | } |
| 92 | 91 | |
| 93 | 92 | impl Store { |
| 93 | + pub async fn set_email_notifications(&self, user_id: &str, on: bool) -> Result<()> { | |
| 94 | + self.update_user( | |
| 95 | + "UPDATE users SET email_notifications = ?2 WHERE id = ?1", | |
| 96 | + (user_id.to_string(), i64::from(on)), | |
| 97 | + ) | |
| 98 | + .await | |
| 99 | + } | |
| 100 | + | |
| 94 | 101 | /// Sets the user's watch level on a repo, creating the row if needed. |
| 95 | 102 | pub async fn set_watch(&self, user_id: &str, repo_id: &str, level: WatchLevel) -> Result<()> { |
| 96 | 103 | let conn = self.inner.conn.lock().await; |
| @@ -405,23 +412,12 @@ impl Store { | ||
| 405 | 412 | /// them. |
| 406 | 413 | pub async fn mark_all_read(&self, user_id: &str, repo_id: Option<&str>) -> Result<()> { |
| 407 | 414 | let conn = self.inner.conn.lock().await; |
| 408 | - let result = match repo_id { | |
| 409 | - Some(repo) => { | |
| 410 | - conn.execute( | |
| 411 | - "UPDATE notifications SET unread = 0 WHERE user_id = ?1 AND repo_id = ?2 AND unread = 1", | |
| 412 | - (user_id.to_string(), repo.to_string()), | |
| 413 | - ) | |
| 414 | - .await | |
| 415 | - } | |
| 416 | - None => { | |
| 417 | - conn.execute( | |
| 418 | - "UPDATE notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1", | |
| 419 | - (user_id.to_string(),), | |
| 420 | - ) | |
| 421 | - .await | |
| 422 | - } | |
| 423 | - }; | |
| 424 | - result.map_err(db_err)?; | |
| 415 | + conn.execute( | |
| 416 | + "UPDATE notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1 AND (?2 IS NULL OR repo_id = ?2)", | |
| 417 | + (user_id.to_string(), repo_id.map(str::to_string)), | |
| 418 | + ) | |
| 419 | + .await | |
| 420 | + .map_err(db_err)?; | |
| 425 | 421 | Ok(()) |
| 426 | 422 | } |
| 427 | 423 | |
| @@ -441,6 +437,7 @@ impl Store { | ||
| 441 | 437 | #[cfg(test)] |
| 442 | 438 | mod tests { |
| 443 | 439 | use super::*; |
| 440 | + use crate::issues::IssueState; | |
| 444 | 441 | use crate::model::Visibility; |
| 445 | 442 | |
| 446 | 443 | struct Fixture { |
| @@ -517,14 +514,25 @@ mod tests { | ||
| 517 | 514 | .id |
| 518 | 515 | } |
| 519 | 516 | |
| 520 | - // Scenarios share one store. Each one uses its own issue, repo or fresh users | |
| 521 | - // wherever the assertions read repo-wide or per-user state. | |
| 517 | + async fn notify( | |
| 518 | + s: &Store, | |
| 519 | + user: &str, | |
| 520 | + repo: &str, | |
| 521 | + issue: &str, | |
| 522 | + reason: Reason, | |
| 523 | + activity: &str, | |
| 524 | + actor: Option<&str>, | |
| 525 | + ) { | |
| 526 | + s.upsert_notification(user, repo, issue, reason, activity, actor) | |
| 527 | + .await | |
| 528 | + .unwrap(); | |
| 529 | + } | |
| 530 | + | |
| 522 | 531 | #[tokio::test] |
| 523 | - async fn watch_and_subscription_rules_hold_in_each_scenario() { | |
| 532 | + async fn watch_and_subscription_rules() { | |
| 524 | 533 | let fx = fixture().await; |
| 525 | 534 | let s = &fx.store; |
| 526 | 535 | |
| 527 | - // Scenario 1: watch levels default to participating; watchers lists only watchers. | |
| 528 | 536 | let repo = s |
| 529 | 537 | .create_repo(&fx.owner, "watch", "", Visibility::Public, "main") |
| 530 | 538 | .await |
| @@ -560,7 +568,6 @@ mod tests { | ||
| 560 | 568 | expected.sort(); |
| 561 | 569 | assert_eq!(watchers, expected, "watch: only watching users listed"); |
| 562 | 570 | |
| 563 | - // Scenario 2: auto-subscribe never overrides an ignore; explicit subscribe does. | |
| 564 | 571 | let issue = s |
| 565 | 572 | .create_issue(&fx.repo, &fx.owner, "Third", "") |
| 566 | 573 | .await |
| @@ -574,7 +581,6 @@ mod tests { | ||
| 574 | 581 | Some((SubState::Subscribed, Reason::Comment)), |
| 575 | 582 | "auto: first subscription" |
| 576 | 583 | ); |
| 577 | - // Existing row stays as it was. | |
| 578 | 584 | s.auto_subscribe(&fx.tahinli, &issue, Reason::Mention) |
| 579 | 585 | .await |
| 580 | 586 | .unwrap(); |
| @@ -583,7 +589,6 @@ mod tests { | ||
| 583 | 589 | Some((SubState::Subscribed, Reason::Comment)), |
| 584 | 590 | "auto: existing row kept" |
| 585 | 591 | ); |
| 586 | - // An explicit ignore is never replaced by auto-subscribe. | |
| 587 | 592 | s.subscribe(&fx.bob, &issue, SubState::Ignored, Reason::Subscribed) |
| 588 | 593 | .await |
| 589 | 594 | .unwrap(); |
| @@ -595,7 +600,6 @@ mod tests { | ||
| 595 | 600 | Some((SubState::Ignored, Reason::Subscribed)), |
| 596 | 601 | "auto: ignore kept" |
| 597 | 602 | ); |
| 598 | - // Explicit subscribe does replace. | |
| 599 | 603 | s.subscribe(&fx.bob, &issue, SubState::Subscribed, Reason::Author) |
| 600 | 604 | .await |
| 601 | 605 | .unwrap(); |
| @@ -610,7 +614,6 @@ mod tests { | ||
| 610 | 614 | "auto: untouched user has no row" |
| 611 | 615 | ); |
| 612 | 616 | |
| 613 | - // Scenario 3: subscribers lists only subscribed users of one issue. | |
| 614 | 617 | let issue = s |
| 615 | 618 | .create_issue(&fx.repo, &fx.owner, "Fourth", "") |
| 616 | 619 | .await |
| @@ -634,32 +637,13 @@ mod tests { | ||
| 634 | 637 | } |
| 635 | 638 | |
| 636 | 639 | #[tokio::test] |
| 637 | - async fn inbox_rules_hold_in_each_scenario() { | |
| 640 | + async fn inbox_rules() { | |
| 638 | 641 | let fx = fixture().await; |
| 639 | 642 | let s = &fx.store; |
| 640 | 643 | |
| 641 | - // Scenario 1: a stronger reason wins while unread; a read row is replaced. | |
| 642 | 644 | let ivy = user(s, "Ivy").await; |
| 643 | - s.upsert_notification( | |
| 644 | - &ivy, | |
| 645 | - &fx.repo, | |
| 646 | - &fx.issue_a, | |
| 647 | - Reason::Mention, | |
| 648 | - "mentioned", | |
| 649 | - Some(&fx.bob), | |
| 650 | - ) | |
| 651 | - .await | |
| 652 | - .unwrap(); | |
| 653 | - s.upsert_notification( | |
| 654 | - &ivy, | |
| 655 | - &fx.repo, | |
| 656 | - &fx.issue_a, | |
| 657 | - Reason::Comment, | |
| 658 | - "comment", | |
| 659 | - Some(&fx.bob), | |
| 660 | - ) | |
| 661 | - .await | |
| 662 | - .unwrap(); | |
| 645 | + notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Mention, "mentioned", Some(&fx.bob)).await; | |
| 646 | + notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&fx.bob)).await; | |
| 663 | 647 | assert_eq!( |
| 664 | 648 | reason_of(s, &ivy, &fx.issue_a).await, |
| 665 | 649 | Reason::Mention, |
| @@ -668,43 +652,16 @@ mod tests { | ||
| 668 | 652 | assert_eq!(s.unread_count(&ivy).await.unwrap(), 1, "upsert: one unread"); |
| 669 | 653 | |
| 670 | 654 | s.mark_issue_read(&ivy, &fx.issue_a).await.unwrap(); |
| 671 | - assert_eq!( | |
| 672 | - s.unread_count(&ivy).await.unwrap(), | |
| 673 | - 0, | |
| 674 | - "upsert: marked read" | |
| 675 | - ); | |
| 676 | - s.upsert_notification( | |
| 677 | - &ivy, | |
| 678 | - &fx.repo, | |
| 679 | - &fx.issue_a, | |
| 680 | - Reason::Comment, | |
| 681 | - "comment", | |
| 682 | - Some(&fx.bob), | |
| 683 | - ) | |
| 684 | - .await | |
| 685 | - .unwrap(); | |
| 655 | + assert_eq!(s.unread_count(&ivy).await.unwrap(), 0, "upsert: marked read"); | |
| 656 | + notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&fx.bob)).await; | |
| 686 | 657 | assert_eq!( |
| 687 | 658 | reason_of(s, &ivy, &fx.issue_a).await, |
| 688 | 659 | Reason::Comment, |
| 689 | 660 | "upsert: read row replaced" |
| 690 | 661 | ); |
| 691 | - assert_eq!( | |
| 692 | - s.unread_count(&ivy).await.unwrap(), | |
| 693 | - 1, | |
| 694 | - "upsert: unread again" | |
| 695 | - ); | |
| 662 | + assert_eq!(s.unread_count(&ivy).await.unwrap(), 1, "upsert: unread again"); | |
| 696 | 663 | |
| 697 | - // A stronger reason while unread still wins. | |
| 698 | - s.upsert_notification( | |
| 699 | - &ivy, | |
| 700 | - &fx.repo, | |
| 701 | - &fx.issue_a, | |
| 702 | - Reason::Assign, | |
| 703 | - "assigned", | |
| 704 | - None, | |
| 705 | - ) | |
| 706 | - .await | |
| 707 | - .unwrap(); | |
| 664 | + notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Assign, "assigned", None).await; | |
| 708 | 665 | let inbox = s.list_notifications(&ivy, false, None, 10).await.unwrap(); |
| 709 | 666 | assert_eq!(inbox.len(), 1, "upsert: still one row"); |
| 710 | 667 | assert_eq!( |
| @@ -715,28 +672,9 @@ mod tests { | ||
| 715 | 672 | assert_eq!(inbox[0].last_activity, "assigned", "upsert: activity text"); |
| 716 | 673 | assert_eq!(inbox[0].last_actor_name, None, "upsert: no actor given"); |
| 717 | 674 | |
| 718 | - // Scenario 2: listing is newest first, paged by cursor, and per user. | |
| 719 | 675 | let kim = user(s, "Kim").await; |
| 720 | - s.upsert_notification( | |
| 721 | - &kim, | |
| 722 | - &fx.repo, | |
| 723 | - &fx.issue_a, | |
| 724 | - Reason::Comment, | |
| 725 | - "comment", | |
| 726 | - Some(&fx.bob), | |
| 727 | - ) | |
| 728 | - .await | |
| 729 | - .unwrap(); | |
| 730 | - s.upsert_notification( | |
| 731 | - &kim, | |
| 732 | - &fx.repo, | |
| 733 | - &fx.issue_b, | |
| 734 | - Reason::Comment, | |
| 735 | - "comment", | |
| 736 | - Some(&fx.bob), | |
| 737 | - ) | |
| 738 | - .await | |
| 739 | - .unwrap(); | |
| 676 | + notify(s, &kim, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&fx.bob)).await; | |
| 677 | + notify(s, &kim, &fx.repo, &fx.issue_b, Reason::Comment, "comment", Some(&fx.bob)).await; | |
| 740 | 678 | s.mark_issue_read(&kim, &fx.issue_b).await.unwrap(); |
| 741 | 679 | |
| 742 | 680 | let all = s.list_notifications(&kim, false, None, 50).await.unwrap(); |
| @@ -746,7 +684,7 @@ mod tests { | ||
| 746 | 684 | assert_eq!(all[0].repo_owner, "Owen", "list: repo owner"); |
| 747 | 685 | assert_eq!(all[0].repo_name, "proj", "list: repo name"); |
| 748 | 686 | assert_eq!(all[0].number, 2, "list: issue number"); |
| 749 | - assert_eq!(all[0].issue_state, "open", "list: issue state"); | |
| 687 | + assert_eq!(all[0].issue_state, IssueState::Open, "list: issue state"); | |
| 750 | 688 | assert!(!all[0].is_pull, "list: issue, not a pull request"); |
| 751 | 689 | assert_eq!( |
| 752 | 690 | all[0].last_actor_name.as_deref(), |
| @@ -758,7 +696,6 @@ mod tests { | ||
| 758 | 696 | assert_eq!(unread.len(), 1, "list: unread filter"); |
| 759 | 697 | assert_eq!(unread[0].issue_id, fx.issue_a, "list: unread row"); |
| 760 | 698 | |
| 761 | - // Cursor: first page of one, then the rest after its stamp. | |
| 762 | 699 | let first = s.list_notifications(&kim, false, None, 1).await.unwrap(); |
| 763 | 700 | assert_eq!(first[0].issue_id, fx.issue_b, "cursor: first page"); |
| 764 | 701 | let second = s |
| @@ -773,7 +710,6 @@ mod tests { | ||
| 773 | 710 | .unwrap(); |
| 774 | 711 | assert!(none.is_empty(), "cursor: past the end"); |
| 775 | 712 | |
| 776 | - // Other users see nothing. | |
| 777 | 713 | assert!( |
| 778 | 714 | s.list_notifications(&fx.bob, false, None, 50) |
| 779 | 715 | .await |
| @@ -782,42 +718,13 @@ mod tests { | ||
| 782 | 718 | "list: other user sees nothing" |
| 783 | 719 | ); |
| 784 | 720 | |
| 785 | - // Scenario 3: mark-read by id and by repo only touches the right rows. | |
| 786 | 721 | let ned = user(s, "Ned").await; |
| 787 | 722 | let olive = user(s, "Olive").await; |
| 788 | - s.upsert_notification( | |
| 789 | - &ned, | |
| 790 | - &fx.repo, | |
| 791 | - &fx.issue_a, | |
| 792 | - Reason::Comment, | |
| 793 | - "comment", | |
| 794 | - None, | |
| 795 | - ) | |
| 796 | - .await | |
| 797 | - .unwrap(); | |
| 798 | - s.upsert_notification( | |
| 799 | - &ned, | |
| 800 | - &fx.repo, | |
| 801 | - &fx.issue_b, | |
| 802 | - Reason::Comment, | |
| 803 | - "comment", | |
| 804 | - None, | |
| 805 | - ) | |
| 806 | - .await | |
| 807 | - .unwrap(); | |
| 808 | - s.upsert_notification( | |
| 809 | - &olive, | |
| 810 | - &fx.repo, | |
| 811 | - &fx.issue_a, | |
| 812 | - Reason::Comment, | |
| 813 | - "comment", | |
| 814 | - None, | |
| 815 | - ) | |
| 816 | - .await | |
| 817 | - .unwrap(); | |
| 723 | + notify(s, &ned, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await; | |
| 724 | + notify(s, &ned, &fx.repo, &fx.issue_b, Reason::Comment, "comment", None).await; | |
| 725 | + notify(s, &olive, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await; | |
| 818 | 726 | assert_eq!(s.unread_count(&ned).await.unwrap(), 2, "read: two unread"); |
| 819 | 727 | |
| 820 | - // mark_read by id, and another user's id does nothing. | |
| 821 | 728 | let inbox = s.list_notifications(&ned, false, None, 50).await.unwrap(); |
| 822 | 729 | let olive_inbox = s.list_notifications(&olive, false, None, 50).await.unwrap(); |
| 823 | 730 | s.mark_read(&ned, &olive_inbox[0].id).await.unwrap(); |
| @@ -831,17 +738,7 @@ mod tests { | ||
| 831 | 738 | s.mark_read(&ned, &inbox[1].id).await.unwrap(); |
| 832 | 739 | assert_eq!(s.unread_count(&ned).await.unwrap(), 0, "read: second by id"); |
| 833 | 740 | |
| 834 | - // mark_all_read per repo leaves other users alone. | |
| 835 | - s.upsert_notification( | |
| 836 | - &ned, | |
| 837 | - &fx.repo, | |
| 838 | - &fx.issue_a, | |
| 839 | - Reason::Comment, | |
| 840 | - "comment", | |
| 841 | - None, | |
| 842 | - ) | |
| 843 | - .await | |
| 844 | - .unwrap(); | |
| 741 | + notify(s, &ned, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await; | |
| 845 | 742 | s.mark_all_read(&ned, Some(&fx.repo)).await.unwrap(); |
| 846 | 743 | assert_eq!(s.unread_count(&ned).await.unwrap(), 0, "read: all in repo"); |
| 847 | 744 | assert_eq!( |
| @@ -850,16 +747,7 @@ mod tests { | ||
| 850 | 747 | "read: other user kept" |
| 851 | 748 | ); |
| 852 | 749 | |
| 853 | - s.upsert_notification( | |
| 854 | - &ned, | |
| 855 | - &fx.repo, | |
| 856 | - &fx.issue_b, | |
| 857 | - Reason::Comment, | |
| 858 | - "comment", | |
| 859 | - None, | |
| 860 | - ) | |
| 861 | - .await | |
| 862 | - .unwrap(); | |
| 750 | + notify(s, &ned, &fx.repo, &fx.issue_b, Reason::Comment, "comment", None).await; | |
| 863 | 751 | s.mark_all_read(&ned, None).await.unwrap(); |
| 864 | 752 | assert_eq!(s.unread_count(&ned).await.unwrap(), 0, "read: all, no repo"); |
| 865 | 753 | s.mark_all_read(&olive, Some("no-such-repo")).await.unwrap(); |
| @@ -869,28 +757,9 @@ mod tests { | ||
| 869 | 757 | "read: unknown repo" |
| 870 | 758 | ); |
| 871 | 759 | |
| 872 | - // Scenario 4: mark_issue_read only touches that issue. | |
| 873 | 760 | let max = user(s, "Max").await; |
| 874 | - s.upsert_notification( | |
| 875 | - &max, | |
| 876 | - &fx.repo, | |
| 877 | - &fx.issue_a, | |
| 878 | - Reason::Comment, | |
| 879 | - "comment", | |
| 880 | - None, | |
| 881 | - ) | |
| 882 | - .await | |
| 883 | - .unwrap(); | |
| 884 | - s.upsert_notification( | |
| 885 | - &max, | |
| 886 | - &fx.repo, | |
| 887 | - &fx.issue_b, | |
| 888 | - Reason::Comment, | |
| 889 | - "comment", | |
| 890 | - None, | |
| 891 | - ) | |
| 892 | - .await | |
| 893 | - .unwrap(); | |
| 761 | + notify(s, &max, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await; | |
| 762 | + notify(s, &max, &fx.repo, &fx.issue_b, Reason::Comment, "comment", None).await; | |
| 894 | 763 | s.mark_issue_read(&max, &fx.issue_a).await.unwrap(); |
| 895 | 764 | assert_eq!( |
| 896 | 765 | s.unread_count(&max).await.unwrap(), |
| @@ -904,13 +773,11 @@ mod tests { | ||
| 904 | 773 | ); |
| 905 | 774 | } |
| 906 | 775 | |
| 907 | - // Deletions come last in their own store scope: each removes state other scenarios need. | |
| 908 | 776 | #[tokio::test] |
| 909 | - async fn delete_rules_hold_in_each_scenario() { | |
| 777 | + async fn delete_rules() { | |
| 910 | 778 | let fx = fixture().await; |
| 911 | 779 | let s = &fx.store; |
| 912 | 780 | |
| 913 | - // Scenario 1: deleting a repo removes its notification rows, subs and watches. | |
| 914 | 781 | let pat = user(s, "Pat").await; |
| 915 | 782 | let doomed = s |
| 916 | 783 | .create_repo(&fx.owner, "doomed", "", Visibility::Public, "main") |
| @@ -928,16 +795,7 @@ mod tests { | ||
| 928 | 795 | s.subscribe(&pat, &doomed_issue, SubState::Subscribed, Reason::Author) |
| 929 | 796 | .await |
| 930 | 797 | .unwrap(); |
| 931 | - s.upsert_notification( | |
| 932 | - &pat, | |
| 933 | - &doomed, | |
| 934 | - &doomed_issue, | |
| 935 | - Reason::Comment, | |
| 936 | - "comment", | |
| 937 | - Some(&fx.bob), | |
| 938 | - ) | |
| 939 | - .await | |
| 940 | - .unwrap(); | |
| 798 | + notify(s, &pat, &doomed, &doomed_issue, Reason::Comment, "comment", Some(&fx.bob)).await; | |
| 941 | 799 | |
| 942 | 800 | s.delete_repo(&doomed).await.unwrap(); |
| 943 | 801 | assert_eq!( |
| @@ -976,7 +834,6 @@ mod tests { | ||
| 976 | 834 | "repo: nothing unread" |
| 977 | 835 | ); |
| 978 | 836 | |
| 979 | - // Scenario 2: deleting a user removes their rows and reassigns last actor to ghost. | |
| 980 | 837 | let ghost = s.ensure_ghost_user().await.unwrap(); |
| 981 | 838 | let quin = user(s, "Quin").await; |
| 982 | 839 | let ray = user(s, "Ray").await; |
| @@ -986,27 +843,8 @@ mod tests { | ||
| 986 | 843 | s.subscribe(&quin, &fx.issue_a, SubState::Subscribed, Reason::Author) |
| 987 | 844 | .await |
| 988 | 845 | .unwrap(); |
| 989 | - // Ray's inbox row whose last actor is Quin, and Quin's own inbox row. | |
| 990 | - s.upsert_notification( | |
| 991 | - &ray, | |
| 992 | - &fx.repo, | |
| 993 | - &fx.issue_a, | |
| 994 | - Reason::Comment, | |
| 995 | - "comment", | |
| 996 | - Some(&quin), | |
| 997 | - ) | |
| 998 | - .await | |
| 999 | - .unwrap(); | |
| 1000 | - s.upsert_notification( | |
| 1001 | - &quin, | |
| 1002 | - &fx.repo, | |
| 1003 | - &fx.issue_b, | |
| 1004 | - Reason::Comment, | |
| 1005 | - "comment", | |
| 1006 | - Some(&fx.bob), | |
| 1007 | - ) | |
| 1008 | - .await | |
| 1009 | - .unwrap(); | |
| 846 | + notify(s, &ray, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&quin)).await; | |
| 847 | + notify(s, &quin, &fx.repo, &fx.issue_b, Reason::Comment, "comment", Some(&fx.bob)).await; | |
| 1010 | 848 | |
| 1011 | 849 | s.delete_user(&quin, &ghost.id).await.unwrap(); |
| 1012 | 850 |
crates/forge-core/src/store/oci.rsmodified+5 -14
| @@ -33,13 +33,9 @@ impl Store { | ||
| 33 | 33 | // A link made again starts its grace period over: the sweep keeps a recent link (see |
| 34 | 34 | // `oci_sweep_unreferenced`), and the push that made it is still on its way to a manifest. |
| 35 | 35 | conn.execute( |
| 36 | - "DELETE FROM oci_blobs WHERE package_id = ?1 AND digest = ?2", | |
| 37 | - (package_id.to_string(), digest.to_string()), | |
| 38 | - ) | |
| 39 | - .await | |
| 40 | - .map_err(db_err)?; | |
| 41 | - conn.execute( | |
| 42 | - "INSERT INTO oci_blobs (package_id, digest, size, created_at) VALUES (?1, ?2, ?3, ?4)", | |
| 36 | + "INSERT INTO oci_blobs (package_id, digest, size, created_at) VALUES (?1, ?2, ?3, ?4) \ | |
| 37 | + ON CONFLICT(package_id, digest) DO UPDATE SET size = excluded.size, \ | |
| 38 | + created_at = excluded.created_at", | |
| 43 | 39 | ( |
| 44 | 40 | package_id.to_string(), |
| 45 | 41 | digest.to_string(), |
| @@ -163,15 +159,10 @@ impl Store { | ||
| 163 | 159 | /// Points `tag` of `package_id` at `manifest_id`, replacing any earlier target. |
| 164 | 160 | pub async fn oci_set_tag(&self, package_id: &str, tag: &str, manifest_id: &str) -> Result<()> { |
| 165 | 161 | let conn = self.inner.conn.lock().await; |
| 166 | - conn.execute( | |
| 167 | - "DELETE FROM oci_tags WHERE package_id = ?1 AND tag = ?2", | |
| 168 | - (package_id.to_string(), tag.to_string()), | |
| 169 | - ) | |
| 170 | - .await | |
| 171 | - .map_err(db_err)?; | |
| 172 | 162 | conn.execute( |
| 173 | 163 | "INSERT INTO oci_tags (package_id, tag, manifest_id, updated_at) \ |
| 174 | - VALUES (?1, ?2, ?3, ?4)", | |
| 164 | + VALUES (?1, ?2, ?3, ?4) ON CONFLICT(package_id, tag) DO UPDATE SET \ | |
| 165 | + manifest_id = excluded.manifest_id, updated_at = excluded.updated_at", | |
| 175 | 166 | ( |
| 176 | 167 | package_id.to_string(), |
| 177 | 168 | tag.to_string(), |
crates/forge-core/src/store/orgs.rsmodified+1 -14
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | |
| 8 | 8 | use turso::{Connection, IntoParams}; |
| 9 | 9 | |
| 10 | -use super::issues::finish; | |
| 10 | +use super::finish; | |
| 11 | 11 | use super::{ |
| 12 | 12 | REPO_COLS, Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, insert_err, |
| 13 | 13 | map_repo, map_user, missing_row, new_id, parse_role, role_str, |
| @@ -1117,17 +1117,4 @@ mod tests { | ||
| 1117 | 1117 | store.delete_org(&cyberdyne.id).await.unwrap(); |
| 1118 | 1118 | assert_eq!(store.orgs_for_user(&quinn.id).await.unwrap().len(), 1); |
| 1119 | 1119 | } |
| 1120 | - | |
| 1121 | - #[test] | |
| 1122 | - fn role_words_round_trip() { | |
| 1123 | - assert_eq!( | |
| 1124 | - OrgMemberRole::parse(OrgMemberRole::Owner.as_str()).unwrap(), | |
| 1125 | - OrgMemberRole::Owner | |
| 1126 | - ); | |
| 1127 | - assert_eq!( | |
| 1128 | - DefaultRepoRole::parse(DefaultRepoRole::Write.as_str()).unwrap(), | |
| 1129 | - DefaultRepoRole::Write | |
| 1130 | - ); | |
| 1131 | - assert!(OrgMemberRole::parse("admin").is_err()); | |
| 1132 | - } | |
| 1133 | 1120 | } |
crates/forge-core/src/store/passkeys.rsmodified+17 -28
| @@ -2,7 +2,9 @@ | ||
| 2 | 2 | //! string; the web crate owns the format. Sign counts live inside that string, so an update |
| 3 | 3 | //! replaces it. |
| 4 | 4 | |
| 5 | -use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; | |
| 5 | +use super::{ | |
| 6 | + Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id, | |
| 7 | +}; | |
| 6 | 8 | use crate::error::{Error, Result}; |
| 7 | 9 | use crate::time::now_stamp; |
| 8 | 10 | |
| @@ -27,6 +29,17 @@ pub struct PasskeyRow { | ||
| 27 | 29 | |
| 28 | 30 | const COLS: &str = "id, user_id, credential_id, passkey, name, created_at, last_used_at"; |
| 29 | 31 | |
| 32 | +async fn count_passkeys(conn: &turso::Connection, user_id: &str) -> Result<i64> { | |
| 33 | + Ok(fetch_opt( | |
| 34 | + conn, | |
| 35 | + "SELECT COUNT(*) FROM passkeys WHERE user_id = ?1", | |
| 36 | + (user_id.to_string(),), | |
| 37 | + |row| col_int(row, 0), | |
| 38 | + ) | |
| 39 | + .await? | |
| 40 | + .unwrap_or(0)) | |
| 41 | +} | |
| 42 | + | |
| 30 | 43 | fn map_row(row: &turso::Row) -> Result<PasskeyRow> { |
| 31 | 44 | Ok(PasskeyRow { |
| 32 | 45 | id: col_text(row, 0)?, |
| @@ -68,14 +81,7 @@ impl Store { | ||
| 68 | 81 | |
| 69 | 82 | pub async fn passkey_count(&self, user_id: &str) -> Result<i64> { |
| 70 | 83 | let conn = self.read_conn().await; |
| 71 | - Ok(fetch_opt( | |
| 72 | - &conn, | |
| 73 | - "SELECT COUNT(*) FROM passkeys WHERE user_id = ?1", | |
| 74 | - (user_id.to_string(),), | |
| 75 | - |row| col_int(row, 0), | |
| 76 | - ) | |
| 77 | - .await? | |
| 78 | - .unwrap_or(0)) | |
| 84 | + count_passkeys(&conn, user_id).await | |
| 79 | 85 | } |
| 80 | 86 | |
| 81 | 87 | /// The passkey with this credential id, whoever owns it. |
| @@ -100,29 +106,12 @@ impl Store { | ||
| 100 | 106 | ) -> Result<PasskeyRow> { |
| 101 | 107 | let name = clean_name(name)?; |
| 102 | 108 | let conn = self.inner.conn.lock().await; |
| 103 | - let held = fetch_opt( | |
| 104 | - &conn, | |
| 105 | - "SELECT COUNT(*) FROM passkeys WHERE user_id = ?1", | |
| 106 | - (user_id.to_string(),), | |
| 107 | - |row| col_int(row, 0), | |
| 108 | - ) | |
| 109 | - .await? | |
| 110 | - .unwrap_or(0); | |
| 109 | + let held = count_passkeys(&conn, user_id).await?; | |
| 111 | 110 | if usize::try_from(held).unwrap_or(usize::MAX) >= MAX_PASSKEYS { |
| 112 | 111 | return Err(Error::Invalid(format!( |
| 113 | 112 | "an account can hold at most {MAX_PASSKEYS} passkeys" |
| 114 | 113 | ))); |
| 115 | 114 | } |
| 116 | - let taken = fetch_opt( | |
| 117 | - &conn, | |
| 118 | - "SELECT 1 FROM passkeys WHERE credential_id = ?1 LIMIT 1", | |
| 119 | - (credential_id.to_string(),), | |
| 120 | - |row| col_int(row, 0), | |
| 121 | - ) | |
| 122 | - .await?; | |
| 123 | - if taken.is_some() { | |
| 124 | - return Err(Error::Conflict("this passkey is already registered".into())); | |
| 125 | - } | |
| 126 | 115 | let row = PasskeyRow { |
| 127 | 116 | id: new_id(), |
| 128 | 117 | user_id: user_id.to_string(), |
| @@ -145,7 +134,7 @@ impl Store { | ||
| 145 | 134 | ), |
| 146 | 135 | ) |
| 147 | 136 | .await |
| 148 | - .map_err(db_err)?; | |
| 137 | + .map_err(|e| insert_err(e, "this passkey is already registered"))?; | |
| 149 | 138 | Ok(row) |
| 150 | 139 | } |
| 151 | 140 |
crates/forge-core/src/store/pulls.rsmodified+28 -128
| @@ -1,22 +1,18 @@ | ||
| 1 | -//! Pull requests and forks. A pull request is an issues row with `kind = 'pull'`, so it shares | |
| 2 | -//! the per-repo numbering with issues, plus a `pull_requests` row. Every multi-row write runs in | |
| 3 | -//! one transaction. | |
| 4 | - | |
| 5 | 1 | use turso::transaction::Transaction; |
| 6 | 2 | use turso::{Connection, Row}; |
| 7 | 3 | |
| 8 | -use super::issues::{finish, insert_event, map_issue, parse_db}; | |
| 4 | +use super::issues::{insert_event, map_issue, parse_db}; | |
| 9 | 5 | use super::{ |
| 6 | + finish, | |
| 10 | 7 | REPO_COLS, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, |
| 11 | 8 | map_repo, new_id, |
| 12 | 9 | }; |
| 13 | 10 | use crate::error::{Error, Result}; |
| 14 | -use crate::issues::{Issue, IssueFilter, IssueListItem, IssueState, validate_body, validate_title}; | |
| 11 | +use crate::issues::{IssueFilter, IssueListItem, IssueState, validate_body, validate_title}; | |
| 15 | 12 | use crate::model::{Id, Repo}; |
| 16 | 13 | use crate::pulls::{AutoMerge, MergeStyle, Mergeable, PullRequest}; |
| 17 | 14 | use crate::time::now_stamp; |
| 18 | 15 | |
| 19 | -/// The issue columns (0 to 14) followed by the `pull_requests` columns (15 to 28). | |
| 20 | 16 | const PULL_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, i.state, i.state_reason, \ |
| 21 | 17 | i.author_id, i.milestone_id, i.comment_count, i.created_at, i.updated_at, \ |
| 22 | 18 | i.closed_at, i.locked, i.lock_reason, p.base_branch, p.head_repo_id, p.head_branch, p.head_oid, \ |
| @@ -25,7 +21,6 @@ const PULL_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, i.state, i. | ||
| 25 | 21 | |
| 26 | 22 | const MERGED_MSG: &str = "pull request is already merged"; |
| 27 | 23 | |
| 28 | -/// Reads `PULL_COLS`. | |
| 29 | 24 | fn map_pull(row: &Row) -> Result<PullRequest> { |
| 30 | 25 | let conflicts_raw = col_text(row, 22)?; |
| 31 | 26 | let conflict_files: Vec<String> = serde_json::from_str(&conflicts_raw) |
| @@ -54,7 +49,6 @@ fn map_pull(row: &Row) -> Result<PullRequest> { | ||
| 54 | 49 | }) |
| 55 | 50 | } |
| 56 | 51 | |
| 57 | -/// The pull request for an issue id, or `NotFound`. | |
| 58 | 52 | async fn load_pull(conn: &Connection, issue_id: &str) -> Result<PullRequest> { |
| 59 | 53 | fetch_opt( |
| 60 | 54 | conn, |
| @@ -69,9 +63,16 @@ async fn load_pull(conn: &Connection, issue_id: &str) -> Result<PullRequest> { | ||
| 69 | 63 | .ok_or(Error::NotFound) |
| 70 | 64 | } |
| 71 | 65 | |
| 72 | -/// Repo deletion for pull requests. Called from `Store::delete_repo` inside its transaction, | |
| 73 | -/// before the issue rows go. Pull request rows whose head was this repo keep their row, with | |
| 74 | -/// `head_repo_id` set to NULL. | |
| 66 | +fn ensure_open(pull: &PullRequest) -> Result<()> { | |
| 67 | + if pull.merged_at.is_some() { | |
| 68 | + return Err(Error::Conflict(MERGED_MSG.into())); | |
| 69 | + } | |
| 70 | + if pull.issue.state == IssueState::Closed { | |
| 71 | + return Err(Error::Conflict("pull request is closed".into())); | |
| 72 | + } | |
| 73 | + Ok(()) | |
| 74 | +} | |
| 75 | + | |
| 75 | 76 | pub(super) async fn delete_repo_pull_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> { |
| 76 | 77 | let id = repo_id.to_string(); |
| 77 | 78 | tx.execute( |
| @@ -89,11 +90,7 @@ pub(super) async fn delete_repo_pull_rows(tx: &Transaction<'_>, repo_id: &str) - | ||
| 89 | 90 | Ok(()) |
| 90 | 91 | } |
| 91 | 92 | |
| 92 | -// pull requests | |
| 93 | 93 | impl Store { |
| 94 | - /// Creates a pull request. The number comes from the repo's shared counter, the same one | |
| 95 | - /// `create_issue` uses, so issues and pulls never share a number. The issue row, the | |
| 96 | - /// `pull_requests` row and the increment run in one transaction. | |
| 97 | 94 | #[allow(clippy::too_many_arguments)] |
| 98 | 95 | pub async fn create_pull( |
| 99 | 96 | &self, |
| @@ -112,7 +109,6 @@ impl Store { | ||
| 112 | 109 | let conn = self.inner.conn.lock().await; |
| 113 | 110 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 114 | 111 | let outcome: Result<PullRequest> = async { |
| 115 | - // Checked here, inside the transaction, so two requests cannot both open the pull. | |
| 116 | 112 | if let Some(number) = |
| 117 | 113 | open_pull_number(&tx, repo_id, base_branch, head_repo_id, head_branch).await? |
| 118 | 114 | { |
| @@ -166,44 +162,12 @@ impl Store { | ||
| 166 | 162 | ) |
| 167 | 163 | .await |
| 168 | 164 | .map_err(db_err)?; |
| 169 | - Ok(PullRequest { | |
| 170 | - issue: Issue { | |
| 171 | - id, | |
| 172 | - repo_id: repo_id.to_string(), | |
| 173 | - number, | |
| 174 | - title, | |
| 175 | - body: body.to_string(), | |
| 176 | - state: IssueState::Open, | |
| 177 | - state_reason: None, | |
| 178 | - author_id: author_id.to_string(), | |
| 179 | - milestone_id: None, | |
| 180 | - comment_count: 0, | |
| 181 | - created_at: now.clone(), | |
| 182 | - updated_at: now, | |
| 183 | - closed_at: None, | |
| 184 | - locked: false, | |
| 185 | - lock_reason: None, | |
| 186 | - }, | |
| 187 | - base_branch: base_branch.to_string(), | |
| 188 | - head_repo_id: Some(head_repo_id.to_string()), | |
| 189 | - head_branch: head_branch.to_string(), | |
| 190 | - head_oid: head_oid.to_string(), | |
| 191 | - base_oid: base_oid.to_string(), | |
| 192 | - merge_base: None, | |
| 193 | - mergeable: Mergeable::Unknown, | |
| 194 | - conflict_files: Vec::new(), | |
| 195 | - merged_at: None, | |
| 196 | - merged_by: None, | |
| 197 | - merge_commit: None, | |
| 198 | - draft: false, | |
| 199 | - auto_merge: None, | |
| 200 | - }) | |
| 165 | + load_pull(&tx, &id).await | |
| 201 | 166 | } |
| 202 | 167 | .await; |
| 203 | 168 | finish(tx, outcome).await |
| 204 | 169 | } |
| 205 | 170 | |
| 206 | - /// The pull request with this number in the repo, if any. | |
| 207 | 171 | pub async fn pull_by_number(&self, repo_id: &str, number: i64) -> Result<Option<PullRequest>> { |
| 208 | 172 | let conn = self.read_conn().await; |
| 209 | 173 | fetch_opt( |
| @@ -218,7 +182,6 @@ impl Store { | ||
| 218 | 182 | .await |
| 219 | 183 | } |
| 220 | 184 | |
| 221 | - /// One page of pull requests, filtered and sorted like `list_issues`, plus the total. | |
| 222 | 185 | pub async fn list_pulls( |
| 223 | 186 | &self, |
| 224 | 187 | repo_id: &str, |
| @@ -227,13 +190,10 @@ impl Store { | ||
| 227 | 190 | self.list_of_kind(repo_id, f, "pull").await |
| 228 | 191 | } |
| 229 | 192 | |
| 230 | - /// Open and closed pull request counts. Merged pull requests count as closed. | |
| 231 | 193 | pub async fn pull_counts(&self, repo_id: &str) -> Result<(u64, u64)> { |
| 232 | 194 | self.counts_of_kind(repo_id, "pull").await |
| 233 | 195 | } |
| 234 | 196 | |
| 235 | - /// Open pull requests whose head is this branch of this repo, as | |
| 236 | - /// `(base repo id, number, issue id)`. | |
| 237 | 197 | pub async fn open_pulls_for_head( |
| 238 | 198 | &self, |
| 239 | 199 | head_repo_id: &str, |
| @@ -252,7 +212,6 @@ impl Store { | ||
| 252 | 212 | .await |
| 253 | 213 | } |
| 254 | 214 | |
| 255 | - /// Open pull requests into this branch of this repo, as `(number, issue id)`. | |
| 256 | 215 | pub async fn open_pulls_for_base( |
| 257 | 216 | &self, |
| 258 | 217 | repo_id: &str, |
| @@ -270,8 +229,6 @@ impl Store { | ||
| 270 | 229 | .await |
| 271 | 230 | } |
| 272 | 231 | |
| 273 | - /// Every pull request of a repo, open or closed, as `(issue id, number)`. A live page follows | |
| 274 | - /// these when something in the repo changes. | |
| 275 | 232 | pub async fn pull_refs(&self, repo_id: &str) -> Result<Vec<(Id, i64)>> { |
| 276 | 233 | let conn = self.read_conn().await; |
| 277 | 234 | fetch_all( |
| @@ -284,7 +241,6 @@ impl Store { | ||
| 284 | 241 | .await |
| 285 | 242 | } |
| 286 | 243 | |
| 287 | - /// The pull requests of a repo whose head is `sha`, open or closed, as `(issue id, number)`. | |
| 288 | 244 | pub async fn pulls_for_head_oid(&self, repo_id: &str, sha: &str) -> Result<Vec<(Id, i64)>> { |
| 289 | 245 | let conn = self.read_conn().await; |
| 290 | 246 | fetch_all( |
| @@ -298,27 +254,32 @@ impl Store { | ||
| 298 | 254 | .await |
| 299 | 255 | } |
| 300 | 256 | |
| 301 | - /// Records a new head commit after the head branch moved. Mergeability goes back to | |
| 302 | - /// `unknown` and the conflict list is cleared until it is recomputed. | |
| 303 | 257 | pub async fn update_pull_head(&self, issue_id: &str, head_oid: &str) -> Result<()> { |
| 304 | 258 | let conn = self.inner.conn.lock().await; |
| 305 | 259 | let changed = conn |
| 306 | 260 | .execute( |
| 307 | 261 | "UPDATE pull_requests SET head_oid = ?2, merge_base = NULL, mergeable = 'unknown', \ |
| 308 | 262 | conflict_files = '[]', auto_merge_style = NULL, auto_merge_user = NULL \ |
| 309 | - WHERE issue_id = ?1", | |
| 263 | + WHERE issue_id = ?1 AND merged_at IS NULL", | |
| 310 | 264 | (issue_id.to_string(), head_oid.to_string()), |
| 311 | 265 | ) |
| 312 | 266 | .await |
| 313 | 267 | .map_err(db_err)?; |
| 314 | 268 | if changed == 0 { |
| 315 | - return Err(Error::NotFound); | |
| 269 | + let exists = fetch_opt( | |
| 270 | + &conn, | |
| 271 | + "SELECT merged_at FROM pull_requests WHERE issue_id = ?1 LIMIT 1", | |
| 272 | + (issue_id.to_string(),), | |
| 273 | + |row| col_opt_text(row, 0), | |
| 274 | + ) | |
| 275 | + .await?; | |
| 276 | + if exists.is_none() { | |
| 277 | + return Err(Error::NotFound); | |
| 278 | + } | |
| 316 | 279 | } |
| 317 | 280 | Ok(()) |
| 318 | 281 | } |
| 319 | 282 | |
| 320 | - /// Stores a computed mergeability result. `Merged` is set only by `mark_merged`. Once a pull | |
| 321 | - /// request is merged its state is final, so this call changes nothing for it. | |
| 322 | 283 | pub async fn set_mergeability( |
| 323 | 284 | &self, |
| 324 | 285 | issue_id: &str, |
| @@ -348,7 +309,6 @@ impl Store { | ||
| 348 | 309 | .await |
| 349 | 310 | .map_err(db_err)?; |
| 350 | 311 | if changed == 0 { |
| 351 | - // Either the pull request is missing, or it is already merged and therefore final. | |
| 352 | 312 | let exists = fetch_opt( |
| 353 | 313 | &conn, |
| 354 | 314 | "SELECT merged_at FROM pull_requests WHERE issue_id = ?1 LIMIT 1", |
| @@ -363,9 +323,6 @@ impl Store { | ||
| 363 | 323 | Ok(()) |
| 364 | 324 | } |
| 365 | 325 | |
| 366 | - /// Sets or clears the draft flag of an open pull request and records a `ready_for_review` or | |
| 367 | - /// `converted_to_draft` event. Returns whether the flag changed. A merged or closed pull | |
| 368 | - /// request is `Conflict`. Turning a pull request into a draft also disables auto-merge. | |
| 369 | 326 | pub async fn set_pull_draft( |
| 370 | 327 | &self, |
| 371 | 328 | issue_id: &str, |
| @@ -376,12 +333,7 @@ impl Store { | ||
| 376 | 333 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 377 | 334 | let outcome: Result<bool> = async { |
| 378 | 335 | let current = load_pull(&tx, issue_id).await?; |
| 379 | - if current.merged_at.is_some() { | |
| 380 | - return Err(Error::Conflict(MERGED_MSG.into())); | |
| 381 | - } | |
| 382 | - if current.issue.state == IssueState::Closed { | |
| 383 | - return Err(Error::Conflict("pull request is closed".into())); | |
| 384 | - } | |
| 336 | + ensure_open(¤t)?; | |
| 385 | 337 | if current.draft == draft { |
| 386 | 338 | return Ok(false); |
| 387 | 339 | } |
| @@ -405,8 +357,6 @@ impl Store { | ||
| 405 | 357 | finish(tx, outcome).await |
| 406 | 358 | } |
| 407 | 359 | |
| 408 | - /// Enables auto-merge for an open, unmerged pull request: the merge will run as `user_id` | |
| 409 | - /// with `style`. Records an `auto_merge_enabled` event. | |
| 410 | 360 | pub async fn enable_auto_merge( |
| 411 | 361 | &self, |
| 412 | 362 | issue_id: &str, |
| @@ -417,12 +367,7 @@ impl Store { | ||
| 417 | 367 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 418 | 368 | let outcome: Result<()> = async { |
| 419 | 369 | let current = load_pull(&tx, issue_id).await?; |
| 420 | - if current.merged_at.is_some() { | |
| 421 | - return Err(Error::Conflict(MERGED_MSG.into())); | |
| 422 | - } | |
| 423 | - if current.issue.state == IssueState::Closed { | |
| 424 | - return Err(Error::Conflict("pull request is closed".into())); | |
| 425 | - } | |
| 370 | + ensure_open(¤t)?; | |
| 426 | 371 | tx.execute( |
| 427 | 372 | "UPDATE pull_requests SET auto_merge_style = ?2, auto_merge_user = ?3 \ |
| 428 | 373 | WHERE issue_id = ?1", |
| @@ -442,8 +387,6 @@ impl Store { | ||
| 442 | 387 | finish(tx, outcome).await |
| 443 | 388 | } |
| 444 | 389 | |
| 445 | - /// Disables auto-merge and records an `auto_merge_disabled` event with `reason` (a short | |
| 446 | - /// machine word such as `manual`, `push` or `refused`). Returns whether it was enabled. | |
| 447 | 390 | pub async fn disable_auto_merge( |
| 448 | 391 | &self, |
| 449 | 392 | issue_id: &str, |
| @@ -472,7 +415,6 @@ impl Store { | ||
| 472 | 415 | finish(tx, outcome).await |
| 473 | 416 | } |
| 474 | 417 | |
| 475 | - /// Open pull requests of this base repo with auto-merge enabled whose head is `sha`. | |
| 476 | 418 | pub async fn auto_merge_pulls_for_head( |
| 477 | 419 | &self, |
| 478 | 420 | repo_id: &str, |
| @@ -492,9 +434,6 @@ impl Store { | ||
| 492 | 434 | .await |
| 493 | 435 | } |
| 494 | 436 | |
| 495 | - /// Marks a pull request merged. It closes the issue with reason `completed`, sets the merge | |
| 496 | - /// fields and records a `merged` event with `{"commit": merge_commit}`. Fails with `Conflict` | |
| 497 | - /// if it is already merged or closed, and with `NotFound` if `issue_id` is not a pull request. | |
| 498 | 437 | pub async fn mark_merged( |
| 499 | 438 | &self, |
| 500 | 439 | issue_id: &str, |
| @@ -505,12 +444,7 @@ impl Store { | ||
| 505 | 444 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 506 | 445 | let outcome: Result<()> = async { |
| 507 | 446 | let current = load_pull(&tx, issue_id).await?; |
| 508 | - if current.merged_at.is_some() { | |
| 509 | - return Err(Error::Conflict(MERGED_MSG.into())); | |
| 510 | - } | |
| 511 | - if current.issue.state == IssueState::Closed { | |
| 512 | - return Err(Error::Conflict("pull request is closed".into())); | |
| 513 | - } | |
| 447 | + ensure_open(¤t)?; | |
| 514 | 448 | let now = now_stamp(); |
| 515 | 449 | tx.execute( |
| 516 | 450 | "UPDATE issues SET state = 'closed', state_reason = 'completed', closed_at = ?2, \ |
| @@ -540,8 +474,6 @@ impl Store { | ||
| 540 | 474 | finish(tx, outcome).await |
| 541 | 475 | } |
| 542 | 476 | |
| 543 | - /// The number of an open pull request for this base and head, if there is one. Used to avoid | |
| 544 | - /// duplicate pull requests. | |
| 545 | 477 | pub async fn find_open_pull( |
| 546 | 478 | &self, |
| 547 | 479 | base_repo: &str, |
| @@ -554,8 +486,6 @@ impl Store { | ||
| 554 | 486 | } |
| 555 | 487 | } |
| 556 | 488 | |
| 557 | -/// The number of the open pull request for this base and head, if any. Runs on whatever | |
| 558 | -/// connection or transaction it is given. | |
| 559 | 489 | async fn open_pull_number( |
| 560 | 490 | conn: &Connection, |
| 561 | 491 | base_repo: &str, |
| @@ -579,11 +509,7 @@ async fn open_pull_number( | ||
| 579 | 509 | .await |
| 580 | 510 | } |
| 581 | 511 | |
| 582 | -// forks | |
| 583 | 512 | impl Store { |
| 584 | - /// Creates a fork of `source`, owned by `owner_id` and named `name`. The fork takes the | |
| 585 | - /// source's visibility, description and default branch, and records `fork_of`. Nothing is | |
| 586 | - /// written to disk; the caller copies the bare repository. | |
| 587 | 513 | pub async fn create_fork(&self, source: &Repo, owner_id: &str, name: &str) -> Result<Repo> { |
| 588 | 514 | self.insert_repo( |
| 589 | 515 | owner_id, |
| @@ -596,7 +522,6 @@ impl Store { | ||
| 596 | 522 | .await |
| 597 | 523 | } |
| 598 | 524 | |
| 599 | - /// Repos forked from `repo_id`, by name. | |
| 600 | 525 | pub async fn list_forks(&self, repo_id: &str) -> Result<Vec<Repo>> { |
| 601 | 526 | let conn = self.read_conn().await; |
| 602 | 527 | fetch_all( |
| @@ -611,7 +536,6 @@ impl Store { | ||
| 611 | 536 | .await |
| 612 | 537 | } |
| 613 | 538 | |
| 614 | - /// How many public forks the repo has (the count of `list_forks` filtered to public). | |
| 615 | 539 | pub async fn public_fork_count(&self, repo_id: &str) -> Result<u64> { |
| 616 | 540 | let conn = self.read_conn().await; |
| 617 | 541 | let n = fetch_opt( |
| @@ -662,7 +586,6 @@ mod tests { | ||
| 662 | 586 | } |
| 663 | 587 | } |
| 664 | 588 | |
| 665 | - /// A fresh repo owned by Tahinli, so each scenario has its own numbering and counts. | |
| 666 | 589 | async fn new_repo(fx: &Fixture, name: &str) -> Repo { |
| 667 | 590 | fx.store |
| 668 | 591 | .create_repo(&fx.tahinli.id, name, "", Visibility::Public, "main") |
| @@ -678,7 +601,6 @@ mod tests { | ||
| 678 | 601 | } |
| 679 | 602 | } |
| 680 | 603 | |
| 681 | - /// A pull from `head_repo` into `main` of `repo`. | |
| 682 | 604 | async fn open_pull( |
| 683 | 605 | fx: &Fixture, |
| 684 | 606 | repo: &Repo, |
| @@ -702,13 +624,10 @@ mod tests { | ||
| 702 | 624 | .unwrap() |
| 703 | 625 | } |
| 704 | 626 | |
| 705 | - // Numbering, counts, head and mergeability updates, merges, drafts, | |
| 706 | - // auto merge and events. Each scenario has its own repo. | |
| 707 | 627 | #[tokio::test] |
| 708 | 628 | async fn pull_scenarios_share_one_store() { |
| 709 | 629 | let fx = fixture().await; |
| 710 | 630 | |
| 711 | - // Issues and pulls share one numbering; each list shows only its kind. | |
| 712 | 631 | let repo = new_repo(&fx, "numbering").await; |
| 713 | 632 | let issue1 = fx |
| 714 | 633 | .store |
| @@ -765,7 +684,6 @@ mod tests { | ||
| 765 | 684 | "numbering: pull reads back" |
| 766 | 685 | ); |
| 767 | 686 | |
| 768 | - // Counts: a merged pull counts as closed; issue counts are untouched. | |
| 769 | 687 | let repo = new_repo(&fx, "counts").await; |
| 770 | 688 | fx.store |
| 771 | 689 | .create_issue(&repo.id, &fx.tahinli.id, "issue", "") |
| @@ -804,7 +722,6 @@ mod tests { | ||
| 804 | 722 | assert_eq!(total, 1, "counts: open filter total"); |
| 805 | 723 | assert_eq!(open[0].issue.title, "pull two", "counts: open filter row"); |
| 806 | 724 | |
| 807 | - // A head push resets mergeability and keeps the base. | |
| 808 | 725 | let repo = new_repo(&fx, "head").await; |
| 809 | 726 | let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await; |
| 810 | 727 | let id = pull.issue.id.clone(); |
| @@ -832,7 +749,6 @@ mod tests { | ||
| 832 | 749 | assert!(after.conflict_files.is_empty(), "head: conflicts cleared"); |
| 833 | 750 | assert_eq!(after.base_oid, "b".repeat(40), "head: base untouched"); |
| 834 | 751 | |
| 835 | - // Mergeability round-trips conflict files; Merged is set only by mark_merged. | |
| 836 | 752 | let repo = new_repo(&fx, "mergeability").await; |
| 837 | 753 | let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await; |
| 838 | 754 | let id = pull.issue.id.clone(); |
| @@ -896,7 +812,6 @@ mod tests { | ||
| 896 | 812 | "mergeability: missing pull" |
| 897 | 813 | ); |
| 898 | 814 | |
| 899 | - // Merging closes the pull, records an event, and is final. | |
| 900 | 815 | let repo = new_repo(&fx, "merge").await; |
| 901 | 816 | let issue = fx |
| 902 | 817 | .store |
| @@ -961,7 +876,6 @@ mod tests { | ||
| 961 | 876 | "merge: event actor" |
| 962 | 877 | ); |
| 963 | 878 | |
| 964 | - // A second merge is refused, and a late mergeability recompute is a no-op. | |
| 965 | 879 | assert!( |
| 966 | 880 | matches!( |
| 967 | 881 | fx.store.mark_merged(&id, &fx.bob.id, &merge_commit).await, |
| @@ -981,7 +895,6 @@ mod tests { | ||
| 981 | 895 | .unwrap(); |
| 982 | 896 | assert_eq!(still.mergeable, Mergeable::Merged, "merge: stays merged"); |
| 983 | 897 | |
| 984 | - // A second open pull for the same comparison is refused, and takes no number. | |
| 985 | 898 | let repo = new_repo(&fx, "refuse").await; |
| 986 | 899 | let first = open_pull(&fx, &repo, &repo.id, "feature", "first").await; |
| 987 | 900 | let second = fx |
| @@ -1012,7 +925,6 @@ mod tests { | ||
| 1012 | 925 | "refuse: no number taken" |
| 1013 | 926 | ); |
| 1014 | 927 | |
| 1015 | - // find_open_pull matches base and head, and a merged pull stops matching. | |
| 1016 | 928 | let repo = new_repo(&fx, "find").await; |
| 1017 | 929 | let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await; |
| 1018 | 930 | let found = fx |
| @@ -1051,7 +963,6 @@ mod tests { | ||
| 1051 | 963 | "find: merged pull no longer blocks" |
| 1052 | 964 | ); |
| 1053 | 965 | |
| 1054 | - // Draft flag: round trip, events, list filter and draft numbers. | |
| 1055 | 966 | let repo = new_repo(&fx, "draft").await; |
| 1056 | 967 | let pr = open_pull(&fx, &repo, &repo.id, "feature", "wip").await; |
| 1057 | 968 | let _ready = open_pull(&fx, &repo, &repo.id, "other", "ready").await; |
| @@ -1064,7 +975,6 @@ mod tests { | ||
| 1064 | 975 | .unwrap(), |
| 1065 | 976 | "draft: set changes the flag" |
| 1066 | 977 | ); |
| 1067 | - // Setting the same value again changes nothing and records no event. | |
| 1068 | 978 | assert!( |
| 1069 | 979 | !fx.store |
| 1070 | 980 | .set_pull_draft(&pr.issue.id, Some(&fx.tahinli.id), true) |
| @@ -1132,7 +1042,6 @@ mod tests { | ||
| 1132 | 1042 | "draft: events" |
| 1133 | 1043 | ); |
| 1134 | 1044 | |
| 1135 | - // Auto merge is cleared by a new head, a draft, or a merge. | |
| 1136 | 1045 | let repo = new_repo(&fx, "auto").await; |
| 1137 | 1046 | let pr = open_pull(&fx, &repo, &repo.id, "feature", "auto").await; |
| 1138 | 1047 | let head = "a".repeat(40); |
| @@ -1233,7 +1142,6 @@ mod tests { | ||
| 1233 | 1142 | "auto: merged pull refuses auto merge" |
| 1234 | 1143 | ); |
| 1235 | 1144 | |
| 1236 | - // Pull event kinds are accepted on pulls. | |
| 1237 | 1145 | let repo = new_repo(&fx, "events").await; |
| 1238 | 1146 | let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await; |
| 1239 | 1147 | for kind in ["head_updated", "base_changed", "head_deleted"] { |
| @@ -1257,13 +1165,10 @@ mod tests { | ||
| 1257 | 1165 | ); |
| 1258 | 1166 | } |
| 1259 | 1167 | |
| 1260 | - // Forks, fork pulls and repo deletion. Forks are created under names that | |
| 1261 | - // are unique for Bob, and the deletions run last. | |
| 1262 | 1168 | #[tokio::test] |
| 1263 | 1169 | async fn fork_scenarios_share_one_store() { |
| 1264 | 1170 | let fx = fixture().await; |
| 1265 | 1171 | |
| 1266 | - // A fork copies the source settings and lists under its source. | |
| 1267 | 1172 | let fork = fx |
| 1268 | 1173 | .store |
| 1269 | 1174 | .create_fork(&fx.repo, &fx.bob.id, "proj-1") |
| @@ -1286,7 +1191,6 @@ mod tests { | ||
| 1286 | 1191 | ); |
| 1287 | 1192 | assert_eq!(fx.repo.fork_of, None, "fork: source is not a fork"); |
| 1288 | 1193 | |
| 1289 | - // fork_of survives a read back through the shared repo queries. | |
| 1290 | 1194 | let read = fx.store.repo_by_id(&fork.id).await.unwrap().unwrap(); |
| 1291 | 1195 | assert_eq!(read.fork_of, Some(fx.repo.id.clone()), "fork: read by id"); |
| 1292 | 1196 | let read = fx |
| @@ -1319,7 +1223,6 @@ mod tests { | ||
| 1319 | 1223 | "fork: name clash is a conflict" |
| 1320 | 1224 | ); |
| 1321 | 1225 | |
| 1322 | - // A fork of a private repo is private and keeps its branch name. | |
| 1323 | 1226 | let private = fx |
| 1324 | 1227 | .store |
| 1325 | 1228 | .create_repo(&fx.tahinli.id, "secret", "", Visibility::Private, "trunk") |
| @@ -1337,7 +1240,6 @@ mod tests { | ||
| 1337 | 1240 | ); |
| 1338 | 1241 | assert_eq!(secret_fork.default_branch, "trunk", "private fork: branch"); |
| 1339 | 1242 | |
| 1340 | - // Open pulls for a head or base skip closed ones; forks feed the head side. | |
| 1341 | 1243 | let source = new_repo(&fx, "fork-src").await; |
| 1342 | 1244 | let fork = fx |
| 1343 | 1245 | .store |
| @@ -1399,8 +1301,6 @@ mod tests { | ||
| 1399 | 1301 | "bases: fork pull remains" |
| 1400 | 1302 | ); |
| 1401 | 1303 | |
| 1402 | - // Deleting a fork detaches its incoming pulls; deleting a source removes | |
| 1403 | - // its pulls and detaches its surviving forks. | |
| 1404 | 1304 | let source = new_repo(&fx, "detach-src").await; |
| 1405 | 1305 | let fork = fx |
| 1406 | 1306 | .store |
crates/forge-core/src/store/pulls_list_extra.rsmodified+11 -18
| @@ -10,40 +10,33 @@ use crate::error::Result; | ||
| 10 | 10 | impl Store { |
| 11 | 11 | /// Which of `numbers` are draft pull requests of this repo. |
| 12 | 12 | pub async fn draft_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> { |
| 13 | - if numbers.is_empty() { | |
| 14 | - return Ok(HashSet::new()); | |
| 15 | - } | |
| 16 | - let placeholders: Vec<String> = (2..=numbers.len() + 1).map(|i| format!("?{i}")).collect(); | |
| 17 | - let sql = format!( | |
| 18 | - "SELECT i.number FROM pull_requests p JOIN issues i ON i.id = p.issue_id \ | |
| 19 | - WHERE i.repo_id = ?1 AND i.kind = 'pull' AND p.draft = 1 AND i.number IN ({})", | |
| 20 | - placeholders.join(", ") | |
| 21 | - ); | |
| 22 | - let mut params: Vec<Value> = Vec::with_capacity(numbers.len() + 1); | |
| 23 | - params.push(Value::Text(repo_id.to_string())); | |
| 24 | - params.extend(numbers.iter().map(|n| Value::Integer(*n))); | |
| 25 | - let conn = self.read_conn().await; | |
| 26 | - let found = fetch_all(&conn, &sql, params, |row| col_int(row, 0)).await?; | |
| 27 | - Ok(found.into_iter().collect()) | |
| 13 | + self.pull_numbers_where(repo_id, numbers, "p.draft = 1").await | |
| 28 | 14 | } |
| 29 | 15 | |
| 30 | 16 | /// Which of `numbers` are merged pull requests of this repo. Numbers that are issues, open |
| 31 | 17 | /// or closed without a merge are left out. |
| 32 | 18 | pub async fn merged_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> { |
| 19 | + self.pull_numbers_where(repo_id, numbers, "p.merged_at IS NOT NULL").await | |
| 20 | + } | |
| 21 | + | |
| 22 | + async fn pull_numbers_where( | |
| 23 | + &self, | |
| 24 | + repo_id: &str, | |
| 25 | + numbers: &[i64], | |
| 26 | + predicate: &str, | |
| 27 | + ) -> Result<HashSet<i64>> { | |
| 33 | 28 | if numbers.is_empty() { |
| 34 | 29 | return Ok(HashSet::new()); |
| 35 | 30 | } |
| 36 | 31 | let placeholders: Vec<String> = (2..=numbers.len() + 1).map(|i| format!("?{i}")).collect(); |
| 37 | 32 | let sql = format!( |
| 38 | 33 | "SELECT i.number FROM pull_requests p JOIN issues i ON i.id = p.issue_id \ |
| 39 | - WHERE i.repo_id = ?1 AND i.kind = 'pull' AND p.merged_at IS NOT NULL \ | |
| 40 | - AND i.number IN ({})", | |
| 34 | + WHERE i.repo_id = ?1 AND i.kind = 'pull' AND {predicate} AND i.number IN ({})", | |
| 41 | 35 | placeholders.join(", ") |
| 42 | 36 | ); |
| 43 | 37 | let mut params: Vec<Value> = Vec::with_capacity(numbers.len() + 1); |
| 44 | 38 | params.push(Value::Text(repo_id.to_string())); |
| 45 | 39 | params.extend(numbers.iter().map(|n| Value::Integer(*n))); |
| 46 | - | |
| 47 | 40 | let conn = self.read_conn().await; |
| 48 | 41 | let found = fetch_all(&conn, &sql, params, |row| col_int(row, 0)).await?; |
| 49 | 42 | Ok(found.into_iter().collect()) |
crates/forge-core/src/store/push_recent.rsmodified+6 -6
| @@ -89,7 +89,7 @@ impl Store { | ||
| 89 | 89 | #[cfg(test)] |
| 90 | 90 | mod tests { |
| 91 | 91 | use crate::model::Visibility; |
| 92 | - use crate::time::{stamp_after, stamp_before}; | |
| 92 | + use crate::time::{stamp_after, stamp_ago}; | |
| 93 | 93 | use std::time::Duration; |
| 94 | 94 | |
| 95 | 95 | use super::*; |
| @@ -121,9 +121,9 @@ mod tests { | ||
| 121 | 121 | #[tokio::test] |
| 122 | 122 | async fn recent_branch_pushes_rules_and_empty_inputs() { |
| 123 | 123 | let (_dir, store, tahinli, bob, demo, other) = store_with_repos().await; |
| 124 | - let since = stamp_before(Duration::from_secs(3600)); | |
| 125 | - let older = stamp_before(Duration::from_secs(600)); | |
| 126 | - let newer = stamp_before(Duration::from_secs(60)); | |
| 124 | + let since = stamp_ago(Duration::from_secs(3600)); | |
| 125 | + let older = stamp_ago(Duration::from_secs(600)); | |
| 126 | + let newer = stamp_ago(Duration::from_secs(60)); | |
| 127 | 127 | |
| 128 | 128 | store |
| 129 | 129 | .record_push_event_at(&demo, &tahinli, "refs/heads/feature", ZERO, OID, &older) |
| @@ -155,7 +155,7 @@ mod tests { | ||
| 155 | 155 | "refs/heads/stale", |
| 156 | 156 | ZERO, |
| 157 | 157 | OID, |
| 158 | - &stamp_before(Duration::from_secs(7200)), | |
| 158 | + &stamp_ago(Duration::from_secs(7200)), | |
| 159 | 159 | ) |
| 160 | 160 | .await |
| 161 | 161 | .unwrap(); |
| @@ -181,7 +181,7 @@ mod tests { | ||
| 181 | 181 | .await |
| 182 | 182 | .unwrap(); |
| 183 | 183 | let none = store |
| 184 | - .recent_branch_pushes(&[], &tahinli, &stamp_before(Duration::from_secs(3600))) | |
| 184 | + .recent_branch_pushes(&[], &tahinli, &stamp_ago(Duration::from_secs(3600))) | |
| 185 | 185 | .await |
| 186 | 186 | .unwrap(); |
| 187 | 187 | assert!(none.is_empty(), "empty repo list"); |
crates/forge-core/src/store/reactions.rsmodified+3 -7
| @@ -4,17 +4,13 @@ | ||
| 4 | 4 | |
| 5 | 5 | use std::collections::{BTreeMap, HashMap}; |
| 6 | 6 | |
| 7 | -use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish}; | |
| 7 | +use super::{ | |
| 8 | + IN_CHUNK, Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish, placeholders, | |
| 9 | +}; | |
| 8 | 10 | use crate::error::{Error, Result}; |
| 9 | 11 | use crate::reactions::{Reaction, ReactionMap, ReactionSummary, ReactionTarget, SUMMARY_USERS}; |
| 10 | 12 | use crate::time::now_stamp; |
| 11 | 13 | |
| 12 | -const IN_CHUNK: usize = 500; | |
| 13 | - | |
| 14 | -fn placeholders(n: usize) -> String { | |
| 15 | - vec!["?"; n].join(",") | |
| 16 | -} | |
| 17 | - | |
| 18 | 14 | impl Store { |
| 19 | 15 | /// Adds the reaction when the user has not put it on the target yet, removes it when they have. |
| 20 | 16 | /// Returns whether it is on afterwards. A target that does not exist is `NotFound`. |
crates/forge-core/src/store/repo_listing.rsmodified+36 -43
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | //! user's repos, a user's stars). Read access is decided in the query with the same rules as |
| 3 | 3 | //! `authz::authorize` for `Action::Read`, so no per-repo role lookup is needed. |
| 4 | 4 | |
| 5 | -use turso::Value; | |
| 5 | +use turso::{Connection, Value}; | |
| 6 | 6 | |
| 7 | 7 | use super::{ |
| 8 | 8 | ListedRepo, REPO_COLS, RepoSort, Store, col_int, col_text, fetch_all, fetch_opt, issues, |
| @@ -26,12 +26,13 @@ const ACTIVITY: &str = "COALESCE((SELECT MAX(p.created_at) FROM push_events p \ | ||
| 26 | 26 | /// The star count of `r`. |
| 27 | 27 | const STARS: &str = "(SELECT COUNT(*) FROM stars s WHERE s.repo_id = r.id)"; |
| 28 | 28 | |
| 29 | -/// The SQL condition under which a signed-in, non-admin viewer may read repo `r`, taking the | |
| 30 | -/// viewer id four times (bind it as four `?` parameters). It mirrors `authorize` for Read: | |
| 31 | -/// public repos, the viewer's own repos, repos where the viewer is a collaborator, and repos of an | |
| 32 | -/// org where the viewer's org role (`Store::org_repo_role`) is some role: an org owner, a member | |
| 33 | -/// when the default repo role is not `none`, or a member of a team covering the repo. | |
| 34 | -pub(crate) const READABLE_BY_VIEWER: &str = "(r.visibility = 'public' OR r.owner_id = ? \ | |
| 29 | +/// The SQL condition under which a signed-in, non-admin viewer may read a private repo `r`, taking | |
| 30 | +/// the viewer id four times (bind it as four `?` parameters). It mirrors `authorize` for Read: | |
| 31 | +/// the viewer's own repos, repos where the viewer is a collaborator, and repos of an org where the | |
| 32 | +/// viewer's org role (`Store::org_repo_role`) is some role: an org owner, a member when the default | |
| 33 | +/// repo role is not `none`, or a member of a team covering the repo. Public repos are added by | |
| 34 | +/// the callers. | |
| 35 | +pub(crate) const VIEWER_ACCESS: &str = "(r.owner_id = ? \ | |
| 35 | 36 | OR EXISTS (SELECT 1 FROM collaborators c WHERE c.repo_id = r.id AND c.user_id = ?) \ |
| 36 | 37 | OR EXISTS (SELECT 1 FROM org_members m WHERE m.org_id = r.owner_id AND m.user_id = ? AND ( \ |
| 37 | 38 | m.role = 'owner' \ |
| @@ -58,7 +59,7 @@ impl Store { | ||
| 58 | 59 | ) -> Result<(Vec<ListedRepo>, u64)> { |
| 59 | 60 | let (from_sql, mut clauses, mut params) = scoped(scope, viewer); |
| 60 | 61 | if let Some(q) = query.map(str::trim).filter(|q| !q.is_empty()) { |
| 61 | - clauses.push("LOWER(r.name) LIKE ? ESCAPE '\\'"); | |
| 62 | + clauses.push("LOWER(r.name) LIKE ? ESCAPE '\\'".to_owned()); | |
| 62 | 63 | params.push(Value::Text(issues::like_pattern(&q.to_lowercase()))); |
| 63 | 64 | } |
| 64 | 65 | self.page_of_repos( |
| @@ -80,37 +81,23 @@ impl Store { | ||
| 80 | 81 | ) -> Result<u64> { |
| 81 | 82 | let (from_sql, clauses, params) = scoped(scope, viewer); |
| 82 | 83 | let conn = self.read_conn().await; |
| 83 | - let n = fetch_opt( | |
| 84 | - &conn, | |
| 85 | - &format!( | |
| 86 | - "SELECT COUNT(*) FROM {from_sql} WHERE {}", | |
| 87 | - clauses.join(" AND ") | |
| 88 | - ), | |
| 89 | - params, | |
| 90 | - |row| col_int(row, 0), | |
| 91 | - ) | |
| 92 | - .await? | |
| 93 | - .unwrap_or(0); | |
| 94 | - Ok(u64::try_from(n).unwrap_or(0)) | |
| 84 | + count_repos(&conn, from_sql, &clauses.join(" AND "), params).await | |
| 95 | 85 | } |
| 96 | 86 | |
| 97 | 87 | /// Up to `limit` repos the signed-in `viewer` is part of: their own, ones they collaborate on, and |
| 98 | 88 | /// org repos they reach. Sorted by owner and name, for the command palette. Other public repos are |
| 99 | 89 | /// left out (Explore lists them), and so are an admin's: on a big instance they would push the |
| 100 | - /// viewer's own repos past the limit. The rule is `READABLE_BY_VIEWER` without its public clause. | |
| 90 | + /// viewer's own repos past the limit. The rule is `VIEWER_ACCESS`. | |
| 101 | 91 | pub async fn list_viewer_repos(&self, viewer: &User, limit: u64) -> Result<Vec<Repo>> { |
| 102 | - let where_sql = READABLE_BY_VIEWER.replacen("r.visibility = 'public' OR ", "", 1); | |
| 103 | - debug_assert_ne!(where_sql, READABLE_BY_VIEWER, "the public clause moved"); | |
| 104 | - let params: Vec<Value> = (0..4).map(|_| Value::Text(viewer.id.clone())).collect(); | |
| 92 | + let mut params: Vec<Value> = (0..4).map(|_| Value::Text(viewer.id.clone())).collect(); | |
| 105 | 93 | let limit = i64::try_from(limit).unwrap_or(i64::MAX); |
| 106 | - let mut params = params; | |
| 107 | 94 | params.push(Value::Integer(limit)); |
| 108 | 95 | let conn = self.read_conn().await; |
| 109 | 96 | fetch_all( |
| 110 | 97 | &conn, |
| 111 | 98 | &format!( |
| 112 | 99 | "SELECT {REPO_COLS} FROM repos r JOIN users u ON u.id = r.owner_id \ |
| 113 | - WHERE {where_sql} ORDER BY u.username_folded ASC, r.name_folded ASC LIMIT ?" | |
| 100 | + WHERE {VIEWER_ACCESS} ORDER BY u.username_folded ASC, r.name_folded ASC LIMIT ?" | |
| 114 | 101 | ), |
| 115 | 102 | params, |
| 116 | 103 | map_repo, |
| @@ -138,15 +125,7 @@ impl Store { | ||
| 138 | 125 | let per_page = per_page.clamp(1, 100); |
| 139 | 126 | |
| 140 | 127 | let conn = self.read_conn().await; |
| 141 | - let total = fetch_opt( | |
| 142 | - &conn, | |
| 143 | - &format!("SELECT COUNT(*) FROM {from_sql} WHERE {where_sql}"), | |
| 144 | - params.clone(), | |
| 145 | - |row| col_int(row, 0), | |
| 146 | - ) | |
| 147 | - .await? | |
| 148 | - .unwrap_or(0); | |
| 149 | - let total = u64::try_from(total).unwrap_or(0); | |
| 128 | + let total = count_repos(&conn, from_sql, where_sql, params.clone()).await?; | |
| 150 | 129 | let pages = total.div_ceil(per_page).max(1); |
| 151 | 130 | let page = page.clamp(1, pages); |
| 152 | 131 | let offset = i64::try_from((page - 1) * per_page).unwrap_or(i64::MAX); |
| @@ -171,11 +150,25 @@ impl Store { | ||
| 171 | 150 | } |
| 172 | 151 | } |
| 173 | 152 | |
| 153 | +async fn count_repos( | |
| 154 | + conn: &Connection, | |
| 155 | + from_sql: &str, | |
| 156 | + where_sql: &str, | |
| 157 | + params: Vec<Value>, | |
| 158 | +) -> Result<u64> { | |
| 159 | + let n = fetch_opt( | |
| 160 | + conn, | |
| 161 | + &format!("SELECT COUNT(*) FROM {from_sql} WHERE {where_sql}"), | |
| 162 | + params, | |
| 163 | + |row| col_int(row, 0), | |
| 164 | + ) | |
| 165 | + .await? | |
| 166 | + .unwrap_or(0); | |
| 167 | + Ok(u64::try_from(n).unwrap_or(0)) | |
| 168 | +} | |
| 169 | + | |
| 174 | 170 | /// The FROM clause, the WHERE clauses and their parameters for `scope` as seen by `viewer`. |
| 175 | -fn scoped( | |
| 176 | - scope: RepoScope<'_>, | |
| 177 | - viewer: Option<&User>, | |
| 178 | -) -> (&'static str, Vec<&'static str>, Vec<Value>) { | |
| 171 | +fn scoped(scope: RepoScope<'_>, viewer: Option<&User>) -> (&'static str, Vec<String>, Vec<Value>) { | |
| 179 | 172 | let (from_sql, scope_id) = match scope { |
| 180 | 173 | RepoScope::OwnedBy(id) => ("repos r JOIN users u ON u.id = r.owner_id", id), |
| 181 | 174 | RepoScope::StarredBy(id) => ( |
| @@ -184,20 +177,20 @@ fn scoped( | ||
| 184 | 177 | ), |
| 185 | 178 | }; |
| 186 | 179 | let mut clauses = vec![match scope { |
| 187 | - RepoScope::OwnedBy(_) => "r.owner_id = ?", | |
| 188 | - RepoScope::StarredBy(_) => "st.user_id = ?", | |
| 180 | + RepoScope::OwnedBy(_) => "r.owner_id = ?".to_owned(), | |
| 181 | + RepoScope::StarredBy(_) => "st.user_id = ?".to_owned(), | |
| 189 | 182 | }]; |
| 190 | 183 | let mut params = vec![Value::Text(scope_id.to_owned())]; |
| 191 | 184 | match viewer { |
| 192 | 185 | // Admins read everything. |
| 193 | 186 | Some(user) if user.is_admin => {} |
| 194 | 187 | Some(user) => { |
| 195 | - clauses.push(READABLE_BY_VIEWER); | |
| 188 | + clauses.push(format!("(r.visibility = 'public' OR {VIEWER_ACCESS})")); | |
| 196 | 189 | for _ in 0..4 { |
| 197 | 190 | params.push(Value::Text(user.id.clone())); |
| 198 | 191 | } |
| 199 | 192 | } |
| 200 | - None => clauses.push("r.visibility = 'public'"), | |
| 193 | + None => clauses.push("r.visibility = 'public'".to_owned()), | |
| 201 | 194 | } |
| 202 | 195 | (from_sql, clauses, params) |
| 203 | 196 | } |
crates/forge-core/src/store/review_requests.rsmodified+17 -26
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | |
| 5 | 5 | use std::collections::HashMap; |
| 6 | 6 | |
| 7 | -use super::{Store, col_text, db_err, fetch_all, fetch_opt}; | |
| 7 | +use super::{IN_CHUNK, Store, col_text, db_err, fetch_all, placeholders}; | |
| 8 | 8 | use crate::error::Result; |
| 9 | 9 | use crate::time::now_stamp; |
| 10 | 10 | |
| @@ -28,29 +28,20 @@ impl Store { | ||
| 28 | 28 | requested_by: &str, |
| 29 | 29 | ) -> Result<bool> { |
| 30 | 30 | let conn = self.inner.conn.lock().await; |
| 31 | - let exists = fetch_opt( | |
| 32 | - &conn, | |
| 33 | - "SELECT 1 FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2", | |
| 34 | - (issue_id.to_string(), reviewer_id.to_string()), | |
| 35 | - |row| col_text(row, 0).or(Ok(String::new())), | |
| 36 | - ) | |
| 37 | - .await?; | |
| 38 | - if exists.is_some() { | |
| 39 | - return Ok(false); | |
| 40 | - } | |
| 41 | - conn.execute( | |
| 42 | - "INSERT INTO review_requests (issue_id, reviewer_id, requested_by, created_at) \ | |
| 43 | - VALUES (?1, ?2, ?3, ?4)", | |
| 44 | - ( | |
| 45 | - issue_id.to_string(), | |
| 46 | - reviewer_id.to_string(), | |
| 47 | - requested_by.to_string(), | |
| 48 | - now_stamp(), | |
| 49 | - ), | |
| 50 | - ) | |
| 51 | - .await | |
| 52 | - .map_err(db_err)?; | |
| 53 | - Ok(true) | |
| 31 | + let n = conn | |
| 32 | + .execute( | |
| 33 | + "INSERT INTO review_requests (issue_id, reviewer_id, requested_by, created_at) \ | |
| 34 | + VALUES (?1, ?2, ?3, ?4) ON CONFLICT (issue_id, reviewer_id) DO NOTHING", | |
| 35 | + ( | |
| 36 | + issue_id.to_string(), | |
| 37 | + reviewer_id.to_string(), | |
| 38 | + requested_by.to_string(), | |
| 39 | + now_stamp(), | |
| 40 | + ), | |
| 41 | + ) | |
| 42 | + .await | |
| 43 | + .map_err(db_err)?; | |
| 44 | + Ok(n == 1) | |
| 54 | 45 | } |
| 55 | 46 | |
| 56 | 47 | /// Withdraws a pending request. Returns whether there was one. |
| @@ -85,8 +76,8 @@ impl Store { | ||
| 85 | 76 | return Ok(out); |
| 86 | 77 | } |
| 87 | 78 | let conn = self.read_conn().await; |
| 88 | - for chunk in ids.chunks(500) { | |
| 89 | - let marks = vec!["?"; chunk.len()].join(","); | |
| 79 | + for chunk in ids.chunks(IN_CHUNK) { | |
| 80 | + let marks = placeholders(chunk.len()); | |
| 90 | 81 | let rows = fetch_all( |
| 91 | 82 | &conn, |
| 92 | 83 | &format!( |
crates/forge-core/src/store/reviews.rsmodified+6 -34
| @@ -2,14 +2,15 @@ | ||
| 2 | 2 | //! with `kind = 'pull'`). Every multi-row write runs in one transaction. Replies are submitted |
| 3 | 3 | //! at once through an auto-created `commented` review with no body. |
| 4 | 4 | |
| 5 | -use std::collections::HashMap; | |
| 5 | +use std::collections::{BTreeMap, HashMap}; | |
| 6 | 6 | |
| 7 | 7 | use serde_json::json; |
| 8 | 8 | use turso::transaction::Transaction; |
| 9 | 9 | use turso::{Connection, Row}; |
| 10 | 10 | |
| 11 | -use super::issues::{finish, insert_event, parse_db}; | |
| 11 | +use super::issues::{insert_event, parse_db}; | |
| 12 | 12 | use super::{ |
| 13 | + finish, | |
| 13 | 14 | Store, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing_row, |
| 14 | 15 | new_id, |
| 15 | 16 | }; |
| @@ -287,7 +288,6 @@ pub(super) async fn delete_repo_review_rows(tx: &Transaction<'_>, repo_id: &str) | ||
| 287 | 288 | Ok(()) |
| 288 | 289 | } |
| 289 | 290 | |
| 290 | -// reviews | |
| 291 | 291 | impl Store { |
| 292 | 292 | /// The author's pending review on a pull request, if any. |
| 293 | 293 | pub async fn pending_review(&self, issue_id: &str, author_id: &str) -> Result<Option<Review>> { |
| @@ -487,7 +487,6 @@ impl Store { | ||
| 487 | 487 | insert_review(&tx, issue_id, author_id, state, body, head_oid, &now).await? |
| 488 | 488 | } |
| 489 | 489 | }; |
| 490 | - // A submitted review answers the author's own review request. | |
| 491 | 490 | tx.execute( |
| 492 | 491 | "DELETE FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2", |
| 493 | 492 | (issue_id.to_string(), author_id.to_string()), |
| @@ -585,7 +584,6 @@ impl Store { | ||
| 585 | 584 | issue_id: &str, |
| 586 | 585 | viewer_id: Option<&str>, |
| 587 | 586 | ) -> Result<Vec<Thread>> { |
| 588 | - // No user id is empty, so `None` matches no pending comment. | |
| 589 | 587 | let viewer = viewer_id.unwrap_or("").to_string(); |
| 590 | 588 | let conn = self.read_conn().await; |
| 591 | 589 | let comments = fetch_all( |
| @@ -839,17 +837,14 @@ impl Store { | ||
| 839 | 837 | }, |
| 840 | 838 | ) |
| 841 | 839 | .await?; |
| 842 | - // Rows are in submission order, so the last one per reviewer is the latest. | |
| 843 | - let mut latest: HashMap<String, (String, ReviewState, String)> = HashMap::new(); | |
| 840 | + let mut latest: BTreeMap<String, (String, ReviewState, String)> = BTreeMap::new(); | |
| 844 | 841 | for (author_id, name, state, commit) in rows { |
| 845 | 842 | latest.insert(author_id, (name, state, commit)); |
| 846 | 843 | } |
| 847 | - let mut out: Vec<(String, String, ReviewState, String)> = latest | |
| 844 | + Ok(latest | |
| 848 | 845 | .into_iter() |
| 849 | 846 | .map(|(id, (name, state, commit))| (id, name, state, commit)) |
| 850 | - .collect(); | |
| 851 | - out.sort_unstable_by(|a, b| a.0.cmp(&b.0)); | |
| 852 | - Ok(out) | |
| 847 | + .collect()) | |
| 853 | 848 | } |
| 854 | 849 | } |
| 855 | 850 | |
| @@ -965,13 +960,10 @@ mod tests { | ||
| 965 | 960 | .unwrap() |
| 966 | 961 | } |
| 967 | 962 | |
| 968 | - // Comment, reply, edit, delete, resolve, outdated and relocate. Each | |
| 969 | - // scenario has its own pull request. | |
| 970 | 963 | #[tokio::test] |
| 971 | 964 | async fn comment_scenarios_share_one_store() { |
| 972 | 965 | let fx = fixture().await; |
| 973 | 966 | |
| 974 | - // A pending comment is visible only to its author and joins one draft. | |
| 975 | 967 | let issue = new_pull(&fx, "pending").await; |
| 976 | 968 | let draft = comment(&fx, &issue, &fx.bob.id, true, "draft").await; |
| 977 | 969 | assert!(draft.pending, "pending: draft is pending"); |
| @@ -1010,7 +1002,6 @@ mod tests { | ||
| 1010 | 1002 | "pending: same draft review" |
| 1011 | 1003 | ); |
| 1012 | 1004 | |
| 1013 | - // A single submitted comment creates its own commented review. | |
| 1014 | 1005 | let issue = new_pull(&fx, "single").await; |
| 1015 | 1006 | let c = comment(&fx, &issue, &fx.bob.id, false, "nit").await; |
| 1016 | 1007 | assert!(!c.pending, "single: submitted"); |
| @@ -1040,7 +1031,6 @@ mod tests { | ||
| 1040 | 1031 | assert_eq!(threads.len(), 1, "single: one thread"); |
| 1041 | 1032 | assert!(threads[0].replies.is_empty(), "single: no replies"); |
| 1042 | 1033 | |
| 1043 | - // A reply copies the root position and needs a submitted root. | |
| 1044 | 1034 | let issue = new_pull(&fx, "reply").await; |
| 1045 | 1035 | let root = comment(&fx, &issue, &fx.bob.id, false, "question").await; |
| 1046 | 1036 | let answer = reply(&fx, &issue, &fx.carol.id, &root.id, "answer").await; |
| @@ -1055,7 +1045,6 @@ mod tests { | ||
| 1055 | 1045 | ); |
| 1056 | 1046 | assert!(!answer.pending, "reply: submitted"); |
| 1057 | 1047 | |
| 1058 | - // Each reply is submitted through its own commented review. | |
| 1059 | 1048 | assert_eq!( |
| 1060 | 1049 | fx.store.list_reviews(&issue).await.unwrap().len(), |
| 1061 | 1050 | 2, |
| @@ -1089,7 +1078,6 @@ mod tests { | ||
| 1089 | 1078 | ); |
| 1090 | 1079 | } |
| 1091 | 1080 | |
| 1092 | - // Edits record the previous body. | |
| 1093 | 1081 | let issue = new_pull(&fx, "edit").await; |
| 1094 | 1082 | let c = comment(&fx, &issue, &fx.bob.id, false, "old text").await; |
| 1095 | 1083 | fx.store |
| @@ -1135,7 +1123,6 @@ mod tests { | ||
| 1135 | 1123 | "edit: missing refused: {err:?}" |
| 1136 | 1124 | ); |
| 1137 | 1125 | |
| 1138 | - // Deleting a root removes its replies; deleting a reply keeps the root. | |
| 1139 | 1126 | let issue = new_pull(&fx, "delete").await; |
| 1140 | 1127 | let root = comment(&fx, &issue, &fx.bob.id, false, "root").await; |
| 1141 | 1128 | let r1 = reply(&fx, &issue, &fx.carol.id, &root.id, "one").await; |
| @@ -1158,7 +1145,6 @@ mod tests { | ||
| 1158 | 1145 | let threads = fx.store.review_threads(&issue, None).await.unwrap(); |
| 1159 | 1146 | assert_eq!(threads.len(), 1, "delete root: other thread remains"); |
| 1160 | 1147 | assert_eq!(threads[0].root.id, other.id, "delete root: other root kept"); |
| 1161 | - // The emptied reviews of the root and its replies are gone too. | |
| 1162 | 1148 | let reviews = fx.store.list_reviews(&issue).await.unwrap(); |
| 1163 | 1149 | assert_eq!(reviews.len(), 1, "delete root: emptied reviews removed"); |
| 1164 | 1150 | assert_eq!( |
| @@ -1186,7 +1172,6 @@ mod tests { | ||
| 1186 | 1172 | "delete: missing refused: {err:?}" |
| 1187 | 1173 | ); |
| 1188 | 1174 | |
| 1189 | - // Resolving records events, and only submitted roots can be resolved. | |
| 1190 | 1175 | let issue = new_pull(&fx, "resolve").await; |
| 1191 | 1176 | let root = comment(&fx, &issue, &fx.bob.id, false, "fix this").await; |
| 1192 | 1177 | |
| @@ -1203,7 +1188,6 @@ mod tests { | ||
| 1203 | 1188 | .resolved, |
| 1204 | 1189 | "resolve: resolved" |
| 1205 | 1190 | ); |
| 1206 | - // Already resolved: no second event. | |
| 1207 | 1191 | fx.store |
| 1208 | 1192 | .set_thread_resolved(&root.id, &fx.carol.id, true) |
| 1209 | 1193 | .await |
| @@ -1266,7 +1250,6 @@ mod tests { | ||
| 1266 | 1250 | ); |
| 1267 | 1251 | } |
| 1268 | 1252 | |
| 1269 | - // Outdated marks only submitted roots. | |
| 1270 | 1253 | let issue = new_pull(&fx, "outdated").await; |
| 1271 | 1254 | let root = comment(&fx, &issue, &fx.bob.id, false, "a").await; |
| 1272 | 1255 | let r = reply(&fx, &issue, &fx.carol.id, &root.id, "b").await; |
| @@ -1289,7 +1272,6 @@ mod tests { | ||
| 1289 | 1272 | let draft_thread = own.iter().find(|t| t.root.id == draft.id).unwrap(); |
| 1290 | 1273 | assert!(!draft_thread.root.outdated, "outdated: draft untouched"); |
| 1291 | 1274 | |
| 1292 | - // Relocation moves the root and its replies, keeping the hunk. | |
| 1293 | 1275 | let issue = new_pull(&fx, "relocate").await; |
| 1294 | 1276 | let root = comment(&fx, &issue, &fx.bob.id, false, "root").await; |
| 1295 | 1277 | let answer = reply(&fx, &issue, &fx.tahinli.id, &root.id, "answer").await; |
| @@ -1336,8 +1318,6 @@ mod tests { | ||
| 1336 | 1318 | ); |
| 1337 | 1319 | } |
| 1338 | 1320 | |
| 1339 | - // Submitting, approving, dismissing and discarding reviews. Each scenario | |
| 1340 | - // has its own pull request. | |
| 1341 | 1321 | #[tokio::test] |
| 1342 | 1322 | async fn review_scenarios_share_one_store() { |
| 1343 | 1323 | let fx = fixture().await; |
| @@ -1347,7 +1327,6 @@ mod tests { | ||
| 1347 | 1327 | .await |
| 1348 | 1328 | .unwrap(); |
| 1349 | 1329 | |
| 1350 | - // A pending draft becomes an approved review. | |
| 1351 | 1330 | let issue = new_pull(&fx, "approve").await; |
| 1352 | 1331 | let draft = comment(&fx, &issue, &fx.bob.id, true, "draft").await; |
| 1353 | 1332 | let review = fx |
| @@ -1393,7 +1372,6 @@ mod tests { | ||
| 1393 | 1372 | "approve: no requests" |
| 1394 | 1373 | ); |
| 1395 | 1374 | |
| 1396 | - // The pull request author may comment but not approve or request changes. | |
| 1397 | 1375 | let issue = new_pull(&fx, "author").await; |
| 1398 | 1376 | for state in [ReviewState::Approved, ReviewState::ChangesRequested] { |
| 1399 | 1377 | let err = fx |
| @@ -1427,7 +1405,6 @@ mod tests { | ||
| 1427 | 1405 | "author: comment allowed" |
| 1428 | 1406 | ); |
| 1429 | 1407 | |
| 1430 | - // A commented review needs text unless it carries a pending comment. | |
| 1431 | 1408 | let issue = new_pull(&fx, "empty").await; |
| 1432 | 1409 | let err = fx |
| 1433 | 1410 | .store |
| @@ -1455,7 +1432,6 @@ mod tests { | ||
| 1455 | 1432 | "empty: approval without body and comment review with draft" |
| 1456 | 1433 | ); |
| 1457 | 1434 | |
| 1458 | - // The latest state of each reviewer counts; dismissed reviews do not. | |
| 1459 | 1435 | let issue = new_pull(&fx, "summary").await; |
| 1460 | 1436 | fx.store |
| 1461 | 1437 | .submit_review(&issue, &fx.bob.id, ReviewState::Approved, "", &oid('a')) |
| @@ -1524,7 +1500,6 @@ mod tests { | ||
| 1524 | 1500 | "summary: dismissed request gone" |
| 1525 | 1501 | ); |
| 1526 | 1502 | |
| 1527 | - // Only approvals and change requests can be dismissed, and only once. | |
| 1528 | 1503 | let issue = new_pull(&fx, "dismiss").await; |
| 1529 | 1504 | let note = comment(&fx, &issue, &fx.bob.id, false, "note").await; |
| 1530 | 1505 | let err = fx |
| @@ -1609,7 +1584,6 @@ mod tests { | ||
| 1609 | 1584 | "dismiss: twice refused: {err:?}" |
| 1610 | 1585 | ); |
| 1611 | 1586 | |
| 1612 | - // A review written before the previous-state column has none. | |
| 1613 | 1587 | { |
| 1614 | 1588 | let conn = fx.store.inner.conn.lock().await; |
| 1615 | 1589 | conn.execute( |
| @@ -1623,7 +1597,6 @@ mod tests { | ||
| 1623 | 1597 | let legacy = listed.iter().find(|r| r.id == approved.id).unwrap(); |
| 1624 | 1598 | assert_eq!(legacy.dismissed_from, None, "legacy: no previous state"); |
| 1625 | 1599 | |
| 1626 | - // Discarding a draft keeps submitted comments. | |
| 1627 | 1600 | let issue = new_pull(&fx, "discard").await; |
| 1628 | 1601 | let submitted = comment(&fx, &issue, &fx.bob.id, false, "done").await; |
| 1629 | 1602 | let d1 = comment(&fx, &issue, &fx.bob.id, true, "d1").await; |
| @@ -1664,7 +1637,6 @@ mod tests { | ||
| 1664 | 1637 | .unwrap(); |
| 1665 | 1638 | assert_eq!(own.len(), 1, "discard: only the submitted thread"); |
| 1666 | 1639 | |
| 1667 | - // Nothing pending left: discarding again is fine. | |
| 1668 | 1640 | fx.store |
| 1669 | 1641 | .discard_pending_review(&issue, &fx.bob.id) |
| 1670 | 1642 | .await |
crates/forge-core/src/store/server_settings.rsmodified+16 -15
| @@ -4,17 +4,13 @@ | ||
| 4 | 4 | |
| 5 | 5 | use std::collections::BTreeMap; |
| 6 | 6 | |
| 7 | -use super::{Store, col_text, db_err, fetch_all}; | |
| 7 | +use super::{Store, col_text, db_err, fetch_all, finish}; | |
| 8 | 8 | use crate::error::{Error, Result}; |
| 9 | 9 | use crate::{secret, server_settings}; |
| 10 | 10 | |
| 11 | 11 | impl Store { |
| 12 | 12 | fn settings_key(&self) -> Result<[u8; 32]> { |
| 13 | - self.inner | |
| 14 | - .secret_key | |
| 15 | - .get() | |
| 16 | - .copied() | |
| 17 | - .ok_or_else(|| Error::Crypto("the instance key is not set".into())) | |
| 13 | + self.secret_key().map(|key| *key) | |
| 18 | 14 | } |
| 19 | 15 | |
| 20 | 16 | /// Every stored override, with secret values opened. A key this binary does not know is |
| @@ -59,16 +55,21 @@ impl Store { | ||
| 59 | 55 | prepared.push((key.clone(), stored)); |
| 60 | 56 | } |
| 61 | 57 | let conn = self.inner.conn.lock().await; |
| 62 | - for (key, stored) in prepared { | |
| 63 | - conn.execute( | |
| 64 | - "INSERT INTO server_settings (key, value, updated_at) VALUES (?1, ?2, ?3) \ | |
| 65 | - ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", | |
| 66 | - (key, stored, now.clone()), | |
| 67 | - ) | |
| 68 | - .await | |
| 69 | - .map_err(db_err)?; | |
| 58 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 59 | + let outcome: Result<()> = async { | |
| 60 | + for (key, stored) in prepared { | |
| 61 | + tx.execute( | |
| 62 | + "INSERT INTO server_settings (key, value, updated_at) VALUES (?1, ?2, ?3) \ | |
| 63 | + ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", | |
| 64 | + (key, stored, now.clone()), | |
| 65 | + ) | |
| 66 | + .await | |
| 67 | + .map_err(db_err)?; | |
| 68 | + } | |
| 69 | + Ok(()) | |
| 70 | 70 | } |
| 71 | - Ok(()) | |
| 71 | + .await; | |
| 72 | + finish(tx, outcome).await | |
| 72 | 73 | } |
| 73 | 74 | |
| 74 | 75 | /// Removes the override of `key`, so the file value (or the default) applies again. |
crates/forge-core/src/store/snapshot.rsmodified+11 -12
| @@ -33,6 +33,11 @@ fn sql_string_literal(text: &str) -> Result<String> { | ||
| 33 | 33 | Ok(format!("'{}'", text.replace('\'', "''"))) |
| 34 | 34 | } |
| 35 | 35 | |
| 36 | +fn utf8_path(path: &Path) -> Result<&str> { | |
| 37 | + path.to_str() | |
| 38 | + .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", path.display()))) | |
| 39 | +} | |
| 40 | + | |
| 36 | 41 | impl Store { |
| 37 | 42 | /// Writes a consistent copy of the database to `dest` with `VACUUM INTO`, then fsyncs it. |
| 38 | 43 | /// `dest` must not exist. The store's connection is held for the whole copy. |
| @@ -43,10 +48,7 @@ impl Store { | ||
| 43 | 48 | dest.display() |
| 44 | 49 | ))); |
| 45 | 50 | } |
| 46 | - let text = dest.to_str().ok_or_else(|| { | |
| 47 | - Error::Config(format!("snapshot path is not UTF-8: {}", dest.display())) | |
| 48 | - })?; | |
| 49 | - let sql = format!("VACUUM INTO {}", sql_string_literal(text)?); | |
| 51 | + let sql = format!("VACUUM INTO {}", sql_string_literal(utf8_path(dest)?)?); | |
| 50 | 52 | { |
| 51 | 53 | let conn = self.inner.conn.lock().await; |
| 52 | 54 | conn.execute(&sql, ()).await.map_err(db_err)?; |
| @@ -74,10 +76,10 @@ impl Store { | ||
| 74 | 76 | /// until every frame is in the main file, and then removes sidecars that are empty. A sidecar that |
| 75 | 77 | /// still has bytes is an error. The main file alone is then the whole database. |
| 76 | 78 | async fn make_self_contained(dest: &Path) -> Result<()> { |
| 77 | - let text = dest | |
| 78 | - .to_str() | |
| 79 | - .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", dest.display())))?; | |
| 80 | - let db = Builder::new_local(text).build().await.map_err(db_err)?; | |
| 79 | + let db = Builder::new_local(utf8_path(dest)?) | |
| 80 | + .build() | |
| 81 | + .await | |
| 82 | + .map_err(db_err)?; | |
| 81 | 83 | let conn = db.connect().map_err(db_err)?; |
| 82 | 84 | // Columns: busy, frames in the log, frames checkpointed. |
| 83 | 85 | let status = fetch_all(&conn, "PRAGMA wal_checkpoint(TRUNCATE)", (), |row| { |
| @@ -116,10 +118,7 @@ async fn make_self_contained(dest: &Path) -> Result<()> { | ||
| 116 | 118 | /// Opens a snapshot read-only with a fresh connection, runs `PRAGMA integrity_check`, checks the |
| 117 | 119 | /// migration history and the repo rows, and returns what it found. Any problem is an error. |
| 118 | 120 | pub async fn verify_snapshot(path: &Path) -> Result<SnapshotInfo> { |
| 119 | - let text = path | |
| 120 | - .to_str() | |
| 121 | - .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", path.display())))?; | |
| 122 | - let db = Builder::new_local(text) | |
| 121 | + let db = Builder::new_local(utf8_path(path)?) | |
| 123 | 122 | .read_only(true) |
| 124 | 123 | .build() |
| 125 | 124 | .await |
crates/forge-core/src/store/suggest.rsmodified+15 -35
| @@ -33,42 +33,22 @@ impl Store { | ||
| 33 | 33 | }; |
| 34 | 34 | // `like_pattern` wraps in `%..%`; for a prefix match drop the leading one (done above). |
| 35 | 35 | let cap = Value::Integer(i64::try_from(limit).unwrap_or(8)); |
| 36 | - let queries = [ | |
| 37 | - // Owner and collaborators. | |
| 38 | - "SELECT u.username FROM users u WHERE u.username_folded LIKE ?2 ESCAPE '\\' AND u.kind = 'user' AND \ | |
| 39 | - (u.id = (SELECT owner_id FROM repos WHERE id = ?1) OR \ | |
| 40 | - u.id IN (SELECT user_id FROM collaborators WHERE repo_id = ?1)) \ | |
| 41 | - ORDER BY u.username_folded LIMIT ?3", | |
| 42 | - // Participants. | |
| 43 | - "SELECT u.username FROM users u WHERE u.username_folded LIKE ?2 ESCAPE '\\' AND u.kind = 'user' AND \ | |
| 44 | - (u.id IN (SELECT author_id FROM issues WHERE repo_id = ?1) OR \ | |
| 45 | - u.id IN (SELECT c.author_id FROM comments c JOIN issues i ON i.id = c.issue_id WHERE i.repo_id = ?1)) \ | |
| 46 | - ORDER BY u.username_folded LIMIT ?3", | |
| 47 | - // Everyone else. | |
| 48 | - "SELECT u.username FROM users u WHERE u.username_folded LIKE ?2 ESCAPE '\\' AND u.kind = 'user' \ | |
| 49 | - AND u.username_folded <> 'ghost' ORDER BY u.username_folded LIMIT ?3", | |
| 50 | - ]; | |
| 51 | 36 | let conn = self.read_conn().await; |
| 52 | - let mut out: Vec<String> = Vec::new(); | |
| 53 | - for sql in queries { | |
| 54 | - let names = fetch_all( | |
| 55 | - &conn, | |
| 56 | - sql, | |
| 57 | - vec![ | |
| 58 | - Value::Text(repo_id.to_string()), | |
| 59 | - Value::Text(pattern.clone()), | |
| 60 | - cap.clone(), | |
| 61 | - ], | |
| 62 | - |row| col_text(row, 0), | |
| 63 | - ) | |
| 64 | - .await?; | |
| 65 | - for name in names { | |
| 66 | - if out.len() < limit && !out.contains(&name) { | |
| 67 | - out.push(name); | |
| 68 | - } | |
| 69 | - } | |
| 70 | - } | |
| 71 | - Ok(out) | |
| 37 | + fetch_all( | |
| 38 | + &conn, | |
| 39 | + "SELECT username FROM (SELECT u.username, u.username_folded, CASE \ | |
| 40 | + WHEN u.id = (SELECT owner_id FROM repos WHERE id = ?1) OR \ | |
| 41 | + u.id IN (SELECT user_id FROM collaborators WHERE repo_id = ?1) THEN 0 \ | |
| 42 | + WHEN u.id IN (SELECT author_id FROM issues WHERE repo_id = ?1) OR \ | |
| 43 | + u.id IN (SELECT c.author_id FROM comments c JOIN issues i ON i.id = c.issue_id WHERE i.repo_id = ?1) THEN 1 \ | |
| 44 | + ELSE 2 END AS tier \ | |
| 45 | + FROM users u WHERE u.username_folded LIKE ?2 ESCAPE '\\' AND u.kind = 'user') \ | |
| 46 | + WHERE tier < 2 OR username_folded <> 'ghost' \ | |
| 47 | + ORDER BY tier, username_folded LIMIT ?3", | |
| 48 | + vec![Value::Text(repo_id.to_string()), Value::Text(pattern), cap], | |
| 49 | + |row| col_text(row, 0), | |
| 50 | + ) | |
| 51 | + .await | |
| 72 | 52 | } |
| 73 | 53 | |
| 74 | 54 | /// Issues and pull requests of the repo whose number starts with `q` (when it is digits) or |
crates/forge-core/src/store/suspension.rsmodified+17 -27
| @@ -3,6 +3,8 @@ | ||
| 3 | 3 | //! A suspended user keeps their data but cannot sign in. The session, token and SSH key lookups |
| 4 | 4 | //! in `store/mod.rs` skip a suspended owner, so every transport stops at once. |
| 5 | 5 | |
| 6 | +use turso::Connection; | |
| 7 | + | |
| 6 | 8 | use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_opt}; |
| 7 | 9 | use crate::error::{Error, Result}; |
| 8 | 10 | use crate::time::now_stamp; |
| @@ -67,16 +69,7 @@ impl Store { | ||
| 67 | 69 | return Err(Error::Invalid("an organization cannot be suspended".into())); |
| 68 | 70 | } |
| 69 | 71 | if row.0 { |
| 70 | - let others = fetch_opt( | |
| 71 | - &conn, | |
| 72 | - "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND id != ?1 \ | |
| 73 | - AND id NOT IN (SELECT user_id FROM user_suspensions)", | |
| 74 | - (uid.clone(),), | |
| 75 | - |row| col_int(row, 0), | |
| 76 | - ) | |
| 77 | - .await? | |
| 78 | - .unwrap_or(0); | |
| 79 | - if others == 0 { | |
| 72 | + if other_active_admins(&conn, &uid).await? == 0 { | |
| 80 | 73 | return Err(Error::Conflict( |
| 81 | 74 | "cannot suspend the last active administrator".into(), |
| 82 | 75 | )); |
| @@ -116,14 +109,7 @@ impl Store { | ||
| 116 | 109 | /// Administrators other than `user_id`: zero means `user_id` is the last one and cannot be demoted. |
| 117 | 110 | pub async fn other_admin_count(&self, user_id: &str) -> Result<i64> { |
| 118 | 111 | let conn = self.read_conn().await; |
| 119 | - Ok(fetch_opt( | |
| 120 | - &conn, | |
| 121 | - "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND id != ?1 AND kind = 'user'", | |
| 122 | - (user_id.to_string(),), | |
| 123 | - |row| col_int(row, 0), | |
| 124 | - ) | |
| 125 | - .await? | |
| 126 | - .unwrap_or(0)) | |
| 112 | + other_active_admins(&conn, user_id).await | |
| 127 | 113 | } |
| 128 | 114 | |
| 129 | 115 | /// Grants or revokes the admin flag. Revoking is refused for the last administrator. |
| @@ -144,15 +130,7 @@ impl Store { | ||
| 144 | 130 | )); |
| 145 | 131 | } |
| 146 | 132 | if !admin { |
| 147 | - let others = fetch_opt( | |
| 148 | - &conn, | |
| 149 | - "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND id != ?1 AND kind = 'user'", | |
| 150 | - (uid.clone(),), | |
| 151 | - |row| col_int(row, 0), | |
| 152 | - ) | |
| 153 | - .await? | |
| 154 | - .unwrap_or(0); | |
| 155 | - if others == 0 { | |
| 133 | + if other_active_admins(&conn, &uid).await? == 0 { | |
| 156 | 134 | return Err(Error::Conflict( |
| 157 | 135 | "cannot remove the last administrator".into(), |
| 158 | 136 | )); |
| @@ -203,6 +181,18 @@ impl Store { | ||
| 203 | 181 | } |
| 204 | 182 | } |
| 205 | 183 | |
| 184 | +async fn other_active_admins(conn: &Connection, user_id: &str) -> Result<i64> { | |
| 185 | + Ok(fetch_opt( | |
| 186 | + conn, | |
| 187 | + "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND id != ?1 AND kind = 'user' \ | |
| 188 | + AND id NOT IN (SELECT user_id FROM user_suspensions)", | |
| 189 | + (user_id.to_string(),), | |
| 190 | + |row| col_int(row, 0), | |
| 191 | + ) | |
| 192 | + .await? | |
| 193 | + .unwrap_or(0)) | |
| 194 | +} | |
| 195 | + | |
| 206 | 196 | #[cfg(test)] |
| 207 | 197 | mod tests { |
| 208 | 198 | use super::*; |
crates/forge-core/src/store/transfers.rsmodified+1 -1
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | use turso::Row; |
| 10 | 10 | |
| 11 | -use super::issues::finish; | |
| 11 | +use super::finish; | |
| 12 | 12 | use super::orgs::OrgMemberRole; |
| 13 | 13 | use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt}; |
| 14 | 14 | use crate::error::{Error, Result}; |
crates/forge-core/src/store/ui_prefs.rsmodified+44 -77
| @@ -4,6 +4,8 @@ | ||
| 4 | 4 | //! 0042 and 0043). The web layer decides which values it offers; the store only checks that a |
| 5 | 5 | //! value is well formed, so a new language, accent or base needs no store change. |
| 6 | 6 | |
| 7 | +use turso::IntoParams; | |
| 8 | + | |
| 7 | 9 | use super::{Store, db_err}; |
| 8 | 10 | use crate::error::{Error, Result}; |
| 9 | 11 | |
| @@ -51,7 +53,7 @@ pub fn valid_language(code: &str) -> bool { | ||
| 51 | 53 | |
| 52 | 54 | /// True for a short lowercase slug such as `sage` or `rose-2`: 1 to 24 ASCII letters, digits or |
| 53 | 55 | /// hyphens. Whether forge offers the id is the web layer's call. |
| 54 | -pub fn valid_accent(id: &str) -> bool { | |
| 56 | +pub fn valid_slug(id: &str) -> bool { | |
| 55 | 57 | (1..=MAX_ACCENT_LEN).contains(&id.len()) |
| 56 | 58 | && id |
| 57 | 59 | .bytes() |
| @@ -64,6 +66,15 @@ pub fn valid_sidebar(side: &str) -> bool { | ||
| 64 | 66 | } |
| 65 | 67 | |
| 66 | 68 | impl Store { |
| 69 | + pub(super) async fn update_user(&self, sql: &str, params: impl IntoParams) -> Result<()> { | |
| 70 | + let conn = self.inner.conn.lock().await; | |
| 71 | + let n = conn.execute(sql, params).await.map_err(db_err)?; | |
| 72 | + if n == 0 { | |
| 73 | + return Err(Error::NotFound); | |
| 74 | + } | |
| 75 | + Ok(()) | |
| 76 | + } | |
| 77 | + | |
| 67 | 78 | /// Sets the user's theme and language. Anything malformed is rejected and nothing is written. |
| 68 | 79 | pub async fn set_ui_prefs(&self, user_id: &str, theme: &str, language: &str) -> Result<()> { |
| 69 | 80 | if !THEMES.contains(&theme) { |
| @@ -72,38 +83,24 @@ impl Store { | ||
| 72 | 83 | if !valid_language(language) { |
| 73 | 84 | return Err(Error::Invalid(format!("language {language:?}"))); |
| 74 | 85 | } |
| 75 | - let conn = self.inner.conn.lock().await; | |
| 76 | - let n = conn | |
| 77 | - .execute( | |
| 78 | - "UPDATE users SET theme = ?2, language = ?3 WHERE id = ?1", | |
| 79 | - (user_id.to_string(), theme.to_string(), language.to_string()), | |
| 80 | - ) | |
| 81 | - .await | |
| 82 | - .map_err(db_err)?; | |
| 83 | - if n == 0 { | |
| 84 | - return Err(Error::NotFound); | |
| 85 | - } | |
| 86 | - Ok(()) | |
| 86 | + self.update_user( | |
| 87 | + "UPDATE users SET theme = ?2, language = ?3 WHERE id = ?1", | |
| 88 | + (user_id.to_string(), theme.to_string(), language.to_string()), | |
| 89 | + ) | |
| 90 | + .await | |
| 87 | 91 | } |
| 88 | 92 | |
| 89 | 93 | /// Sets the user's accent colour id for both themes. A malformed id is rejected and nothing is |
| 90 | 94 | /// written. |
| 91 | 95 | pub async fn set_accent(&self, user_id: &str, accent: &str) -> Result<()> { |
| 92 | - if !valid_accent(accent) { | |
| 96 | + if !valid_slug(accent) { | |
| 93 | 97 | return Err(Error::Invalid(format!("accent {accent:?}"))); |
| 94 | 98 | } |
| 95 | - let conn = self.inner.conn.lock().await; | |
| 96 | - let n = conn | |
| 97 | - .execute( | |
| 98 | - "UPDATE users SET accent = ?2, accent_dark = ?2 WHERE id = ?1", | |
| 99 | - (user_id.to_string(), accent.to_string()), | |
| 100 | - ) | |
| 101 | - .await | |
| 102 | - .map_err(db_err)?; | |
| 103 | - if n == 0 { | |
| 104 | - return Err(Error::NotFound); | |
| 105 | - } | |
| 106 | - Ok(()) | |
| 99 | + self.update_user( | |
| 100 | + "UPDATE users SET accent = ?2, accent_dark = ?2 WHERE id = ?1", | |
| 101 | + (user_id.to_string(), accent.to_string()), | |
| 102 | + ) | |
| 103 | + .await | |
| 107 | 104 | } |
| 108 | 105 | |
| 109 | 106 | /// Sets the four colour choices: the accent and the base for the light theme, then the accent |
| @@ -117,34 +114,27 @@ impl Store { | ||
| 117 | 114 | base_dark: &str, |
| 118 | 115 | ) -> Result<()> { |
| 119 | 116 | for accent in [accent_light, accent_dark] { |
| 120 | - if !valid_accent(accent) { | |
| 117 | + if !valid_slug(accent) { | |
| 121 | 118 | return Err(Error::Invalid(format!("accent {accent:?}"))); |
| 122 | 119 | } |
| 123 | 120 | } |
| 124 | 121 | for base in [base_light, base_dark] { |
| 125 | - if !valid_accent(base) { | |
| 122 | + if !valid_slug(base) { | |
| 126 | 123 | return Err(Error::Invalid(format!("base {base:?}"))); |
| 127 | 124 | } |
| 128 | 125 | } |
| 129 | - let conn = self.inner.conn.lock().await; | |
| 130 | - let n = conn | |
| 131 | - .execute( | |
| 132 | - "UPDATE users SET accent = ?2, accent_dark = ?3, base_light = ?4, base_dark = ?5 \ | |
| 133 | - WHERE id = ?1", | |
| 134 | - ( | |
| 135 | - user_id.to_string(), | |
| 136 | - accent_light.to_string(), | |
| 137 | - accent_dark.to_string(), | |
| 138 | - base_light.to_string(), | |
| 139 | - base_dark.to_string(), | |
| 140 | - ), | |
| 141 | - ) | |
| 142 | - .await | |
| 143 | - .map_err(db_err)?; | |
| 144 | - if n == 0 { | |
| 145 | - return Err(Error::NotFound); | |
| 146 | - } | |
| 147 | - Ok(()) | |
| 126 | + self.update_user( | |
| 127 | + "UPDATE users SET accent = ?2, accent_dark = ?3, base_light = ?4, base_dark = ?5 \ | |
| 128 | + WHERE id = ?1", | |
| 129 | + ( | |
| 130 | + user_id.to_string(), | |
| 131 | + accent_light.to_string(), | |
| 132 | + accent_dark.to_string(), | |
| 133 | + base_light.to_string(), | |
| 134 | + base_dark.to_string(), | |
| 135 | + ), | |
| 136 | + ) | |
| 137 | + .await | |
| 148 | 138 | } |
| 149 | 139 | |
| 150 | 140 | /// Sets the side the shell sidebar sits on. Anything but `left` or `right` is rejected and |
| @@ -153,34 +143,11 @@ impl Store { | ||
| 153 | 143 | if !valid_sidebar(side) { |
| 154 | 144 | return Err(Error::Invalid(format!("sidebar {side:?}"))); |
| 155 | 145 | } |
| 156 | - let conn = self.inner.conn.lock().await; | |
| 157 | - let n = conn | |
| 158 | - .execute( | |
| 159 | - "UPDATE users SET sidebar_side = ?2 WHERE id = ?1", | |
| 160 | - (user_id.to_string(), side.to_string()), | |
| 161 | - ) | |
| 162 | - .await | |
| 163 | - .map_err(db_err)?; | |
| 164 | - if n == 0 { | |
| 165 | - return Err(Error::NotFound); | |
| 166 | - } | |
| 167 | - Ok(()) | |
| 168 | - } | |
| 169 | - | |
| 170 | - /// Turns the email copy of notifications on or off for one user (migration 0035). | |
| 171 | - pub async fn set_email_notifications(&self, user_id: &str, on: bool) -> Result<()> { | |
| 172 | - let conn = self.inner.conn.lock().await; | |
| 173 | - let n = conn | |
| 174 | - .execute( | |
| 175 | - "UPDATE users SET email_notifications = ?2 WHERE id = ?1", | |
| 176 | - (user_id.to_string(), i64::from(on)), | |
| 177 | - ) | |
| 178 | - .await | |
| 179 | - .map_err(db_err)?; | |
| 180 | - if n == 0 { | |
| 181 | - return Err(Error::NotFound); | |
| 182 | - } | |
| 183 | - Ok(()) | |
| 146 | + self.update_user( | |
| 147 | + "UPDATE users SET sidebar_side = ?2 WHERE id = ?1", | |
| 148 | + (user_id.to_string(), side.to_string()), | |
| 149 | + ) | |
| 150 | + .await | |
| 184 | 151 | } |
| 185 | 152 | } |
| 186 | 153 | |
| @@ -208,10 +175,10 @@ mod tests { | ||
| 208 | 175 | let longest = "a".repeat(MAX_ACCENT_LEN); |
| 209 | 176 | let too_long = "a".repeat(MAX_ACCENT_LEN + 1); |
| 210 | 177 | for ok in ["sage", "rose-2", "a", longest.as_str()] { |
| 211 | - assert!(valid_accent(ok), "case accent {ok}"); | |
| 178 | + assert!(valid_slug(ok), "case accent {ok}"); | |
| 212 | 179 | } |
| 213 | 180 | for bad in ["", "Sage", "sage_2", "../x", "a b", too_long.as_str()] { |
| 214 | - assert!(!valid_accent(bad), "case accent {bad}"); | |
| 181 | + assert!(!valid_slug(bad), "case accent {bad}"); | |
| 215 | 182 | } |
| 216 | 183 | |
| 217 | 184 | // Sidebar sides. |
crates/forge-core/src/store/user_delete.rsmodified+17 -40
| @@ -6,10 +6,10 @@ | ||
| 6 | 6 | use turso::Connection; |
| 7 | 7 | use turso::transaction::Transaction; |
| 8 | 8 | |
| 9 | -use super::issues::finish; | |
| 9 | +use super::finish; | |
| 10 | 10 | use super::{Store, USER_COLS, col_bool, col_int, col_text, db_err, fetch_opt, map_user, new_id}; |
| 11 | 11 | use crate::error::{Error, Result}; |
| 12 | -use crate::model::{AccountKind, User}; | |
| 12 | +use crate::model::User; | |
| 13 | 13 | use crate::time::now_stamp; |
| 14 | 14 | |
| 15 | 15 | /// Login name of the reserved ghost account. `names::RESERVED` contains it, so nobody can |
| @@ -86,7 +86,8 @@ const REASSIGNED: &[(&str, &str, &str, &str)] = &[ | ||
| 86 | 86 | "created_by", |
| 87 | 87 | "", |
| 88 | 88 | ), |
| 89 | - // Inbox rows where the user acted last; rows removed with the account are excluded. | |
| 89 | + ("merge queue entries", "merge_queue", "enqueued_by", ""), | |
| 90 | + ("package versions", "package_versions", "publisher_id", ""), | |
| 90 | 91 | ( |
| 91 | 92 | "notification actors", |
| 92 | 93 | "notifications", |
| @@ -165,41 +166,28 @@ impl Store { | ||
| 165 | 166 | if let Some(user) = existing { |
| 166 | 167 | return Ok(user); |
| 167 | 168 | } |
| 168 | - let user = User { | |
| 169 | - id: new_id(), | |
| 170 | - username: GHOST_USERNAME.to_string(), | |
| 171 | - email: None, | |
| 172 | - password_hash: GHOST_PASSWORD_HASH.to_string(), | |
| 173 | - is_admin: false, | |
| 174 | - created_at: now_stamp(), | |
| 175 | - about: String::new(), | |
| 176 | - display_name: None, | |
| 177 | - timezone: "UTC".to_string(), | |
| 178 | - avatar_hash: None, | |
| 179 | - theme: "light".into(), | |
| 180 | - language: "auto".into(), | |
| 181 | - accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | |
| 182 | - accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(), | |
| 183 | - base_light: crate::store::ui_prefs::DEFAULT_BASE.into(), | |
| 184 | - base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(), | |
| 185 | - sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(), | |
| 186 | - kind: AccountKind::User, | |
| 187 | - email_notifications: true, | |
| 188 | - }; | |
| 169 | + let id = new_id(); | |
| 189 | 170 | conn.execute( |
| 190 | 171 | "INSERT INTO users (id, username, username_folded, email, password_hash, is_admin, created_at, theme) \ |
| 191 | 172 | VALUES (?1, ?2, ?3, NULL, ?4, 0, ?5, 'light')", |
| 192 | 173 | ( |
| 193 | - user.id.clone(), | |
| 194 | - user.username.clone(), | |
| 174 | + id.clone(), | |
| 195 | 175 | GHOST_USERNAME.to_string(), |
| 196 | - user.password_hash.clone(), | |
| 197 | - user.created_at.clone(), | |
| 176 | + GHOST_USERNAME.to_string(), | |
| 177 | + GHOST_PASSWORD_HASH.to_string(), | |
| 178 | + now_stamp(), | |
| 198 | 179 | ), |
| 199 | 180 | ) |
| 200 | 181 | .await |
| 201 | 182 | .map_err(db_err)?; |
| 202 | - Ok(user) | |
| 183 | + fetch_opt( | |
| 184 | + &conn, | |
| 185 | + &format!("SELECT {USER_COLS} FROM users WHERE id = ?1 LIMIT 1"), | |
| 186 | + (id,), | |
| 187 | + map_user, | |
| 188 | + ) | |
| 189 | + .await? | |
| 190 | + .ok_or_else(missing) | |
| 203 | 191 | } |
| 204 | 192 | |
| 205 | 193 | /// Checks whether `user_id` can be deleted and reports what would happen. Changes nothing. |
| @@ -318,7 +306,6 @@ async fn apply(tx: &Transaction<'_>, user_id: &str, ghost_id: &str) -> Result<() | ||
| 318 | 306 | let uid = user_id.to_string(); |
| 319 | 307 | let gid = ghost_id.to_string(); |
| 320 | 308 | |
| 321 | - // Drafts go first, with their comments and edit history. They are deleted, not moved. | |
| 322 | 309 | let draft_edits = format!( |
| 323 | 310 | "DELETE FROM edit_history WHERE target_kind = 'review_comment' AND target_id IN ({DRAFT_COMMENTS})" |
| 324 | 311 | ); |
| @@ -342,7 +329,6 @@ async fn apply(tx: &Transaction<'_>, user_id: &str, ghost_id: &str) -> Result<() | ||
| 342 | 329 | let sql = format!("DELETE FROM {table} WHERE {column} = ?1"); |
| 343 | 330 | tx.execute(&sql, (uid.clone(),)).await.map_err(db_err)?; |
| 344 | 331 | } |
| 345 | - // Cached commit verdicts that name the deleted account as their signer. | |
| 346 | 332 | tx.execute( |
| 347 | 333 | "DELETE FROM commit_signatures WHERE signer_user_id = ?1", |
| 348 | 334 | (uid.clone(),), |
| @@ -434,7 +420,6 @@ mod tests { | ||
| 434 | 420 | async fn ghost_account_and_refused_deletions() { |
| 435 | 421 | let fx = fixture().await; |
| 436 | 422 | |
| 437 | - // Scenario: the ghost is created once and cannot log in. | |
| 438 | 423 | let again = fx.store.ensure_ghost_user().await.unwrap(); |
| 439 | 424 | assert_eq!(again.id, fx.ghost.id); |
| 440 | 425 | assert_eq!(fx.ghost.username, "ghost"); |
| @@ -447,13 +432,11 @@ mod tests { | ||
| 447 | 432 | &fx.ghost.password_hash |
| 448 | 433 | )); |
| 449 | 434 | |
| 450 | - // Scenario: the ghost itself cannot be deleted. | |
| 451 | 435 | assert!(matches!( |
| 452 | 436 | fx.store.delete_user(&fx.ghost.id, &fx.ghost.id).await, |
| 453 | 437 | Err(Error::Forbidden(_)) |
| 454 | 438 | )); |
| 455 | 439 | |
| 456 | - // Scenario: a user who owns a repo is refused and nothing changes. | |
| 457 | 440 | let err = fx.store.delete_user(&fx.bob.id, &fx.ghost.id).await; |
| 458 | 441 | assert!( |
| 459 | 442 | matches!(err, Err(Error::Conflict(ref m)) if m == "transfer or delete their repositories first"), |
| @@ -462,7 +445,6 @@ mod tests { | ||
| 462 | 445 | assert!(fx.store.user_by_id(&fx.bob.id).await.unwrap().is_some()); |
| 463 | 446 | assert!(fx.store.repo_by_id(&fx.repo_id).await.unwrap().is_some()); |
| 464 | 447 | |
| 465 | - // Scenario: the last administrator is refused (before a second admin exists). | |
| 466 | 448 | let err = fx.store.delete_user(&fx.admin.id, &fx.ghost.id).await; |
| 467 | 449 | assert!(matches!(err, Err(Error::Conflict(_))), "{err:?}"); |
| 468 | 450 | assert!(fx.store.user_by_id(&fx.admin.id).await.unwrap().is_some()); |
| @@ -472,7 +454,6 @@ mod tests { | ||
| 472 | 454 | async fn authored_content_moves_to_ghost_and_preview_changes_nothing() { |
| 473 | 455 | let fx = fixture().await; |
| 474 | 456 | |
| 475 | - // Scenario: authored content moves to the ghost and stays readable. | |
| 476 | 457 | let issue = fx |
| 477 | 458 | .store |
| 478 | 459 | .create_issue(&fx.repo_id, &fx.tahinli.id, "Bug", "body") |
| @@ -483,7 +464,6 @@ mod tests { | ||
| 483 | 464 | .add_comment(&issue.id, &fx.tahinli.id, "a comment") |
| 484 | 465 | .await |
| 485 | 466 | .unwrap(); |
| 486 | - // A submitted review and a pending draft, both by Tahinli on the issue row. | |
| 487 | 467 | { |
| 488 | 468 | let conn = fx.store.inner.conn.lock().await; |
| 489 | 469 | for (id, state) in [("rev-done", "commented"), ("rev-draft", "pending")] { |
| @@ -545,7 +525,6 @@ mod tests { | ||
| 545 | 525 | ); |
| 546 | 526 | assert!(fx.store.user_by_id(&fx.tahinli.id).await.unwrap().is_none()); |
| 547 | 527 | |
| 548 | - // Scenario: a deletion preview reports counts and changes nothing. | |
| 549 | 528 | let second_admin = fx |
| 550 | 529 | .store |
| 551 | 530 | .create_user("Carol", None, "hash", true) |
| @@ -631,7 +610,6 @@ mod tests { | ||
| 631 | 610 | #[tokio::test] |
| 632 | 611 | async fn discussions_and_comments_move_to_ghost() { |
| 633 | 612 | let fx = fixture().await; |
| 634 | - // Tahinli's discussion in Bob's repo, with Bob's reply: Tahinli's inbox row goes with her. | |
| 635 | 613 | let mine = fx |
| 636 | 614 | .store |
| 637 | 615 | .create_discussion( |
| @@ -652,7 +630,6 @@ mod tests { | ||
| 652 | 630 | .add_discussion_comment(&mine.id, &fx.bob.id, None, "a reply", false) |
| 653 | 631 | .await |
| 654 | 632 | .unwrap(); |
| 655 | - // Bob's discussion that Tahinli commented on: Bob's inbox row names Tahinli as last actor. | |
| 656 | 633 | let theirs = fx |
| 657 | 634 | .store |
| 658 | 635 | .create_discussion( |
crates/forge-core/src/store/web_push.rsmodified+2 -2
| @@ -7,7 +7,7 @@ use crate::time::now_stamp; | ||
| 7 | 7 | |
| 8 | 8 | /// Most devices one account may hold. A subscription past this is refused, so a client cannot |
| 9 | 9 | /// grow the table without bound. |
| 10 | -pub const MAX_DEVICES: usize = 20; | |
| 10 | +pub const MAX_DEVICES: i64 = 20; | |
| 11 | 11 | |
| 12 | 12 | /// One browser or installed app that receives pushes for `user_id`. |
| 13 | 13 | #[derive(Debug, Clone, PartialEq, Eq)] |
| @@ -118,7 +118,7 @@ impl Store { | ||
| 118 | 118 | ) |
| 119 | 119 | .await? |
| 120 | 120 | .unwrap_or(0); |
| 121 | - if usize::try_from(held).unwrap_or(usize::MAX) >= MAX_DEVICES { | |
| 121 | + if held >= MAX_DEVICES { | |
| 122 | 122 | return Err(Error::Invalid(format!( |
| 123 | 123 | "an account can enable push on at most {MAX_DEVICES} devices" |
| 124 | 124 | ))); |
crates/forge-core/src/store/webhooks.rsmodified+63 -94
| @@ -9,8 +9,8 @@ use std::time::Duration; | ||
| 9 | 9 | use turso::{Connection, Row, Value}; |
| 10 | 10 | |
| 11 | 11 | use super::{ |
| 12 | - Store, col_blob, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, | |
| 13 | - finish, new_id, | |
| 12 | + Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, | |
| 13 | + fetch_opt, finish, new_id, opt_int_value, opt_text, | |
| 14 | 14 | }; |
| 15 | 15 | use crate::error::{Error, Result}; |
| 16 | 16 | use crate::secret; |
| @@ -68,13 +68,13 @@ fn map_delivery(row: &Row) -> Result<Delivery> { | ||
| 68 | 68 | attempt: u32::try_from(col_int(row, 8)?) |
| 69 | 69 | .map_err(|_| Error::Database("negative delivery attempt count".into()))?, |
| 70 | 70 | next_attempt_at: col_opt_text(row, 9)?, |
| 71 | - response_status: opt_int(row, 10)? | |
| 71 | + response_status: col_opt_int(row, 10)? | |
| 72 | 72 | .map(|n| u16::try_from(n).map_err(|_| Error::Database("bad response status".into()))) |
| 73 | 73 | .transpose()?, |
| 74 | 74 | response_headers: col_opt_text(row, 11)?, |
| 75 | 75 | response_body: col_opt_text(row, 12)?, |
| 76 | 76 | error: col_opt_text(row, 13)?, |
| 77 | - duration_ms: opt_int(row, 14)? | |
| 77 | + duration_ms: col_opt_int(row, 14)? | |
| 78 | 78 | .map(|n| u64::try_from(n).map_err(|_| Error::Database("bad duration".into()))) |
| 79 | 79 | .transpose()?, |
| 80 | 80 | created_at: col_text(row, 15)?, |
| @@ -82,15 +82,6 @@ fn map_delivery(row: &Row) -> Result<Delivery> { | ||
| 82 | 82 | }) |
| 83 | 83 | } |
| 84 | 84 | |
| 85 | -/// An integer column that may be NULL. | |
| 86 | -fn opt_int(row: &Row, i: usize) -> Result<Option<i64>> { | |
| 87 | - match row.get_value(i).map_err(db_err)? { | |
| 88 | - Value::Integer(n) => Ok(Some(n)), | |
| 89 | - Value::Null => Ok(None), | |
| 90 | - _ => Err(Error::Database(format!("column {i} is not an integer"))), | |
| 91 | - } | |
| 92 | -} | |
| 93 | - | |
| 94 | 85 | /// Headers the worker adds at send time. They are never kept in the stored request headers, so a |
| 95 | 86 | /// redelivery gets a fresh GUID and signature. Keep this list in step with `WORKER_HEADERS` in |
| 96 | 87 | /// forge-web's webhook worker. |
| @@ -112,14 +103,6 @@ fn strip_worker_headers(raw: &str) -> String { | ||
| 112 | 103 | } |
| 113 | 104 | } |
| 114 | 105 | |
| 115 | -fn opt_text(v: Option<&str>) -> Value { | |
| 116 | - v.map_or(Value::Null, |s| Value::Text(s.to_string())) | |
| 117 | -} | |
| 118 | - | |
| 119 | -fn opt_int_value(v: Option<i64>) -> Value { | |
| 120 | - v.map_or(Value::Null, Value::Integer) | |
| 121 | -} | |
| 122 | - | |
| 123 | 106 | /// JSON array of event names, in the order given. |
| 124 | 107 | fn events_json(events: &[WebhookEvent]) -> String { |
| 125 | 108 | let names: Vec<&str> = events.iter().map(|e| e.as_str()).collect(); |
| @@ -172,6 +155,35 @@ async fn insert_delivery(conn: &Connection, d: &Delivery) -> Result<()> { | ||
| 172 | 155 | Ok(()) |
| 173 | 156 | } |
| 174 | 157 | |
| 158 | +fn pending_delivery( | |
| 159 | + hook_id: &str, | |
| 160 | + event: WebhookEvent, | |
| 161 | + action: String, | |
| 162 | + request_headers: String, | |
| 163 | + request_body: String, | |
| 164 | +) -> Delivery { | |
| 165 | + let now = now_stamp(); | |
| 166 | + Delivery { | |
| 167 | + id: new_id(), | |
| 168 | + hook_id: hook_id.to_string(), | |
| 169 | + guid: new_guid(), | |
| 170 | + event, | |
| 171 | + action, | |
| 172 | + request_headers, | |
| 173 | + request_body, | |
| 174 | + state: DeliveryState::Pending, | |
| 175 | + attempt: 0, | |
| 176 | + next_attempt_at: Some(now.clone()), | |
| 177 | + response_status: None, | |
| 178 | + response_headers: None, | |
| 179 | + response_body: None, | |
| 180 | + error: None, | |
| 181 | + duration_ms: None, | |
| 182 | + created_at: now, | |
| 183 | + delivered_at: None, | |
| 184 | + } | |
| 185 | +} | |
| 186 | + | |
| 175 | 187 | /// Most webhooks one repository can have. |
| 176 | 188 | pub const MAX_WEBHOOKS: i64 = 20; |
| 177 | 189 | |
| @@ -214,7 +226,7 @@ impl Store { | ||
| 214 | 226 | "SELECT COUNT(*) FROM webhooks WHERE repo_id = ?1", |
| 215 | 227 | repo_id, |
| 216 | 228 | MAX_WEBHOOKS, |
| 217 | - "a repository can have at most 20 webhooks", | |
| 229 | + &format!("a repository can have at most {MAX_WEBHOOKS} webhooks"), | |
| 218 | 230 | ) |
| 219 | 231 | .await?; |
| 220 | 232 | conn.execute( |
| @@ -240,38 +252,22 @@ impl Store { | ||
| 240 | 252 | let now = now_stamp(); |
| 241 | 253 | { |
| 242 | 254 | let conn = self.inner.conn.lock().await; |
| 243 | - let n = match secret_sealed { | |
| 244 | - Some(sealed) => { | |
| 245 | - conn.execute( | |
| 246 | - "UPDATE webhooks SET url = ?2, secret_sealed = ?3, events = ?4, \ | |
| 247 | - active = ?5, updated_at = ?6 WHERE id = ?1", | |
| 248 | - vec![ | |
| 249 | - Value::Text(id.to_string()), | |
| 250 | - Value::Text(url.to_string()), | |
| 251 | - Value::Blob(sealed.to_vec()), | |
| 252 | - Value::Text(events_json(events)), | |
| 253 | - Value::Integer(i64::from(active)), | |
| 254 | - Value::Text(now), | |
| 255 | - ], | |
| 256 | - ) | |
| 257 | - .await | |
| 258 | - } | |
| 259 | - None => { | |
| 260 | - conn.execute( | |
| 261 | - "UPDATE webhooks SET url = ?2, events = ?3, active = ?4, updated_at = ?5 \ | |
| 262 | - WHERE id = ?1", | |
| 263 | - vec![ | |
| 264 | - Value::Text(id.to_string()), | |
| 265 | - Value::Text(url.to_string()), | |
| 266 | - Value::Text(events_json(events)), | |
| 267 | - Value::Integer(i64::from(active)), | |
| 268 | - Value::Text(now), | |
| 269 | - ], | |
| 270 | - ) | |
| 271 | - .await | |
| 272 | - } | |
| 273 | - } | |
| 274 | - .map_err(db_err)?; | |
| 255 | + let sealed = secret_sealed.map_or(Value::Null, |s| Value::Blob(s.to_vec())); | |
| 256 | + let n = conn | |
| 257 | + .execute( | |
| 258 | + "UPDATE webhooks SET url = ?2, secret_sealed = COALESCE(?3, secret_sealed), \ | |
| 259 | + events = ?4, active = ?5, updated_at = ?6 WHERE id = ?1", | |
| 260 | + vec![ | |
| 261 | + Value::Text(id.to_string()), | |
| 262 | + Value::Text(url.to_string()), | |
| 263 | + sealed, | |
| 264 | + Value::Text(events_json(events)), | |
| 265 | + Value::Integer(i64::from(active)), | |
| 266 | + Value::Text(now), | |
| 267 | + ], | |
| 268 | + ) | |
| 269 | + .await | |
| 270 | + .map_err(db_err)?; | |
| 275 | 271 | if n == 0 { |
| 276 | 272 | return Err(Error::NotFound); |
| 277 | 273 | } |
| @@ -391,26 +387,13 @@ impl Store { | ||
| 391 | 387 | headers_json: &str, |
| 392 | 388 | body: &str, |
| 393 | 389 | ) -> Result<Delivery> { |
| 394 | - let now = now_stamp(); | |
| 395 | - let delivery = Delivery { | |
| 396 | - id: new_id(), | |
| 397 | - hook_id: hook_id.to_string(), | |
| 398 | - guid: new_guid(), | |
| 390 | + let delivery = pending_delivery( | |
| 391 | + hook_id, | |
| 399 | 392 | event, |
| 400 | - action: action.to_string(), | |
| 401 | - request_headers: headers_json.to_string(), | |
| 402 | - request_body: body.to_string(), | |
| 403 | - state: DeliveryState::Pending, | |
| 404 | - attempt: 0, | |
| 405 | - next_attempt_at: Some(now.clone()), | |
| 406 | - response_status: None, | |
| 407 | - response_headers: None, | |
| 408 | - response_body: None, | |
| 409 | - error: None, | |
| 410 | - duration_ms: None, | |
| 411 | - created_at: now, | |
| 412 | - delivered_at: None, | |
| 413 | - }; | |
| 393 | + action.to_string(), | |
| 394 | + headers_json.to_string(), | |
| 395 | + body.to_string(), | |
| 396 | + ); | |
| 414 | 397 | let conn = self.inner.conn.lock().await; |
| 415 | 398 | insert_delivery(&conn, &delivery).await?; |
| 416 | 399 | Ok(delivery) |
| @@ -570,27 +553,13 @@ impl Store { | ||
| 570 | 553 | ) |
| 571 | 554 | .await? |
| 572 | 555 | .ok_or(Error::NotFound)?; |
| 573 | - let guid = new_guid(); | |
| 574 | - let now = now_stamp(); | |
| 575 | - let copy = Delivery { | |
| 576 | - id: new_id(), | |
| 577 | - hook_id: original.hook_id, | |
| 578 | - guid: guid.clone(), | |
| 579 | - event: original.event, | |
| 580 | - action: original.action, | |
| 581 | - request_headers: strip_worker_headers(&original.request_headers), | |
| 582 | - request_body: original.request_body, | |
| 583 | - state: DeliveryState::Pending, | |
| 584 | - attempt: 0, | |
| 585 | - next_attempt_at: Some(now.clone()), | |
| 586 | - response_status: None, | |
| 587 | - response_headers: None, | |
| 588 | - response_body: None, | |
| 589 | - error: None, | |
| 590 | - duration_ms: None, | |
| 591 | - created_at: now, | |
| 592 | - delivered_at: None, | |
| 593 | - }; | |
| 556 | + let copy = pending_delivery( | |
| 557 | + &original.hook_id, | |
| 558 | + original.event, | |
| 559 | + original.action, | |
| 560 | + strip_worker_headers(&original.request_headers), | |
| 561 | + original.request_body, | |
| 562 | + ); | |
| 594 | 563 | insert_delivery(&conn, ©).await?; |
| 595 | 564 | Ok(copy) |
| 596 | 565 | } |
crates/forge-core/src/suggestions.rsmodified+2 -1
| @@ -99,7 +99,7 @@ pub fn replace_line( | ||
| 99 | 99 | let replacement: Vec<&str> = replacement.iter().map(String::as_str).collect(); |
| 100 | 100 | lines.splice(index..=index, replacement); |
| 101 | 101 | let mut out = lines.join("\n"); |
| 102 | - if ends_with_newline { | |
| 102 | + if ends_with_newline && !lines.is_empty() { | |
| 103 | 103 | out.push('\n'); |
| 104 | 104 | } |
| 105 | 105 | Ok(out) |
| @@ -168,6 +168,7 @@ mod tests { | ||
| 168 | 168 | ("a\nb\nc\n", 2, "b", &["B"], Ok("a\nB\nc\n")), |
| 169 | 169 | ("a\nb", 2, "b", &["b1", "b2"], Ok("a\nb1\nb2")), |
| 170 | 170 | ("a\nb\nc\n", 2, "b", &[], Ok("a\nc\n")), |
| 171 | + ("a\n", 1, "a", &[], Ok("")), | |
| 171 | 172 | ("a\nb\n", 2, "old", &["x"], Err(ApplyError::Changed)), |
| 172 | 173 | ("a\nb\n", 3, "b", &["x"], Err(ApplyError::OutOfRange)), |
| 173 | 174 | ("a\n", 0, "a", &["x"], Err(ApplyError::OutOfRange)), |
crates/forge-core/src/time.rsmodified+1 -7
| @@ -26,13 +26,6 @@ pub fn stamp_after(after: Duration) -> String { | ||
| 26 | 26 | format_stamp(OffsetDateTime::now_utc().saturating_add(delta)) |
| 27 | 27 | } |
| 28 | 28 | |
| 29 | -/// The stamp for `now - before`, in the same format as [`now_stamp`]. | |
| 30 | -/// Saturates at the minimum representable time instead of panicking. | |
| 31 | -pub fn stamp_before(before: Duration) -> String { | |
| 32 | - let delta = SignedDuration::try_from(before).unwrap_or(SignedDuration::MAX); | |
| 33 | - format_stamp(OffsetDateTime::now_utc().saturating_sub(delta)) | |
| 34 | -} | |
| 35 | - | |
| 36 | 29 | /// The stamp for `now - ago`, in the same format as [`now_stamp`]. Saturates at the minimum |
| 37 | 30 | /// representable time instead of panicking. |
| 38 | 31 | pub fn stamp_ago(ago: Duration) -> String { |
| @@ -75,6 +68,7 @@ mod tests { | ||
| 75 | 68 | #[test] |
| 76 | 69 | fn stamps_sort_lexicographically_in_time_order() { |
| 77 | 70 | let a = now_stamp(); |
| 71 | + assert!(is_valid_stamp(&a), "bad stamp: {a}"); | |
| 78 | 72 | let b = stamp_after(Duration::from_secs(3600)); |
| 79 | 73 | assert!(is_valid_stamp(&b), "bad stamp: {b}"); |
| 80 | 74 | assert!(a < b); |
crates/forge-core/src/token.rsmodified+5 -1
| @@ -26,8 +26,12 @@ pub fn random_readable(len: usize) -> String { | ||
| 26 | 26 | .collect() |
| 27 | 27 | } |
| 28 | 28 | |
| 29 | +pub fn random_b64url() -> String { | |
| 30 | + BASE64_URL_SAFE_NO_PAD.encode(random_32()) | |
| 31 | +} | |
| 32 | + | |
| 29 | 33 | pub fn generate_token() -> String { |
| 30 | - format!("forge_{}", BASE64_URL_SAFE_NO_PAD.encode(random_32())) | |
| 34 | + format!("forge_{}", random_b64url()) | |
| 31 | 35 | } |
| 32 | 36 | |
| 33 | 37 | /// Hex-encoded sha256 of the token. |
crates/forge-core/tests/integration/audit_store.rsmodified+0 -1
| @@ -101,7 +101,6 @@ async fn filters_by_actor_action_target_and_involved_user() { | ||
| 101 | 101 | 1 |
| 102 | 102 | ); |
| 103 | 103 | |
| 104 | - // Bob is involved in three entries: his own key, the reset of him, and nothing else. | |
| 105 | 104 | let involving = AuditFilter { |
| 106 | 105 | involving_user: Some(bob.id.clone()), |
| 107 | 106 | ..Default::default() |
crates/forge-core/tests/integration/main.rsmodified+0 -2
| @@ -1,9 +1,7 @@ | ||
| 1 | 1 | //! Store integration tests for forge-core, built as one test binary. |
| 2 | 2 | |
| 3 | -#[allow(dead_code)] | |
| 4 | 3 | mod common; |
| 5 | 4 | |
| 6 | 5 | mod audit_store; |
| 7 | -mod read_pool; | |
| 8 | 6 | mod stars_store; |
| 9 | 7 | mod store_basic; |
crates/forge-core/tests/integration/read_pool.rsdeleted+0 -149
| @@ -1,149 +0,0 @@ | ||
| 1 | -//! Concurrency spike for the store read pool: one turso `Database` with several connections. | |
| 2 | -//! Checks read-after-commit visibility, isolation from an open writer transaction, and that | |
| 3 | -//! concurrent readers next to a busy writer neither error nor report "database is locked". | |
| 4 | - | |
| 5 | -use std::sync::Arc; | |
| 6 | -use std::time::Duration; | |
| 7 | - | |
| 8 | -use turso::{Builder, Connection, Database}; | |
| 9 | - | |
| 10 | -const BUSY_TIMEOUT: Duration = Duration::from_millis(5000); | |
| 11 | - | |
| 12 | -async fn open_db(dir: &tempfile::TempDir) -> Database { | |
| 13 | - let path = dir.path().join("spike.db"); | |
| 14 | - let db = Builder::new_local(path.to_str().expect("utf-8 path")) | |
| 15 | - .build() | |
| 16 | - .await | |
| 17 | - .expect("build database"); | |
| 18 | - let writer = db.connect().expect("writer connect"); | |
| 19 | - let mut rows = writer | |
| 20 | - .query("PRAGMA journal_mode = WAL", ()) | |
| 21 | - .await | |
| 22 | - .expect("wal"); | |
| 23 | - while rows.next().await.expect("wal row").is_some() {} | |
| 24 | - writer | |
| 25 | - .execute( | |
| 26 | - "CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, v INTEGER NOT NULL)", | |
| 27 | - (), | |
| 28 | - ) | |
| 29 | - .await | |
| 30 | - .expect("create table"); | |
| 31 | - db | |
| 32 | -} | |
| 33 | - | |
| 34 | -/// A connection configured the way the store's readers will be: busy timeout and query_only. | |
| 35 | -async fn reader_conn(db: &Database) -> Connection { | |
| 36 | - let conn = db.connect().expect("reader connect"); | |
| 37 | - conn.busy_timeout(BUSY_TIMEOUT).expect("busy timeout"); | |
| 38 | - let mut rows = conn | |
| 39 | - .query("PRAGMA query_only = 1", ()) | |
| 40 | - .await | |
| 41 | - .expect("query_only"); | |
| 42 | - while rows.next().await.expect("query_only row").is_some() {} | |
| 43 | - conn | |
| 44 | -} | |
| 45 | - | |
| 46 | -fn writer_conn(db: &Database) -> Connection { | |
| 47 | - let conn = db.connect().expect("writer connect"); | |
| 48 | - conn.busy_timeout(BUSY_TIMEOUT).expect("busy timeout"); | |
| 49 | - conn | |
| 50 | -} | |
| 51 | - | |
| 52 | -async fn count(conn: &Connection) -> i64 { | |
| 53 | - let mut rows = conn | |
| 54 | - .query("SELECT COUNT(*) FROM t", ()) | |
| 55 | - .await | |
| 56 | - .expect("count query"); | |
| 57 | - let row = rows.next().await.expect("count row").expect("one row"); | |
| 58 | - row.get::<i64>(0).expect("count value") | |
| 59 | -} | |
| 60 | - | |
| 61 | -#[tokio::test] | |
| 62 | -async fn reader_sees_committed_rows_immediately() { | |
| 63 | - let dir = tempfile::tempdir().unwrap(); | |
| 64 | - let db = open_db(&dir).await; | |
| 65 | - let writer = writer_conn(&db); | |
| 66 | - let reader = reader_conn(&db).await; | |
| 67 | - | |
| 68 | - assert_eq!(count(&reader).await, 0); | |
| 69 | - writer | |
| 70 | - .execute("INSERT INTO t (v) VALUES (1)", ()) | |
| 71 | - .await | |
| 72 | - .expect("insert"); | |
| 73 | - assert_eq!( | |
| 74 | - count(&reader).await, | |
| 75 | - 1, | |
| 76 | - "reader must see the autocommitted row" | |
| 77 | - ); | |
| 78 | -} | |
| 79 | - | |
| 80 | -#[tokio::test] | |
| 81 | -async fn reader_does_not_see_uncommitted_rows_and_does_not_block() { | |
| 82 | - let dir = tempfile::tempdir().unwrap(); | |
| 83 | - let db = open_db(&dir).await; | |
| 84 | - let writer = writer_conn(&db); | |
| 85 | - let reader = reader_conn(&db).await; | |
| 86 | - | |
| 87 | - writer.execute("BEGIN", ()).await.expect("begin"); | |
| 88 | - writer | |
| 89 | - .execute("INSERT INTO t (v) VALUES (2)", ()) | |
| 90 | - .await | |
| 91 | - .expect("insert in tx"); | |
| 92 | - writer | |
| 93 | - .execute("INSERT INTO t (v) VALUES (3)", ()) | |
| 94 | - .await | |
| 95 | - .expect("insert in tx"); | |
| 96 | - | |
| 97 | - // The writer still holds its transaction open here. | |
| 98 | - let seen = tokio::time::timeout(BUSY_TIMEOUT, count(&reader)) | |
| 99 | - .await | |
| 100 | - .expect("reader must not block on an open writer transaction"); | |
| 101 | - assert_eq!(seen, 0, "reader must not see uncommitted rows"); | |
| 102 | - | |
| 103 | - writer.execute("COMMIT", ()).await.expect("commit"); | |
| 104 | - assert_eq!(count(&reader).await, 2, "reader must see rows after commit"); | |
| 105 | -} | |
| 106 | - | |
| 107 | -#[tokio::test] | |
| 108 | -async fn eight_readers_with_busy_writer_all_succeed() { | |
| 109 | - let dir = tempfile::tempdir().unwrap(); | |
| 110 | - let db = Arc::new(open_db(&dir).await); | |
| 111 | - let writer = writer_conn(&db); | |
| 112 | - | |
| 113 | - let mut readers = Vec::new(); | |
| 114 | - for _ in 0..8 { | |
| 115 | - let db = Arc::clone(&db); | |
| 116 | - readers.push(tokio::spawn(async move { | |
| 117 | - let conn = reader_conn(&db).await; | |
| 118 | - let mut last = 0; | |
| 119 | - for _ in 0..200 { | |
| 120 | - let n = count(&conn).await; | |
| 121 | - assert!(n >= last, "reader saw count go backwards: {last} -> {n}"); | |
| 122 | - last = n; | |
| 123 | - } | |
| 124 | - last | |
| 125 | - })); | |
| 126 | - } | |
| 127 | - | |
| 128 | - for i in 0..200 { | |
| 129 | - writer | |
| 130 | - .execute("INSERT INTO t (v) VALUES (?1)", (i as i64,)) | |
| 131 | - .await | |
| 132 | - .expect("writer insert must not fail"); | |
| 133 | - } | |
| 134 | - | |
| 135 | - for handle in readers { | |
| 136 | - handle.await.expect("reader task panicked"); | |
| 137 | - } | |
| 138 | - assert_eq!(count(&reader_conn(&db).await).await, 200); | |
| 139 | -} | |
| 140 | - | |
| 141 | -#[tokio::test] | |
| 142 | -async fn reader_rejects_writes_when_query_only() { | |
| 143 | - let dir = tempfile::tempdir().unwrap(); | |
| 144 | - let db = open_db(&dir).await; | |
| 145 | - let reader = reader_conn(&db).await; | |
| 146 | - let result = reader.execute("INSERT INTO t (v) VALUES (9)", ()).await; | |
| 147 | - assert!(result.is_err(), "query_only reader must refuse writes"); | |
| 148 | - assert_eq!(count(&reader).await, 0); | |
| 149 | -} |
crates/forge-core/tests/integration/stars_store.rsmodified+4 -14
| @@ -1,5 +1,3 @@ | ||
| 1 | -//! Store tests for stars, the public repo listing and the 0005 migration. | |
| 2 | - | |
| 3 | 1 | use forge_core::Visibility; |
| 4 | 2 | use forge_core::store::RepoSort; |
| 5 | 3 | use forge_core::store::migrate::{MIGRATIONS, migrate}; |
| @@ -22,19 +20,16 @@ async fn star_and_unstar_round_trip_with_count() { | ||
| 22 | 20 | |
| 23 | 21 | assert_eq!(store.star_count(&repo.id).await.unwrap(), 0); |
| 24 | 22 | store.star(&bob.id, &repo.id).await.unwrap(); |
| 25 | - store.star(&bob.id, &repo.id).await.unwrap(); // second star is a no-op | |
| 23 | + store.star(&bob.id, &repo.id).await.unwrap(); | |
| 26 | 24 | store.star(&tahinli.id, &repo.id).await.unwrap(); |
| 27 | 25 | assert_eq!(store.star_count(&repo.id).await.unwrap(), 2); |
| 28 | 26 | assert!(store.is_starred(&bob.id, &repo.id).await.unwrap()); |
| 29 | 27 | |
| 30 | 28 | store.unstar(&bob.id, &repo.id).await.unwrap(); |
| 31 | - store.unstar(&bob.id, &repo.id).await.unwrap(); // removing twice is fine | |
| 29 | + store.unstar(&bob.id, &repo.id).await.unwrap(); | |
| 32 | 30 | assert!(!store.is_starred(&bob.id, &repo.id).await.unwrap()); |
| 31 | + assert!(store.is_starred(&tahinli.id, &repo.id).await.unwrap()); | |
| 33 | 32 | assert_eq!(store.star_count(&repo.id).await.unwrap(), 1); |
| 34 | - | |
| 35 | - let starred = store.starred_repos(&tahinli.id).await.unwrap(); | |
| 36 | - assert_eq!(starred.len(), 1); | |
| 37 | - assert_eq!(store.starred_repos(&bob.id).await.unwrap().len(), 0); | |
| 38 | 33 | } |
| 39 | 34 | |
| 40 | 35 | #[tokio::test] |
| @@ -53,7 +48,7 @@ async fn delete_repo_removes_its_stars() { | ||
| 53 | 48 | |
| 54 | 49 | store.delete_repo(&repo.id).await.unwrap(); |
| 55 | 50 | |
| 56 | - assert!(store.starred_repos(&tahinli.id).await.unwrap().is_empty()); | |
| 51 | + assert!(!store.is_starred(&tahinli.id, &repo.id).await.unwrap()); | |
| 57 | 52 | assert_eq!(store.star_count(&repo.id).await.unwrap(), 0); |
| 58 | 53 | } |
| 59 | 54 | |
| @@ -96,7 +91,6 @@ async fn public_listing_hides_private_repos_and_matches_literally() { | ||
| 96 | 91 | let names: Vec<&str> = all.iter().map(|(r, _, _)| r.name.as_str()).collect(); |
| 97 | 92 | assert_eq!(names, vec!["100%_done", "other", "tools"]); |
| 98 | 93 | |
| 99 | - // `%` and `_` are literal: "%" alone matches only the repo whose name contains one. | |
| 100 | 94 | let (hits, total) = store |
| 101 | 95 | .list_public_repos(Some("%"), RepoSort::Name, 1, 30) |
| 102 | 96 | .await |
| @@ -108,14 +102,12 @@ async fn public_listing_hides_private_repos_and_matches_literally() { | ||
| 108 | 102 | .await |
| 109 | 103 | .unwrap(); |
| 110 | 104 | assert_eq!(hits.len(), 1); |
| 111 | - // A backslash matches a literal backslash in the description. | |
| 112 | 105 | let (hits, _) = store |
| 113 | 106 | .list_public_repos(Some("\\"), RepoSort::Name, 1, 30) |
| 114 | 107 | .await |
| 115 | 108 | .unwrap(); |
| 116 | 109 | assert_eq!(hits.len(), 1); |
| 117 | 110 | assert_eq!(hits[0].0.name, "other"); |
| 118 | - // Private repos never match, even by exact name. | |
| 119 | 111 | let (hits, _) = store |
| 120 | 112 | .list_public_repos(Some("secret"), RepoSort::Name, 1, 30) |
| 121 | 113 | .await |
| @@ -179,7 +171,6 @@ async fn recently_updated_uses_latest_push_over_creation() { | ||
| 179 | 171 | .create_repo(&tahinli.id, "newer", "", Visibility::Public, "main") |
| 180 | 172 | .await |
| 181 | 173 | .unwrap(); |
| 182 | - // Only "older" gets a push, so it is the most recently updated. | |
| 183 | 174 | store |
| 184 | 175 | .record_push_event(&older.id, &tahinli.id, "refs/heads/main", "0", "1", "https") |
| 185 | 176 | .await |
| @@ -240,7 +231,6 @@ async fn database_at_0004_gains_stars_table() { | ||
| 240 | 231 | ) |
| 241 | 232 | .await |
| 242 | 233 | .unwrap(); |
| 243 | - // Store::open turns foreign keys on; this raw connection must do it too. | |
| 244 | 234 | conn.execute_batch("PRAGMA foreign_keys = ON") |
| 245 | 235 | .await |
| 246 | 236 | .unwrap(); |
crates/forge-core/tests/integration/store_basic.rsmodified+4 -20
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | //! Store round-trip tests against a real turso database file in a temp directory. |
| 2 | 2 | |
| 3 | -use forge_core::time::{now_stamp, stamp_after}; | |
| 3 | +use forge_core::time::{stamp_after, stamp_ago}; | |
| 4 | 4 | use forge_core::{Error, Role, Visibility}; |
| 5 | 5 | use std::time::Duration; |
| 6 | 6 | |
| @@ -117,14 +117,12 @@ async fn sessions_respect_expiry() { | ||
| 117 | 117 | &user.id, |
| 118 | 118 | "hash-dead", |
| 119 | 119 | "csrf-dead", |
| 120 | - &stamp_after(Duration::from_secs(0)), | |
| 120 | + &stamp_ago(Duration::from_secs(1)), | |
| 121 | 121 | None, |
| 122 | 122 | None, |
| 123 | 123 | ) |
| 124 | 124 | .await |
| 125 | 125 | .unwrap(); |
| 126 | - // Make sure the "expired" session is strictly in the past. | |
| 127 | - tokio::time::sleep(Duration::from_millis(5)).await; | |
| 128 | 126 | |
| 129 | 127 | let found = store |
| 130 | 128 | .session_by_token_hash("hash-live") |
| @@ -186,10 +184,7 @@ async fn ssh_key_exact_blob_lookup() { | ||
| 186 | 184 | .await |
| 187 | 185 | .unwrap(); |
| 188 | 186 | |
| 189 | - let blob: Vec<u8> = vec![ | |
| 190 | - 0, 0, 0, 11, b's', b's', b'h', b'-', b'e', b'd', b'2', b'5', b'5', b'1', b'9', 0, 0, 0, 32, | |
| 191 | - 1, 2, 3, | |
| 192 | - ]; | |
| 187 | + let blob = b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20\x01\x02\x03".to_vec(); | |
| 193 | 188 | let key = store |
| 194 | 189 | .add_ssh_key(&user.id, "laptop", "ssh-ed25519", &blob, "SHA256:abc") |
| 195 | 190 | .await |
| @@ -257,11 +252,10 @@ async fn access_token_create_lookup_and_expiry() { | ||
| 257 | 252 | "old", |
| 258 | 253 | "tok-old", |
| 259 | 254 | &[], |
| 260 | - Some(&stamp_after(Duration::from_secs(0))), | |
| 255 | + Some(&stamp_ago(Duration::from_secs(1))), | |
| 261 | 256 | ) |
| 262 | 257 | .await |
| 263 | 258 | .unwrap(); |
| 264 | - tokio::time::sleep(Duration::from_millis(5)).await; | |
| 265 | 259 | |
| 266 | 260 | let found = store |
| 267 | 261 | .token_by_hash("tok-live") |
| @@ -487,16 +481,6 @@ async fn reopening_keeps_data_and_migrations_are_idempotent() { | ||
| 487 | 481 | ); |
| 488 | 482 | } |
| 489 | 483 | |
| 490 | -#[tokio::test] | |
| 491 | -async fn stamps_are_fixed_width_utc() { | |
| 492 | - // Expiry comparisons are string comparisons, so stamps must sort chronologically. | |
| 493 | - let a = now_stamp(); | |
| 494 | - let b = stamp_after(Duration::from_secs(1)); | |
| 495 | - assert_eq!(a.len(), b.len()); | |
| 496 | - assert!(a < b); | |
| 497 | - assert!(a.ends_with('Z')); | |
| 498 | -} | |
| 499 | - | |
| 500 | 484 | #[tokio::test] |
| 501 | 485 | async fn create_first_admin_only_inserts_into_empty_table() { |
| 502 | 486 | let dir = tempfile::tempdir().unwrap(); |
crates/forge-git/src/backup.rsmodified+8 -14
| @@ -8,7 +8,7 @@ use sha2::{Digest, Sha256}; | ||
| 8 | 8 | use crate::command::{GitCommand, GitEnv}; |
| 9 | 9 | use crate::error::{Error, Result}; |
| 10 | 10 | |
| 11 | -const REFS_FORMAT: &str = "--format=%(objectname) %(refname)"; | |
| 11 | +pub const REFS_FORMAT: &str = "--format=%(objectname) %(refname)"; | |
| 12 | 12 | |
| 13 | 13 | fn path_str(p: &Path) -> Result<&str> { |
| 14 | 14 | p.to_str() |
| @@ -48,11 +48,11 @@ pub fn refs_checksum_of_listing(listing: &[u8]) -> String { | ||
| 48 | 48 | hex::encode(hasher.finalize()) |
| 49 | 49 | } |
| 50 | 50 | |
| 51 | -/// Writes `git bundle create <out> --all` for `repo`. `out` must not exist. Returns `Ok(None)` | |
| 51 | +/// Writes `git bundle create <out> --all` for `repo`. `out` must not exist. Returns `Ok(false)` | |
| 52 | 52 | /// without writing anything when the repo has no refs, because git refuses to create an empty |
| 53 | -/// bundle. Returns `Ok(Some(()))` when the bundle was written. The caller must `bundle_verify` it. | |
| 53 | +/// bundle. Returns `Ok(true)` when the bundle was written. The caller must `bundle_verify` it. | |
| 54 | 54 | /// The written file is set to mode 0600. |
| 55 | -pub async fn bundle_create(env: &GitEnv, repo: &Path, out: &Path) -> Result<Option<()>> { | |
| 55 | +pub async fn bundle_create(env: &GitEnv, repo: &Path, out: &Path) -> Result<bool> { | |
| 56 | 56 | if std::fs::symlink_metadata(out).is_ok() { |
| 57 | 57 | return Err(Error::InvalidInput(format!( |
| 58 | 58 | "bundle target already exists: {}", |
| @@ -64,7 +64,7 @@ pub async fn bundle_create(env: &GitEnv, repo: &Path, out: &Path) -> Result<Opti | ||
| 64 | 64 | .iter() |
| 65 | 65 | .all(|b| b.is_ascii_whitespace()) |
| 66 | 66 | { |
| 67 | - return Ok(None); | |
| 67 | + return Ok(false); | |
| 68 | 68 | } |
| 69 | 69 | GitCommand::new(env, "bundle") |
| 70 | 70 | .git_dir(repo) |
| @@ -74,7 +74,7 @@ pub async fn bundle_create(env: &GitEnv, repo: &Path, out: &Path) -> Result<Opti | ||
| 74 | 74 | .status() |
| 75 | 75 | .await?; |
| 76 | 76 | set_private_mode(out)?; |
| 77 | - Ok(Some(())) | |
| 77 | + Ok(true) | |
| 78 | 78 | } |
| 79 | 79 | |
| 80 | 80 | fn set_private_mode(path: &Path) -> Result<()> { |
| @@ -163,10 +163,7 @@ mod tests { | ||
| 163 | 163 | .await |
| 164 | 164 | .expect("init"); |
| 165 | 165 | let out = dir.path().join("empty.bundle"); |
| 166 | - assert_eq!( | |
| 167 | - bundle_create(&env, &bare, &out).await.expect("create"), | |
| 168 | - None | |
| 169 | - ); | |
| 166 | + assert!(!bundle_create(&env, &bare, &out).await.expect("create")); | |
| 170 | 167 | assert!(!out.exists(), "nothing is written for an empty repo"); |
| 171 | 168 | assert_eq!( |
| 172 | 169 | refs_checksum(&env, &bare).await.expect("checksum"), |
| @@ -180,10 +177,7 @@ mod tests { | ||
| 180 | 177 | let env = env(dir.path()); |
| 181 | 178 | let git_dir = repo_with_refs(dir.path()); |
| 182 | 179 | let out = dir.path().join("r.bundle"); |
| 183 | - assert_eq!( | |
| 184 | - bundle_create(&env, &git_dir, &out).await.expect("create"), | |
| 185 | - Some(()) | |
| 186 | - ); | |
| 180 | + assert!(bundle_create(&env, &git_dir, &out).await.expect("create")); | |
| 187 | 181 | let scratch = dir.path().join("scratch.git"); |
| 188 | 182 | crate::repo::init_bare(&env, &scratch, "main") |
| 189 | 183 | .await |
crates/forge-git/src/blame.rsmodified+1 -3
| @@ -41,9 +41,7 @@ pub struct Blame { | ||
| 41 | 41 | fn is_header(line: &str) -> Option<(&str, u32)> { |
| 42 | 42 | let mut parts = line.split(' '); |
| 43 | 43 | let oid = parts.next()?; |
| 44 | - if !(oid.len() == 40 || oid.len() == 64) || !oid.bytes().all(|b| b.is_ascii_hexdigit()) { | |
| 45 | - return None; | |
| 46 | - } | |
| 44 | + validate_oid(oid).ok()?; | |
| 47 | 45 | let _orig = parts.next()?.parse::<u32>().ok()?; |
| 48 | 46 | let fin = parts.next()?.parse::<u32>().ok()?; |
| 49 | 47 | Some((oid, fin)) |
crates/forge-git/src/branches.rsmodified+1 -5
| @@ -4,7 +4,7 @@ use std::path::Path; | ||
| 4 | 4 | |
| 5 | 5 | use crate::command::GitEnv; |
| 6 | 6 | use crate::error::{Error, Result}; |
| 7 | -use crate::history::{git, validate_oid}; | |
| 7 | +use crate::history::{git, validate_oid, zero_oid}; | |
| 8 | 8 | use crate::pulls::{delete_ref_cas, update_ref_cas}; |
| 9 | 9 | |
| 10 | 10 | /// `(ahead, behind)` of `tip` relative to `base`: commits only in `tip`, and commits only in `base`. |
| @@ -31,10 +31,6 @@ pub async fn ahead_behind(env: &GitEnv, repo: &Path, base: &str, tip: &str) -> R | ||
| 31 | 31 | } |
| 32 | 32 | } |
| 33 | 33 | |
| 34 | -fn zero_oid(like: &str) -> String { | |
| 35 | - "0".repeat(like.len()) | |
| 36 | -} | |
| 37 | - | |
| 38 | 34 | /// Creates `refs/heads/<name>` at `oid`. Fails when the branch exists already. |
| 39 | 35 | pub async fn create_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> { |
| 40 | 36 | validate_oid(oid)?; |
crates/forge-git/src/browse.rsmodified+15 -10
| @@ -350,6 +350,16 @@ fn map_kind(kind: GixEntryKind) -> EntryKind { | ||
| 350 | 350 | } |
| 351 | 351 | } |
| 352 | 352 | |
| 353 | +fn commit_root<'r>(repo: &'r gix::Repository, commit: &str) -> Result<Option<gix::Tree<'r>>> { | |
| 354 | + let id = parse_oid(commit)?; | |
| 355 | + if !is_commit(repo, id)? { | |
| 356 | + return Ok(None); | |
| 357 | + } | |
| 358 | + Ok(Some( | |
| 359 | + repo.find_commit(id).map_err(gerr)?.tree().map_err(gerr)?, | |
| 360 | + )) | |
| 361 | +} | |
| 362 | + | |
| 353 | 363 | /// Tree object for `commit` at `path` ("" is the root). Ok(None) if the commit is missing or the |
| 354 | 364 | /// path does not exist. A path that is a blob also yields None. |
| 355 | 365 | fn tree_at<'r>( |
| @@ -357,15 +367,12 @@ fn tree_at<'r>( | ||
| 357 | 367 | commit: &str, |
| 358 | 368 | path: &str, |
| 359 | 369 | ) -> Result<Option<gix::Tree<'r>>> { |
| 360 | - let id = parse_oid(commit)?; | |
| 361 | - if !is_commit(repo, id)? { | |
| 370 | + let Some(mut root) = commit_root(repo, commit)? else { | |
| 362 | 371 | return Ok(None); |
| 363 | - } | |
| 364 | - let root = repo.find_commit(id).map_err(gerr)?.tree().map_err(gerr)?; | |
| 372 | + }; | |
| 365 | 373 | if path.is_empty() { |
| 366 | 374 | return Ok(Some(root)); |
| 367 | 375 | } |
| 368 | - let mut root = root; | |
| 369 | 376 | let Some(entry) = root.peel_to_entry_by_path(path).map_err(gerr)? else { |
| 370 | 377 | return Ok(None); |
| 371 | 378 | }; |
| @@ -439,11 +446,9 @@ fn blob_at( | ||
| 439 | 446 | return Ok(None); |
| 440 | 447 | } |
| 441 | 448 | let repo = open(repo)?; |
| 442 | - let id = parse_oid(commit)?; | |
| 443 | - if !is_commit(&repo, id)? { | |
| 449 | + let Some(mut root) = commit_root(&repo, commit)? else { | |
| 444 | 450 | return Ok(None); |
| 445 | - } | |
| 446 | - let mut root = repo.find_commit(id).map_err(gerr)?.tree().map_err(gerr)?; | |
| 451 | + }; | |
| 447 | 452 | let Some(entry) = root.peel_to_entry_by_path(path).map_err(gerr)? else { |
| 448 | 453 | return Ok(None); |
| 449 | 454 | }; |
| @@ -496,7 +501,7 @@ pub fn read_text_blob( | ||
| 496 | 501 | let Some(blob) = blob_at(repo, commit, path, max_bytes, true)? else { |
| 497 | 502 | return Ok(None); |
| 498 | 503 | }; |
| 499 | - if matches!(blob.kind, EntryKind::Tree | EntryKind::Submodule) || blob.is_binary { | |
| 504 | + if blob.kind == EntryKind::Submodule || blob.is_binary { | |
| 500 | 505 | return Ok(None); |
| 501 | 506 | } |
| 502 | 507 | Ok(String::from_utf8(blob.data).ok()) |
crates/forge-git/src/command.rsmodified+9 -6
| @@ -256,16 +256,19 @@ impl GitCommand { | ||
| 256 | 256 | } |
| 257 | 257 | } |
| 258 | 258 | |
| 259 | +pub(crate) fn failed(subcommand: &str, out: &Output) -> Error { | |
| 260 | + Error::Failed(format!( | |
| 261 | + "git {subcommand} exited with {}: {}", | |
| 262 | + out.status, | |
| 263 | + String::from_utf8_lossy(&out.stderr).trim() | |
| 264 | + )) | |
| 265 | +} | |
| 266 | + | |
| 259 | 267 | fn check_status(subcommand: &str, out: &Output) -> Result<()> { |
| 260 | 268 | if out.status.success() { |
| 261 | 269 | return Ok(()); |
| 262 | 270 | } |
| 263 | - let stderr = String::from_utf8_lossy(&out.stderr); | |
| 264 | - Err(Error::Failed(format!( | |
| 265 | - "git {subcommand} exited with {}: {}", | |
| 266 | - out.status, | |
| 267 | - stderr.trim() | |
| 268 | - ))) | |
| 271 | + Err(failed(subcommand, out)) | |
| 269 | 272 | } |
| 270 | 273 | |
| 271 | 274 | #[cfg(test)] |
crates/forge-git/src/history.rsmodified+7 -80
| @@ -1,6 +1,3 @@ | ||
| 1 | -//! git CLI history: log, commit diff, last commits, archive. | |
| 2 | -//! Every commit argument is a validated full hex OID; paths go after `--` as literal pathspecs. | |
| 3 | - | |
| 4 | 1 | use std::collections::{HashMap, HashSet}; |
| 5 | 2 | use std::path::Path; |
| 6 | 3 | use std::process::Stdio; |
| @@ -11,16 +8,13 @@ use crate::browse::{self, CommitInfo}; | ||
| 11 | 8 | use crate::command::{GitCommand, GitEnv, ObjectSource}; |
| 12 | 9 | use crate::error::{Error, Result}; |
| 13 | 10 | |
| 14 | -/// Byte cap on any single git output stream read by this module. | |
| 15 | 11 | const OUTPUT_CAP: usize = 20 * 1024 * 1024; |
| 16 | 12 | const EMPTY_TREE_SHA1: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; |
| 17 | 13 | const EMPTY_TREE_SHA256: &str = "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321"; |
| 18 | 14 | |
| 19 | -/// Record start (`%x1e`), field separator (`%x1f`), end of fields (`%x1d`). | |
| 20 | 15 | const REC: u8 = 0x1e; |
| 21 | 16 | const FIELD: u8 = 0x1f; |
| 22 | 17 | const END: u8 = 0x1d; |
| 23 | -/// Commit fields: oid, parents, author name/email/time, committer name/email/time, summary, message. | |
| 24 | 18 | const COMMIT_FORMAT: &str = |
| 25 | 19 | "--format=%x1e%H%x1f%P%x1f%an%x1f%ae%x1f%at%x1f%cn%x1f%ce%x1f%ct%x1f%s%x1f%B%x1d"; |
| 26 | 20 | |
| @@ -87,8 +81,6 @@ pub struct CommitDiff { | ||
| 87 | 81 | pub truncated_files: bool, |
| 88 | 82 | } |
| 89 | 83 | |
| 90 | -/// `git` with the forge-wide config overrides: `core.quotePath=false` through the | |
| 91 | -/// environment (`GIT_CONFIG_COUNT`), so it applies before the subcommand as `-c` would. | |
| 92 | 84 | pub(crate) fn git(env: &GitEnv, subcommand: &'static str) -> GitCommand { |
| 93 | 85 | GitCommand::new(env, subcommand) |
| 94 | 86 | .env("GIT_CONFIG_COUNT", "1") |
| @@ -96,7 +88,6 @@ pub(crate) fn git(env: &GitEnv, subcommand: &'static str) -> GitCommand { | ||
| 96 | 88 | .env("GIT_CONFIG_VALUE_0", "false") |
| 97 | 89 | } |
| 98 | 90 | |
| 99 | -/// Accepts only a full SHA-1 (40) or SHA-256 (64) hex object id. | |
| 100 | 91 | pub(crate) fn validate_oid(oid: &str) -> Result<()> { |
| 101 | 92 | let len_ok = oid.len() == 40 || oid.len() == 64; |
| 102 | 93 | if len_ok && oid.bytes().all(|b| b.is_ascii_hexdigit()) { |
| @@ -108,12 +99,14 @@ pub(crate) fn validate_oid(oid: &str) -> Result<()> { | ||
| 108 | 99 | } |
| 109 | 100 | } |
| 110 | 101 | |
| 111 | -/// Pathspec that matches the given path literally (no glob or magic interpretation). | |
| 102 | +pub fn zero_oid(like: &str) -> String { | |
| 103 | + "0".repeat(like.len()) | |
| 104 | +} | |
| 105 | + | |
| 112 | 106 | fn literal_spec(path: &str) -> String { |
| 113 | 107 | format!(":(literal){path}") |
| 114 | 108 | } |
| 115 | 109 | |
| 116 | -/// Accepts `[A-Za-z0-9._-]+`, excluding `.` and `..` and a leading `-`. | |
| 117 | 110 | fn validate_prefix(prefix: &str) -> Result<()> { |
| 118 | 111 | let charset_ok = !prefix.is_empty() |
| 119 | 112 | && prefix |
| @@ -127,11 +120,8 @@ fn validate_prefix(prefix: &str) -> Result<()> { | ||
| 127 | 120 | Ok(()) |
| 128 | 121 | } |
| 129 | 122 | |
| 130 | -/// Longest kept head of a child's output pipe, in bytes. | |
| 131 | 123 | const PIPE_HEAD_CAP: u64 = 64 * 1024; |
| 132 | 124 | |
| 133 | -/// Keeps the first [`PIPE_HEAD_CAP`] bytes of a child's output pipe. The rest is read and | |
| 134 | -/// dropped, so the child never blocks on a full pipe while it is being waited for. | |
| 135 | 125 | pub(crate) async fn read_pipe_head(mut pipe: impl AsyncRead + Unpin) -> Vec<u8> { |
| 136 | 126 | let mut kept = Vec::new(); |
| 137 | 127 | let _ = (&mut pipe).take(PIPE_HEAD_CAP).read_to_end(&mut kept).await; |
| @@ -139,9 +129,6 @@ pub(crate) async fn read_pipe_head(mut pipe: impl AsyncRead + Unpin) -> Vec<u8> | ||
| 139 | 129 | kept |
| 140 | 130 | } |
| 141 | 131 | |
| 142 | -/// Feeds stdout chunks to `f` until EOF, until `f` returns false, or until | |
| 143 | -/// [`OUTPUT_CAP`] bytes. Returns `true` only when EOF was reached. A non-zero exit | |
| 144 | -/// after EOF becomes `Error::Failed` with stderr. | |
| 145 | 132 | async fn for_each_chunk(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Result<bool> { |
| 146 | 133 | let mut command = cmd.into_tokio(); |
| 147 | 134 | command.stdout(Stdio::piped()).stderr(Stdio::piped()); |
| @@ -186,7 +173,6 @@ async fn for_each_chunk(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Re | ||
| 186 | 173 | Ok(eof) |
| 187 | 174 | } |
| 188 | 175 | |
| 189 | -/// Reads the whole stdout up to [`OUTPUT_CAP`]. The flag is `false` when the cap cut it short. | |
| 190 | 176 | pub(crate) async fn read_capped(cmd: GitCommand) -> Result<(Vec<u8>, bool)> { |
| 191 | 177 | let mut buf = Vec::new(); |
| 192 | 178 | let complete = for_each_chunk(cmd, |c| { |
| @@ -197,9 +183,6 @@ pub(crate) async fn read_capped(cmd: GitCommand) -> Result<(Vec<u8>, bool)> { | ||
| 197 | 183 | Ok((buf, complete)) |
| 198 | 184 | } |
| 199 | 185 | |
| 200 | -/// Feeds each NUL-terminated record of stdout to `f` as it arrives, until `f` returns false. | |
| 201 | -/// Empty records are skipped and a record cut off by the output cap is dropped. Returns `true` | |
| 202 | -/// only when EOF was reached. | |
| 203 | 186 | async fn for_each_nul_record(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Result<bool> { |
| 204 | 187 | let mut carry = Vec::new(); |
| 205 | 188 | for_each_chunk(cmd, |chunk| { |
| @@ -219,8 +202,6 @@ async fn for_each_nul_record(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) | ||
| 219 | 202 | .await |
| 220 | 203 | } |
| 221 | 204 | |
| 222 | -/// Parses one record (the bytes after a `%x1e` up to the next one). Returns the commit | |
| 223 | -/// and the bytes after `%x1d` (file names when `--name-only` is used). | |
| 224 | 205 | fn parse_record(rec: &[u8]) -> Option<(CommitInfo, &[u8])> { |
| 225 | 206 | let end = rec.iter().position(|&b| b == END)?; |
| 226 | 207 | let fields = &rec[..end]; |
| @@ -260,7 +241,6 @@ fn parse_record(rec: &[u8]) -> Option<(CommitInfo, &[u8])> { | ||
| 260 | 241 | Some((info, rest)) |
| 261 | 242 | } |
| 262 | 243 | |
| 263 | -/// Commit history for `commit`, optionally limited to `path`, newest first. | |
| 264 | 244 | pub async fn log( |
| 265 | 245 | env: &GitEnv, |
| 266 | 246 | repo: &Path, |
| @@ -291,8 +271,6 @@ pub async fn log( | ||
| 291 | 271 | .collect()) |
| 292 | 272 | } |
| 293 | 273 | |
| 294 | -/// Number of commits reachable from `commit`, limited to `path` when given (`git rev-list | |
| 295 | -/// --count`). Counts every commit, not just the ones a history page shows. | |
| 296 | 274 | pub async fn count(env: &GitEnv, repo: &Path, commit: &str, path: Option<&str>) -> Result<u64> { |
| 297 | 275 | validate_oid(commit)?; |
| 298 | 276 | let mut cmd = git(env, "rev-list") |
| @@ -311,9 +289,6 @@ pub async fn count(env: &GitEnv, repo: &Path, commit: &str, path: Option<&str>) | ||
| 311 | 289 | .map_err(|_| Error::Failed(format!("unexpected rev-list count: {:?}", text.trim()))) |
| 312 | 290 | } |
| 313 | 291 | |
| 314 | -/// Commits reachable from `new` but not from `old` (when `old` is given), oldest first. At most | |
| 315 | -/// `max` of the newest commits are returned. Both ids must be full object ids; they are passed | |
| 316 | -/// after `--end-of-options`, so no value can be read as an option. | |
| 317 | 292 | pub async fn new_commits( |
| 318 | 293 | env: &GitEnv, |
| 319 | 294 | repo: &Path, |
| @@ -324,7 +299,6 @@ pub async fn new_commits( | ||
| 324 | 299 | new_commits_with(env, repo, ObjectSource::default(), old, new, max).await |
| 325 | 300 | } |
| 326 | 301 | |
| 327 | -/// [`new_commits`], reading objects that are missing from `repo` from `src` as well. | |
| 328 | 302 | pub async fn new_commits_with( |
| 329 | 303 | env: &GitEnv, |
| 330 | 304 | repo: &Path, |
| @@ -363,11 +337,11 @@ pub async fn new_commits_with( | ||
| 363 | 337 | Ok(commits) |
| 364 | 338 | } |
| 365 | 339 | |
| 366 | -/// Which `diff-tree` output a command produces. | |
| 367 | 340 | #[derive(Clone, Copy)] |
| 368 | 341 | enum DiffMode { |
| 369 | 342 | NameStatus, |
| 370 | 343 | Patch, |
| 344 | + Raw, | |
| 371 | 345 | } |
| 372 | 346 | |
| 373 | 347 | fn diff_tree_cmd( |
| @@ -387,12 +361,11 @@ fn diff_tree_cmd( | ||
| 387 | 361 | .arg("--no-color") |
| 388 | 362 | .arg("--no-ext-diff") |
| 389 | 363 | .arg("--no-textconv"); |
| 390 | - // `-w` on both runs drops files whose only changes are whitespace from the names as well as | |
| 391 | - // the patch, so the two streams still line up by position. | |
| 392 | 364 | let cmd = if ignore_ws { cmd.arg("-w") } else { cmd }; |
| 393 | 365 | let cmd = match mode { |
| 394 | 366 | DiffMode::NameStatus => cmd.arg("-z").arg("--name-status"), |
| 395 | 367 | DiffMode::Patch => cmd.arg("-p").arg("--full-index"), |
| 368 | + DiffMode::Raw => cmd.arg("-p").arg("--binary"), | |
| 396 | 369 | }; |
| 397 | 370 | cmd.objects(src)?.user_revs(&[base, oid]) |
| 398 | 371 | } |
| @@ -405,7 +378,6 @@ pub fn empty_tree_for(oid: &str) -> &'static str { | ||
| 405 | 378 | } |
| 406 | 379 | } |
| 407 | 380 | |
| 408 | -/// First parent of `oid`, or `None` for a root commit. | |
| 409 | 381 | async fn first_parent(env: &GitEnv, repo: &Path, oid: &str) -> Result<Option<String>> { |
| 410 | 382 | let out = git(env, "rev-list") |
| 411 | 383 | .git_dir(repo) |
| @@ -426,7 +398,6 @@ async fn first_parent(env: &GitEnv, repo: &Path, oid: &str) -> Result<Option<Str | ||
| 426 | 398 | } |
| 427 | 399 | } |
| 428 | 400 | |
| 429 | -/// One entry of `--name-status -z` output. | |
| 430 | 401 | struct NameEntry { |
| 431 | 402 | status: DiffStatus, |
| 432 | 403 | old_path: Option<String>, |
| @@ -444,7 +415,6 @@ fn status_of(code: u8) -> DiffStatus { | ||
| 444 | 415 | } |
| 445 | 416 | } |
| 446 | 417 | |
| 447 | -/// Parses NUL-separated `--name-status -z` output. A trailing partial record is dropped. | |
| 448 | 418 | fn parse_name_status(buf: &[u8]) -> Vec<NameEntry> { |
| 449 | 419 | let text = |p: &[u8]| String::from_utf8_lossy(p).into_owned(); |
| 450 | 420 | let mut out = Vec::new(); |
| @@ -478,7 +448,6 @@ fn parse_name_status(buf: &[u8]) -> Vec<NameEntry> { | ||
| 478 | 448 | out |
| 479 | 449 | } |
| 480 | 450 | |
| 481 | -/// Byte offsets where `diff --git` headers start at the beginning of a line. | |
| 482 | 451 | fn block_starts(text: &str) -> Vec<usize> { |
| 483 | 452 | text.match_indices("diff --git ") |
| 484 | 453 | .map(|(i, _)| i) |
| @@ -486,7 +455,6 @@ fn block_starts(text: &str) -> Vec<usize> { | ||
| 486 | 455 | .collect() |
| 487 | 456 | } |
| 488 | 457 | |
| 489 | -/// `@@ -a[,b] +c[,d] @@` to the old and new start line numbers. | |
| 490 | 458 | fn parse_hunk_start(line: &str) -> (u32, u32) { |
| 491 | 459 | let mut parts = line.split_whitespace().skip(1); |
| 492 | 460 | let start = |p: Option<&str>, sign: char| { |
| @@ -500,7 +468,6 @@ fn parse_hunk_start(line: &str) -> (u32, u32) { | ||
| 500 | 468 | (old, new) |
| 501 | 469 | } |
| 502 | 470 | |
| 503 | -/// Totals and hunks of one file's section of the patch. | |
| 504 | 471 | #[derive(Default)] |
| 505 | 472 | struct BlockOut { |
| 506 | 473 | is_binary: bool, |
| @@ -510,8 +477,6 @@ struct BlockOut { | ||
| 510 | 477 | truncated: bool, |
| 511 | 478 | } |
| 512 | 479 | |
| 513 | -/// Parses one `diff --git` section. Lines beyond `limits.max_lines_per_file` or the | |
| 514 | -/// shared `total_left` budget are dropped and mark the block truncated. Counts stay exact. | |
| 515 | 480 | fn parse_block(block: &str, limits: &DiffLimits, total_left: &mut usize) -> BlockOut { |
| 516 | 481 | let mut out = BlockOut::default(); |
| 517 | 482 | let mut file_lines = 0usize; |
| @@ -589,9 +554,6 @@ fn parse_block(block: &str, limits: &DiffLimits, total_left: &mut usize) -> Bloc | ||
| 589 | 554 | out |
| 590 | 555 | } |
| 591 | 556 | |
| 592 | -/// The diff of `oid` against its first parent (or the empty tree for a root commit). | |
| 593 | -/// Uses `diff-tree -M` for names and statuses and a second `diff-tree -p` run for hunks, | |
| 594 | -/// joined by position. Both streams are capped at [`OUTPUT_CAP`]. | |
| 595 | 557 | pub async fn commit_diff( |
| 596 | 558 | env: &GitEnv, |
| 597 | 559 | repo: &Path, |
| @@ -601,7 +563,6 @@ pub async fn commit_diff( | ||
| 601 | 563 | commit_diff_ws(env, repo, oid, limits, false).await |
| 602 | 564 | } |
| 603 | 565 | |
| 604 | -/// [`commit_diff`], optionally ignoring whitespace changes (`git diff -w`). | |
| 605 | 566 | pub async fn commit_diff_ws( |
| 606 | 567 | env: &GitEnv, |
| 607 | 568 | repo: &Path, |
| @@ -626,8 +587,6 @@ pub async fn commit_diff_ws( | ||
| 626 | 587 | .await |
| 627 | 588 | } |
| 628 | 589 | |
| 629 | -/// The diff from `base` (a commit or tree id) to `oid` (a commit id), with the same parsing and | |
| 630 | -/// limits as [`commit_diff`]. Both ids must be full object ids. | |
| 631 | 590 | pub(crate) async fn diff_between( |
| 632 | 591 | env: &GitEnv, |
| 633 | 592 | repo: &Path, |
| @@ -672,16 +631,12 @@ pub(crate) async fn diff_between( | ||
| 672 | 631 | .await?; |
| 673 | 632 | let patch = String::from_utf8_lossy(&patch_buf); |
| 674 | 633 | let starts = block_starts(&patch); |
| 675 | - // A capped patch may end inside its last section, so that section is dropped. | |
| 676 | 634 | let usable = if patch_complete { |
| 677 | 635 | starts.len() |
| 678 | 636 | } else { |
| 679 | 637 | starts.len().saturating_sub(1) |
| 680 | 638 | }; |
| 681 | 639 | |
| 682 | - // Some git versions keep whitespace-only files in the name list under `-w` while the patch | |
| 683 | - // omits them. Then the streams no longer line up by position, so match by path and drop | |
| 684 | - // names that have no section in the patch. | |
| 685 | 640 | let mut slots: Vec<usize> = (0..entries.len()).collect(); |
| 686 | 641 | if ignore_ws && patch_complete && starts.len() != entries.len() { |
| 687 | 642 | let mut j = 0usize; |
| @@ -731,7 +686,6 @@ pub(crate) async fn diff_between( | ||
| 731 | 686 | }); |
| 732 | 687 | } |
| 733 | 688 | if ignore_ws { |
| 734 | - // Whatever git listed, a text file with no changed lines left is whitespace only. | |
| 735 | 689 | files.retain(|f| { |
| 736 | 690 | f.status != DiffStatus::Modified |
| 737 | 691 | || f.is_binary |
| @@ -745,14 +699,11 @@ pub(crate) async fn diff_between( | ||
| 745 | 699 | }) |
| 746 | 700 | } |
| 747 | 701 | |
| 748 | -/// A downloadable patch: the bytes and whether they are complete (not cut at the output cap). | |
| 749 | 702 | pub struct PatchOut { |
| 750 | 703 | pub data: Vec<u8>, |
| 751 | 704 | pub complete: bool, |
| 752 | 705 | } |
| 753 | 706 | |
| 754 | -/// Mbox of one commit in `format-patch` style (`/commit/{oid}.patch`). Binary changes are | |
| 755 | -/// included so the patch applies. | |
| 756 | 707 | pub async fn commit_patch(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchOut> { |
| 757 | 708 | validate_oid(oid)?; |
| 758 | 709 | let cmd = git(env, "format-patch") |
| @@ -768,7 +719,6 @@ pub async fn commit_patch(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchO | ||
| 768 | 719 | Ok(PatchOut { data, complete }) |
| 769 | 720 | } |
| 770 | 721 | |
| 771 | -/// Plain unified diff of one commit against its first parent (`/commit/{oid}.diff`). | |
| 772 | 722 | pub async fn commit_raw_diff(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchOut> { |
| 773 | 723 | validate_oid(oid)?; |
| 774 | 724 | let base = match first_parent(env, repo, oid).await? { |
| @@ -778,7 +728,6 @@ pub async fn commit_raw_diff(env: &GitEnv, repo: &Path, oid: &str) -> Result<Pat | ||
| 778 | 728 | raw_diff(env, repo, ObjectSource::default(), &base, oid).await |
| 779 | 729 | } |
| 780 | 730 | |
| 781 | -/// Plain unified diff from `base` to `oid`, both full object ids. | |
| 782 | 731 | pub async fn raw_diff( |
| 783 | 732 | env: &GitEnv, |
| 784 | 733 | repo: &Path, |
| @@ -788,23 +737,11 @@ pub async fn raw_diff( | ||
| 788 | 737 | ) -> Result<PatchOut> { |
| 789 | 738 | validate_oid(base)?; |
| 790 | 739 | validate_oid(oid)?; |
| 791 | - let cmd = git(env, "diff-tree") | |
| 792 | - .git_dir(repo) | |
| 793 | - .arg("-r") | |
| 794 | - .arg("-p") | |
| 795 | - .arg("-M") | |
| 796 | - .arg("--binary") | |
| 797 | - .arg("--no-commit-id") | |
| 798 | - .arg("--no-color") | |
| 799 | - .arg("--no-ext-diff") | |
| 800 | - .arg("--no-textconv") | |
| 801 | - .objects(src)? | |
| 802 | - .user_revs(&[base, oid])?; | |
| 740 | + let cmd = diff_tree_cmd(env, repo, src, base, oid, DiffMode::Raw, false)?; | |
| 803 | 741 | let (data, complete) = read_capped(cmd).await?; |
| 804 | 742 | Ok(PatchOut { data, complete }) |
| 805 | 743 | } |
| 806 | 744 | |
| 807 | -/// Mbox of the commits reachable from `head` but not from `base`, oldest first. | |
| 808 | 745 | pub async fn range_patch( |
| 809 | 746 | env: &GitEnv, |
| 810 | 747 | repo: &Path, |
| @@ -827,8 +764,6 @@ pub async fn range_patch( | ||
| 827 | 764 | Ok(PatchOut { data, complete }) |
| 828 | 765 | } |
| 829 | 766 | |
| 830 | -/// Every file path in the tree of `commit`, in tree order, at most `max` of them. The flag is true | |
| 831 | -/// when the list was cut at `max` or at the output cap. | |
| 832 | 767 | pub async fn list_files( |
| 833 | 768 | env: &GitEnv, |
| 834 | 769 | repo: &Path, |
| @@ -857,8 +792,6 @@ pub async fn list_files( | ||
| 857 | 792 | Ok((paths, cut || !complete)) |
| 858 | 793 | } |
| 859 | 794 | |
| 860 | -/// Every blob in the tree of `commit` with its size in bytes, at most `max` of them. The flag is | |
| 861 | -/// true when the list was cut. Submodules (commits) and symlinks are left out. | |
| 862 | 795 | pub async fn list_file_sizes( |
| 863 | 796 | env: &GitEnv, |
| 864 | 797 | repo: &Path, |
| @@ -876,7 +809,6 @@ pub async fn list_file_sizes( | ||
| 876 | 809 | let mut out = Vec::new(); |
| 877 | 810 | let mut cut = false; |
| 878 | 811 | let complete = for_each_nul_record(cmd, |rec| { |
| 879 | - // `<mode> SP <type> SP <oid> SP+ <size>\t<path>`; the path may hold tabs, so split at the first. | |
| 880 | 812 | let Some(tab) = rec.iter().position(|&b| b == b'\t') else { |
| 881 | 813 | return true; |
| 882 | 814 | }; |
| @@ -904,9 +836,6 @@ pub async fn list_file_sizes( | ||
| 904 | 836 | Ok((out, cut || !complete)) |
| 905 | 837 | } |
| 906 | 838 | |
| 907 | -/// The newest commit (walking back from `commit`) that touched each direct child of `dir`, | |
| 908 | -/// keyed by child name. One `git log` walk, limited to `max_walk` commits, and it stops | |
| 909 | -/// early once every name is found. `dir` is `""` for the repo root. | |
| 910 | 839 | pub async fn last_commits( |
| 911 | 840 | env: &GitEnv, |
| 912 | 841 | repo: &Path, |
| @@ -948,7 +877,6 @@ pub async fn last_commits( | ||
| 948 | 877 | let Some((info, files)) = parse_record(rec) else { |
| 949 | 878 | return true; |
| 950 | 879 | }; |
| 951 | - // `-z --name-only` puts a NUL and/or newline between the format and the names. | |
| 952 | 880 | let start = files |
| 953 | 881 | .iter() |
| 954 | 882 | .position(|&b| b != 0 && b != b'\n') |
| @@ -997,7 +925,6 @@ pub async fn last_commits( | ||
| 997 | 925 | Ok(found) |
| 998 | 926 | } |
| 999 | 927 | |
| 1000 | -/// `git archive` for `commit`, with every entry under `<prefix>/`. The caller streams stdout. | |
| 1001 | 928 | pub fn archive_command( |
| 1002 | 929 | env: &GitEnv, |
| 1003 | 930 | repo: &Path, |
crates/forge-git/src/mirror.rsmodified+3 -1
| @@ -223,7 +223,9 @@ async fn fetch( | ||
| 223 | 223 | let head = base_command(env, Some(repo), "ls-remote", auth, allow_http, pin, local)? |
| 224 | 224 | .arg("--symref") |
| 225 | 225 | .user_revs(&[url, "HEAD"])?; |
| 226 | - let listing = run_checked(head, "ls-remote", auth, url).await?; | |
| 226 | + let Ok(listing) = run_checked(head, "ls-remote", auth, url).await else { | |
| 227 | + return Ok(()); | |
| 228 | + }; | |
| 227 | 229 | let listing = String::from_utf8_lossy(&listing); |
| 228 | 230 | let Some(default_ref) = remote_default_branch(&listing) else { |
| 229 | 231 | return Ok(()); |
crates/forge-git/src/pulls.rsmodified+23 -139
| @@ -1,31 +1,32 @@ | ||
| 1 | -//! Pull request plumbing: PR head refs, merge checks, merge commits and compare-and-swap ref | |
| 2 | -//! updates. Every object id is validated as a full hex id and every ref name against a strict | |
| 3 | -//! allowlist before it reaches git. User values follow `--end-of-options` where git allows it. | |
| 4 | - | |
| 5 | 1 | use std::path::Path; |
| 6 | 2 | use std::process::{Output, Stdio}; |
| 7 | 3 | |
| 8 | 4 | use tokio::io::AsyncWriteExt; |
| 9 | 5 | |
| 10 | 6 | use crate::browse::{CommitInfo, validate_repo_path}; |
| 11 | -use crate::command::{GitCommand, GitEnv, ObjectSource}; | |
| 7 | +use crate::command::{GitCommand, GitEnv, ObjectSource, failed}; | |
| 12 | 8 | use crate::error::{Error, Result}; |
| 13 | 9 | use crate::history::{ |
| 14 | 10 | CommitDiff, DiffLimits, diff_between, empty_tree_for, git, new_commits_with, validate_oid, |
| 15 | 11 | }; |
| 16 | 12 | |
| 17 | -/// Outcome of a merge check between a base tip and a head commit. | |
| 13 | +fn conflict_files<'a>(lines: impl Iterator<Item = &'a str>) -> Vec<String> { | |
| 14 | + let mut files: Vec<String> = Vec::new(); | |
| 15 | + for line in lines.map(str::trim).filter(|l| !l.is_empty()) { | |
| 16 | + if !files.iter().any(|f| f == line) { | |
| 17 | + files.push(line.to_owned()); | |
| 18 | + } | |
| 19 | + } | |
| 20 | + files | |
| 21 | +} | |
| 22 | + | |
| 18 | 23 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 19 | 24 | pub enum MergeCheck { |
| 20 | - /// The merge would be clean; `tree` is the id of the resulting tree. | |
| 21 | 25 | Clean { tree: String }, |
| 22 | - /// The merge would conflict; `files` are the conflicted paths, deduplicated. | |
| 23 | 26 | Conflict { files: Vec<String> }, |
| 24 | - /// The head is already contained in the base. | |
| 25 | 27 | UpToDate, |
| 26 | 28 | } |
| 27 | 29 | |
| 28 | -/// Author or committer identity for [`commit_tree`]. `time_unix` is written as `<unix> +0000`. | |
| 29 | 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 30 | 31 | pub struct Signature { |
| 31 | 32 | pub name: String, |
| @@ -33,7 +34,6 @@ pub struct Signature { | ||
| 33 | 34 | pub time_unix: i64, |
| 34 | 35 | } |
| 35 | 36 | |
| 36 | -/// Runs a command without turning a non-zero exit into an error, optionally feeding stdin. | |
| 37 | 37 | async fn run_raw(cmd: GitCommand, stdin: Option<&[u8]>) -> Result<Output> { |
| 38 | 38 | let mut command = cmd.into_tokio(); |
| 39 | 39 | command.stdout(Stdio::piped()).stderr(Stdio::piped()); |
| @@ -43,24 +43,14 @@ async fn run_raw(cmd: GitCommand, stdin: Option<&[u8]>) -> Result<Output> { | ||
| 43 | 43 | let mut child = command.spawn()?; |
| 44 | 44 | if let (Some(data), Some(mut pipe)) = (stdin, child.stdin.take()) { |
| 45 | 45 | pipe.write_all(data).await?; |
| 46 | - // `pipe` is dropped here, which closes git's stdin. | |
| 47 | 46 | } |
| 48 | 47 | Ok(child.wait_with_output().await?) |
| 49 | 48 | } |
| 50 | 49 | |
| 51 | -fn failed(subcommand: &str, out: &Output) -> Error { | |
| 52 | - Error::Failed(format!( | |
| 53 | - "git {subcommand} exited with {}: {}", | |
| 54 | - out.status, | |
| 55 | - String::from_utf8_lossy(&out.stderr).trim() | |
| 56 | - )) | |
| 57 | -} | |
| 58 | - | |
| 59 | 50 | fn stdout_trimmed(out: &Output) -> String { |
| 60 | 51 | String::from_utf8_lossy(&out.stdout).trim().to_owned() |
| 61 | 52 | } |
| 62 | 53 | |
| 63 | -/// Accepts `refs/heads/<name>` and `refs/pull/<N>/head`, with a conservative character set. | |
| 64 | 54 | fn validate_ref(refname: &str) -> Result<()> { |
| 65 | 55 | let heads_ok = refname |
| 66 | 56 | .strip_prefix("refs/heads/") |
| @@ -93,7 +83,6 @@ fn valid_branch_rest(rest: &str) -> bool { | ||
| 93 | 83 | .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'-' | b'+')) |
| 94 | 84 | } |
| 95 | 85 | |
| 96 | -/// Rejects identity fields git would refuse or misparse. | |
| 97 | 86 | fn validate_signature(sig: &Signature) -> Result<()> { |
| 98 | 87 | let bad = |s: &str| s.is_empty() || s.contains(['<', '>', '\n', '\0']); |
| 99 | 88 | if bad(&sig.name) || bad(&sig.email) { |
| @@ -102,7 +91,6 @@ fn validate_signature(sig: &Signature) -> Result<()> { | ||
| 102 | 91 | Ok(()) |
| 103 | 92 | } |
| 104 | 93 | |
| 105 | -/// True when both paths name the same repository (equal, or equal after canonicalization). | |
| 106 | 94 | fn same_repo(a: &Path, b: &Path) -> bool { |
| 107 | 95 | if a == b { |
| 108 | 96 | return true; |
| @@ -113,15 +101,11 @@ fn same_repo(a: &Path, b: &Path) -> bool { | ||
| 113 | 101 | } |
| 114 | 102 | } |
| 115 | 103 | |
| 116 | -/// Fetches `oid` from `head_repo` into `base_repo`'s object store. The first attempt uses a plain | |
| 117 | -/// fetch of the raw id. If git refuses it, the one call is retried with | |
| 118 | -/// `uploadpack.allowAnySHA1InWant=true` for the local upload-pack process. | |
| 119 | 104 | async fn fetch_object(env: &GitEnv, base_repo: &Path, head_repo: &Path, oid: &str) -> Result<()> { |
| 120 | 105 | let head_path = head_repo |
| 121 | 106 | .to_str() |
| 122 | 107 | .ok_or_else(|| Error::InvalidInput("repo path is not valid UTF-8".into()))?; |
| 123 | 108 | let build = |allow_any: bool| -> Result<GitCommand> { |
| 124 | - // `head_repo` is a fork repo from repo_path(), so the local transport is allowed here only. | |
| 125 | 109 | let cmd = git(env, "fetch") |
| 126 | 110 | .allow_local_transport() |
| 127 | 111 | .git_dir(base_repo) |
| @@ -143,8 +127,6 @@ async fn fetch_object(env: &GitEnv, base_repo: &Path, head_repo: &Path, oid: &st | ||
| 143 | 127 | } |
| 144 | 128 | } |
| 145 | 129 | |
| 146 | -/// Points `refs/pull/<number>/head` at `head_oid` in `base_repo`. When the head lives in another | |
| 147 | -/// repository, the object is fetched into `base_repo` first. | |
| 148 | 130 | pub async fn fetch_into_pull_ref( |
| 149 | 131 | env: &GitEnv, |
| 150 | 132 | base_repo: &Path, |
| @@ -171,13 +153,10 @@ pub async fn fetch_into_pull_ref( | ||
| 171 | 153 | .await |
| 172 | 154 | } |
| 173 | 155 | |
| 174 | -/// Best common ancestor of `a` and `b`, or `None` when they share no history. | |
| 175 | 156 | pub async fn merge_base(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<Option<String>> { |
| 176 | 157 | merge_base_with(env, repo, ObjectSource::default(), a, b).await |
| 177 | 158 | } |
| 178 | 159 | |
| 179 | -/// [`merge_base`], reading objects missing from `repo` (such as a fork's head commit) from `src`. | |
| 180 | -/// Nothing is written to `repo`. | |
| 181 | 160 | pub async fn merge_base_with( |
| 182 | 161 | env: &GitEnv, |
| 183 | 162 | repo: &Path, |
| @@ -203,42 +182,23 @@ pub async fn merge_base_with( | ||
| 203 | 182 | } |
| 204 | 183 | } |
| 205 | 184 | |
| 206 | -/// Blob id of `path` in `commit`, or `None` when the path is absent or is not a blob (a tree or a | |
| 207 | -/// submodule). `commit` must be a full object id. `path` is a relative `/`-separated repo path. | |
| 208 | 185 | pub async fn blob_at( |
| 209 | 186 | env: &GitEnv, |
| 210 | 187 | repo: &Path, |
| 211 | 188 | commit: &str, |
| 212 | 189 | path: &str, |
| 213 | -) -> Result<Option<String>> { | |
| 214 | - blob_at_with(env, repo, ObjectSource::default(), commit, path).await | |
| 215 | -} | |
| 216 | - | |
| 217 | -/// [`blob_at`], reading objects missing from `repo` (such as a fork's commit) from `src`. | |
| 218 | -/// Nothing is written to `repo`. | |
| 219 | -pub async fn blob_at_with( | |
| 220 | - env: &GitEnv, | |
| 221 | - repo: &Path, | |
| 222 | - src: ObjectSource<'_>, | |
| 223 | - commit: &str, | |
| 224 | - path: &str, | |
| 225 | 190 | ) -> Result<Option<String>> { |
| 226 | 191 | validate_oid(commit)?; |
| 227 | 192 | validate_blob_path(path)?; |
| 228 | - // `ls-tree` rather than `rev-parse <commit>:<path>`: the path is a pathspec after `--`, so it is | |
| 229 | - // never read as a revision. `:(literal)` stops globs and magic such as `:x` from matching | |
| 230 | - // other entries. Output is NUL-terminated and unquoted, so any name is safe to parse. | |
| 231 | 193 | let spec = format!(":(literal){path}"); |
| 232 | 194 | let out = git(env, "ls-tree") |
| 233 | 195 | .git_dir(repo) |
| 234 | - .objects(src)? | |
| 235 | 196 | .arg("-z") |
| 236 | 197 | .arg("--full-tree") |
| 237 | 198 | .user_arg(commit)? |
| 238 | 199 | .paths(&[spec.as_str()]) |
| 239 | 200 | .output() |
| 240 | 201 | .await?; |
| 241 | - // Pathspecs can match more than one entry, so keep only the exact path. | |
| 242 | 202 | let entry = out.split(|&b| b == 0).find_map(|rec| { |
| 243 | 203 | let text = std::str::from_utf8(rec).ok()?; |
| 244 | 204 | let (meta, name) = text.split_once('\t')?; |
| @@ -260,8 +220,6 @@ pub async fn blob_at_with( | ||
| 260 | 220 | } |
| 261 | 221 | } |
| 262 | 222 | |
| 263 | -/// Rules for the path argument of [`blob_at`]: non-empty, relative, no newline, and the segment | |
| 264 | -/// rules of [`validate_repo_path`]. | |
| 265 | 223 | fn validate_blob_path(path: &str) -> Result<()> { |
| 266 | 224 | if path.is_empty() { |
| 267 | 225 | return Err(Error::InvalidInput("empty path".into())); |
| @@ -275,7 +233,6 @@ fn validate_blob_path(path: &str) -> Result<()> { | ||
| 275 | 233 | validate_repo_path(path) |
| 276 | 234 | } |
| 277 | 235 | |
| 278 | -/// True when `a` is an ancestor of `b` (or equal to it). | |
| 279 | 236 | pub async fn is_ancestor(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<bool> { |
| 280 | 237 | validate_oid(a)?; |
| 281 | 238 | validate_oid(b)?; |
| @@ -291,7 +248,6 @@ pub async fn is_ancestor(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result< | ||
| 291 | 248 | } |
| 292 | 249 | } |
| 293 | 250 | |
| 294 | -/// Checks whether `head` merges cleanly into `base`, without touching any ref. | |
| 295 | 251 | pub async fn check_merge( |
| 296 | 252 | env: &GitEnv, |
| 297 | 253 | repo: &Path, |
| @@ -321,20 +277,14 @@ pub async fn check_merge( | ||
| 321 | 277 | let mut lines = text.lines(); |
| 322 | 278 | let tree = lines.next().unwrap_or_default().trim().to_owned(); |
| 323 | 279 | validate_oid(&tree)?; |
| 324 | - let mut files: Vec<String> = Vec::new(); | |
| 325 | - for line in lines.map(str::trim).filter(|l| !l.is_empty()) { | |
| 326 | - if !files.iter().any(|f| f == line) { | |
| 327 | - files.push(line.to_owned()); | |
| 328 | - } | |
| 329 | - } | |
| 330 | - Ok(MergeCheck::Conflict { files }) | |
| 280 | + Ok(MergeCheck::Conflict { | |
| 281 | + files: conflict_files(lines), | |
| 282 | + }) | |
| 331 | 283 | } |
| 332 | 284 | _ => Err(failed("merge-tree", &out)), |
| 333 | 285 | } |
| 334 | 286 | } |
| 335 | 287 | |
| 336 | -/// Creates a commit for `tree` with the given parents and returns its id. The message is written | |
| 337 | -/// to stdin. Author and committer come from `GIT_AUTHOR_*` and `GIT_COMMITTER_*`. | |
| 338 | 288 | pub async fn commit_tree( |
| 339 | 289 | env: &GitEnv, |
| 340 | 290 | repo: &Path, |
| @@ -377,8 +327,6 @@ pub async fn commit_tree( | ||
| 377 | 327 | Ok(oid) |
| 378 | 328 | } |
| 379 | 329 | |
| 380 | -/// Moves `refname` from `old` to `new` only if it still points at `old`. A stale `old` gives | |
| 381 | -/// `Error::RefMoved`. Use the zero id as `old` to require that the ref does not exist yet. | |
| 382 | 330 | pub async fn update_ref_cas( |
| 383 | 331 | env: &GitEnv, |
| 384 | 332 | repo: &Path, |
| @@ -406,10 +354,7 @@ pub async fn update_ref_cas( | ||
| 406 | 354 | Err(failed("update-ref", &out)) |
| 407 | 355 | } |
| 408 | 356 | |
| 409 | -/// Points `refname` at `new`, whatever it pointed at before. Used for the temporary refs that name | |
| 410 | -/// a merge queue candidate; a rebuild replaces them. | |
| 411 | 357 | pub async fn set_ref(env: &GitEnv, repo: &Path, refname: &str, new: &str) -> Result<()> { |
| 412 | - // Only the merge queue's temporary namespace is writable here, besides the usual checks. | |
| 413 | 358 | let queue_ok = refname |
| 414 | 359 | .strip_prefix("refs/forge/merge-queue/") |
| 415 | 360 | .is_some_and(valid_branch_rest); |
| @@ -430,10 +375,6 @@ pub async fn set_ref(env: &GitEnv, repo: &Path, refname: &str, new: &str) -> Res | ||
| 430 | 375 | Err(failed("update-ref", &out)) |
| 431 | 376 | } |
| 432 | 377 | |
| 433 | -/// Deletes `refname` only if it still points at `old`. `git update-ref -d <ref> <old>` checks the | |
| 434 | -/// old value itself, so a ref that moved, or one that is already gone, gives `Error::RefMoved` | |
| 435 | -/// and is left alone. The zero id is not accepted as `old`: a deletion needs a real value to | |
| 436 | -/// compare against. | |
| 437 | 378 | pub async fn delete_ref_cas(env: &GitEnv, repo: &Path, refname: &str, old: &str) -> Result<()> { |
| 438 | 379 | validate_ref(refname)?; |
| 439 | 380 | validate_oid(old)?; |
| @@ -453,8 +394,6 @@ pub async fn delete_ref_cas(env: &GitEnv, repo: &Path, refname: &str, old: &str) | ||
| 453 | 394 | Err(failed("update-ref", &out)) |
| 454 | 395 | } |
| 455 | 396 | |
| 456 | -/// The diff of the head side of a three-dot range: `merge-base(base, head)..head`. Parsed the same | |
| 457 | -/// way as [`crate::history::commit_diff`]. With no common ancestor it is the diff from the empty tree. | |
| 458 | 397 | pub async fn range_diff_files( |
| 459 | 398 | env: &GitEnv, |
| 460 | 399 | repo: &Path, |
| @@ -462,30 +401,18 @@ pub async fn range_diff_files( | ||
| 462 | 401 | head_oid: &str, |
| 463 | 402 | limits: DiffLimits, |
| 464 | 403 | ) -> Result<CommitDiff> { |
| 465 | - range_diff_files_with( | |
| 404 | + range_diff_files_ws( | |
| 466 | 405 | env, |
| 467 | 406 | repo, |
| 468 | 407 | ObjectSource::default(), |
| 469 | 408 | base_oid, |
| 470 | 409 | head_oid, |
| 471 | 410 | limits, |
| 411 | + false, | |
| 472 | 412 | ) |
| 473 | 413 | .await |
| 474 | 414 | } |
| 475 | 415 | |
| 476 | -/// [`range_diff_files`], reading objects missing from `repo` from `src`. Nothing is written. | |
| 477 | -pub async fn range_diff_files_with( | |
| 478 | - env: &GitEnv, | |
| 479 | - repo: &Path, | |
| 480 | - src: ObjectSource<'_>, | |
| 481 | - base_oid: &str, | |
| 482 | - head_oid: &str, | |
| 483 | - limits: DiffLimits, | |
| 484 | -) -> Result<CommitDiff> { | |
| 485 | - range_diff_files_ws(env, repo, src, base_oid, head_oid, limits, false).await | |
| 486 | -} | |
| 487 | - | |
| 488 | -/// [`range_diff_files_with`], optionally ignoring whitespace changes. | |
| 489 | 416 | pub async fn range_diff_files_ws( |
| 490 | 417 | env: &GitEnv, |
| 491 | 418 | repo: &Path, |
| @@ -504,8 +431,6 @@ pub async fn range_diff_files_ws( | ||
| 504 | 431 | diff_between(env, repo, src, &from, head_oid, limits, ignore_ws).await |
| 505 | 432 | } |
| 506 | 433 | |
| 507 | -/// Commits reachable from `head` but not from `base` (`log <head> ^<base>`), oldest first. | |
| 508 | -/// At most `max` of the newest such commits are returned. | |
| 509 | 434 | pub async fn range_log( |
| 510 | 435 | env: &GitEnv, |
| 511 | 436 | repo: &Path, |
| @@ -516,7 +441,6 @@ pub async fn range_log( | ||
| 516 | 441 | range_log_with(env, repo, ObjectSource::default(), base_oid, head_oid, max).await |
| 517 | 442 | } |
| 518 | 443 | |
| 519 | -/// [`range_log`], reading objects missing from `repo` from `src`. Nothing is written. | |
| 520 | 444 | pub async fn range_log_with( |
| 521 | 445 | env: &GitEnv, |
| 522 | 446 | repo: &Path, |
| @@ -530,20 +454,12 @@ pub async fn range_log_with( | ||
| 530 | 454 | new_commits_with(env, repo, src, Some(base_oid), head_oid, max).await |
| 531 | 455 | } |
| 532 | 456 | |
| 533 | -/// Outcome of replaying head commits onto a base tip. | |
| 534 | 457 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 535 | 458 | pub enum RebaseResult { |
| 536 | - /// The commits replay cleanly; `tip` is the new head (the base tip when every commit was | |
| 537 | - /// already applied) and `count` the number of commits created. | |
| 538 | 459 | Clean { tip: String, count: usize }, |
| 539 | - /// A commit does not apply; `commit` is its id and `files` the conflicted paths. | |
| 540 | 460 | Conflict { commit: String, files: Vec<String> }, |
| 541 | 461 | } |
| 542 | 462 | |
| 543 | -/// Replays the commits reachable from `head_oid` but not from `base_oid` onto `base_oid`, oldest | |
| 544 | -/// first, keeping each author and message. The committer is `committer`. Merge commits in the | |
| 545 | -/// range are skipped and a commit whose changes the base already has is dropped. Nothing is | |
| 546 | -/// written but objects: no ref moves. | |
| 547 | 463 | pub async fn rebase_commits( |
| 548 | 464 | env: &GitEnv, |
| 549 | 465 | repo: &Path, |
| @@ -609,18 +525,10 @@ pub async fn rebase_commits( | ||
| 609 | 525 | let tree = match out.status.code() { |
| 610 | 526 | Some(0) => text.lines().next().unwrap_or_default().trim().to_owned(), |
| 611 | 527 | Some(1) => { |
| 612 | - let mut files: Vec<String> = Vec::new(); | |
| 613 | - for line in text | |
| 614 | - .lines() | |
| 615 | - .skip(1) | |
| 616 | - .map(str::trim) | |
| 617 | - .filter(|l| !l.is_empty()) | |
| 618 | - { | |
| 619 | - if !files.iter().any(|f| f == line) { | |
| 620 | - files.push(line.to_owned()); | |
| 621 | - } | |
| 622 | - } | |
| 623 | - return Ok(RebaseResult::Conflict { commit, files }); | |
| 528 | + return Ok(RebaseResult::Conflict { | |
| 529 | + commit, | |
| 530 | + files: conflict_files(text.lines().skip(1)), | |
| 531 | + }); | |
| 624 | 532 | } |
| 625 | 533 | _ => return Err(failed("merge-tree", &out)), |
| 626 | 534 | }; |
| @@ -657,21 +565,14 @@ pub async fn rebase_commits( | ||
| 657 | 565 | Ok(RebaseResult::Clean { tip, count }) |
| 658 | 566 | } |
| 659 | 567 | |
| 660 | -/// One file of a commit made by [`commit_file_edit`]. | |
| 661 | 568 | #[derive(Debug, Clone, Copy)] |
| 662 | 569 | pub struct FileEdit<'a> { |
| 663 | - /// Repo path of the file. It must be a regular file in the base commit. | |
| 664 | 570 | pub path: &'a str, |
| 665 | - /// The new content of the file. | |
| 666 | 571 | pub content: &'a [u8], |
| 667 | 572 | } |
| 668 | 573 | |
| 669 | 574 | static EDIT_INDEX_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 670 | 575 | |
| 671 | -/// Commits `edit` on top of `base` and moves `refname` from `base` to the new commit, only if the | |
| 672 | -/// ref still holds `base`. A moved ref gives `Error::RefMoved` and nothing changes. The new tree is | |
| 673 | -/// `base`'s tree with the one file replaced and its mode kept. It is built in a temporary index in | |
| 674 | -/// the repo, so no working tree is needed. The commit's only parent is `base`. Returns its id. | |
| 675 | 576 | #[allow(clippy::too_many_arguments)] |
| 676 | 577 | pub async fn commit_file_edit( |
| 677 | 578 | env: &GitEnv, |
| @@ -692,7 +593,6 @@ pub async fn commit_file_edit( | ||
| 692 | 593 | env, repo, &index, refname, base, edit, message, author, committer, |
| 693 | 594 | ) |
| 694 | 595 | .await; |
| 695 | - // The index is scratch space. A leftover file is harmless, but do not keep it. | |
| 696 | 596 | let _ = tokio::fs::remove_file(&index).await; |
| 697 | 597 | result |
| 698 | 598 | } |
| @@ -725,15 +625,13 @@ async fn edit_and_commit( | ||
| 725 | 625 | .status() |
| 726 | 626 | .await?; |
| 727 | 627 | |
| 728 | - // `ls-files -s` gives `<mode> <oid> <stage>\t<path>`. The path must be the file itself, and a | |
| 729 | - // regular file: a symlink or a submodule is not something a suggestion can rewrite. | |
| 628 | + let spec = format!(":(literal){}", edit.path); | |
| 730 | 629 | let listing = GitCommand::new(env, "ls-files") |
| 731 | 630 | .git_dir(repo) |
| 732 | 631 | .env("GIT_INDEX_FILE", index) |
| 733 | 632 | .arg("-s") |
| 734 | 633 | .arg("-z") |
| 735 | - .arg("--") | |
| 736 | - .user_arg(edit.path)? | |
| 634 | + .paths(&[spec.as_str()]) | |
| 737 | 635 | .output() |
| 738 | 636 | .await?; |
| 739 | 637 | let entry = |
| @@ -786,7 +684,6 @@ mod tests { | ||
| 786 | 684 | max_total_lines: 10_000, |
| 787 | 685 | }; |
| 788 | 686 | |
| 789 | - /// Runs git in `dir` with a cleared environment and fixed identities. | |
| 790 | 687 | fn git_in(dir: &Path, home: &Path, args: &[&str]) -> String { |
| 791 | 688 | let out = Command::new("/usr/bin/git") |
| 792 | 689 | .arg("-C") |
| @@ -818,8 +715,6 @@ mod tests { | ||
| 818 | 715 | } |
| 819 | 716 | |
| 820 | 717 | impl Sandbox { |
| 821 | - /// The data dir holds the real managed gitconfig, as written at boot, so these tests see | |
| 822 | - /// the same `protocol.file.allow = never` setting that the server runs with. | |
| 823 | 718 | fn new() -> Self { |
| 824 | 719 | let dir = tempfile::tempdir().expect("tempdir"); |
| 825 | 720 | let home = dir.path().join("home"); |
| @@ -835,7 +730,6 @@ mod tests { | ||
| 835 | 730 | } |
| 836 | 731 | } |
| 837 | 732 | |
| 838 | - /// A non-bare repo named `name` with `main` checked out. | |
| 839 | 733 | fn repo(&self, name: &str) -> Work { |
| 840 | 734 | let work = self._dir.path().join(name); |
| 841 | 735 | std::fs::create_dir(&work).expect("work dir"); |
| @@ -865,7 +759,6 @@ mod tests { | ||
| 865 | 759 | std::fs::write(self.work.join(name), content).expect("write file"); |
| 866 | 760 | } |
| 867 | 761 | |
| 868 | - /// Stages everything, commits, and returns the new full id. | |
| 869 | 762 | fn commit(&self, msg: &str) -> String { |
| 870 | 763 | self.git(&["add", "-A"]); |
| 871 | 764 | self.git(&["commit", "-q", "--allow-empty", "-m", msg]); |
| @@ -1001,7 +894,6 @@ mod tests { | ||
| 1001 | 894 | let c2 = w.commit("c2"); |
| 1002 | 895 | let gd = w.git_dir(); |
| 1003 | 896 | |
| 1004 | - // The base is at c2, so a CAS expecting c0 must fail and leave the ref alone. | |
| 1005 | 897 | let stale = update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c0).await; |
| 1006 | 898 | assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}"); |
| 1007 | 899 | assert_eq!(w.git(&["rev-parse", "main"]), c2); |
| @@ -1024,7 +916,6 @@ mod tests { | ||
| 1024 | 916 | let c1 = w.commit("c1"); |
| 1025 | 917 | let gd = w.git_dir(); |
| 1026 | 918 | |
| 1027 | - // topic is at c0, so a deletion expecting c1 must fail and leave the ref alone. | |
| 1028 | 919 | let stale = delete_ref_cas(&env, &gd, "refs/heads/topic", &c1).await; |
| 1029 | 920 | assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}"); |
| 1030 | 921 | assert_eq!(w.git(&["rev-parse", "topic"]), c0); |
| @@ -1035,7 +926,6 @@ mod tests { | ||
| 1035 | 926 | let gone = w.git(&["for-each-ref", "refs/heads/topic"]); |
| 1036 | 927 | assert!(gone.is_empty(), "{gone:?}"); |
| 1037 | 928 | |
| 1038 | - // Deleting a ref that is already gone is a refusal, not a silent success. | |
| 1039 | 929 | let missing = delete_ref_cas(&env, &gd, "refs/heads/topic", &c0).await; |
| 1040 | 930 | assert!(matches!(missing, Err(Error::RefMoved(_))), "{missing:?}"); |
| 1041 | 931 | } |
| @@ -1089,7 +979,6 @@ mod tests { | ||
| 1089 | 979 | assert_eq!(diff.files[0].status, DiffStatus::Added); |
| 1090 | 980 | } |
| 1091 | 981 | |
| 1092 | - /// True when the repo at `git_dir` has `oid` in its object store. | |
| 1093 | 982 | fn has_object(git_dir: &Path, oid: &str) -> bool { |
| 1094 | 983 | Command::new("/usr/bin/git") |
| 1095 | 984 | .arg("--git-dir") |
| @@ -1111,7 +1000,6 @@ mod tests { | ||
| 1111 | 1000 | let base = sb.repo("base"); |
| 1112 | 1001 | base.write("a.txt", "1\n"); |
| 1113 | 1002 | let base_tip = base.commit("base"); |
| 1114 | - // The fork is a clone, so both histories share `base_tip`. | |
| 1115 | 1003 | let fork_dir = sb._dir.path().join("fork"); |
| 1116 | 1004 | git_in( |
| 1117 | 1005 | sb._dir.path(), |
| @@ -1128,7 +1016,6 @@ mod tests { | ||
| 1128 | 1016 | let fork_objects = fork.git_dir().join("objects"); |
| 1129 | 1017 | assert!(!has_object(&base_git, &fork_head)); |
| 1130 | 1018 | |
| 1131 | - // Without the alternate the base cannot see the fork's commit. | |
| 1132 | 1019 | assert!( |
| 1133 | 1020 | range_log(&env, &base_git, &base_tip, &fork_head, 10) |
| 1134 | 1021 | .await |
| @@ -1149,7 +1036,7 @@ mod tests { | ||
| 1149 | 1036 | .expect("merge base through alternate"); |
| 1150 | 1037 | assert_eq!(merge.as_deref(), Some(base_tip.as_str())); |
| 1151 | 1038 | |
| 1152 | - let diff = range_diff_files_with(&env, &base_git, src, &base_tip, &fork_head, LIMITS) | |
| 1039 | + let diff = range_diff_files_ws(&env, &base_git, src, &base_tip, &fork_head, LIMITS, false) | |
| 1153 | 1040 | .await |
| 1154 | 1041 | .expect("range diff through alternate"); |
| 1155 | 1042 | let paths: Vec<String> = diff |
| @@ -1159,7 +1046,6 @@ mod tests { | ||
| 1159 | 1046 | .collect(); |
| 1160 | 1047 | assert_eq!(paths, vec!["b.txt".to_owned()]); |
| 1161 | 1048 | |
| 1162 | - // Reading through the alternate wrote nothing into the base repo. | |
| 1163 | 1049 | assert!(!has_object(&base_git, &fork_head)); |
| 1164 | 1050 | } |
| 1165 | 1051 | |
| @@ -1238,7 +1124,6 @@ mod tests { | ||
| 1238 | 1124 | let a1 = blob_at(&env, &gd, &c1, "a.txt").await.expect("ok"); |
| 1239 | 1125 | assert_eq!(a1, Some(w.git(&["hash-object", "a.txt"]))); |
| 1240 | 1126 | assert_ne!(a1, Some(a0)); |
| 1241 | - // The older commit still maps to the older blob. | |
| 1242 | 1127 | let old_spec = format!("{c0}:a.txt"); |
| 1243 | 1128 | assert_eq!( |
| 1244 | 1129 | blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"), |
| @@ -1273,7 +1158,6 @@ mod tests { | ||
| 1273 | 1158 | blob_at(&env, &gd, &c0, ":colon").await.expect("ok"), |
| 1274 | 1159 | Some(w.git(&["hash-object", ":colon"])) |
| 1275 | 1160 | ); |
| 1276 | - // A glob must not match other entries. | |
| 1277 | 1161 | assert_eq!(blob_at(&env, &gd, &c0, "st*").await.expect("ok"), None); |
| 1278 | 1162 | assert_eq!(blob_at(&env, &gd, &c0, "*").await.expect("ok"), None); |
| 1279 | 1163 | } |
crates/forge-git/src/seed.rsmodified+2 -1
| @@ -6,6 +6,7 @@ use std::path::Path; | ||
| 6 | 6 | |
| 7 | 7 | use crate::command::{GitCommand, GitEnv}; |
| 8 | 8 | use crate::error::Result; |
| 9 | +use crate::history::zero_oid; | |
| 9 | 10 | use crate::repo::check_branch; |
| 10 | 11 | use crate::wiki::temp_index; |
| 11 | 12 | |
| @@ -97,7 +98,7 @@ async fn write_commit( | ||
| 97 | 98 | .arg("forge initial commit") |
| 98 | 99 | .user_arg(&format!("refs/heads/{branch}"))? |
| 99 | 100 | .user_arg(&oid)? |
| 100 | - .user_arg(&"0".repeat(oid.len()))? | |
| 101 | + .user_arg(&zero_oid(&oid))? | |
| 101 | 102 | .status() |
| 102 | 103 | .await?; |
| 103 | 104 | Ok(oid) |
crates/forge-git/src/tags.rsmodified+5 -5
| @@ -5,10 +5,10 @@ use std::path::Path; | ||
| 5 | 5 | |
| 6 | 6 | use crate::command::GitEnv; |
| 7 | 7 | use crate::error::{Error, Result}; |
| 8 | -use crate::history::{git, validate_oid}; | |
| 8 | +use crate::history::{git, validate_oid, zero_oid}; | |
| 9 | 9 | |
| 10 | 10 | /// Longest tag name, in bytes. |
| 11 | -pub const MAX_TAG_NAME_LEN: usize = 100; | |
| 11 | +const MAX_TAG_NAME_LEN: usize = 100; | |
| 12 | 12 | |
| 13 | 13 | /// True for a tag name git accepts and forge allows: ASCII letters, digits and `._-+`, with no |
| 14 | 14 | /// slash, no `..`, no leading `.` or `-`, and no trailing `.` or `.lock`. |
| @@ -16,7 +16,7 @@ pub fn valid_tag_name(name: &str) -> bool { | ||
| 16 | 16 | !name.is_empty() |
| 17 | 17 | && name.len() <= MAX_TAG_NAME_LEN |
| 18 | 18 | && !name.starts_with(['.', '-']) |
| 19 | - && !name.ends_with(['.', '/']) | |
| 19 | + && !name.ends_with('.') | |
| 20 | 20 | && !name.ends_with(".lock") |
| 21 | 21 | && !name.contains("..") |
| 22 | 22 | && name |
| @@ -37,7 +37,7 @@ pub async fn create_lightweight_tag( | ||
| 37 | 37 | } |
| 38 | 38 | validate_oid(target)?; |
| 39 | 39 | let refname = format!("refs/tags/{name}"); |
| 40 | - let zero = "0".repeat(target.len()); | |
| 40 | + let zero = zero_oid(target); | |
| 41 | 41 | git(env, "update-ref") |
| 42 | 42 | .git_dir(repo) |
| 43 | 43 | .user_arg(&refname)? |
| @@ -89,7 +89,7 @@ pub async fn previous_tag( | ||
| 89 | 89 | env: &GitEnv, |
| 90 | 90 | repo: &Path, |
| 91 | 91 | oid: &str, |
| 92 | -) -> crate::error::Result<Option<(String, String)>> { | |
| 92 | +) -> Result<Option<(String, String)>> { | |
| 93 | 93 | validate_oid(oid)?; |
| 94 | 94 | let parent = format!("{oid}^"); |
| 95 | 95 | let described = git(env, "describe") |
crates/forge-git/src/trailers.rsmodified+9 -19
| @@ -16,7 +16,7 @@ pub struct CoAuthor { | ||
| 16 | 16 | pub fn co_authors(message: &str) -> Vec<CoAuthor> { |
| 17 | 17 | let lines = lines(message); |
| 18 | 18 | let mut seen = HashSet::new(); |
| 19 | - trailer_lines(&lines) | |
| 19 | + lines[last_paragraph_start(&lines)..] | |
| 20 | 20 | .iter() |
| 21 | 21 | .filter_map(|line| parse(line)) |
| 22 | 22 | .filter(|author| seen.insert(author.email.to_lowercase())) |
| @@ -26,15 +26,14 @@ pub fn co_authors(message: &str) -> Vec<CoAuthor> { | ||
| 26 | 26 | /// The message with every `Co-authored-by:` line removed and trailing blank lines trimmed. |
| 27 | 27 | pub fn strip_co_authors(message: &str) -> String { |
| 28 | 28 | let lines = lines(message); |
| 29 | - let start = last_paragraph_start(&lines); | |
| 30 | - let kept: Vec<&str> = lines[..start] | |
| 29 | + let (head, tail) = lines.split_at(last_paragraph_start(&lines)); | |
| 30 | + let kept: Vec<&str> = head | |
| 31 | 31 | .iter() |
| 32 | 32 | .copied() |
| 33 | 33 | .chain( |
| 34 | - lines[start..] | |
| 35 | - .iter() | |
| 34 | + tail.iter() | |
| 36 | 35 | .copied() |
| 37 | - .filter(|line| !is_trailer(line)), | |
| 36 | + .filter(|line| trailer_value(line).is_none()), | |
| 38 | 37 | ) |
| 39 | 38 | .collect(); |
| 40 | 39 | kept.join("\n").trim_end().to_owned() |
| @@ -53,23 +52,14 @@ fn last_paragraph_start(lines: &[&str]) -> usize { | ||
| 53 | 52 | .map_or(0, |i| i + 1) |
| 54 | 53 | } |
| 55 | 54 | |
| 56 | -fn trailer_lines<'a>(lines: &[&'a str]) -> Vec<&'a str> { | |
| 57 | - lines[last_paragraph_start(lines)..].to_vec() | |
| 58 | -} | |
| 59 | - | |
| 60 | -/// Whether a line's key is `Co-authored-by`, in any letter case. | |
| 61 | -fn is_trailer(line: &str) -> bool { | |
| 62 | - line.split_once(':') | |
| 63 | - .is_some_and(|(key, _)| key.trim().eq_ignore_ascii_case(KEY)) | |
| 55 | +fn trailer_value(line: &str) -> Option<&str> { | |
| 56 | + let (key, value) = line.split_once(':')?; | |
| 57 | + key.trim().eq_ignore_ascii_case(KEY).then_some(value) | |
| 64 | 58 | } |
| 65 | 59 | |
| 66 | 60 | /// Parses `Co-authored-by: Name <email>`. Lines without a non-empty `<email>` give `None`. |
| 67 | 61 | fn parse(line: &str) -> Option<CoAuthor> { |
| 68 | - let (key, value) = line.trim().split_once(':')?; | |
| 69 | - if !key.trim().eq_ignore_ascii_case(KEY) { | |
| 70 | - return None; | |
| 71 | - } | |
| 72 | - let value = value.trim(); | |
| 62 | + let value = trailer_value(line.trim())?.trim(); | |
| 73 | 63 | let open = value.find('<')?; |
| 74 | 64 | let close = open + value[open..].find('>')?; |
| 75 | 65 | let email = value[open + 1..close].trim(); |
crates/forge-git/src/verify.rsmodified+2 -11
| @@ -11,6 +11,7 @@ use forge_core::store::signatures::SigKind; | ||
| 11 | 11 | |
| 12 | 12 | use crate::command::{GitCommand, GitEnv}; |
| 13 | 13 | use crate::error::{Error, Result}; |
| 14 | +use crate::history::validate_oid; | |
| 14 | 15 | |
| 15 | 16 | /// What git said about one commit's signature. |
| 16 | 17 | #[derive(Debug, Clone, PartialEq, Eq)] |
| @@ -47,19 +48,9 @@ impl RawVerify { | ||
| 47 | 48 | } |
| 48 | 49 | } |
| 49 | 50 | |
| 50 | -/// Rejects anything that is not a full hex object id, so no user text reaches git as an option. | |
| 51 | -fn check_oid(oid: &str) -> Result<()> { | |
| 52 | - let ok = (oid.len() == 40 || oid.len() == 64) && oid.bytes().all(|b| b.is_ascii_hexdigit()); | |
| 53 | - if ok { | |
| 54 | - Ok(()) | |
| 55 | - } else { | |
| 56 | - Err(Error::InvalidInput(format!("not a full object id: {oid}"))) | |
| 57 | - } | |
| 58 | -} | |
| 59 | - | |
| 60 | 51 | /// The raw commit object (`git cat-file commit <oid>`). |
| 61 | 52 | async fn commit_object(env: &GitEnv, repo: &Path, oid: &str) -> Result<Vec<u8>> { |
| 62 | - check_oid(oid)?; | |
| 53 | + validate_oid(oid)?; | |
| 63 | 54 | GitCommand::new(env, "cat-file") |
| 64 | 55 | .git_dir(repo) |
| 65 | 56 | .arg("commit") |
crates/forge-git/src/version.rsmodified+2 -2
| @@ -1,4 +1,4 @@ | ||
| 1 | -//! Git version detection. forge requires git 2.38.0 or newer. | |
| 1 | +//! Git version detection. forge requires git 2.40.0 or newer. | |
| 2 | 2 | |
| 3 | 3 | use crate::command::{GitCommand, GitEnv}; |
| 4 | 4 | use crate::error::{Error, Result}; |
| @@ -21,7 +21,7 @@ fn leading_number(s: &str) -> Option<u32> { | ||
| 21 | 21 | digits.parse().ok() |
| 22 | 22 | } |
| 23 | 23 | |
| 24 | -fn fmt_version((major, minor, patch): (u32, u32, u32)) -> String { | |
| 24 | +pub fn fmt_version((major, minor, patch): (u32, u32, u32)) -> String { | |
| 25 | 25 | format!("{major}.{minor}.{patch}") |
| 26 | 26 | } |
| 27 | 27 |
crates/forge-git/src/wiki.rsmodified+16 -9
| @@ -9,16 +9,17 @@ use std::sync::atomic::{AtomicU64, Ordering}; | ||
| 9 | 9 | use crate::browse::{EntryKind, default_branch_commit, read_text_blob, read_tree}; |
| 10 | 10 | use crate::command::{GitCommand, GitEnv}; |
| 11 | 11 | use crate::error::{Error, Result}; |
| 12 | +use crate::history::zero_oid; | |
| 12 | 13 | use crate::repo::init_bare; |
| 13 | 14 | |
| 14 | 15 | /// The branch that holds the pages. |
| 15 | 16 | pub const WIKI_BRANCH: &str = "main"; |
| 16 | 17 | /// Extension of a page file. |
| 17 | -pub const PAGE_EXT: &str = ".md"; | |
| 18 | +const PAGE_EXT: &str = ".md"; | |
| 18 | 19 | /// Largest page the editor accepts, and the largest one read back. |
| 19 | 20 | pub const MAX_PAGE_BYTES: usize = 256 * 1024; |
| 20 | 21 | /// Longest page name, in characters. |
| 21 | -pub const MAX_PAGE_NAME: usize = 100; | |
| 22 | +const MAX_PAGE_NAME: usize = 100; | |
| 22 | 23 | |
| 23 | 24 | /// One page edit. `name` is the page name without the extension. |
| 24 | 25 | #[derive(Debug, Clone, Copy)] |
| @@ -115,7 +116,7 @@ pub async fn page_history(env: &GitEnv, wiki: &Path, name: &str) -> Result<Vec<P | ||
| 115 | 116 | let out = GitCommand::new(env, "log") |
| 116 | 117 | .git_dir(wiki) |
| 117 | 118 | .arg("--format=%H%x1f%an%x1f%at%x1f%s") |
| 118 | - .arg("--max-count=200") | |
| 119 | + .user_opt("--max-count", &HISTORY_LIMIT.to_string())? | |
| 119 | 120 | .user_arg(&format!("refs/heads/{WIKI_BRANCH}"))? |
| 120 | 121 | .paths(&[file.as_str()]) |
| 121 | 122 | .output() |
| @@ -238,10 +239,9 @@ async fn write_commit( | ||
| 238 | 239 | // Compare-and-swap: the ref must still hold `base`, or be absent when there was no base. |
| 239 | 240 | let old = match base { |
| 240 | 241 | Some(base) => base.to_owned(), |
| 241 | - None => "0".repeat(oid.len()), | |
| 242 | + None => zero_oid(&oid), | |
| 242 | 243 | }; |
| 243 | - // Any failure here is treated as a lost race: the only expected cause is a concurrent edit. | |
| 244 | - GitCommand::new(env, "update-ref") | |
| 244 | + let swapped = GitCommand::new(env, "update-ref") | |
| 245 | 245 | .git_dir(wiki) |
| 246 | 246 | .arg("-m") |
| 247 | 247 | .arg("forge wiki edit") |
| @@ -249,9 +249,16 @@ async fn write_commit( | ||
| 249 | 249 | .user_arg(&oid)? |
| 250 | 250 | .user_arg(&old)? |
| 251 | 251 | .status() |
| 252 | - .await | |
| 253 | - .map_err(|_| Error::RefMoved(format!("wiki {WIKI_BRANCH} moved during the edit")))?; | |
| 254 | - Ok(oid) | |
| 252 | + .await; | |
| 253 | + match swapped { | |
| 254 | + Ok(()) => Ok(oid), | |
| 255 | + Err(Error::Failed(msg)) | |
| 256 | + if msg.contains("but expected") || msg.contains("unable to resolve reference") => | |
| 257 | + { | |
| 258 | + Err(Error::RefMoved(format!("wiki {WIKI_BRANCH} moved during the edit"))) | |
| 259 | + } | |
| 260 | + Err(e) => Err(e), | |
| 261 | + } | |
| 255 | 262 | } |
| 256 | 263 | |
| 257 | 264 | #[cfg(test)] |
crates/forge-git/tests/integration/browse.rsmodified+0 -2
| @@ -35,7 +35,6 @@ fn git(dir: &Path, args: &[&str]) -> String { | ||
| 35 | 35 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 36 | 36 | } |
| 37 | 37 | |
| 38 | -/// Builds a work repo with the real git CLI, then clones it bare so tests read a bare repo. | |
| 39 | 38 | fn fixture() -> Fixture { |
| 40 | 39 | let dir = tempfile::tempdir().unwrap(); |
| 41 | 40 | let work = dir.path().join("work"); |
| @@ -172,7 +171,6 @@ fn resolve_commit_rejects_revision_syntax_and_unknown() { | ||
| 172 | 171 | ] { |
| 173 | 172 | assert_eq!(resolve_commit(&f.bare, rev).unwrap(), None, "rev {rev:?}"); |
| 174 | 173 | } |
| 175 | - // 3 hex chars is below the minimum prefix length. | |
| 176 | 174 | assert_eq!(resolve_commit(&f.bare, &f.head[..3]).unwrap(), None); |
| 177 | 175 | } |
| 178 | 176 |
crates/forge-git/tests/integration/browse_tools.rsmodified+9 -81
| @@ -1,88 +1,16 @@ | ||
| 1 | 1 | //! Tests for the code-browsing helpers: whitespace-free diffs, patches, the recursive file list, |
| 2 | 2 | //! blame and branch operations. |
| 3 | 3 | |
| 4 | -use std::path::{Path, PathBuf}; | |
| 5 | -use std::process::Command; | |
| 6 | - | |
| 7 | -use forge_git::GitEnv; | |
| 8 | 4 | use forge_git::blame::blame; |
| 9 | 5 | use forge_git::branches::{ahead_behind, create_branch, delete_branch}; |
| 10 | 6 | use forge_git::command::ObjectSource; |
| 11 | 7 | use forge_git::history::{commit_diff_ws, commit_patch, commit_raw_diff, list_files, range_patch}; |
| 12 | 8 | |
| 13 | -use crate::common::{BIG, git_env}; | |
| 14 | - | |
| 15 | -struct Fixture { | |
| 16 | - _dir: tempfile::TempDir, | |
| 17 | - work: PathBuf, | |
| 18 | - git_dir: PathBuf, | |
| 19 | - env: GitEnv, | |
| 20 | -} | |
| 21 | - | |
| 22 | -fn run(dir: &Path, home: &Path, args: &[&str]) -> String { | |
| 23 | - let out = Command::new("/usr/bin/git") | |
| 24 | - .arg("-C") | |
| 25 | - .arg(dir) | |
| 26 | - .args([ | |
| 27 | - "-c", | |
| 28 | - "user.name=tahinli", | |
| 29 | - "-c", | |
| 30 | - "user.email=tahinli@example.com", | |
| 31 | - "-c", | |
| 32 | - "commit.gpgsign=false", | |
| 33 | - ]) | |
| 34 | - .args(args) | |
| 35 | - .env_clear() | |
| 36 | - .env("PATH", "/usr/bin:/bin") | |
| 37 | - .env("HOME", home) | |
| 38 | - .env("GIT_CONFIG_NOSYSTEM", "1") | |
| 39 | - .env("GIT_CONFIG_GLOBAL", "/dev/null") | |
| 40 | - .output() | |
| 41 | - .unwrap(); | |
| 42 | - assert!( | |
| 43 | - out.status.success(), | |
| 44 | - "{args:?} failed: {}", | |
| 45 | - String::from_utf8_lossy(&out.stderr) | |
| 46 | - ); | |
| 47 | - String::from_utf8_lossy(&out.stdout).into_owned() | |
| 48 | -} | |
| 49 | - | |
| 50 | -fn fixture() -> Fixture { | |
| 51 | - let dir = tempfile::tempdir().unwrap(); | |
| 52 | - let work = dir.path().join("work"); | |
| 53 | - std::fs::create_dir(&work).unwrap(); | |
| 54 | - run(&work, dir.path(), &["init", "-q", "-b", "main"]); | |
| 55 | - let env = git_env(dir.path()); | |
| 56 | - let git_dir = work.join(".git"); | |
| 57 | - Fixture { | |
| 58 | - _dir: dir, | |
| 59 | - work, | |
| 60 | - git_dir, | |
| 61 | - env, | |
| 62 | - } | |
| 63 | -} | |
| 64 | - | |
| 65 | -impl Fixture { | |
| 66 | - fn sh(&self, args: &[&str]) -> String { | |
| 67 | - run(&self.work, self._dir.path(), args) | |
| 68 | - } | |
| 69 | - | |
| 70 | - fn write(&self, name: &str, content: &str) { | |
| 71 | - let p = self.work.join(name); | |
| 72 | - std::fs::create_dir_all(p.parent().unwrap()).unwrap(); | |
| 73 | - std::fs::write(p, content).unwrap(); | |
| 74 | - } | |
| 75 | - | |
| 76 | - fn commit(&self, msg: &str) -> String { | |
| 77 | - self.sh(&["add", "-A"]); | |
| 78 | - self.sh(&["commit", "-q", "--allow-empty", "-m", msg]); | |
| 79 | - self.sh(&["rev-parse", "HEAD"]).trim().to_owned() | |
| 80 | - } | |
| 81 | -} | |
| 9 | +use crate::common::{BIG, WorkRepo}; | |
| 82 | 10 | |
| 83 | 11 | #[tokio::test] |
| 84 | 12 | async fn ignore_whitespace_drops_whitespace_only_files() { |
| 85 | - let f = fixture(); | |
| 13 | + let f = WorkRepo::new(); | |
| 86 | 14 | f.write("x.txt", "a\nb\n"); |
| 87 | 15 | f.write("y.txt", "c\n"); |
| 88 | 16 | f.commit("one"); |
| @@ -104,7 +32,7 @@ async fn ignore_whitespace_drops_whitespace_only_files() { | ||
| 104 | 32 | |
| 105 | 33 | #[tokio::test] |
| 106 | 34 | async fn patch_and_diff_outputs() { |
| 107 | - let f = fixture(); | |
| 35 | + let f = WorkRepo::new(); | |
| 108 | 36 | f.write("x.txt", "a\n"); |
| 109 | 37 | let root = f.commit("root commit"); |
| 110 | 38 | f.write("x.txt", "a\nb\n"); |
| @@ -139,7 +67,7 @@ async fn patch_and_diff_outputs() { | ||
| 139 | 67 | |
| 140 | 68 | #[tokio::test] |
| 141 | 69 | async fn list_files_is_recursive_and_capped() { |
| 142 | - let f = fixture(); | |
| 70 | + let f = WorkRepo::new(); | |
| 143 | 71 | f.write("a.txt", "1"); |
| 144 | 72 | f.write("dir/b.txt", "2"); |
| 145 | 73 | f.write("dir/sub/c.txt", "3"); |
| @@ -155,7 +83,7 @@ async fn list_files_is_recursive_and_capped() { | ||
| 155 | 83 | |
| 156 | 84 | #[tokio::test] |
| 157 | 85 | async fn blame_groups_by_commit() { |
| 158 | - let f = fixture(); | |
| 86 | + let f = WorkRepo::new(); | |
| 159 | 87 | f.write("f.txt", "one\ntwo\nthree\n"); |
| 160 | 88 | let first = f.commit("first"); |
| 161 | 89 | f.write("f.txt", "one\nTWO\nthree\nfour\n"); |
| @@ -189,14 +117,14 @@ async fn blame_groups_by_commit() { | ||
| 189 | 117 | |
| 190 | 118 | #[tokio::test] |
| 191 | 119 | async fn branch_counts_create_and_delete() { |
| 192 | - let f = fixture(); | |
| 120 | + let f = WorkRepo::new(); | |
| 193 | 121 | f.write("a.txt", "1"); |
| 194 | 122 | let base = f.commit("base"); |
| 195 | - f.sh(&["checkout", "-q", "-b", "feature"]); | |
| 123 | + f.git(&["checkout", "-q", "-b", "feature"]); | |
| 196 | 124 | f.write("b.txt", "2"); |
| 197 | 125 | f.commit("feature 1"); |
| 198 | 126 | let tip = f.commit("feature 2"); |
| 199 | - f.sh(&["checkout", "-q", "main"]); | |
| 127 | + f.git(&["checkout", "-q", "main"]); | |
| 200 | 128 | f.write("c.txt", "3"); |
| 201 | 129 | let main_tip = f.commit("main moved"); |
| 202 | 130 | |
| @@ -209,7 +137,7 @@ async fn branch_counts_create_and_delete() { | ||
| 209 | 137 | .await |
| 210 | 138 | .unwrap(); |
| 211 | 139 | assert_eq!( |
| 212 | - f.sh(&["rev-parse", "refs/heads/topic/x"]).trim(), | |
| 140 | + f.git(&["rev-parse", "refs/heads/topic/x"]).trim(), | |
| 213 | 141 | base.as_str() |
| 214 | 142 | ); |
| 215 | 143 | assert!( |
crates/forge-git/tests/integration/common.rsmodified+66 -0
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | use std::path::Path; |
| 4 | 4 | use std::path::PathBuf; |
| 5 | +use std::process::Command; | |
| 5 | 6 | |
| 6 | 7 | use forge_git::GitEnv; |
| 7 | 8 | use forge_git::history::DiffLimits; |
| @@ -18,3 +19,68 @@ pub fn git_env(data_dir: &Path) -> GitEnv { | ||
| 18 | 19 | data_dir: data_dir.to_path_buf(), |
| 19 | 20 | } |
| 20 | 21 | } |
| 22 | + | |
| 23 | +pub struct WorkRepo { | |
| 24 | + _dir: tempfile::TempDir, | |
| 25 | + pub work: PathBuf, | |
| 26 | + pub git_dir: PathBuf, | |
| 27 | + pub env: GitEnv, | |
| 28 | +} | |
| 29 | + | |
| 30 | +impl WorkRepo { | |
| 31 | + pub fn new() -> Self { | |
| 32 | + let dir = tempfile::tempdir().unwrap(); | |
| 33 | + let work = dir.path().join("work"); | |
| 34 | + std::fs::create_dir(&work).unwrap(); | |
| 35 | + let env = git_env(dir.path()); | |
| 36 | + let git_dir = work.join(".git"); | |
| 37 | + let repo = Self { | |
| 38 | + _dir: dir, | |
| 39 | + work, | |
| 40 | + git_dir, | |
| 41 | + env, | |
| 42 | + }; | |
| 43 | + repo.git(&["init", "-q", "-b", "main"]); | |
| 44 | + repo | |
| 45 | + } | |
| 46 | + | |
| 47 | + pub fn git(&self, args: &[&str]) -> String { | |
| 48 | + let out = Command::new("/usr/bin/git") | |
| 49 | + .arg("-C") | |
| 50 | + .arg(&self.work) | |
| 51 | + .args([ | |
| 52 | + "-c", | |
| 53 | + "user.name=tahinli", | |
| 54 | + "-c", | |
| 55 | + "user.email=tahinli@example.com", | |
| 56 | + "-c", | |
| 57 | + "commit.gpgsign=false", | |
| 58 | + ]) | |
| 59 | + .args(args) | |
| 60 | + .env_clear() | |
| 61 | + .env("PATH", "/usr/bin:/bin") | |
| 62 | + .env("HOME", self._dir.path()) | |
| 63 | + .env("GIT_CONFIG_NOSYSTEM", "1") | |
| 64 | + .env("GIT_CONFIG_GLOBAL", "/dev/null") | |
| 65 | + .output() | |
| 66 | + .unwrap(); | |
| 67 | + assert!( | |
| 68 | + out.status.success(), | |
| 69 | + "{args:?} failed: {}", | |
| 70 | + String::from_utf8_lossy(&out.stderr) | |
| 71 | + ); | |
| 72 | + String::from_utf8_lossy(&out.stdout).into_owned() | |
| 73 | + } | |
| 74 | + | |
| 75 | + pub fn write(&self, name: &str, content: impl AsRef<[u8]>) { | |
| 76 | + let p = self.work.join(name); | |
| 77 | + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); | |
| 78 | + std::fs::write(p, content).unwrap(); | |
| 79 | + } | |
| 80 | + | |
| 81 | + pub fn commit(&self, msg: &str) -> String { | |
| 82 | + self.git(&["add", "-A"]); | |
| 83 | + self.git(&["commit", "-q", "--allow-empty", "-m", msg]); | |
| 84 | + self.git(&["rev-parse", "HEAD"]).trim().to_owned() | |
| 85 | + } | |
| 86 | +} |
crates/forge-git/tests/integration/forge_git.rsmodified+11 -13
| @@ -2,7 +2,7 @@ use std::path::{Path, PathBuf}; | ||
| 2 | 2 | use std::process::Command; |
| 3 | 3 | |
| 4 | 4 | use forge_git::command::GitCommand; |
| 5 | -use forge_git::pktline::{FLUSH_PKT, pkt_line, service_advertisement_header}; | |
| 5 | +use forge_git::pktline::{pkt_line, service_advertisement_header}; | |
| 6 | 6 | use forge_git::repo::{init_bare, list_branches, repo_path}; |
| 7 | 7 | use forge_git::service::{GitService, service_command}; |
| 8 | 8 | use forge_git::setup::{write_hook_shims, write_managed_gitconfig}; |
| @@ -14,24 +14,22 @@ const ULID: &str = "01arz3ndektsv4rrffq69g5fav"; | ||
| 14 | 14 | |
| 15 | 15 | #[test] |
| 16 | 16 | fn version_parse() { |
| 17 | - assert_eq!(parse_git_version("git version 2.56.0\n"), Some((2, 56, 0))); | |
| 18 | - assert_eq!( | |
| 19 | - parse_git_version("git version 2.39.2.windows.1"), | |
| 20 | - Some((2, 39, 2)) | |
| 21 | - ); | |
| 22 | - assert_eq!(parse_git_version("git version 2.46"), Some((2, 46, 0))); | |
| 23 | - assert_eq!( | |
| 24 | - parse_git_version("git version 2.46.0-rc1"), | |
| 25 | - Some((2, 46, 0)) | |
| 26 | - ); | |
| 27 | - assert_eq!(parse_git_version("garbage"), None); | |
| 17 | + let cases = [ | |
| 18 | + ("git version 2.56.0\n", Some((2, 56, 0))), | |
| 19 | + ("git version 2.39.2.windows.1", Some((2, 39, 2))), | |
| 20 | + ("git version 2.46", Some((2, 46, 0))), | |
| 21 | + ("git version 2.46.0-rc1", Some((2, 46, 0))), | |
| 22 | + ("garbage", None), | |
| 23 | + ]; | |
| 24 | + for (input, expected) in cases { | |
| 25 | + assert_eq!(parse_git_version(input), expected, "{input:?}"); | |
| 26 | + } | |
| 28 | 27 | } |
| 29 | 28 | |
| 30 | 29 | #[test] |
| 31 | 30 | fn pkt_line_encoding() { |
| 32 | 31 | assert_eq!(pkt_line("a\n"), b"0006a\n".to_vec()); |
| 33 | 32 | assert_eq!(pkt_line(""), b"0004".to_vec()); |
| 34 | - assert_eq!(FLUSH_PKT, b"0000"); | |
| 35 | 33 | let header = service_advertisement_header(GitService::UploadPack); |
| 36 | 34 | assert_eq!(header, b"001e# service=git-upload-pack\n0000".to_vec()); |
| 37 | 35 | } |
crates/forge-git/tests/integration/history.rsmodified+11 -83
| @@ -1,85 +1,13 @@ | ||
| 1 | 1 | use std::io::Write; |
| 2 | -use std::path::{Path, PathBuf}; | |
| 3 | 2 | use std::process::{Command, Stdio}; |
| 4 | 3 | |
| 4 | +use forge_git::Error; | |
| 5 | 5 | use forge_git::history::{ |
| 6 | 6 | ArchiveFormat, CommitDiff, DiffLimits, DiffStatus, FileDiff, LineKind, archive_command, |
| 7 | 7 | commit_diff, count, last_commits, log, |
| 8 | 8 | }; |
| 9 | -use forge_git::{Error, GitEnv}; | |
| 10 | 9 | |
| 11 | -use crate::common::{BIG, git_env}; | |
| 12 | - | |
| 13 | -struct Fixture { | |
| 14 | - _dir: tempfile::TempDir, | |
| 15 | - work: PathBuf, | |
| 16 | - git_dir: PathBuf, | |
| 17 | - env: GitEnv, | |
| 18 | -} | |
| 19 | - | |
| 20 | -fn git_in(dir: &Path, home: &Path, args: &[&str]) -> String { | |
| 21 | - let out = Command::new("/usr/bin/git") | |
| 22 | - .arg("-C") | |
| 23 | - .arg(dir) | |
| 24 | - .args([ | |
| 25 | - "-c", | |
| 26 | - "user.name=Tester", | |
| 27 | - "-c", | |
| 28 | - "user.email=tester@example.com", | |
| 29 | - "-c", | |
| 30 | - "commit.gpgsign=false", | |
| 31 | - ]) | |
| 32 | - .args(args) | |
| 33 | - .env_clear() | |
| 34 | - .env("PATH", "/usr/bin:/bin") | |
| 35 | - .env("HOME", home) | |
| 36 | - .env("GIT_CONFIG_NOSYSTEM", "1") | |
| 37 | - .env("GIT_CONFIG_GLOBAL", "/dev/null") | |
| 38 | - .output() | |
| 39 | - .unwrap(); | |
| 40 | - assert!( | |
| 41 | - out.status.success(), | |
| 42 | - "git {args:?} failed: {}", | |
| 43 | - String::from_utf8_lossy(&out.stderr) | |
| 44 | - ); | |
| 45 | - String::from_utf8_lossy(&out.stdout).into_owned() | |
| 46 | -} | |
| 47 | - | |
| 48 | -fn fixture() -> Fixture { | |
| 49 | - let dir = tempfile::tempdir().unwrap(); | |
| 50 | - let work = dir.path().join("work"); | |
| 51 | - std::fs::create_dir(&work).unwrap(); | |
| 52 | - git_in(&work, dir.path(), &["init", "-q", "-b", "main"]); | |
| 53 | - let env = git_env(dir.path()); | |
| 54 | - let git_dir = work.join(".git"); | |
| 55 | - Fixture { | |
| 56 | - _dir: dir, | |
| 57 | - work, | |
| 58 | - git_dir, | |
| 59 | - env, | |
| 60 | - } | |
| 61 | -} | |
| 62 | - | |
| 63 | -impl Fixture { | |
| 64 | - fn git(&self, args: &[&str]) -> String { | |
| 65 | - git_in(&self.work, self._dir.path(), args) | |
| 66 | - } | |
| 67 | - | |
| 68 | - fn write(&self, name: &str, content: impl AsRef<[u8]>) { | |
| 69 | - let p = self.work.join(name); | |
| 70 | - if let Some(parent) = p.parent() { | |
| 71 | - std::fs::create_dir_all(parent).unwrap(); | |
| 72 | - } | |
| 73 | - std::fs::write(p, content).unwrap(); | |
| 74 | - } | |
| 75 | - | |
| 76 | - /// Stages everything, commits, and returns the new full oid. | |
| 77 | - fn commit(&self, msg: &str) -> String { | |
| 78 | - self.git(&["add", "-A"]); | |
| 79 | - self.git(&["commit", "-q", "--allow-empty", "-m", msg]); | |
| 80 | - self.git(&["rev-parse", "HEAD"]).trim().to_owned() | |
| 81 | - } | |
| 82 | -} | |
| 10 | +use crate::common::{BIG, WorkRepo}; | |
| 83 | 11 | |
| 84 | 12 | fn find<'a>(diff: &'a CommitDiff, path: &str) -> &'a FileDiff { |
| 85 | 13 | diff.files |
| @@ -94,7 +22,7 @@ fn summaries(commits: &[forge_git::browse::CommitInfo]) -> Vec<&str> { | ||
| 94 | 22 | |
| 95 | 23 | #[tokio::test] |
| 96 | 24 | async fn log_path_filter_and_pagination() { |
| 97 | - let f = fixture(); | |
| 25 | + let f = WorkRepo::new(); | |
| 98 | 26 | f.write("a.txt", "1\n"); |
| 99 | 27 | f.commit("add a"); |
| 100 | 28 | f.write("b.txt", "1\n"); |
| @@ -126,7 +54,7 @@ async fn log_path_filter_and_pagination() { | ||
| 126 | 54 | |
| 127 | 55 | #[tokio::test] |
| 128 | 56 | async fn commit_diff_modify_add_delete_rename_binary() { |
| 129 | - let f = fixture(); | |
| 57 | + let f = WorkRepo::new(); | |
| 130 | 58 | f.write("a.txt", "one\ntwo\n"); |
| 131 | 59 | f.write("gone.txt", "bye\n"); |
| 132 | 60 | f.write("old.txt", "alpha\nbeta\ngamma\ndelta\nepsilon\n"); |
| @@ -174,7 +102,7 @@ async fn commit_diff_modify_add_delete_rename_binary() { | ||
| 174 | 102 | |
| 175 | 103 | #[tokio::test] |
| 176 | 104 | async fn commit_diff_line_numbers_on_known_hunk() { |
| 177 | - let f = fixture(); | |
| 105 | + let f = WorkRepo::new(); | |
| 178 | 106 | f.write("n.txt", "l1\nl2\nl3\nl4\nl5\n"); |
| 179 | 107 | f.commit("base"); |
| 180 | 108 | f.write("n.txt", "l1\nl2\nX3\nl4\nl5\nl6\n"); |
| @@ -207,7 +135,7 @@ async fn commit_diff_line_numbers_on_known_hunk() { | ||
| 207 | 135 | |
| 208 | 136 | #[tokio::test] |
| 209 | 137 | async fn commit_diff_root_commit_uses_empty_tree() { |
| 210 | - let f = fixture(); | |
| 138 | + let f = WorkRepo::new(); | |
| 211 | 139 | f.write("a.txt", "x\ny\n"); |
| 212 | 140 | f.write("d/b.txt", "z\n"); |
| 213 | 141 | let oid = f.commit("root"); |
| @@ -225,7 +153,7 @@ async fn commit_diff_root_commit_uses_empty_tree() { | ||
| 225 | 153 | |
| 226 | 154 | #[tokio::test] |
| 227 | 155 | async fn commit_diff_limits_truncate() { |
| 228 | - let f = fixture(); | |
| 156 | + let f = WorkRepo::new(); | |
| 229 | 157 | let old: String = (0..10).map(|i| format!("old{i}\n")).collect(); |
| 230 | 158 | f.write("big.txt", &old); |
| 231 | 159 | f.commit("base"); |
| @@ -272,7 +200,7 @@ async fn commit_diff_limits_truncate() { | ||
| 272 | 200 | |
| 273 | 201 | #[tokio::test] |
| 274 | 202 | async fn last_commits_finds_newest_touch_per_child() { |
| 275 | - let f = fixture(); | |
| 203 | + let f = WorkRepo::new(); | |
| 276 | 204 | f.write("d/x.txt", "1\n"); |
| 277 | 205 | f.commit("c1 add x"); |
| 278 | 206 | f.write("d/y.txt", "1\n"); |
| @@ -317,7 +245,7 @@ async fn last_commits_finds_newest_touch_per_child() { | ||
| 317 | 245 | |
| 318 | 246 | #[tokio::test] |
| 319 | 247 | async fn count_counts_all_commits_or_those_touching_a_path() { |
| 320 | - let f = fixture(); | |
| 248 | + let f = WorkRepo::new(); | |
| 321 | 249 | f.write("d/x.txt", "1\n"); |
| 322 | 250 | f.commit("c1 add x"); |
| 323 | 251 | f.write("d/y.txt", "1\n"); |
| @@ -354,7 +282,7 @@ async fn count_counts_all_commits_or_those_touching_a_path() { | ||
| 354 | 282 | |
| 355 | 283 | #[tokio::test] |
| 356 | 284 | async fn archive_command_produces_listable_tar_gz() { |
| 357 | - let f = fixture(); | |
| 285 | + let f = WorkRepo::new(); | |
| 358 | 286 | f.write("a.txt", "hello\n"); |
| 359 | 287 | f.write("d/b.txt", "world\n"); |
| 360 | 288 | let oid = f.commit("archive me"); |
| @@ -381,7 +309,7 @@ async fn archive_command_produces_listable_tar_gz() { | ||
| 381 | 309 | |
| 382 | 310 | #[tokio::test] |
| 383 | 311 | async fn non_hex_commit_arguments_are_rejected() { |
| 384 | - let f = fixture(); | |
| 312 | + let f = WorkRepo::new(); | |
| 385 | 313 | f.write("a.txt", "1\n"); |
| 386 | 314 | let oid = f.commit("one"); |
| 387 | 315 |
crates/forge-git/tests/integration/main.rsmodified+0 -1
| @@ -1,6 +1,5 @@ | ||
| 1 | 1 | //! forge-git integration tests. All modules compile into this single test binary. |
| 2 | 2 | |
| 3 | -#[allow(dead_code)] | |
| 4 | 3 | mod common; |
| 5 | 4 | |
| 6 | 5 | mod browse; |
crates/forge-ssh/src/backend.rsmodified+4 -5
| @@ -4,7 +4,7 @@ use std::future::Future; | ||
| 4 | 4 | |
| 5 | 5 | use forge_git::GitService; |
| 6 | 6 | |
| 7 | -use crate::parse::LfsOperation; | |
| 7 | +use crate::parse::{LfsOperation, RepoPath}; | |
| 8 | 8 | |
| 9 | 9 | /// Implemented by forge-web. The SSH server holds it in an `Arc`. |
| 10 | 10 | pub trait GitBackend: Send + Sync + 'static { |
| @@ -21,17 +21,16 @@ pub trait GitBackend: Send + Sync + 'static { | ||
| 21 | 21 | &self, |
| 22 | 22 | user_id: &str, |
| 23 | 23 | service: GitService, |
| 24 | - repo_path: &str, | |
| 24 | + repo_path: &RepoPath, | |
| 25 | 25 | git_protocol: Option<&str>, |
| 26 | 26 | ) -> impl Future<Output = Result<tokio::process::Command, String>> + Send; |
| 27 | 27 | |
| 28 | 28 | /// Authorizes a `git-lfs-authenticate` request and returns the JSON reply for stdout. |
| 29 | - /// `repo_path` is `owner/repo` with `.git` stripped. `Err` sends the message on stderr | |
| 30 | - /// and exits 1. | |
| 29 | + /// `Err` sends the message on stderr and exits 1. | |
| 31 | 30 | fn lfs_authenticate( |
| 32 | 31 | &self, |
| 33 | 32 | user_id: &str, |
| 34 | - repo_path: &str, | |
| 33 | + repo_path: &RepoPath, | |
| 35 | 34 | operation: LfsOperation, |
| 36 | 35 | ) -> impl Future<Output = Result<String, String>> + Send; |
| 37 | 36 | } |
crates/forge-ssh/src/lib.rsmodified+5 -5
| @@ -1,11 +1,11 @@ | ||
| 1 | 1 | //! git-over-SSH server for forge, built on russh. |
| 2 | 2 | |
| 3 | -pub mod backend; | |
| 4 | -pub mod error; | |
| 5 | -pub mod parse; | |
| 6 | -pub mod server; | |
| 3 | +mod backend; | |
| 4 | +mod error; | |
| 5 | +mod parse; | |
| 6 | +mod server; | |
| 7 | 7 | |
| 8 | 8 | pub use backend::GitBackend; |
| 9 | 9 | pub use error::{Error, Result}; |
| 10 | -pub use parse::{LfsOperation, ParseError, parse_exec, parse_lfs_authenticate}; | |
| 10 | +pub use parse::{LfsOperation, RepoPath}; | |
| 11 | 11 | pub use server::{SshConfig, run}; |
crates/forge-ssh/src/parse.rsmodified+22 -19
| @@ -23,9 +23,15 @@ const PREFIXES: &[(&str, GitService)] = &[ | ||
| 23 | 23 | ("git receive-pack ", GitService::ReceivePack), |
| 24 | 24 | ]; |
| 25 | 25 | |
| 26 | -/// Returns the service and the repository path with `.git` stripped and the | |
| 27 | -/// leading `/` or `~/` removed. Anything else is an error. | |
| 28 | -pub fn parse_exec(cmd: &str) -> Result<(GitService, String), ParseError> { | |
| 26 | +/// Owner and repository name with `.git` stripped and the leading `/` or `~/` removed. | |
| 27 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 28 | +pub struct RepoPath { | |
| 29 | + pub owner: String, | |
| 30 | + pub name: String, | |
| 31 | +} | |
| 32 | + | |
| 33 | +/// Returns the service and the repository path. Anything else is an error. | |
| 34 | +pub(crate) fn parse_exec(cmd: &str) -> Result<(GitService, RepoPath), ParseError> { | |
| 29 | 35 | let (service, rest) = split_service(cmd)?; |
| 30 | 36 | let raw = unquote_argument(rest)?; |
| 31 | 37 | let path = normalize_path(raw)?; |
| @@ -44,20 +50,14 @@ pub enum LfsOperation { | ||
| 44 | 50 | |
| 45 | 51 | /// Parses `git-lfs-authenticate '<owner>/<repo>[.git]' download|upload`. The path follows the |
| 46 | 52 | /// same rules as `parse_exec`, and the operation must be exactly `download` or `upload`. |
| 47 | -pub fn parse_lfs_authenticate(cmd: &str) -> Result<(String, LfsOperation), ParseError> { | |
| 53 | +pub(crate) fn parse_lfs_authenticate(cmd: &str) -> Result<(RepoPath, LfsOperation), ParseError> { | |
| 48 | 54 | let rest = cmd |
| 49 | 55 | .strip_prefix(LFS_AUTHENTICATE_PREFIX) |
| 50 | 56 | .ok_or(ParseError::UnsupportedCommand)?; |
| 51 | - // The path argument ends at its closing quote, or at the first space when it is bare. | |
| 52 | - let end = if let Some(quoted) = rest.strip_prefix('\'') { | |
| 53 | - quoted.find('\'').ok_or(ParseError::MalformedPath)? + 2 | |
| 54 | - } else { | |
| 55 | - rest.find(' ').ok_or(ParseError::MalformedPath)? | |
| 56 | - }; | |
| 57 | - let (arg, tail) = rest.split_at(end); | |
| 58 | - let operation = match tail { | |
| 59 | - " download" => LfsOperation::Download, | |
| 60 | - " upload" => LfsOperation::Upload, | |
| 57 | + let (arg, op) = rest.rsplit_once(' ').ok_or(ParseError::MalformedPath)?; | |
| 58 | + let operation = match op { | |
| 59 | + "download" => LfsOperation::Download, | |
| 60 | + "upload" => LfsOperation::Upload, | |
| 61 | 61 | _ => return Err(ParseError::MalformedPath), |
| 62 | 62 | }; |
| 63 | 63 | let path = normalize_path(unquote_argument(arg)?)?; |
| @@ -96,8 +96,8 @@ fn unquote_argument(rest: &str) -> Result<&str, ParseError> { | ||
| 96 | 96 | } |
| 97 | 97 | |
| 98 | 98 | /// Strips one leading `/` or `~/`, then requires exactly `owner/repo` or |
| 99 | -/// `owner/repo.git`, returning `owner/repo`. | |
| 100 | -fn normalize_path(raw: &str) -> Result<String, ParseError> { | |
| 99 | +/// `owner/repo.git`. | |
| 100 | +fn normalize_path(raw: &str) -> Result<RepoPath, ParseError> { | |
| 101 | 101 | let path = raw.strip_prefix('/').unwrap_or(raw); |
| 102 | 102 | let path = path.strip_prefix("~/").unwrap_or(path); |
| 103 | 103 | |
| @@ -122,7 +122,10 @@ fn normalize_path(raw: &str) -> Result<String, ParseError> { | ||
| 122 | 122 | if repo.is_empty() { |
| 123 | 123 | return Err(ParseError::MalformedPath); |
| 124 | 124 | } |
| 125 | - Ok(format!("{owner}/{repo}")) | |
| 125 | + Ok(RepoPath { | |
| 126 | + owner: owner.to_string(), | |
| 127 | + name: repo.to_string(), | |
| 128 | + }) | |
| 126 | 129 | } |
| 127 | 130 | |
| 128 | 131 | #[cfg(test)] |
| @@ -131,7 +134,7 @@ mod tests { | ||
| 131 | 134 | |
| 132 | 135 | fn ok(cmd: &str) -> (GitService, String) { |
| 133 | 136 | match parse_exec(cmd) { |
| 134 | - Ok(v) => v, | |
| 137 | + Ok((service, path)) => (service, format!("{}/{}", path.owner, path.name)), | |
| 135 | 138 | Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"), |
| 136 | 139 | } |
| 137 | 140 | } |
| @@ -293,7 +296,7 @@ mod tests { | ||
| 293 | 296 | |
| 294 | 297 | fn lfs_ok(cmd: &str) -> (String, LfsOperation) { |
| 295 | 298 | match parse_lfs_authenticate(cmd) { |
| 296 | - Ok(v) => v, | |
| 299 | + Ok((path, operation)) => (format!("{}/{}", path.owner, path.name), operation), | |
| 297 | 300 | Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"), |
| 298 | 301 | } |
| 299 | 302 | } |
crates/forge-ssh/src/server.rsmodified+30 -77
| @@ -1,5 +1,3 @@ | ||
| 1 | -//! russh server: host key, pubkey auth, exec and env handling, piping, timeouts. | |
| 2 | - | |
| 3 | 1 | use std::borrow::Cow; |
| 4 | 2 | use std::collections::HashMap; |
| 5 | 3 | use std::fs::OpenOptions; |
| @@ -30,28 +28,20 @@ use crate::backend::GitBackend; | ||
| 30 | 28 | use crate::error::{Error, Result}; |
| 31 | 29 | use crate::parse::{LFS_AUTHENTICATE_PREFIX, parse_exec, parse_lfs_authenticate}; |
| 32 | 30 | |
| 33 | -/// Stdout and stderr read size per message sent to the client. | |
| 34 | 31 | const PUMP_CHUNK: usize = 32 * 1024; |
| 35 | -/// Client input chunks buffered in front of the child's stdin. This bounds memory and | |
| 36 | -/// propagates backpressure to the SSH read loop. | |
| 37 | 32 | const STDIN_QUEUE: usize = 8; |
| 38 | -/// Failed publickey attempts before the connection is dropped. | |
| 39 | 33 | const MAX_AUTH_ATTEMPTS: usize = 6; |
| 40 | -/// Connections served at once, counting unauthenticated ones. Each can hold a russh packet | |
| 41 | -/// buffer of up to 256 KiB before auth, so this bounds that memory. | |
| 42 | 34 | const MAX_CONNECTIONS: usize = 256; |
| 35 | +const AUTH_TIMEOUT: Duration = Duration::from_secs(30); | |
| 36 | +const INACTIVITY_TIMEOUT: Duration = Duration::from_secs(10 * 60); | |
| 43 | 37 | |
| 44 | 38 | #[derive(Debug, Clone)] |
| 45 | 39 | pub struct SshConfig { |
| 46 | 40 | pub listen: SocketAddr, |
| 47 | 41 | pub host_key_path: PathBuf, |
| 48 | - pub auth_timeout: Duration, | |
| 49 | - pub inactivity_timeout: Duration, | |
| 50 | - /// Delay before a failed authentication attempt is answered (forge-web: `ssh_auth_rejection_secs`). | |
| 51 | 42 | pub auth_rejection_time: Duration, |
| 52 | 43 | } |
| 53 | 44 | |
| 54 | -/// Runs the SSH server until it fails. Creates the ed25519 host key on first boot. | |
| 55 | 45 | pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()> { |
| 56 | 46 | let host_key = load_or_create_host_key(&config.host_key_path)?; |
| 57 | 47 | let russh_config = Arc::new(Config { |
| @@ -59,7 +49,7 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<() | ||
| 59 | 49 | methods: publickey_only(), |
| 60 | 50 | auth_rejection_time: config.auth_rejection_time, |
| 61 | 51 | max_auth_attempts: MAX_AUTH_ATTEMPTS, |
| 62 | - inactivity_timeout: Some(config.inactivity_timeout), | |
| 52 | + inactivity_timeout: Some(INACTIVITY_TIMEOUT), | |
| 63 | 53 | preferred: preferred_algorithms(), |
| 64 | 54 | ..Config::default() |
| 65 | 55 | }); |
| @@ -72,13 +62,11 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<() | ||
| 72 | 62 | let (stream, peer) = match listener.accept().await { |
| 73 | 63 | Ok(v) => v, |
| 74 | 64 | Err(e) => { |
| 75 | - // Typically EMFILE. Back off briefly instead of tearing the server down. | |
| 76 | 65 | tracing::warn!(error = %e, "ssh accept failed"); |
| 77 | 66 | tokio::time::sleep(Duration::from_millis(100)).await; |
| 78 | 67 | continue; |
| 79 | 68 | } |
| 80 | 69 | }; |
| 81 | - // At the limit the socket is dropped at once rather than queued. | |
| 82 | 70 | let Ok(permit) = connection_slots.clone().try_acquire_owned() else { |
| 83 | 71 | tracing::warn!(%peer, "ssh connection limit reached, dropping connection"); |
| 84 | 72 | continue; |
| @@ -86,28 +74,34 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<() | ||
| 86 | 74 | let authed = Arc::new(AtomicBool::new(false)); |
| 87 | 75 | let client = Client { |
| 88 | 76 | backend: Arc::clone(&backend), |
| 89 | - peer: Some(peer), | |
| 77 | + peer, | |
| 90 | 78 | authed: Arc::clone(&authed), |
| 91 | 79 | user_id: None, |
| 92 | 80 | git_protocol: None, |
| 93 | 81 | channels: HashMap::new(), |
| 94 | 82 | }; |
| 95 | 83 | let russh_config = Arc::clone(&russh_config); |
| 96 | - let auth_timeout = config.auth_timeout; | |
| 97 | 84 | tokio::spawn(async move { |
| 98 | - // Held until the connection ends, then the slot is free for the next client. | |
| 99 | 85 | let _permit = permit; |
| 100 | - let running = match run_stream(russh_config, stream, client).await { | |
| 101 | - Ok(running) => running, | |
| 102 | - Err(e) => { | |
| 86 | + let running = match tokio::time::timeout( | |
| 87 | + AUTH_TIMEOUT, | |
| 88 | + run_stream(russh_config, stream, client), | |
| 89 | + ) | |
| 90 | + .await | |
| 91 | + { | |
| 92 | + Ok(Ok(running)) => running, | |
| 93 | + Ok(Err(e)) => { | |
| 103 | 94 | tracing::debug!(%peer, error = %e, "ssh handshake failed"); |
| 104 | 95 | return; |
| 105 | 96 | } |
| 97 | + Err(_) => { | |
| 98 | + tracing::debug!(%peer, "ssh handshake timed out"); | |
| 99 | + return; | |
| 100 | + } | |
| 106 | 101 | }; |
| 107 | - // Drop unauthenticated connections after the auth timeout. | |
| 108 | 102 | let handle = running.handle(); |
| 109 | 103 | tokio::spawn(async move { |
| 110 | - tokio::time::sleep(auth_timeout).await; | |
| 104 | + tokio::time::sleep(AUTH_TIMEOUT).await; | |
| 111 | 105 | if !authed.load(Ordering::Acquire) { |
| 112 | 106 | let _ = handle |
| 113 | 107 | .disconnect( |
| @@ -125,14 +119,12 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<() | ||
| 125 | 119 | } |
| 126 | 120 | } |
| 127 | 121 | |
| 128 | -/// Publickey is the only accepted method. | |
| 129 | 122 | fn publickey_only() -> MethodSet { |
| 130 | 123 | let mut methods = MethodSet::empty(); |
| 131 | 124 | methods.push(MethodKind::PublicKey); |
| 132 | 125 | methods |
| 133 | 126 | } |
| 134 | 127 | |
| 135 | -/// Host and user key algorithms this server negotiates. RSA is not listed: russh is built without it. | |
| 136 | 128 | fn preferred_algorithms() -> Preferred { |
| 137 | 129 | Preferred { |
| 138 | 130 | key: Cow::Owned(vec![ |
| @@ -153,7 +145,6 @@ fn preferred_algorithms() -> Preferred { | ||
| 153 | 145 | } |
| 154 | 146 | } |
| 155 | 147 | |
| 156 | -/// Key types accepted for authentication. RSA keys are refused, as they are when a key is added. | |
| 157 | 148 | fn key_type_allowed(algorithm: &Algorithm) -> bool { |
| 158 | 149 | matches!( |
| 159 | 150 | algorithm, |
| @@ -164,7 +155,6 @@ fn key_type_allowed(algorithm: &Algorithm) -> bool { | ||
| 164 | 155 | ) |
| 165 | 156 | } |
| 166 | 157 | |
| 167 | -/// Accepts exactly `version=<digit>`, e.g. `version=2`. | |
| 168 | 158 | fn valid_git_protocol(value: &str) -> bool { |
| 169 | 159 | let bytes = value.as_bytes(); |
| 170 | 160 | bytes.len() == 9 && value.starts_with("version=") && bytes[8].is_ascii_digit() |
| @@ -191,7 +181,6 @@ fn load_or_create_host_key(path: &Path) -> Result<PrivateKey> { | ||
| 191 | 181 | if let Some(parent) = path.parent() { |
| 192 | 182 | std::fs::create_dir_all(parent)?; |
| 193 | 183 | } |
| 194 | - // create_new so an existing key is never overwritten. The mode applies at creation. | |
| 195 | 184 | let mut file = OpenOptions::new() |
| 196 | 185 | .write(true) |
| 197 | 186 | .create_new(true) |
| @@ -204,15 +193,12 @@ fn load_or_create_host_key(path: &Path) -> Result<PrivateKey> { | ||
| 204 | 193 | Ok(key) |
| 205 | 194 | } |
| 206 | 195 | |
| 207 | -/// Per-connection SSH handler. | |
| 208 | 196 | struct Client<B> { |
| 209 | 197 | backend: Arc<B>, |
| 210 | - peer: Option<SocketAddr>, | |
| 198 | + peer: SocketAddr, | |
| 211 | 199 | authed: Arc<AtomicBool>, |
| 212 | 200 | user_id: Option<String>, |
| 213 | 201 | git_protocol: Option<String>, |
| 214 | - /// Open exec channels. Entries are removed on channel EOF or close, which drops the | |
| 215 | - /// sender and closes the child's stdin. | |
| 216 | 202 | channels: HashMap<ChannelId, mpsc::Sender<Bytes>>, |
| 217 | 203 | } |
| 218 | 204 | |
| @@ -227,8 +213,6 @@ impl<B: GitBackend> Client<B> { | ||
| 227 | 213 | .await |
| 228 | 214 | } |
| 229 | 215 | |
| 230 | - /// Answers `git-lfs-authenticate` with the JSON reply on stdout and exit status 0. Nothing is | |
| 231 | - /// left open afterwards: the channel is closed once the reply is queued. | |
| 232 | 216 | async fn exec_lfs_authenticate( |
| 233 | 217 | &self, |
| 234 | 218 | session: &mut Session, |
| @@ -265,7 +249,6 @@ impl<B: GitBackend> Handler for Client<B> { | ||
| 265 | 249 | _user: &str, |
| 266 | 250 | offer: PublicKeyOffer<'_>, |
| 267 | 251 | ) -> std::result::Result<Auth, Self::Error> { |
| 268 | - // Probe before the client signs. Reject early so unknown keys never get a signature. | |
| 269 | 252 | if self.lookup(offer.public_key).await.is_some() { |
| 270 | 253 | Ok(Auth::Accept) |
| 271 | 254 | } else { |
| @@ -280,7 +263,7 @@ impl<B: GitBackend> Handler for Client<B> { | ||
| 280 | 263 | ) -> std::result::Result<Auth, Self::Error> { |
| 281 | 264 | match self.lookup(verified.public_key).await { |
| 282 | 265 | Some(user_id) => { |
| 283 | - tracing::info!(peer = ?self.peer, %user_id, "ssh publickey auth accepted"); | |
| 266 | + tracing::info!(peer = %self.peer, %user_id, "ssh publickey auth accepted"); | |
| 284 | 267 | self.user_id = Some(user_id); |
| 285 | 268 | self.authed.store(true, Ordering::Release); |
| 286 | 269 | Ok(Auth::Accept) |
| @@ -312,7 +295,6 @@ impl<B: GitBackend> Handler for Client<B> { | ||
| 312 | 295 | variable_value: &str, |
| 313 | 296 | _session: &mut Session, |
| 314 | 297 | ) -> std::result::Result<(), Self::Error> { |
| 315 | - // Only GIT_PROTOCOL is kept. Everything else is ignored, never forwarded. | |
| 316 | 298 | if variable_name == "GIT_PROTOCOL" && valid_git_protocol(variable_value) { |
| 317 | 299 | self.git_protocol = Some(variable_value.to_owned()); |
| 318 | 300 | } |
| @@ -382,7 +364,6 @@ impl<B: GitBackend> Handler for Client<B> { | ||
| 382 | 364 | _session: &mut Session, |
| 383 | 365 | ) -> std::result::Result<(), Self::Error> { |
| 384 | 366 | if let Some(tx) = self.channels.get(&channel) { |
| 385 | - // Err means the child has exited. Its output is still flushed, so this is not fatal. | |
| 386 | 367 | let _ = tx.send(Bytes::copy_from_slice(data)).await; |
| 387 | 368 | } |
| 388 | 369 | Ok(()) |
| @@ -452,27 +433,8 @@ impl<B: GitBackend> Handler for Client<B> { | ||
| 452 | 433 | session.channel_failure(channel)?; |
| 453 | 434 | Ok(()) |
| 454 | 435 | } |
| 455 | - | |
| 456 | - async fn tcpip_forward( | |
| 457 | - &mut self, | |
| 458 | - _address: &str, | |
| 459 | - _port: &mut u32, | |
| 460 | - _session: &mut Session, | |
| 461 | - ) -> std::result::Result<bool, Self::Error> { | |
| 462 | - Ok(false) | |
| 463 | - } | |
| 464 | - | |
| 465 | - async fn agent_request( | |
| 466 | - &mut self, | |
| 467 | - _channel: ChannelId, | |
| 468 | - _session: &mut Session, | |
| 469 | - ) -> std::result::Result<bool, Self::Error> { | |
| 470 | - Ok(false) | |
| 471 | - } | |
| 472 | 436 | } |
| 473 | 437 | |
| 474 | -/// Sends a rejection as the spec requires: the message on stderr, exit status 1, then EOF and close. | |
| 475 | -/// The request itself is acknowledged so git reads the message instead of failing at the protocol level. | |
| 476 | 438 | fn reject_exec( |
| 477 | 439 | session: &mut Session, |
| 478 | 440 | channel: ChannelId, |
| @@ -486,27 +448,29 @@ fn reject_exec( | ||
| 486 | 448 | Ok(()) |
| 487 | 449 | } |
| 488 | 450 | |
| 489 | -/// Runs one git process for an exec channel. Stdin is fed from `stdin_rx`, stdout goes to | |
| 490 | -/// channel data and stderr to extended data 1. Exit status, EOF and close are sent last. | |
| 491 | 451 | async fn run_child( |
| 492 | 452 | handle: Handle, |
| 493 | 453 | channel: ChannelId, |
| 494 | 454 | mut child: Child, |
| 495 | 455 | stdin_rx: mpsc::Receiver<Bytes>, |
| 496 | 456 | ) { |
| 497 | - // Raised by a pump when the client has gone away, so the child is killed. | |
| 498 | 457 | let abort = Arc::new(Notify::new()); |
| 458 | + let (Some(stdin), Some(stdout), Some(stderr)) = | |
| 459 | + (child.stdin.take(), child.stdout.take(), child.stderr.take()) | |
| 460 | + else { | |
| 461 | + return; | |
| 462 | + }; | |
| 499 | 463 | |
| 500 | - let feeder = tokio::spawn(feed_stdin(child.stdin.take(), stdin_rx)); | |
| 464 | + let feeder = tokio::spawn(feed_stdin(stdin, stdin_rx)); | |
| 501 | 465 | let stdout_task = tokio::spawn(pump( |
| 502 | - child.stdout.take(), | |
| 466 | + stdout, | |
| 503 | 467 | handle.clone(), |
| 504 | 468 | channel, |
| 505 | 469 | None, |
| 506 | 470 | Arc::clone(&abort), |
| 507 | 471 | )); |
| 508 | 472 | let stderr_task = tokio::spawn(pump( |
| 509 | - child.stderr.take(), | |
| 473 | + stderr, | |
| 510 | 474 | handle.clone(), |
| 511 | 475 | channel, |
| 512 | 476 | Some(1), |
| @@ -521,7 +485,6 @@ async fn run_child( | ||
| 521 | 485 | } |
| 522 | 486 | }; |
| 523 | 487 | |
| 524 | - // Wait for the pumps so every byte of output is queued before exit status and EOF. | |
| 525 | 488 | let _ = stdout_task.await; |
| 526 | 489 | let _ = stderr_task.await; |
| 527 | 490 | feeder.abort(); |
| @@ -531,23 +494,17 @@ async fn run_child( | ||
| 531 | 494 | let _ = handle.close(channel).await; |
| 532 | 495 | } |
| 533 | 496 | |
| 534 | -async fn feed_stdin(stdin: Option<ChildStdin>, mut rx: mpsc::Receiver<Bytes>) { | |
| 535 | - let Some(mut stdin) = stdin else { | |
| 536 | - return; | |
| 537 | - }; | |
| 497 | +async fn feed_stdin(mut stdin: ChildStdin, mut rx: mpsc::Receiver<Bytes>) { | |
| 538 | 498 | while let Some(chunk) = rx.recv().await { |
| 539 | 499 | if stdin.write_all(&chunk).await.is_err() { |
| 540 | 500 | break; |
| 541 | 501 | } |
| 542 | 502 | } |
| 543 | - // Dropping stdin here closes the child's input. | |
| 544 | 503 | let _ = stdin.shutdown().await; |
| 545 | 504 | } |
| 546 | 505 | |
| 547 | -/// Forwards one child output stream to the client. `ext` = Some(n) sends extended data | |
| 548 | -/// type n. Sets `abort` when the client has gone away. | |
| 549 | 506 | async fn pump<R>( |
| 550 | - reader: Option<R>, | |
| 507 | + mut reader: R, | |
| 551 | 508 | handle: Handle, |
| 552 | 509 | channel: ChannelId, |
| 553 | 510 | ext: Option<u32>, |
| @@ -555,17 +512,13 @@ async fn pump<R>( | ||
| 555 | 512 | ) where |
| 556 | 513 | R: AsyncRead + Unpin + Send + 'static, |
| 557 | 514 | { |
| 558 | - let Some(mut reader) = reader else { | |
| 559 | - return; | |
| 560 | - }; | |
| 561 | 515 | let mut buf = vec![0u8; PUMP_CHUNK]; |
| 562 | 516 | loop { |
| 563 | 517 | let n = match reader.read(&mut buf).await { |
| 564 | 518 | Ok(0) | Err(_) => break, |
| 565 | 519 | Ok(n) => n, |
| 566 | 520 | }; |
| 567 | - // A right-sized copy: a chunk queued for the client holds only the bytes read. | |
| 568 | - let chunk = Bytes::copy_from_slice(buf.get(..n).unwrap_or_default()); | |
| 521 | + let chunk = Bytes::copy_from_slice(&buf[..n]); | |
| 569 | 522 | let sent = match ext { |
| 570 | 523 | None => handle.data(channel, chunk).await.is_ok(), |
| 571 | 524 | Some(kind) => handle.extended_data(channel, kind, chunk).await.is_ok(), |
crates/forge-ssh/tests/ssh_e2e.rsmodified+7 -8
| @@ -8,7 +8,7 @@ use std::process::Output; | ||
| 8 | 8 | use std::time::Duration; |
| 9 | 9 | |
| 10 | 10 | use forge_git::GitService; |
| 11 | -use forge_ssh::{GitBackend, LfsOperation, SshConfig}; | |
| 11 | +use forge_ssh::{GitBackend, LfsOperation, RepoPath, SshConfig}; | |
| 12 | 12 | use russh::keys::PublicKey; |
| 13 | 13 | use tokio::process::Command; |
| 14 | 14 | |
| @@ -30,7 +30,7 @@ impl GitBackend for TestBackend { | ||
| 30 | 30 | &self, |
| 31 | 31 | user_id: &str, |
| 32 | 32 | service: GitService, |
| 33 | - repo_path: &str, | |
| 33 | + repo_path: &RepoPath, | |
| 34 | 34 | _git_protocol: Option<&str>, |
| 35 | 35 | ) -> Result<Command, String> { |
| 36 | 36 | if user_id != self.user_id { |
| @@ -38,7 +38,7 @@ impl GitBackend for TestBackend { | ||
| 38 | 38 | } |
| 39 | 39 | let repo = self |
| 40 | 40 | .repos |
| 41 | - .get(repo_path) | |
| 41 | + .get(&format!("{}/{}", repo_path.owner, repo_path.name)) | |
| 42 | 42 | .ok_or_else(|| "repository not found".to_owned())?; |
| 43 | 43 | let mut cmd = Command::new("git"); |
| 44 | 44 | cmd.arg(service.name().trim_start_matches("git-")).arg(repo); |
| @@ -48,10 +48,11 @@ impl GitBackend for TestBackend { | ||
| 48 | 48 | async fn lfs_authenticate( |
| 49 | 49 | &self, |
| 50 | 50 | user_id: &str, |
| 51 | - repo_path: &str, | |
| 51 | + repo_path: &RepoPath, | |
| 52 | 52 | operation: LfsOperation, |
| 53 | 53 | ) -> Result<String, String> { |
| 54 | - if user_id != self.user_id || !self.repos.contains_key(repo_path) { | |
| 54 | + let repo = format!("{}/{}", repo_path.owner, repo_path.name); | |
| 55 | + if user_id != self.user_id || !self.repos.contains_key(&repo) { | |
| 55 | 56 | return Err("repository not found".to_owned()); |
| 56 | 57 | } |
| 57 | 58 | let op = match operation { |
| @@ -59,7 +60,7 @@ impl GitBackend for TestBackend { | ||
| 59 | 60 | LfsOperation::Upload => "upload", |
| 60 | 61 | }; |
| 61 | 62 | Ok(format!( |
| 62 | - r#"{{"href":"http://lfs.test/{repo_path}.git/info/lfs","header":{{"Authorization":"RemoteAuth {op}"}},"expires_in":3600}}"# | |
| 63 | + r#"{{"href":"http://lfs.test/{repo}.git/info/lfs","header":{{"Authorization":"RemoteAuth {op}"}},"expires_in":3600}}"# | |
| 63 | 64 | )) |
| 64 | 65 | } |
| 65 | 66 | } |
| @@ -191,8 +192,6 @@ async fn clone_push_clone_over_ssh() { | ||
| 191 | 192 | let config = SshConfig { |
| 192 | 193 | listen: ([127, 0, 0, 1], port).into(), |
| 193 | 194 | host_key_path: host_key.clone(), |
| 194 | - auth_timeout: Duration::from_secs(10), | |
| 195 | - inactivity_timeout: Duration::from_secs(60), | |
| 196 | 195 | // Production rejects a failed auth after 1s. OpenSSH's `none` probe fails on every |
| 197 | 196 | // connection, so the test would wait that second for each of its ~20 connections. |
| 198 | 197 | auth_rejection_time: Duration::ZERO, |
crates/forge-web-account/src/pages/banner.rsmodified+7 -9
| @@ -4,8 +4,6 @@ | ||
| 4 | 4 | //! in the `forge_banner` cookie for a signed-out visitor, and as the `banner_dismissed` account |
| 5 | 5 | //! preference for a signed-in user. |
| 6 | 6 | |
| 7 | -use std::time::Duration; | |
| 8 | - | |
| 9 | 7 | use serde::Deserialize; |
| 10 | 8 | use topcoat::Result; |
| 11 | 9 | use topcoat::context::{Cx, context}; |
| @@ -19,8 +17,6 @@ use crate::pages::theme_cookie::safe_back; | ||
| 19 | 17 | use crate::state::AppState; |
| 20 | 18 | use crate::views::{BANNER_COOKIE, BANNER_PREF}; |
| 21 | 19 | |
| 22 | -const BANNER_COOKIE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60); | |
| 23 | - | |
| 24 | 20 | #[derive(Deserialize)] |
| 25 | 21 | struct DismissForm { |
| 26 | 22 | #[serde(default)] |
| @@ -32,21 +28,22 @@ struct DismissForm { | ||
| 32 | 28 | #[route(POST "/-/banner/dismiss")] |
| 33 | 29 | async fn dismiss(cx: &Cx, Form(form): Form<DismissForm>) -> Result<SeeOther> { |
| 34 | 30 | let hash_ok = form.hash.len() == 16 && form.hash.bytes().all(|b| b.is_ascii_hexdigit()); |
| 35 | - if hash_ok && let Some((user, _)) = current_user(cx).await? { | |
| 31 | + if !hash_ok { | |
| 32 | + return Ok(see_other(safe_back(&form.back))); | |
| 33 | + } | |
| 34 | + if let Some((user, _)) = current_user(cx).await? { | |
| 36 | 35 | context::<AppState>(cx) |
| 37 | 36 | .store |
| 38 | 37 | .set_user_pref(&user.id, BANNER_PREF, &form.hash) |
| 39 | 38 | .await?; |
| 40 | - } else if hash_ok { | |
| 41 | - let max_age = | |
| 42 | - time::Duration::seconds(i64::try_from(BANNER_COOKIE_TTL.as_secs()).unwrap_or(i64::MAX)); | |
| 39 | + } else { | |
| 43 | 40 | cookies(cx).add( |
| 44 | 41 | Cookie::build((BANNER_COOKIE, form.hash)) |
| 45 | 42 | .path("/") |
| 46 | 43 | .secure(true) |
| 47 | 44 | .http_only(true) |
| 48 | 45 | .same_site(SameSite::Lax) |
| 49 | - .max_age(max_age) | |
| 46 | + .max_age(time::Duration::days(365)) | |
| 50 | 47 | .build(), |
| 51 | 48 | ); |
| 52 | 49 | } |
| @@ -91,5 +88,6 @@ mod tests { | ||
| 91 | 88 | Some(86_400 + 60) |
| 92 | 89 | ); |
| 93 | 90 | assert!(forge_core::config::parse_banner_expiry("tomorrow").is_none()); |
| 91 | + assert!(forge_core::config::parse_banner_expiry("2026-02-31 10:00").is_none()); | |
| 94 | 92 | } |
| 95 | 93 | } |
crates/forge-web-account/src/pages/passkeys.rsmodified+1 -2
| @@ -12,7 +12,6 @@ use std::time::{Duration, Instant}; | ||
| 12 | 12 | |
| 13 | 13 | use base64::Engine; |
| 14 | 14 | use base64::engine::general_purpose::URL_SAFE_NO_PAD; |
| 15 | -use forge_core::session::new_csrf_token; | |
| 16 | 15 | use forge_core::store::passkeys::{MAX_PASSKEYS, PasskeyRow, clean_name}; |
| 17 | 16 | use forge_core::{AuditAction, User}; |
| 18 | 17 | use http::header::{HeaderValue, RETRY_AFTER}; |
| @@ -125,7 +124,7 @@ fn stash(ceremony: Ceremony) -> Option<String> { | ||
| 125 | 124 | if map.len() >= CEREMONY_CAP { |
| 126 | 125 | return None; |
| 127 | 126 | } |
| 128 | - let id = new_csrf_token(); | |
| 127 | + let id = forge_core::token::random_b64url(); | |
| 129 | 128 | map.insert(id.clone(), (now, ceremony)); |
| 130 | 129 | Some(id) |
| 131 | 130 | } |
crates/forge-web-app/src/auth.rsmodified+4 -5
| @@ -7,9 +7,8 @@ use std::sync::{Arc, OnceLock}; | ||
| 7 | 7 | use std::time::Duration; |
| 8 | 8 | |
| 9 | 9 | use forge_core::password::{hash_password, verify_password}; |
| 10 | -use forge_core::session::{new_csrf_token, new_session_token}; | |
| 11 | 10 | use forge_core::time::stamp_after; |
| 12 | -use forge_core::token::{constant_time_eq, hash_token}; | |
| 11 | +use forge_core::token::{constant_time_eq, hash_token, random_b64url}; | |
| 13 | 12 | use forge_core::{Session, Store, User, secret, totp}; |
| 14 | 13 | use tokio::sync::Semaphore; |
| 15 | 14 | use topcoat::Result; |
| @@ -77,13 +76,13 @@ pub async fn current_user(cx: &Cx) -> forge_core::Result<Option<(User, Session)> | ||
| 77 | 76 | /// Creates a session for `user` and sets the session cookie on the response. |
| 78 | 77 | pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> { |
| 79 | 78 | let store = &context::<AppState>(cx).store; |
| 80 | - let token = new_session_token(); | |
| 79 | + let token = random_b64url(); | |
| 81 | 80 | let addr = client_addr(cx).to_string(); |
| 82 | 81 | let session = store |
| 83 | 82 | .create_session( |
| 84 | 83 | &user.id, |
| 85 | 84 | &hash_token(&token), |
| 86 | - &new_csrf_token(), | |
| 85 | + &random_b64url(), | |
| 87 | 86 | &stamp_after(SESSION_TTL), |
| 88 | 87 | user_agent(cx).as_deref(), |
| 89 | 88 | Some(&addr), |
| @@ -134,7 +133,7 @@ pub fn pre_csrf_token(cx: &Cx) -> String { | ||
| 134 | 133 | return value.to_owned(); |
| 135 | 134 | } |
| 136 | 135 | } |
| 137 | - let token = new_csrf_token(); | |
| 136 | + let token = random_b64url(); | |
| 138 | 137 | session_jar(cx).add(pre_csrf_cookie(token.clone())); |
| 139 | 138 | token |
| 140 | 139 | } |
crates/forge-web-app/src/backup/create.rsmodified+16 -19
| @@ -265,27 +265,24 @@ async fn bundle_git_repo( | ||
| 265 | 265 | ) -> Result<(String, Option<String>)> { |
| 266 | 266 | let refs_sha256 = forge_git::backup::refs_checksum(git, repo_dir).await?; |
| 267 | 267 | let out = staging.join(rel); |
| 268 | - let bundle = match forge_git::backup::bundle_create(git, repo_dir, &out).await? { | |
| 269 | - None => { | |
| 270 | - if refs_sha256 != empty_sha256() { | |
| 271 | - return Err(Error::Conflict(format!( | |
| 272 | - "repo {label} changed while it was being bundled; run the backup again" | |
| 273 | - ))); | |
| 274 | - } | |
| 275 | - None | |
| 268 | + let bundle = if forge_git::backup::bundle_create(git, repo_dir, &out).await? { | |
| 269 | + let scratch = scratch_root.join(scratch_name); | |
| 270 | + forge_git::repo::init_bare(git, &scratch, "main").await?; | |
| 271 | + let imported = forge_git::backup::bundle_verify(git, &scratch, &out).await?; | |
| 272 | + remove_if_exists(&scratch); | |
| 273 | + if imported != refs_sha256 { | |
| 274 | + return Err(Error::Conflict(format!( | |
| 275 | + "repo {label} changed while it was being bundled; run the backup again" | |
| 276 | + ))); | |
| 276 | 277 | } |
| 277 | - Some(()) => { | |
| 278 | - let scratch = scratch_root.join(scratch_name); | |
| 279 | - forge_git::repo::init_bare(git, &scratch, "main").await?; | |
| 280 | - let imported = forge_git::backup::bundle_verify(git, &scratch, &out).await?; | |
| 281 | - remove_if_exists(&scratch); | |
| 282 | - if imported != refs_sha256 { | |
| 283 | - return Err(Error::Conflict(format!( | |
| 284 | - "repo {label} changed while it was being bundled; run the backup again" | |
| 285 | - ))); | |
| 286 | - } | |
| 287 | - Some(rel.to_string()) | |
| 278 | + Some(rel.to_string()) | |
| 279 | + } else { | |
| 280 | + if refs_sha256 != empty_sha256() { | |
| 281 | + return Err(Error::Conflict(format!( | |
| 282 | + "repo {label} changed while it was being bundled; run the backup again" | |
| 283 | + ))); | |
| 288 | 284 | } |
| 285 | + None | |
| 289 | 286 | }; |
| 290 | 287 | Ok((refs_sha256, bundle)) |
| 291 | 288 | } |
crates/forge-web-app/src/ci/api.rsmodified+7 -8
| @@ -7,16 +7,16 @@ | ||
| 7 | 7 | //! Every response is JSON except the empty 204 of an empty claim and the body of a log append. |
| 8 | 8 | |
| 9 | 9 | use forge_ci::config::JobSpec; |
| 10 | -use forge_ci::mask::Masker; | |
| 10 | +use forge_ci::mask::{MaskStream, Masker}; | |
| 11 | 11 | use forge_ci::proto::{ |
| 12 | 12 | BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, |
| 13 | 13 | JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER, |
| 14 | - RegisterRequest, RegisterResponse, RequeueRequest, RestartMode as WireRestart, | |
| 15 | - RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch, | |
| 14 | + RegisterRequest, RegisterResponse, RequeueRequest, RunnerConfigOverrides, RunnerConfigReport, | |
| 15 | + RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch, | |
| 16 | 16 | }; |
| 17 | 17 | use forge_core::Error as CoreError; |
| 18 | 18 | use forge_core::ci::{ |
| 19 | - CiJob, CiRun, CiRunner, JobState, MemoryOffer, QueueSkips, RunState, RunnerReport, | |
| 19 | + CiJob, CiRun, CiRunner, JobState, MemoryOffer, QueueSkips, RestartMode, RunState, RunnerReport, | |
| 20 | 20 | }; |
| 21 | 21 | use futures_util::StreamExt; |
| 22 | 22 | use http::header::HeaderValue; |
| @@ -308,9 +308,8 @@ async fn set_memory_headers(state: &AppState, runner_id: &str, res: &mut Respons | ||
| 308 | 308 | } |
| 309 | 309 | |
| 310 | 310 | /// The restart an admin asked for, in the wire type. `None` when nothing is pending. |
| 311 | -async fn pending_restart(state: &AppState, runner_id: &str) -> Option<WireRestart> { | |
| 312 | - let mode = state.store.runner_restart(runner_id).await.ok().flatten()?; | |
| 313 | - WireRestart::parse(mode.as_str()) | |
| 311 | +async fn pending_restart(state: &AppState, runner_id: &str) -> Option<RestartMode> { | |
| 312 | + state.store.runner_restart(runner_id).await.ok().flatten() | |
| 314 | 313 | } |
| 315 | 314 | |
| 316 | 315 | /// Adds the pending restart request to a claim answer. Sent on every answer until the runner |
| @@ -976,7 +975,7 @@ async fn mask_for_job(state: &AppState, job: &CiJob, chunk: &[u8]) -> Result<Vec | ||
| 976 | 975 | .await |
| 977 | 976 | .map_err(api::internal)?; |
| 978 | 977 | let masker = Masker::new(values.into_values()); |
| 979 | - let mut stream = masker.stream(); | |
| 978 | + let mut stream = MaskStream::new(masker); | |
| 980 | 979 | let mut out = stream.push(chunk); |
| 981 | 980 | out.extend(stream.finish()); |
| 982 | 981 | Ok(out) |
crates/forge-web-app/src/ci/api_tests.rsmodified+51 -103
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | |
| 4 | 4 | use std::path::PathBuf; |
| 5 | 5 | |
| 6 | -use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, NewJob}; | |
| 6 | +use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, NewJob, NewRun}; | |
| 7 | 7 | use forge_core::{Repo, Store, Visibility}; |
| 8 | 8 | use http::header::{AUTHORIZATION, CONTENT_TYPE}; |
| 9 | 9 | use serde_json::{Value, json}; |
| @@ -72,12 +72,12 @@ struct Bare { | ||
| 72 | 72 | _dir: tempfile::TempDir, |
| 73 | 73 | } |
| 74 | 74 | |
| 75 | -async fn bare(tune: impl FnOnce(&mut forge_core::config::CiConfig)) -> Bare { | |
| 75 | +async fn bare(tune: impl FnOnce(&mut forge_core::config::Config)) -> Bare { | |
| 76 | 76 | let dir = tempfile::tempdir().expect("tempdir"); |
| 77 | 77 | let data_dir = dir.path().to_path_buf(); |
| 78 | 78 | let mut state = test_state(&data_dir).await; |
| 79 | 79 | let mut config = (*state.config).clone(); |
| 80 | - tune(&mut config.ci); | |
| 80 | + tune(&mut config); | |
| 81 | 81 | state.set_config(config); |
| 82 | 82 | let store = state.store.clone(); |
| 83 | 83 | let router = app_router(state); |
| @@ -99,6 +99,11 @@ async fn bare(tune: impl FnOnce(&mut forge_core::config::CiConfig)) -> Bare { | ||
| 99 | 99 | } |
| 100 | 100 | } |
| 101 | 101 | |
| 102 | +fn self_update_on(c: &mut forge_core::config::Config) { | |
| 103 | + c.self_update.enabled = true; | |
| 104 | + c.self_update.repo = format!("{OWNER}/{REPO}"); | |
| 105 | +} | |
| 106 | + | |
| 102 | 107 | /// A runner registered through the store, with its secret. |
| 103 | 108 | async fn runner(env: &Bare, labels: &[&str]) -> (CiRunner, String) { |
| 104 | 109 | let token = env |
| @@ -147,15 +152,17 @@ async fn make_run( | ||
| 147 | 152 | .collect(); |
| 148 | 153 | env.store |
| 149 | 154 | .create_run( |
| 150 | - &env.repo.id, | |
| 151 | - trigger, | |
| 152 | - "refs/heads/main", | |
| 153 | - commit, | |
| 154 | - pull, | |
| 155 | - &env.owner_id, | |
| 156 | - false, | |
| 155 | + &NewRun { | |
| 156 | + repo_id: &env.repo.id, | |
| 157 | + trigger, | |
| 158 | + git_ref: "refs/heads/main", | |
| 159 | + commit_oid: commit, | |
| 160 | + pull_number: pull, | |
| 161 | + actor_id: &env.owner_id, | |
| 162 | + needs_approval: false, | |
| 163 | + config_error: None, | |
| 164 | + }, | |
| 157 | 165 | &new, |
| 158 | - None, | |
| 159 | 166 | ) |
| 160 | 167 | .await |
| 161 | 168 | .unwrap() |
| @@ -792,9 +799,9 @@ async fn put_artifact( | ||
| 792 | 799 | |
| 793 | 800 | #[tokio::test] |
| 794 | 801 | async fn artifact_upload_stores_and_checks_name_count_and_size() { |
| 795 | - let env = bare(|ci| { | |
| 796 | - ci.max_artifacts_per_job = 3; | |
| 797 | - ci.max_artifact_mb = 1; | |
| 802 | + let env = bare(|c| { | |
| 803 | + c.ci.max_artifacts_per_job = 3; | |
| 804 | + c.ci.max_artifact_mb = 1; | |
| 798 | 805 | }) |
| 799 | 806 | .await; |
| 800 | 807 | let (_, secret) = runner(&env, &[]).await; |
| @@ -851,18 +858,22 @@ fn finish_body(outcome: &str) -> Vec<u8> { | ||
| 851 | 858 | json_body(&json!({ "outcome": outcome, "exit_code": 0, "message": null })) |
| 852 | 859 | } |
| 853 | 860 | |
| 861 | +async fn finish_as(router: &Router, job_id: &str, token: &str, body: Vec<u8>) -> Sent { | |
| 862 | + send( | |
| 863 | + router, | |
| 864 | + "POST", | |
| 865 | + &format!("/api/v1/ci/jobs/{job_id}/finish"), | |
| 866 | + &[bearer(token)], | |
| 867 | + body, | |
| 868 | + ) | |
| 869 | + .await | |
| 870 | +} | |
| 871 | + | |
| 854 | 872 | async fn finish_with(env: &Bare, secret: &str, body: Value) -> (String, Value) { |
| 855 | 873 | let assignment = claim_job(&env.router, secret).await; |
| 856 | 874 | let id = assignment["job_id"].as_str().unwrap().to_owned(); |
| 857 | 875 | let token = assignment["job_token"].as_str().unwrap(); |
| 858 | - let sent = send( | |
| 859 | - &env.router, | |
| 860 | - "POST", | |
| 861 | - &format!("/api/v1/ci/jobs/{id}/finish"), | |
| 862 | - &[bearer(token)], | |
| 863 | - json_body(&body), | |
| 864 | - ) | |
| 865 | - .await; | |
| 876 | + let sent = finish_as(&env.router, &id, token, json_body(&body)).await; | |
| 866 | 877 | assert_eq!(sent.status, 200, "{}", sent.json()); |
| 867 | 878 | (id, sent.json()) |
| 868 | 879 | } |
| @@ -957,14 +968,7 @@ async fn finish_queues_dependants_on_success_and_skips_them_on_failure() { | ||
| 957 | 968 | let job_id = assignment["job_id"].as_str().unwrap(); |
| 958 | 969 | let token = assignment["job_token"].as_str().unwrap(); |
| 959 | 970 | |
| 960 | - let sent = send( | |
| 961 | - &env.router, | |
| 962 | - "POST", | |
| 963 | - &format!("/api/v1/ci/jobs/{job_id}/finish"), | |
| 964 | - &[bearer(token)], | |
| 965 | - finish_body("success"), | |
| 966 | - ) | |
| 967 | - .await; | |
| 971 | + let sent = finish_as(&env.router, job_id, token, finish_body("success")).await; | |
| 968 | 972 | assert_eq!(sent.status, 200, "{}", sent.json()); |
| 969 | 973 | |
| 970 | 974 | let jobs = env.store.jobs_for_run(&run.id).await.unwrap(); |
| @@ -976,14 +980,7 @@ async fn finish_queues_dependants_on_success_and_skips_them_on_failure() { | ||
| 976 | 980 | assert_eq!(next["job_name"], "b"); |
| 977 | 981 | let b_id = next["job_id"].as_str().unwrap(); |
| 978 | 982 | let b_token = next["job_token"].as_str().unwrap(); |
| 979 | - let sent = send( | |
| 980 | - &env.router, | |
| 981 | - "POST", | |
| 982 | - &format!("/api/v1/ci/jobs/{b_id}/finish"), | |
| 983 | - &[bearer(b_token)], | |
| 984 | - finish_body("success"), | |
| 985 | - ) | |
| 986 | - .await; | |
| 983 | + let sent = finish_as(&env.router, b_id, b_token, finish_body("success")).await; | |
| 987 | 984 | assert_eq!(sent.status, 200, "{}", sent.json()); |
| 988 | 985 | |
| 989 | 986 | // Scenario 2: a failed `a` skips `b`, and the run ends in failure. |
| @@ -992,14 +989,7 @@ async fn finish_queues_dependants_on_success_and_skips_them_on_failure() { | ||
| 992 | 989 | let job_id = assignment["job_id"].as_str().unwrap(); |
| 993 | 990 | let token = assignment["job_token"].as_str().unwrap(); |
| 994 | 991 | |
| 995 | - let sent = send( | |
| 996 | - &env.router, | |
| 997 | - "POST", | |
| 998 | - &format!("/api/v1/ci/jobs/{job_id}/finish"), | |
| 999 | - &[bearer(token)], | |
| 1000 | - finish_body("failure"), | |
| 1001 | - ) | |
| 1002 | - .await; | |
| 992 | + let sent = finish_as(&env.router, job_id, token, finish_body("failure")).await; | |
| 1003 | 993 | assert_eq!(sent.status, 200, "{}", sent.json()); |
| 1004 | 994 | assert_eq!(sent.json()["state"], "failure"); |
| 1005 | 995 | |
| @@ -1010,14 +1000,7 @@ async fn finish_queues_dependants_on_success_and_skips_them_on_failure() { | ||
| 1010 | 1000 | assert_eq!(run_now.state.as_str(), "failure"); |
| 1011 | 1001 | |
| 1012 | 1002 | // A finished job's token is refused. |
| 1013 | - let again = send( | |
| 1014 | - &env.router, | |
| 1015 | - "POST", | |
| 1016 | - &format!("/api/v1/ci/jobs/{job_id}/finish"), | |
| 1017 | - &[bearer(token)], | |
| 1018 | - finish_body("success"), | |
| 1019 | - ) | |
| 1020 | - .await; | |
| 1003 | + let again = finish_as(&env.router, job_id, token, finish_body("success")).await; | |
| 1021 | 1004 | assert_eq!(again.status, 401); |
| 1022 | 1005 | } |
| 1023 | 1006 | |
| @@ -1025,7 +1008,7 @@ async fn finish_queues_dependants_on_success_and_skips_them_on_failure() { | ||
| 1025 | 1008 | /// fails. Neither finish leaves the run in a state that self-update deploys. |
| 1026 | 1009 | #[tokio::test] |
| 1027 | 1010 | async fn build_green_before_test_fails_never_qualifies_for_self_update() { |
| 1028 | - let env = bare_with_self_update().await; | |
| 1011 | + let env = bare(self_update_on).await; | |
| 1029 | 1012 | let (_, secret) = runner(&env, &[]).await; |
| 1030 | 1013 | let run = make_run( |
| 1031 | 1014 | &env, |
| @@ -1059,16 +1042,7 @@ async fn build_green_before_test_fails_never_qualifies_for_self_update() { | ||
| 1059 | 1042 | let job_id = assignment["job_id"].as_str().unwrap().to_owned(); |
| 1060 | 1043 | let token = assignment["job_token"].as_str().unwrap().to_owned(); |
| 1061 | 1044 | let router = env.router.clone(); |
| 1062 | - async move { | |
| 1063 | - send( | |
| 1064 | - &router, | |
| 1065 | - "POST", | |
| 1066 | - &format!("/api/v1/ci/jobs/{job_id}/finish"), | |
| 1067 | - &[bearer(&token)], | |
| 1068 | - finish_body(outcome), | |
| 1069 | - ) | |
| 1070 | - .await | |
| 1071 | - } | |
| 1045 | + async move { finish_as(&router, &job_id, &token, finish_body(outcome)).await } | |
| 1072 | 1046 | }; |
| 1073 | 1047 | |
| 1074 | 1048 | let sent = finish(&build, "success").await; |
| @@ -1131,19 +1105,21 @@ async fn job_token_reads_over_smart_http_but_never_pushes() { | ||
| 1131 | 1105 | let owner_id = fx.store.user_by_username(OWNER).await.unwrap().unwrap().id; |
| 1132 | 1106 | fx.store |
| 1133 | 1107 | .create_run( |
| 1134 | - &repo.id, | |
| 1135 | - "push", | |
| 1136 | - "refs/heads/main", | |
| 1137 | - &fx.root, | |
| 1138 | - None, | |
| 1139 | - &owner_id, | |
| 1140 | - false, | |
| 1108 | + &NewRun { | |
| 1109 | + repo_id: &repo.id, | |
| 1110 | + trigger: "push", | |
| 1111 | + git_ref: "refs/heads/main", | |
| 1112 | + commit_oid: &fx.root, | |
| 1113 | + pull_number: None, | |
| 1114 | + actor_id: &owner_id, | |
| 1115 | + needs_approval: false, | |
| 1116 | + config_error: None, | |
| 1117 | + }, | |
| 1141 | 1118 | &[NewJob { |
| 1142 | 1119 | name: "a", |
| 1143 | 1120 | spec_json: &spec(&[], &[]), |
| 1144 | 1121 | needs: &[], |
| 1145 | 1122 | }], |
| 1146 | - None, | |
| 1147 | 1123 | ) |
| 1148 | 1124 | .await |
| 1149 | 1125 | .unwrap(); |
| @@ -1231,34 +1207,6 @@ async fn job_token_reads_over_smart_http_but_never_pushes() { | ||
| 1231 | 1207 | ); |
| 1232 | 1208 | } |
| 1233 | 1209 | |
| 1234 | -/// Like `bare`, with self-update enabled for `OWNER/REPO`. | |
| 1235 | -async fn bare_with_self_update() -> Bare { | |
| 1236 | - let dir = tempfile::tempdir().expect("tempdir"); | |
| 1237 | - let data_dir = dir.path().to_path_buf(); | |
| 1238 | - let mut state = test_state(&data_dir).await; | |
| 1239 | - let mut config = (*state.config).clone(); | |
| 1240 | - config.self_update.enabled = true; | |
| 1241 | - config.self_update.repo = format!("{OWNER}/{REPO}"); | |
| 1242 | - state.set_config(config); | |
| 1243 | - let store = state.store.clone(); | |
| 1244 | - let router = app_router(state); | |
| 1245 | - let owner = store | |
| 1246 | - .create_user(OWNER, None, "not-a-real-hash", false) | |
| 1247 | - .await | |
| 1248 | - .unwrap(); | |
| 1249 | - let repo = store | |
| 1250 | - .create_repo(&owner.id, REPO, "", Visibility::Public, "main") | |
| 1251 | - .await | |
| 1252 | - .unwrap(); | |
| 1253 | - Bare { | |
| 1254 | - router, | |
| 1255 | - store, | |
| 1256 | - data_dir, | |
| 1257 | - owner_id: owner.id, | |
| 1258 | - repo, | |
| 1259 | - _dir: dir, | |
| 1260 | - } | |
| 1261 | -} | |
| 1262 | 1210 | |
| 1263 | 1211 | #[tokio::test] |
| 1264 | 1212 | async fn runner_binary_needs_runner_auth_and_self_update() { |
| @@ -1277,7 +1225,7 @@ async fn runner_binary_needs_runner_auth_and_self_update() { | ||
| 1277 | 1225 | async fn runner_binary_streams_the_running_binary_with_its_sha() { |
| 1278 | 1226 | use sha2::{Digest, Sha256}; |
| 1279 | 1227 | |
| 1280 | - let env = bare_with_self_update().await; | |
| 1228 | + let env = bare(self_update_on).await; | |
| 1281 | 1229 | let (_, secret) = runner(&env, &[]).await; |
| 1282 | 1230 | let uri = "/api/v1/ci/runners/binary"; |
| 1283 | 1231 | |
| @@ -1315,7 +1263,7 @@ async fn runner_binary_streams_the_running_binary_with_its_sha() { | ||
| 1315 | 1263 | |
| 1316 | 1264 | #[tokio::test] |
| 1317 | 1265 | async fn claim_advertises_the_binary_only_to_a_matching_target() { |
| 1318 | - let env = bare_with_self_update().await; | |
| 1266 | + let env = bare(self_update_on).await; | |
| 1319 | 1267 | let (_, secret) = runner(&env, &["linux"]).await; |
| 1320 | 1268 | let target = crate::self_update::target(); |
| 1321 | 1269 | let claim_with = |target: Option<String>| { |
crates/forge-web-app/src/ci/schedule.rsmodified+11 -9
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | use forge_ci::config::{CiConfig, Event, parse_config}; |
| 8 | 8 | use forge_core::authz::{Action, authorize}; |
| 9 | -use forge_core::ci::{CiRun, NewJob}; | |
| 9 | +use forge_core::ci::{CiRun, NewJob, NewRun}; | |
| 10 | 10 | use forge_core::store::commit_status::StatusState; |
| 11 | 11 | use forge_core::{PullRequest, Repo}; |
| 12 | 12 | use forge_git::browse::{peel_to_commit, read_blob, resolve_commit}; |
| @@ -358,15 +358,17 @@ async fn create( | ||
| 358 | 358 | let run = state |
| 359 | 359 | .store |
| 360 | 360 | .create_run( |
| 361 | - &req.repo.id, | |
| 362 | - req.trigger, | |
| 363 | - req.git_ref, | |
| 364 | - req.commit, | |
| 365 | - req.pull_number, | |
| 366 | - req.actor_id, | |
| 367 | - req.needs_approval, | |
| 361 | + &NewRun { | |
| 362 | + repo_id: &req.repo.id, | |
| 363 | + trigger: req.trigger, | |
| 364 | + git_ref: req.git_ref, | |
| 365 | + commit_oid: req.commit, | |
| 366 | + pull_number: req.pull_number, | |
| 367 | + actor_id: req.actor_id, | |
| 368 | + needs_approval: req.needs_approval, | |
| 369 | + config_error, | |
| 370 | + }, | |
| 368 | 371 | &new_jobs, |
| 369 | - config_error, | |
| 370 | 372 | ) |
| 371 | 373 | .await?; |
| 372 | 374 | state.ci_live.bump_repo(&run.repo_id); |
crates/forge-web-app/src/exporter.rsmodified+1 -2
| @@ -249,8 +249,7 @@ async fn stage_repo(state: &AppState, repo: &Repo, dir: &Path) -> Result<(), Str | ||
| 249 | 249 | forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?; |
| 250 | 250 | let bundled = bundle_create(&state.git, &git_dir, &dir.join("repo.bundle")) |
| 251 | 251 | .await |
| 252 | - .map_err(|e| format!("bundling {}: {e}", repo.name))? | |
| 253 | - .is_some(); | |
| 252 | + .map_err(|e| format!("bundling {}: {e}", repo.name))?; | |
| 254 | 253 | |
| 255 | 254 | let labels = state |
| 256 | 255 | .store |
crates/forge-web-app/src/mail/worker.rsmodified+8 -8
| @@ -131,7 +131,7 @@ pub fn sleep_for(next_due: Option<&str>, now: OffsetDateTime) -> Duration { | ||
| 131 | 131 | mod tests { |
| 132 | 132 | use std::sync::Arc; |
| 133 | 133 | |
| 134 | - use forge_core::mail::{MailKind, MailSettingsUpdate, OutboxStatus, Security}; | |
| 134 | + use forge_core::mail::{MailKind, MailSettingsUpdate, MailState, Security}; | |
| 135 | 135 | use forge_core::time::{now_stamp, stamp_after}; |
| 136 | 136 | |
| 137 | 137 | use super::*; |
| @@ -207,7 +207,7 @@ mod tests { | ||
| 207 | 207 | "the released row goes out without waiting" |
| 208 | 208 | ); |
| 209 | 209 | let row = state.store.recent_mail(10).await.expect("rows").remove(0); |
| 210 | - assert_eq!(row.status(), OutboxStatus::Sent); | |
| 210 | + assert_eq!(row.state_at(&now_stamp()), MailState::Sent); | |
| 211 | 211 | } |
| 212 | 212 | |
| 213 | 213 | #[tokio::test] |
| @@ -249,7 +249,7 @@ mod tests { | ||
| 249 | 249 | assert_eq!(sent[0].to, "a@example.com"); |
| 250 | 250 | let row = state.store.recent_mail(10).await.expect("rows"); |
| 251 | 251 | assert_eq!(row.len(), 1); |
| 252 | - assert_eq!(row[0].status(), OutboxStatus::Sent); | |
| 252 | + assert_eq!(row[0].state_at(&now_stamp()), MailState::Sent); | |
| 253 | 253 | } |
| 254 | 254 | |
| 255 | 255 | #[tokio::test] |
| @@ -284,7 +284,7 @@ mod tests { | ||
| 284 | 284 | assert_eq!(tick(&state).await.expect("pass"), BACKSTOP); |
| 285 | 285 | assert!(fake.sent().is_empty()); |
| 286 | 286 | let row = state.store.recent_mail(10).await.expect("rows"); |
| 287 | - assert_eq!(row[0].status(), OutboxStatus::Queued); | |
| 287 | + assert_eq!(row[0].state_at(&now_stamp()), MailState::Queued); | |
| 288 | 288 | assert_eq!(row[0].attempts, 0, "waiting costs no attempts"); |
| 289 | 289 | } |
| 290 | 290 | |
| @@ -322,7 +322,7 @@ mod tests { | ||
| 322 | 322 | let by_key = |to: &str| rows.iter().find(|r| r.to_addr == to).expect("row").clone(); |
| 323 | 323 | |
| 324 | 324 | let retried = by_key("a@example.com"); |
| 325 | - assert_eq!(retried.status(), OutboxStatus::Queued); | |
| 325 | + assert_eq!(retried.state_at(&now_stamp()), MailState::Retrying); | |
| 326 | 326 | assert_eq!(retried.attempts, 1); |
| 327 | 327 | assert_eq!(retried.last_error.as_deref(), Some("timeout")); |
| 328 | 328 | let due = retried.next_attempt_at.expect("scheduled"); |
| @@ -330,7 +330,7 @@ mod tests { | ||
| 330 | 330 | assert!(due <= stamp_after(Duration::from_secs(120))); |
| 331 | 331 | |
| 332 | 332 | let bounced = by_key("b@example.com"); |
| 333 | - assert_eq!(bounced.status(), OutboxStatus::GaveUp); | |
| 333 | + assert_eq!(bounced.state_at(&now_stamp()), MailState::Failed); | |
| 334 | 334 | assert_eq!(bounced.attempts, 1); |
| 335 | 335 | assert_eq!(bounced.last_error.as_deref(), Some("550 no such user")); |
| 336 | 336 | assert_eq!(fake.sent().len(), 0, "nothing reached the transport"); |
| @@ -362,13 +362,13 @@ mod tests { | ||
| 362 | 362 | }; |
| 363 | 363 | deliver(&state, &last).await; |
| 364 | 364 | let after = state.store.recent_mail(10).await.expect("rows").remove(0); |
| 365 | - assert_eq!(after.status(), OutboxStatus::GaveUp); | |
| 365 | + assert_eq!(after.state_at(&now_stamp()), MailState::Failed); | |
| 366 | 366 | assert_eq!(after.last_error.as_deref(), Some("timeout")); |
| 367 | 367 | |
| 368 | 368 | // The same failure on an early try is rescheduled instead. |
| 369 | 369 | let early = OutboxEntry { attempts: 1, ..row }; |
| 370 | 370 | deliver(&state, &early).await; |
| 371 | 371 | let after = state.store.recent_mail(10).await.expect("rows").remove(0); |
| 372 | - assert_eq!(after.status(), OutboxStatus::Queued); | |
| 372 | + assert_eq!(after.state_at(&now_stamp()), MailState::Retrying); | |
| 373 | 373 | } |
| 374 | 374 | } |
crates/forge-web-app/src/merge.rsmodified+2 -2
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | //! Merging a pull request: the merge gate, the merge itself and what follows it, shared by the |
| 2 | 2 | //! merge page, auto-merge and the merge queue. |
| 3 | 3 | |
| 4 | -use forge_core::protection::{Protection, effective}; | |
| 4 | +use forge_core::protection::{RuleFlags, effective}; | |
| 5 | 5 | use forge_core::store::commit_status::StatusState; |
| 6 | 6 | use forge_core::{MergeStyle, PullRequest, ReviewState, Role, User}; |
| 7 | 7 | use forge_git::browse::{CommitInfo, default_branch_commit}; |
| @@ -99,7 +99,7 @@ pub fn counts_for_merge_rules(repo: &forge_core::Repo, user: &User, role: Option | ||
| 99 | 99 | /// The base branch's merge rule for a pull request, with the facts that rule checks. |
| 100 | 100 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 101 | 101 | pub struct MergeGate { |
| 102 | - pub rule: Protection, | |
| 102 | + pub rule: RuleFlags, | |
| 103 | 103 | /// Distinct counting reviewers whose latest submitted review is an approval. |
| 104 | 104 | pub approvals: u32, |
| 105 | 105 | /// Some counting reviewer's latest submitted review requests changes. |
crates/forge-web-app/src/release_ops.rsmodified+26 -38
| @@ -18,6 +18,7 @@ use forge_core::releases::{ | ||
| 18 | 18 | use forge_core::webhooks::WebhookEvent; |
| 19 | 19 | use forge_core::{Repo, User}; |
| 20 | 20 | use forge_git::browse::{self, RefInfo, RefKind}; |
| 21 | +use forge_git::history::zero_oid; | |
| 21 | 22 | use forge_git::repo::repo_path; |
| 22 | 23 | use forge_git::tags::{create_lightweight_tag, move_lightweight_tag, valid_tag_name}; |
| 23 | 24 | use futures_util::{Stream, StreamExt}; |
| @@ -167,11 +168,6 @@ async fn resolve_target( | ||
| 167 | 168 | ))) |
| 168 | 169 | } |
| 169 | 170 | |
| 170 | -/// The zero object id, which git reads as "no ref yet". | |
| 171 | -fn zero_oid(len: usize) -> String { | |
| 172 | - "0".repeat(len) | |
| 173 | -} | |
| 174 | - | |
| 175 | 171 | /// Tells the ref hooks, webhooks, CI and mirrors that a tag moved from `old` to `new`. |
| 176 | 172 | async fn fire_tag_hook( |
| 177 | 173 | state: &AppState, |
| @@ -202,6 +198,24 @@ fn check_fields(title: &str, body: &str) -> Result<(), ReleaseError> { | ||
| 202 | 198 | Ok(()) |
| 203 | 199 | } |
| 204 | 200 | |
| 201 | +fn check_tag_name(tag: &str) -> Result<(), ReleaseError> { | |
| 202 | + if !valid_tag_name(tag) { | |
| 203 | + return Err(ReleaseError::Invalid( | |
| 204 | + "the tag name may only use letters, digits and . _ - +".to_owned(), | |
| 205 | + )); | |
| 206 | + } | |
| 207 | + Ok(()) | |
| 208 | +} | |
| 209 | + | |
| 210 | +async fn ensure_tag_unused(state: &AppState, repo: &Repo, tag: &str) -> Result<(), ReleaseError> { | |
| 211 | + if state.store.release_by_tag(&repo.id, tag).await?.is_some() { | |
| 212 | + return Err(ReleaseError::Conflict( | |
| 213 | + "a release already exists for this tag".to_owned(), | |
| 214 | + )); | |
| 215 | + } | |
| 216 | + Ok(()) | |
| 217 | +} | |
| 218 | + | |
| 205 | 219 | /// `NotFound` when the release belongs to another repo. |
| 206 | 220 | fn ensure_same_repo(repo: &Repo, release: &Release) -> Result<(), ReleaseError> { |
| 207 | 221 | if release.repo_id == repo.id { |
| @@ -244,22 +258,9 @@ pub async fn create( | ||
| 244 | 258 | actor: &User, |
| 245 | 259 | input: CreateRelease, |
| 246 | 260 | ) -> Result<Release, ReleaseError> { |
| 247 | - if !valid_tag_name(&input.tag) { | |
| 248 | - return Err(ReleaseError::Invalid( | |
| 249 | - "the tag name may only use letters, digits and . _ - +".to_owned(), | |
| 250 | - )); | |
| 251 | - } | |
| 261 | + check_tag_name(&input.tag)?; | |
| 252 | 262 | check_fields(&input.title, &input.body)?; |
| 253 | - if state | |
| 254 | - .store | |
| 255 | - .release_by_tag(&repo.id, &input.tag) | |
| 256 | - .await? | |
| 257 | - .is_some() | |
| 258 | - { | |
| 259 | - return Err(ReleaseError::Conflict( | |
| 260 | - "a release already exists for this tag".to_owned(), | |
| 261 | - )); | |
| 262 | - } | |
| 263 | + ensure_tag_unused(state, repo, &input.tag).await?; | |
| 263 | 264 | let path = path_of(state, repo)?; |
| 264 | 265 | let refs = refs_of(path.clone()).await?; |
| 265 | 266 | let target_oid = match tag_oid(&refs, &input.tag) { |
| @@ -272,7 +273,7 @@ pub async fn create( | ||
| 272 | 273 | .unwrap_or(&repo.default_branch); |
| 273 | 274 | let oid = resolve_target(&path, &refs, target).await?; |
| 274 | 275 | create_lightweight_tag(&state.git, &path, &input.tag, &oid).await?; |
| 275 | - fire_tag_hook(state, repo, actor, &input.tag, &zero_oid(oid.len()), &oid).await; | |
| 276 | + fire_tag_hook(state, repo, actor, &input.tag, &zero_oid(&oid), &oid).await; | |
| 276 | 277 | oid |
| 277 | 278 | } |
| 278 | 279 | }; |
| @@ -310,27 +311,14 @@ pub async fn update( | ||
| 310 | 311 | check_fields(&edit.title, &edit.body)?; |
| 311 | 312 | let new_tag = edit.tag.clone().unwrap_or_else(|| release.tag.clone()); |
| 312 | 313 | let retag = new_tag != release.tag; |
| 313 | - if retag && !valid_tag_name(&new_tag) { | |
| 314 | - return Err(ReleaseError::Invalid( | |
| 315 | - "the tag name may only use letters, digits and . _ - +".to_owned(), | |
| 316 | - )); | |
| 317 | - } | |
| 318 | 314 | let wanted = edit.target.as_deref().filter(|t| !t.is_empty()); |
| 319 | 315 | let path = path_of(state, repo)?; |
| 320 | 316 | let refs = refs_of(path.clone()).await?; |
| 321 | 317 | let mut target_oid = release.target_oid.clone(); |
| 322 | 318 | |
| 323 | 319 | if retag { |
| 324 | - if state | |
| 325 | - .store | |
| 326 | - .release_by_tag(&repo.id, &new_tag) | |
| 327 | - .await? | |
| 328 | - .is_some() | |
| 329 | - { | |
| 330 | - return Err(ReleaseError::Conflict( | |
| 331 | - "a release already exists for this tag".to_owned(), | |
| 332 | - )); | |
| 333 | - } | |
| 320 | + check_tag_name(&new_tag)?; | |
| 321 | + ensure_tag_unused(state, repo, &new_tag).await?; | |
| 334 | 322 | match tag_oid(&refs, &new_tag) { |
| 335 | 323 | Some(existing) => { |
| 336 | 324 | if let Some(target) = wanted |
| @@ -348,7 +336,7 @@ pub async fn update( | ||
| 348 | 336 | None => release.target_oid.clone(), |
| 349 | 337 | }; |
| 350 | 338 | create_lightweight_tag(&state.git, &path, &new_tag, &oid).await?; |
| 351 | - fire_tag_hook(state, repo, actor, &new_tag, &zero_oid(oid.len()), &oid).await; | |
| 339 | + fire_tag_hook(state, repo, actor, &new_tag, &zero_oid(&oid), &oid).await; | |
| 352 | 340 | target_oid = oid; |
| 353 | 341 | } |
| 354 | 342 | } |
| @@ -367,7 +355,7 @@ pub async fn update( | ||
| 367 | 355 | } |
| 368 | 356 | None => { |
| 369 | 357 | create_lightweight_tag(&state.git, &path, &release.tag, &oid).await?; |
| 370 | - fire_tag_hook(state, repo, actor, &release.tag, &zero_oid(oid.len()), &oid).await; | |
| 358 | + fire_tag_hook(state, repo, actor, &release.tag, &zero_oid(&oid), &oid).await; | |
| 371 | 359 | } |
| 372 | 360 | } |
| 373 | 361 | target_oid = oid; |
crates/forge-web-app/src/replication/mod.rsmodified+1 -69
| @@ -1,12 +1,3 @@ | ||
| 1 | -//! Standby replication: pushes every repo and a database snapshot to a passive SSH host (see | |
| 2 | -//! `docs/backup.md`, "Standby replication"). The standby is a dedicated unix account that holds | |
| 3 | -//! bare repos and snapshots. It never runs forge. | |
| 4 | -//! | |
| 5 | -//! Everything that reaches the standby goes through [`StandbyTransport`]. [`SshTransport`] runs | |
| 6 | -//! the system `ssh`; [`LocalTransport`] (tests only) runs the same shell commands with `sh -c` on | |
| 7 | -//! this machine, where the remote base is a temporary directory. Remote paths are validated and | |
| 8 | -//! quoted before they are placed in any command. | |
| 9 | - | |
| 10 | 1 | pub mod worker; |
| 11 | 2 | |
| 12 | 3 | use std::collections::HashMap; |
| @@ -17,31 +8,22 @@ use std::sync::{Mutex, PoisonError}; | ||
| 17 | 8 | use std::time::{Duration, Instant}; |
| 18 | 9 | |
| 19 | 10 | use forge_git::GitEnv; |
| 11 | +use forge_git::backup::REFS_FORMAT; | |
| 20 | 12 | use forge_git::command::GitCommand; |
| 21 | 13 | use tokio::process::Command; |
| 22 | 14 | use tokio::sync::Notify; |
| 23 | 15 | |
| 24 | 16 | use crate::state::AppState; |
| 25 | 17 | |
| 26 | -/// How long a repo waits after its last ref update before it is pushed. | |
| 27 | 18 | pub const PUSH_DEBOUNCE: Duration = Duration::from_secs(5); |
| 28 | -/// Newest database snapshots kept on the standby. | |
| 29 | 19 | pub const KEEP_SNAPSHOTS: usize = 24; |
| 30 | -/// Name of the snapshot directory on the standby, under the base. | |
| 31 | 20 | const DB_DIR: &str = "db"; |
| 32 | -/// Name of the repo directory on the standby, under the base. | |
| 33 | 21 | const REPOS_DIR: &str = "repos"; |
| 34 | -/// Suffix of the replication status subject that names a repo's wiki. | |
| 35 | 22 | const WIKI_SUBJECT_SUFFIX: &str = ".wiki"; |
| 36 | -/// Prefix and suffix of a snapshot file name: `forge-<UTC stamp>.db`. | |
| 37 | 23 | const SNAPSHOT_PREFIX: &str = "forge-"; |
| 38 | 24 | const SNAPSHOT_SUFFIX: &str = ".db"; |
| 39 | -/// Stamp layout in snapshot names: `YYYYMMDDTHHMMSSZ`. | |
| 40 | 25 | const STAMP_LEN: usize = 16; |
| 41 | -const REFS_FORMAT: &str = "--format=%(objectname) %(refname)"; | |
| 42 | 26 | |
| 43 | -/// Checks a remote base or repo path: an absolute path of `[A-Za-z0-9._/-]`, with no `..`, no | |
| 44 | -/// empty components and no trailing slash. | |
| 45 | 27 | pub fn validate_remote_path(path: &str) -> Result<(), String> { |
| 46 | 28 | let well_formed = path.starts_with('/') |
| 47 | 29 | && path.len() > 1 |
| @@ -60,17 +42,14 @@ pub fn validate_remote_path(path: &str) -> Result<(), String> { | ||
| 60 | 42 | } |
| 61 | 43 | } |
| 62 | 44 | |
| 63 | -/// The replication status subject of a repo's wiki: `<id>.wiki`. | |
| 64 | 45 | pub fn wiki_subject(repo_id: &str) -> String { |
| 65 | 46 | format!("{repo_id}{WIKI_SUBJECT_SUFFIX}") |
| 66 | 47 | } |
| 67 | 48 | |
| 68 | -/// The repo id a wiki subject names, or `None` for any other subject. | |
| 69 | 49 | pub fn wiki_subject_repo(subject: &str) -> Option<&str> { |
| 70 | 50 | subject.strip_suffix(WIKI_SUBJECT_SUFFIX) |
| 71 | 51 | } |
| 72 | 52 | |
| 73 | -/// Repo ids are ULIDs: 26 ASCII alphanumerics. Checked before an id is used in a remote path. | |
| 74 | 53 | pub fn validate_repo_id(id: &str) -> Result<(), String> { |
| 75 | 54 | if id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) { |
| 76 | 55 | Ok(()) |
| @@ -79,25 +58,19 @@ pub fn validate_repo_id(id: &str) -> Result<(), String> { | ||
| 79 | 58 | } |
| 80 | 59 | } |
| 81 | 60 | |
| 82 | -/// Quotes one argument for a POSIX shell: wraps it in single quotes and writes each embedded | |
| 83 | -/// single quote as `'\''`. The result is one word whatever the input holds. | |
| 84 | 61 | pub fn sh_quote(arg: &str) -> String { |
| 85 | 62 | format!("'{}'", arg.replace('\'', "'\\''")) |
| 86 | 63 | } |
| 87 | 64 | |
| 88 | -/// Where the standby is and how to reach it: `[user@]host:/absolute/base` plus the SSH port. | |
| 89 | 65 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 90 | 66 | pub struct Target { |
| 91 | 67 | pub user: Option<String>, |
| 92 | 68 | pub host: String, |
| 93 | 69 | pub port: u16, |
| 94 | - /// Validated absolute base directory on the standby. | |
| 95 | 70 | pub base: String, |
| 96 | 71 | } |
| 97 | 72 | |
| 98 | 73 | impl Target { |
| 99 | - /// Parses the `target` setting. Host and user may use `[A-Za-z0-9.-]` and `[A-Za-z0-9._-]`; | |
| 100 | - /// neither may start with `-`, so neither can be read by ssh as an option. | |
| 101 | 74 | pub fn parse(spec: &str, port: u16) -> Result<Target, String> { |
| 102 | 75 | let (dest, base) = spec |
| 103 | 76 | .split_once(':') |
| @@ -133,7 +106,6 @@ impl Target { | ||
| 133 | 106 | }) |
| 134 | 107 | } |
| 135 | 108 | |
| 136 | - /// `user@host`, or `host` without a user. | |
| 137 | 109 | pub fn destination(&self) -> String { |
| 138 | 110 | match &self.user { |
| 139 | 111 | Some(user) => format!("{user}@{}", self.host), |
| @@ -141,7 +113,6 @@ impl Target { | ||
| 141 | 113 | } |
| 142 | 114 | } |
| 143 | 115 | |
| 144 | - /// The `ssh://` URL git pushes a repo to. | |
| 145 | 116 | pub fn repo_url(&self, remote_repo_dir: &str) -> String { |
| 146 | 117 | format!( |
| 147 | 118 | "ssh://{}:{}{remote_repo_dir}", |
| @@ -151,8 +122,6 @@ impl Target { | ||
| 151 | 122 | } |
| 152 | 123 | } |
| 153 | 124 | |
| 154 | -/// Remote layout under the base. `repos/<id>.git` holds bare repos, `db/` holds snapshots and the | |
| 155 | -/// `latest` link. `keys/` belongs to the operator and is never written here. | |
| 156 | 125 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 157 | 126 | pub struct Layout { |
| 158 | 127 | pub base: String, |
| @@ -174,19 +143,16 @@ impl Layout { | ||
| 174 | 143 | format!("{}/{DB_DIR}", self.base) |
| 175 | 144 | } |
| 176 | 145 | |
| 177 | - /// `<base>/repos/<id>.git`. Fails for an id that is not a ULID. | |
| 178 | 146 | pub fn repo_dir(&self, repo_id: &str) -> Result<String, String> { |
| 179 | 147 | validate_repo_id(repo_id)?; |
| 180 | 148 | Ok(format!("{}/{repo_id}.git", self.repos_dir())) |
| 181 | 149 | } |
| 182 | 150 | |
| 183 | - /// `<base>/repos/<id>.wiki.git`: the standby copy of the repo's wiki. | |
| 184 | 151 | pub fn wiki_dir(&self, repo_id: &str) -> Result<String, String> { |
| 185 | 152 | validate_repo_id(repo_id)?; |
| 186 | 153 | Ok(format!("{}/{repo_id}.wiki.git", self.repos_dir())) |
| 187 | 154 | } |
| 188 | 155 | |
| 189 | - /// `<base>/db/forge-<stamp>.db`. | |
| 190 | 156 | pub fn snapshot_file(&self, stamp: &str) -> String { |
| 191 | 157 | format!( |
| 192 | 158 | "{}/{SNAPSHOT_PREFIX}{stamp}{SNAPSHOT_SUFFIX}", |
| @@ -199,7 +165,6 @@ impl Layout { | ||
| 199 | 165 | } |
| 200 | 166 | } |
| 201 | 167 | |
| 202 | -/// A snapshot name `forge-<16-char stamp>.db` with a stamp of digits, `T` and `Z`. | |
| 203 | 168 | pub fn is_snapshot_name(name: &str) -> bool { |
| 204 | 169 | let Some(stamp) = name |
| 205 | 170 | .strip_prefix(SNAPSHOT_PREFIX) |
| @@ -215,7 +180,6 @@ pub fn is_snapshot_name(name: &str) -> bool { | ||
| 215 | 180 | }) |
| 216 | 181 | } |
| 217 | 182 | |
| 218 | -/// The UTC stamp used in snapshot names, `YYYYMMDDTHHMMSSZ`. | |
| 219 | 183 | pub fn snapshot_stamp() -> String { |
| 220 | 184 | const FORMAT: &[time::format_description::FormatItem<'static>] = |
| 221 | 185 | time::macros::format_description!("[year][month][day]T[hour][minute][second]Z"); |
| @@ -224,23 +188,15 @@ pub fn snapshot_stamp() -> String { | ||
| 224 | 188 | .unwrap_or_else(|_| "00000000T000000Z".to_owned()) |
| 225 | 189 | } |
| 226 | 190 | |
| 227 | -/// Moves data to the standby and runs commands there. Implemented by [`SshTransport`] and, in | |
| 228 | -/// tests, [`LocalTransport`]. The worker only calls these three methods. | |
| 229 | 191 | pub trait StandbyTransport: Send + Sync { |
| 230 | - /// Runs one shell command (already quoted) on the standby and returns its stdout. | |
| 231 | 192 | fn run(&self, remote_cmd: &str) -> impl Future<Output = Result<Vec<u8>, String>> + Send; |
| 232 | 193 | |
| 233 | - /// The URL git pushes the repo at `remote_repo_dir` to. | |
| 234 | 194 | fn repo_url(&self, remote_repo_dir: &str) -> String; |
| 235 | 195 | |
| 236 | - /// Whether git must be told to allow a plain local path as a transport. | |
| 237 | 196 | fn local_git(&self) -> bool; |
| 238 | 197 | |
| 239 | - /// The `GIT_SSH_COMMAND` git must use to reach the standby, if any. | |
| 240 | 198 | fn push_ssh_command(&self) -> Option<String>; |
| 241 | 199 | |
| 242 | - /// Streams the local file `local` to `remote_path` on the standby. The data goes to a temporary | |
| 243 | - /// file in the same directory first, and is renamed into place only once complete. | |
| 244 | 200 | fn upload( |
| 245 | 201 | &self, |
| 246 | 202 | local: &Path, |
| @@ -248,7 +204,6 @@ pub trait StandbyTransport: Send + Sync { | ||
| 248 | 204 | ) -> impl Future<Output = Result<(), String>> + Send; |
| 249 | 205 | } |
| 250 | 206 | |
| 251 | -/// Builds the `cat > tmp && mv tmp final` command used by every upload. | |
| 252 | 207 | fn upload_command(remote_path: &str) -> String { |
| 253 | 208 | let (dir, name) = remote_path.rsplit_once('/').unwrap_or(("", remote_path)); |
| 254 | 209 | let tmp = format!("{dir}/.tmp-{name}"); |
| @@ -260,7 +215,6 @@ fn upload_command(remote_path: &str) -> String { | ||
| 260 | 215 | ) |
| 261 | 216 | } |
| 262 | 217 | |
| 263 | -/// Runs `command` with its stdin fed from `file`, and fails on a non-zero exit. | |
| 264 | 218 | async fn pipe_file(mut command: Command, file: &Path) -> Result<(), String> { |
| 265 | 219 | use std::process::Stdio; |
| 266 | 220 | use tokio::io::AsyncWriteExt; |
| @@ -302,7 +256,6 @@ async fn pipe_file(mut command: Command, file: &Path) -> Result<(), String> { | ||
| 302 | 256 | } |
| 303 | 257 | } |
| 304 | 258 | |
| 305 | -/// Runs `command` and returns stdout. A non-zero exit is an error carrying stderr. | |
| 306 | 259 | async fn capture(mut command: Command) -> Result<Vec<u8>, String> { |
| 307 | 260 | use std::process::Stdio; |
| 308 | 261 | command.stdin(Stdio::null()).kill_on_drop(true); |
| @@ -321,7 +274,6 @@ async fn capture(mut command: Command) -> Result<Vec<u8>, String> { | ||
| 321 | 274 | } |
| 322 | 275 | } |
| 323 | 276 | |
| 324 | -/// Pushes every ref of the local bare repo `repo_dir` to `url` with `--mirror --force`. | |
| 325 | 277 | async fn push_mirror( |
| 326 | 278 | git: &GitEnv, |
| 327 | 279 | repo_dir: &Path, |
| @@ -348,8 +300,6 @@ async fn push_mirror( | ||
| 348 | 300 | .map_err(|e| e.to_string()) |
| 349 | 301 | } |
| 350 | 302 | |
| 351 | -/// Replication over the system `ssh`, with the options that pin the standby's host key and use | |
| 352 | -/// only the configured identity. Argument construction is unit-tested; no test connects. | |
| 353 | 303 | #[derive(Debug, Clone)] |
| 354 | 304 | pub struct SshTransport { |
| 355 | 305 | target: Target, |
| @@ -366,7 +316,6 @@ impl SshTransport { | ||
| 366 | 316 | } |
| 367 | 317 | } |
| 368 | 318 | |
| 369 | - /// The `-i`/`-o`/`-p` options, in order. Every one is a fixed word or a configured path. | |
| 370 | 319 | pub fn ssh_options(&self) -> Vec<String> { |
| 371 | 320 | vec![ |
| 372 | 321 | "-i".to_owned(), |
| @@ -389,7 +338,6 @@ impl SshTransport { | ||
| 389 | 338 | ] |
| 390 | 339 | } |
| 391 | 340 | |
| 392 | - /// The full argv after the program name: options, destination, then the remote command. | |
| 393 | 341 | pub fn ssh_argv(&self, remote_cmd: &str) -> Vec<String> { |
| 394 | 342 | let mut argv = self.ssh_options(); |
| 395 | 343 | argv.push(self.target.destination()); |
| @@ -397,7 +345,6 @@ impl SshTransport { | ||
| 397 | 345 | argv |
| 398 | 346 | } |
| 399 | 347 | |
| 400 | - /// The value for `GIT_SSH_COMMAND`: the same ssh invocation, each word quoted for the shell. | |
| 401 | 348 | pub fn git_ssh_command(&self) -> String { |
| 402 | 349 | std::iter::once("ssh".to_owned()) |
| 403 | 350 | .chain(self.ssh_options()) |
| @@ -442,8 +389,6 @@ impl StandbyTransport for SshTransport { | ||
| 442 | 389 | } |
| 443 | 390 | } |
| 444 | 391 | |
| 445 | -/// Runs the same shell commands as [`SshTransport`], but with `sh -c` on this machine. The remote | |
| 446 | -/// base is then a local directory. Test only. | |
| 447 | 392 | #[cfg(any(test, feature = "test-support"))] |
| 448 | 393 | #[derive(Debug, Clone, Copy, Default)] |
| 449 | 394 | pub struct LocalTransport; |
| @@ -480,8 +425,6 @@ impl StandbyTransport for LocalTransport { | ||
| 480 | 425 | } |
| 481 | 426 | } |
| 482 | 427 | |
| 483 | -/// Pushes one local repo with `--mirror --force` through a transport. The remote directory must | |
| 484 | -/// already exist (see `worker::replicate_repo`). | |
| 485 | 428 | pub async fn push_repo<T: StandbyTransport>( |
| 486 | 429 | transport: &T, |
| 487 | 430 | git: &GitEnv, |
| @@ -498,7 +441,6 @@ pub async fn push_repo<T: StandbyTransport>( | ||
| 498 | 441 | .await |
| 499 | 442 | } |
| 500 | 443 | |
| 501 | -/// The refs checksum of the bare repo at `remote_repo_dir`, read through the transport. | |
| 502 | 444 | pub async fn remote_refs_checksum<T: StandbyTransport>( |
| 503 | 445 | transport: &T, |
| 504 | 446 | remote_repo_dir: &str, |
| @@ -512,8 +454,6 @@ pub async fn remote_refs_checksum<T: StandbyTransport>( | ||
| 512 | 454 | Ok(forge_git::backup::refs_checksum_of_listing(&out)) |
| 513 | 455 | } |
| 514 | 456 | |
| 515 | -/// The queue the web side writes and the replication worker drains. Holds repos waiting for a | |
| 516 | -/// debounced push, and the "reconcile now" request. | |
| 517 | 457 | #[derive(Default)] |
| 518 | 458 | pub struct ReplicationQueue { |
| 519 | 459 | notify: Notify, |
| @@ -522,7 +462,6 @@ pub struct ReplicationQueue { | ||
| 522 | 462 | } |
| 523 | 463 | |
| 524 | 464 | impl ReplicationQueue { |
| 525 | - /// Queues `repo_id` for a push once [`PUSH_DEBOUNCE`] has passed without another update. | |
| 526 | 465 | pub fn enqueue(&self, repo_id: &str) { |
| 527 | 466 | let due = Instant::now() + PUSH_DEBOUNCE; |
| 528 | 467 | self.pending |
| @@ -532,7 +471,6 @@ impl ReplicationQueue { | ||
| 532 | 471 | self.notify.notify_one(); |
| 533 | 472 | } |
| 534 | 473 | |
| 535 | - /// Removes and returns the repos whose debounce has passed at `now`, sorted by id. | |
| 536 | 474 | pub fn take_due(&self, now: Instant) -> Vec<String> { |
| 537 | 475 | let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner); |
| 538 | 476 | let mut due: Vec<String> = pending |
| @@ -547,7 +485,6 @@ impl ReplicationQueue { | ||
| 547 | 485 | due |
| 548 | 486 | } |
| 549 | 487 | |
| 550 | - /// The earliest debounce due time among the queued repos, or `None` when nothing is queued. | |
| 551 | 488 | pub fn next_due(&self) -> Option<Instant> { |
| 552 | 489 | self.pending |
| 553 | 490 | .lock() |
| @@ -557,24 +494,20 @@ impl ReplicationQueue { | ||
| 557 | 494 | .copied() |
| 558 | 495 | } |
| 559 | 496 | |
| 560 | - /// Asks the worker for a full reconcile pass as soon as it can. | |
| 561 | 497 | pub fn request_reconcile(&self) { |
| 562 | 498 | self.reconcile.store(true, Ordering::SeqCst); |
| 563 | 499 | self.notify.notify_one(); |
| 564 | 500 | } |
| 565 | 501 | |
| 566 | - /// Returns true once per request. | |
| 567 | 502 | pub fn take_reconcile_request(&self) -> bool { |
| 568 | 503 | self.reconcile.swap(false, Ordering::SeqCst) |
| 569 | 504 | } |
| 570 | 505 | |
| 571 | - /// Resolves when something is queued or a reconcile is requested. | |
| 572 | 506 | pub async fn wait(&self) { |
| 573 | 507 | self.notify.notified().await; |
| 574 | 508 | } |
| 575 | 509 | } |
| 576 | 510 | |
| 577 | -/// Queues a repo after any ref update. Does nothing when replication is disabled. | |
| 578 | 511 | pub fn enqueue_repo(state: &AppState, repo_id: &str) { |
| 579 | 512 | if state.config.replication.enabled() { |
| 580 | 513 | state.replication.enqueue(repo_id); |
| @@ -628,7 +561,6 @@ mod tests { | ||
| 628 | 561 | assert_eq!(sh_quote("it's"), "'it'\\''s'"); |
| 629 | 562 | assert_eq!(sh_quote("$(rm -rf /)`x`;|&"), "'$(rm -rf /)`x`;|&'"); |
| 630 | 563 | assert_eq!(sh_quote("'"), "''\\'''"); |
| 631 | - // Round trip through a real shell: each quoted word comes back unchanged. | |
| 632 | 564 | let words = ["plain", "it's", "a b", "$HOME", "x'y'z", "back\\slash"]; |
| 633 | 565 | let line = words |
| 634 | 566 | .iter() |
crates/forge-web-app/src/ssh_backend.rsmodified+13 -19
| @@ -6,7 +6,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; | ||
| 6 | 6 | use forge_core::lfs_token::{self, LfsOp}; |
| 7 | 7 | use forge_core::{Repo, User}; |
| 8 | 8 | use forge_git::GitService; |
| 9 | -use forge_ssh::{GitBackend, LfsOperation}; | |
| 9 | +use forge_ssh::{GitBackend, LfsOperation, RepoPath}; | |
| 10 | 10 | |
| 11 | 11 | use crate::access::{self, AccessError, Transport}; |
| 12 | 12 | use crate::state::AppState; |
| @@ -97,15 +97,12 @@ impl GitBackend for SshBackend { | ||
| 97 | 97 | &self, |
| 98 | 98 | user_id: &str, |
| 99 | 99 | service: GitService, |
| 100 | - repo_path: &str, | |
| 100 | + repo_path: &RepoPath, | |
| 101 | 101 | git_protocol: Option<&str>, |
| 102 | 102 | ) -> Result<tokio::process::Command, String> { |
| 103 | - // parse_exec has already stripped the leading '/' and the trailing ".git". | |
| 104 | - let (owner, name) = repo_path | |
| 105 | - .split_once('/') | |
| 106 | - .ok_or_else(|| MSG_NOT_FOUND.to_string())?; | |
| 107 | - | |
| 108 | - let (user, repo, path) = self.authorize(user_id, owner, name, service).await?; | |
| 103 | + let (user, repo, path) = self | |
| 104 | + .authorize(user_id, &repo_path.owner, &repo_path.name, service) | |
| 105 | + .await?; | |
| 109 | 106 | |
| 110 | 107 | Ok(access::git_process( |
| 111 | 108 | &self.state, |
| @@ -123,20 +120,17 @@ impl GitBackend for SshBackend { | ||
| 123 | 120 | async fn lfs_authenticate( |
| 124 | 121 | &self, |
| 125 | 122 | user_id: &str, |
| 126 | - repo_path: &str, | |
| 123 | + repo_path: &RepoPath, | |
| 127 | 124 | operation: LfsOperation, |
| 128 | 125 | ) -> Result<String, String> { |
| 129 | - // parse_lfs_authenticate has already stripped the leading '/' and the trailing ".git". | |
| 130 | - let (owner, name) = repo_path | |
| 131 | - .split_once('/') | |
| 132 | - .ok_or_else(|| MSG_NOT_FOUND.to_string())?; | |
| 133 | - | |
| 134 | 126 | // Download is a read and upload is a write, checked exactly as git does. |
| 135 | - let service = match operation { | |
| 136 | - LfsOperation::Download => GitService::UploadPack, | |
| 137 | - LfsOperation::Upload => GitService::ReceivePack, | |
| 127 | + let (service, op) = match operation { | |
| 128 | + LfsOperation::Download => (GitService::UploadPack, LfsOp::Download), | |
| 129 | + LfsOperation::Upload => (GitService::ReceivePack, LfsOp::Upload), | |
| 138 | 130 | }; |
| 139 | - let (_user, repo, _path) = self.authorize(user_id, owner, name, service).await?; | |
| 131 | + let (_user, repo, _path) = self | |
| 132 | + .authorize(user_id, &repo_path.owner, &repo_path.name, service) | |
| 133 | + .await?; | |
| 140 | 134 | |
| 141 | 135 | if operation == LfsOperation::Upload { |
| 142 | 136 | // Archived repos are refused by the Write check. Pull mirrors are read-only. |
| @@ -153,7 +147,7 @@ impl GitBackend for SshBackend { | ||
| 153 | 147 | let token = lfs_token::issue( |
| 154 | 148 | &self.state.key, |
| 155 | 149 | &repo.id, |
| 156 | - LfsOp::Any, | |
| 150 | + op, | |
| 157 | 151 | now_unix() + LFS_TOKEN_TTL_SECS, |
| 158 | 152 | ); |
| 159 | 153 | let base = self.state.config.base_url.trim_end_matches('/'); |
crates/forge-web-base/src/accent.rsmodified+1 -1
| @@ -280,7 +280,7 @@ mod tests { | ||
| 280 | 280 | let mut seen = HashSet::new(); |
| 281 | 281 | for id in ids { |
| 282 | 282 | assert!( |
| 283 | - forge_core::store::ui_prefs::valid_accent(id), | |
| 283 | + forge_core::store::ui_prefs::valid_slug(id), | |
| 284 | 284 | "{kind} {id} is not a slug" |
| 285 | 285 | ); |
| 286 | 286 | assert!(seen.insert(id), "{kind} {id} is listed twice"); |
crates/forge-web-pages/src/pages/ci_fail.rsmodified+2 -1
| @@ -12,8 +12,9 @@ use crate::i18n::{ | ||
| 12 | 12 | releases_ci::{self as g, K}, |
| 13 | 13 | }; |
| 14 | 14 | use crate::pages::ci_job::log_tail; |
| 15 | -use crate::pages::ci_runs::{job_href, strip_ansi}; | |
| 15 | +use crate::pages::ci_runs::job_href; | |
| 16 | 16 | use crate::state::AppState; |
| 17 | +use forge_ci::steps::strip_ansi; | |
| 17 | 18 | |
| 18 | 19 | /// How far after the first error line its reason and place are looked for. |
| 19 | 20 | const WINDOW: usize = 30; |
crates/forge-web-pages/src/pages/ci_job.rsmodified+2 -1
| @@ -12,6 +12,7 @@ use std::sync::{Arc, Mutex, OnceLock}; | ||
| 12 | 12 | use std::time::Duration; |
| 13 | 13 | |
| 14 | 14 | use bytes::Bytes; |
| 15 | +use forge_ci::steps::strip_ansi; | |
| 15 | 16 | use forge_core::ci::{CiArtifact, CiJob, CiRun, JobState}; |
| 16 | 17 | use forge_core::{Store, User}; |
| 17 | 18 | use futures_util::{Stream, TryStreamExt}; |
| @@ -37,7 +38,7 @@ use crate::i18n::{ | ||
| 37 | 38 | use crate::live::{changed_event, events_response}; |
| 38 | 39 | use crate::pages::ci_runs::{ |
| 39 | 40 | age_text, can_write, commit_reachable_for, dock_bars, duration_text, job_href, run_href, |
| 40 | - state_text, strip_ansi, | |
| 41 | + state_text, | |
| 41 | 42 | }; |
| 42 | 43 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable}; |
| 43 | 44 | use crate::state::AppState; |
crates/forge-web-pages/src/pages/ci_runs.rsmodified+1 -32
| @@ -12,6 +12,7 @@ use std::collections::{HashMap, HashSet}; | ||
| 12 | 12 | use std::future::Future; |
| 13 | 13 | use std::path::Path; |
| 14 | 14 | |
| 15 | +use forge_ci::steps::strip_ansi; | |
| 15 | 16 | use forge_core::ci::{CiJob, CiRun, JobSample, JobState, JobStep, RunState, StepSample, StepState}; |
| 16 | 17 | use forge_core::{Action, Denied, Store, User, authorize}; |
| 17 | 18 | use forge_git::browse::{RefInfo, RefKind, commit_reachable, reachable_commits, read_commit}; |
| @@ -1471,38 +1472,6 @@ fn row_meta(run: &CiRun, jobs: &[Timing], actor: &str, lang: Lang) -> RowMeta { | ||
| 1471 | 1472 | } |
| 1472 | 1473 | } |
| 1473 | 1474 | |
| 1474 | -/// Drops the ANSI escape sequences and the other control characters (a tab stays) of a log line. | |
| 1475 | -pub fn strip_ansi(line: &str) -> String { | |
| 1476 | - let mut out = String::with_capacity(line.len()); | |
| 1477 | - let mut chars = line.chars().peekable(); | |
| 1478 | - while let Some(c) = chars.next() { | |
| 1479 | - if c == '\u{1b}' { | |
| 1480 | - match chars.next() { | |
| 1481 | - // A CSI sequence ends at a byte from `@` to `~`. | |
| 1482 | - Some('[') => { | |
| 1483 | - for n in chars.by_ref() { | |
| 1484 | - if ('@'..='~').contains(&n) { | |
| 1485 | - break; | |
| 1486 | - } | |
| 1487 | - } | |
| 1488 | - } | |
| 1489 | - // An OSC sequence ends at BEL or ESC. | |
| 1490 | - Some(']') => { | |
| 1491 | - for n in chars.by_ref() { | |
| 1492 | - if n == '\u{7}' || n == '\u{1b}' { | |
| 1493 | - break; | |
| 1494 | - } | |
| 1495 | - } | |
| 1496 | - } | |
| 1497 | - _ => {} | |
| 1498 | - } | |
| 1499 | - } else if c == '\t' || !c.is_control() { | |
| 1500 | - out.push(c); | |
| 1501 | - } | |
| 1502 | - } | |
| 1503 | - out | |
| 1504 | -} | |
| 1505 | - | |
| 1506 | 1475 | /// The last non-empty line of a tail: what a job row previews. |
| 1507 | 1476 | fn last_line(tail: &[String]) -> Option<&str> { |
| 1508 | 1477 | tail.iter() |
crates/forge-web-pages/src/pages/edit_history.rsmodified+15 -25
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | use std::collections::HashMap; |
| 8 | 8 | use std::sync::Arc; |
| 9 | 9 | |
| 10 | -use forge_core::{EditVersion, Issue, Thread}; | |
| 10 | +use forge_core::{EditTarget, EditVersion, Issue, Thread}; | |
| 11 | 11 | use similar::{ChangeTag, TextDiff}; |
| 12 | 12 | use topcoat::Result; |
| 13 | 13 | use topcoat::context::{Cx, context}; |
| @@ -36,35 +36,23 @@ path_param!(target_id); | ||
| 36 | 36 | /// Unchanged lines shown around each change. |
| 37 | 37 | const CONTEXT_LINES: usize = 3; |
| 38 | 38 | |
| 39 | -/// The target kinds that have edit history, as the URL spells them. | |
| 40 | -const KINDS: [&str; 3] = ["issue", "comment", "review_comment"]; | |
| 41 | - | |
| 42 | 39 | /// The history URL of one target of an item: `/{o}/{r}/{issues|pulls}/{n}/history/{kind}/{id}`. |
| 43 | 40 | pub fn history_href( |
| 44 | 41 | owner: &str, |
| 45 | 42 | repo_name: &str, |
| 46 | 43 | kind: ItemKind, |
| 47 | 44 | number: i64, |
| 48 | - target_kind: &str, | |
| 45 | + target_kind: EditTarget, | |
| 49 | 46 | target: &str, |
| 50 | 47 | ) -> String { |
| 51 | 48 | repo_href( |
| 52 | 49 | owner, |
| 53 | 50 | repo_name, |
| 54 | 51 | kind.segment(), |
| 55 | - &format!("{number}/history/{target_kind}/{target}"), | |
| 52 | + &format!("{number}/history/{}/{target}", target_kind.as_str()), | |
| 56 | 53 | ) |
| 57 | 54 | } |
| 58 | 55 | |
| 59 | -/// Edit counts for a batch of targets, one query per call. Targets never edited are absent. | |
| 60 | -pub async fn edit_counts( | |
| 61 | - state: &AppState, | |
| 62 | - target_kind: &str, | |
| 63 | - ids: &[&str], | |
| 64 | -) -> Result<HashMap<String, u64>> { | |
| 65 | - Ok(state.store.edit_count(target_kind, ids).await?) | |
| 66 | -} | |
| 67 | - | |
| 68 | 56 | /// Edit counts for the root comments and replies of `threads`, shared by every thread of a page. |
| 69 | 57 | pub async fn thread_edit_counts( |
| 70 | 58 | state: &AppState, |
| @@ -75,7 +63,7 @@ pub async fn thread_edit_counts( | ||
| 75 | 63 | .flat_map(|thread| std::iter::once(&thread.root).chain(thread.replies.iter())) |
| 76 | 64 | .map(|comment| comment.id.as_str()) |
| 77 | 65 | .collect(); |
| 78 | - Ok(Arc::new(edit_counts(state, "review_comment", &ids).await?)) | |
| 66 | + Ok(Arc::new(state.store.edit_count(EditTarget::ReviewComment, &ids).await?)) | |
| 79 | 67 | } |
| 80 | 68 | |
| 81 | 69 | /// One line of a diff: its CSS class from the `diff-*` set and its text with its sign. |
| @@ -170,7 +158,7 @@ async fn history_page( | ||
| 170 | 158 | ctx: RepoCtx, |
| 171 | 159 | kind_item: ItemKind, |
| 172 | 160 | item: Issue, |
| 173 | - target_kind: &'static str, | |
| 161 | + target_kind: EditTarget, | |
| 174 | 162 | target: String, |
| 175 | 163 | ) -> Result<impl View> { |
| 176 | 164 | let target = target.as_str(); |
| @@ -187,14 +175,14 @@ async fn history_page( | ||
| 187 | 175 | } |
| 188 | 176 | |
| 189 | 177 | let (current_title, current_body): (Option<String>, String) = match target_kind { |
| 190 | - "issue" => (Some(item.title.clone()), item.body.clone()), | |
| 191 | - "comment" => { | |
| 178 | + EditTarget::Issue => (Some(item.title.clone()), item.body.clone()), | |
| 179 | + EditTarget::Comment => { | |
| 192 | 180 | let Some(comment) = state.store.comment_by_id(&item.id, target).await? else { |
| 193 | 181 | return Err(not_found().into()); |
| 194 | 182 | }; |
| 195 | 183 | (None, comment.body) |
| 196 | 184 | } |
| 197 | - _ => { | |
| 185 | + EditTarget::ReviewComment => { | |
| 198 | 186 | let Some(comment) = state.store.review_comment(target).await? else { |
| 199 | 187 | return Err(not_found().into()); |
| 200 | 188 | }; |
| @@ -214,7 +202,7 @@ async fn history_page( | ||
| 214 | 202 | now, |
| 215 | 203 | ); |
| 216 | 204 | |
| 217 | - let what = g::history_what(lang, kind_item == ItemKind::Pull, target_kind); | |
| 205 | + let what = g::history_what(lang, kind_item == ItemKind::Pull, target_kind.as_str()); | |
| 218 | 206 | let back = repo_href(&owner, &name, kind_item.segment(), &number.to_string()); |
| 219 | 207 | let page_title = g::history_title(lang, what, &format!("{owner}/{name} #{number}")); |
| 220 | 208 | let header = ctx |
| @@ -305,10 +293,12 @@ async fn history_entry(cx: &Cx, lang: Lang, entry: HistoryEntry) -> Result<impl | ||
| 305 | 293 | } |
| 306 | 294 | |
| 307 | 295 | /// Parses the `{kind}` segment, or 404 for anything without edit history. |
| 308 | -fn parse_kind(raw: &str) -> Result<&'static str> { | |
| 309 | - match KINDS.into_iter().find(|known| *known == raw) { | |
| 310 | - Some(known) => Ok(known), | |
| 311 | - None => Err(not_found().into()), | |
| 296 | +fn parse_kind(raw: &str) -> Result<EditTarget> { | |
| 297 | + match raw { | |
| 298 | + "issue" => Ok(EditTarget::Issue), | |
| 299 | + "comment" => Ok(EditTarget::Comment), | |
| 300 | + "review_comment" => Ok(EditTarget::ReviewComment), | |
| 301 | + _ => Err(not_found().into()), | |
| 312 | 302 | } |
| 313 | 303 | } |
| 314 | 304 |
crates/forge-web-pages/src/pages/issue_parts.rsmodified+13 -24
| @@ -6,7 +6,9 @@ | ||
| 6 | 6 | use std::collections::HashSet; |
| 7 | 7 | use topcoat::context::Cx; |
| 8 | 8 | |
| 9 | -use forge_core::{Action, Comment, Issue, IssueEvent, IssueState, Session, StateReason, User}; | |
| 9 | +use forge_core::{ | |
| 10 | + Action, Comment, EditTarget, Issue, IssueEvent, IssueState, Session, StateReason, User, | |
| 11 | +}; | |
| 10 | 12 | use forge_core::{Reaction, ReactionSummary, ReactionTarget}; |
| 11 | 13 | use forge_core::{ReviewState, Thread, authorize, validate_body}; |
| 12 | 14 | use serde::Deserialize; |
| @@ -19,7 +21,7 @@ use crate::auth::check_csrf; | ||
| 19 | 21 | use crate::i18n::Lang; |
| 20 | 22 | use crate::i18n::issues::{self as g, K}; |
| 21 | 23 | use crate::notify::{self, Activity}; |
| 22 | -use crate::pages::edit_history::{edit_counts, history_href, thread_edit_counts}; | |
| 24 | +use crate::pages::edit_history::{history_href, thread_edit_counts}; | |
| 23 | 25 | use crate::pages::notifications::{NotifyBox, notify_pill}; |
| 24 | 26 | use crate::pages::pull_reviews::suggest_states; |
| 25 | 27 | use crate::pages::repo_ctx::RepoCtx; |
| @@ -52,7 +54,6 @@ impl ItemKind { | ||
| 52 | 54 | } |
| 53 | 55 | } |
| 54 | 56 | |
| 55 | -// Permissions | |
| 56 | 57 | |
| 57 | 58 | pub fn viewer(ctx: &RepoCtx) -> Option<&User> { |
| 58 | 59 | ctx.viewer.as_ref().map(|(user, _)| user) |
| @@ -116,7 +117,6 @@ pub fn csrf_of(ctx: &RepoCtx) -> String { | ||
| 116 | 117 | .unwrap_or_default() |
| 117 | 118 | } |
| 118 | 119 | |
| 119 | -// Lookups | |
| 120 | 120 | |
| 121 | 121 | /// Parses an issue number: digits only, greater than zero. Anything else is 404. |
| 122 | 122 | pub fn parse_number(raw: &str) -> Result<i64> { |
| @@ -181,7 +181,6 @@ pub async fn reachable_among(path: &std::path::Path, oids: Vec<String>) -> HashS | ||
| 181 | 181 | .unwrap_or_default() |
| 182 | 182 | } |
| 183 | 183 | |
| 184 | -// Timeline | |
| 185 | 184 | |
| 186 | 185 | /// One comment, or the item body (which uses the same item shape without a delete action). |
| 187 | 186 | pub struct CommentView { |
| @@ -343,7 +342,6 @@ fn event_line( | ||
| 343 | 342 | "base_changed" => g::event_base_changed(lang, &text("from"), &text("to")), |
| 344 | 343 | other => other.to_owned(), |
| 345 | 344 | }; |
| 346 | - // A commit no branch, tag or pull request reaches keeps its short hash, as plain text. | |
| 347 | 345 | let (link_href, link_label) = if is_hex_oid(&commit) { |
| 348 | 346 | let href = reachable |
| 349 | 347 | .contains(&commit) |
| @@ -702,7 +700,6 @@ pub async fn load_discussion( | ||
| 702 | 700 | let comments = store.list_comments(&item.id).await?; |
| 703 | 701 | let events = store.list_events(&item.id).await?; |
| 704 | 702 | |
| 705 | - // Every event's commit, checked against git in one walk before any row is built. | |
| 706 | 703 | let event_commits: Vec<String> = events |
| 707 | 704 | .iter() |
| 708 | 705 | .filter_map(|e| e.data.get("commit").and_then(Json::as_str)) |
| @@ -711,7 +708,6 @@ pub async fn load_discussion( | ||
| 711 | 708 | .collect(); |
| 712 | 709 | let reachable = reachable_among(&ctx.path, event_commits).await; |
| 713 | 710 | |
| 714 | - // One batched lookup for every author and event actor on the page. | |
| 715 | 711 | let mut ids: Vec<String> = std::iter::once(item.author_id.clone()) |
| 716 | 712 | .chain(comments.iter().map(|c| c.author_id.clone())) |
| 717 | 713 | .chain(events.iter().filter_map(|e| e.actor_id.clone())) |
| @@ -731,8 +727,6 @@ pub async fn load_discussion( | ||
| 731 | 727 | let link = link_context(state, &ctx.repo, &ctx.repo.default_branch, ""); |
| 732 | 728 | let csrf = csrf_of(ctx); |
| 733 | 729 | |
| 734 | - // Reactions: one batched read for the body and one for all comments. Viewers who cannot react | |
| 735 | - // (signed out, or an archived repo) see the counts without buttons. | |
| 736 | 730 | let viewer_id = viewer(ctx).map(|user| user.id.clone()); |
| 737 | 731 | let can_react = viewer_id.is_some() && !ctx.repo.archived && may_converse(ctx, item); |
| 738 | 732 | let reaction_action = repo_href(&owner, &name, segment, &format!("{number}/reactions")); |
| @@ -752,7 +746,6 @@ pub async fn load_discussion( | ||
| 752 | 746 | ) |
| 753 | 747 | .await?; |
| 754 | 748 | |
| 755 | - // Body: first entry of the timeline. | |
| 756 | 749 | let (author, author_hash) = who(&item.author_id); |
| 757 | 750 | let body_source = if item.body.trim().is_empty() { |
| 758 | 751 | g::t(lang, K::NoDescription) |
| @@ -764,11 +757,11 @@ pub async fn load_discussion( | ||
| 764 | 757 | ItemKind::Pull => format!("pull-{number}"), |
| 765 | 758 | }; |
| 766 | 759 | let opened = When::new(lang, &item.created_at, &tz, now); |
| 767 | - let body_edits = edit_counts(state, "issue", &[item.id.as_str()]).await?; | |
| 760 | + let body_edits = state.store.edit_count(EditTarget::Issue, &[item.id.as_str()]).await?; | |
| 768 | 761 | let body_history = body_edits |
| 769 | 762 | .get(&item.id) |
| 770 | 763 | .is_some_and(|count| *count > 0) |
| 771 | - .then(|| history_href(&owner, &name, kind, number, "issue", &item.id)); | |
| 764 | + .then(|| history_href(&owner, &name, kind, number, EditTarget::Issue, &item.id)); | |
| 772 | 765 | let body = CommentView { |
| 773 | 766 | anchor: body_anchor, |
| 774 | 767 | author: display_name(lang, &author), |
| @@ -797,9 +790,8 @@ pub async fn load_discussion( | ||
| 797 | 790 | ), |
| 798 | 791 | }; |
| 799 | 792 | |
| 800 | - // Comments and events, merged by creation time. | |
| 801 | 793 | let comment_ids: Vec<&str> = comments.iter().map(|c| c.id.as_str()).collect(); |
| 802 | - let comment_edits = edit_counts(state, "comment", &comment_ids).await?; | |
| 794 | + let comment_edits = state.store.edit_count(EditTarget::Comment, &comment_ids).await?; | |
| 803 | 795 | let mut keyed: Vec<(String, Entry)> = Vec::new(); |
| 804 | 796 | for comment in comments { |
| 805 | 797 | let (who_name, hash) = who(&comment.author_id); |
| @@ -816,7 +808,9 @@ pub async fn load_discussion( | ||
| 816 | 808 | when: When::new(lang, &comment.created_at, &tz, now), |
| 817 | 809 | html: render_markdown(&comment.body, Some(&link)), |
| 818 | 810 | history_href: edited |
| 819 | - .then(|| history_href(&owner, &name, kind, number, "comment", &comment.id)), | |
| 811 | + .then(|| { | |
| 812 | + history_href(&owner, &name, kind, number, EditTarget::Comment, &comment.id) | |
| 813 | + }), | |
| 820 | 814 | edit_href: mine |
| 821 | 815 | .then(|| repo_href(&owner, &name, segment, &format!("{comment_path}/edit"))), |
| 822 | 816 | delete_href: mine |
| @@ -992,7 +986,6 @@ pub fn reaction_bar_for( | ||
| 992 | 986 | }) |
| 993 | 987 | } |
| 994 | 988 | |
| 995 | -/// The hover text of a reaction: who made it, and how many more beyond the first names. | |
| 996 | 989 | /// A reaction's name in the viewer's language, for its picker button. |
| 997 | 990 | fn reaction_label(lang: Lang, reaction: Reaction) -> &'static str { |
| 998 | 991 | use crate::i18n::s; |
| @@ -1008,6 +1001,7 @@ fn reaction_label(lang: Lang, reaction: Reaction) -> &'static str { | ||
| 1008 | 1001 | } |
| 1009 | 1002 | } |
| 1010 | 1003 | |
| 1004 | +/// The hover text of a reaction: who made it, and how many more beyond the first names. | |
| 1011 | 1005 | fn reaction_title(lang: Lang, users: &[String], count: usize) -> String { |
| 1012 | 1006 | let names = users.join(", "); |
| 1013 | 1007 | match count.saturating_sub(users.len()) { |
| @@ -1108,7 +1102,6 @@ async fn review_entries( | ||
| 1108 | 1102 | Ok(keyed) |
| 1109 | 1103 | } |
| 1110 | 1104 | |
| 1111 | -// Sidebar | |
| 1112 | 1105 | |
| 1113 | 1106 | pub struct LabelRow { |
| 1114 | 1107 | id: String, |
| @@ -1422,7 +1415,6 @@ pub async fn item_sidebar( | ||
| 1422 | 1415 | locked, |
| 1423 | 1416 | lock_reason, |
| 1424 | 1417 | } = sidebar; |
| 1425 | - // "Assign to me" posts the whole list with the viewer added, since the route replaces it. | |
| 1426 | 1418 | let assign_next = match viewer { |
| 1427 | 1419 | Some(me) if write && !assignees.iter().any(|a| *a == me) => { |
| 1428 | 1420 | let mut next = assignees.clone(); |
| @@ -1447,7 +1439,6 @@ pub async fn item_sidebar( | ||
| 1447 | 1439 | }) |
| 1448 | 1440 | } |
| 1449 | 1441 | |
| 1450 | -// Comment form | |
| 1451 | 1442 | |
| 1452 | 1443 | /// The id of the comment form. The head's Close and Reopen buttons post it with `form=`, so a |
| 1453 | 1444 | /// close can carry the draft text as its comment, as it always did. |
| @@ -1514,7 +1505,6 @@ pub async fn comment_form( | ||
| 1514 | 1505 | }) |
| 1515 | 1506 | } |
| 1516 | 1507 | |
| 1517 | -// Comment and state POSTs | |
| 1518 | 1508 | |
| 1519 | 1509 | /// The form fields of a comment or state POST. |
| 1520 | 1510 | #[derive(Deserialize)] |
| @@ -1582,7 +1572,6 @@ pub async fn post_comment( | ||
| 1582 | 1572 | if !pull { |
| 1583 | 1573 | state.live.bump_issue(&ctx.repo.id, &item.id); |
| 1584 | 1574 | } |
| 1585 | - // The author's contribution calendar counts the comment. | |
| 1586 | 1575 | state.live.bump(&crate::live::Topic::User(user.id.clone())); |
| 1587 | 1576 | emit_comment(state, &ctx.repo, &sender, "created", pull, item, &comment).await; |
| 1588 | 1577 | notify::dispatch( |
| @@ -1611,11 +1600,11 @@ pub async fn post_comment( | ||
| 1611 | 1600 | ("reopened", Activity::Reopened) |
| 1612 | 1601 | }; |
| 1613 | 1602 | emit_item_action(state, &ctx.repo, &sender, pull, item.number, action).await; |
| 1614 | - if pull && action == "closed" { | |
| 1603 | + if pull && next == IssueState::Closed { | |
| 1615 | 1604 | crate::merge_queue::drop_pull(state, &ctx.repo, &item.id, "closed").await; |
| 1616 | 1605 | } |
| 1617 | 1606 | if pull |
| 1618 | - && action == "reopened" | |
| 1607 | + && next == IssueState::Open | |
| 1619 | 1608 | && let Some(pr) = state |
| 1620 | 1609 | .store |
| 1621 | 1610 | .pull_by_number(&ctx.repo.id, item.number) |
crates/forge-web-pages/src/pages/notifications.rsmodified+11 -7
| @@ -11,7 +11,7 @@ use forge_core::discussions::{DiscussionNotification, DiscussionReason}; | ||
| 11 | 11 | use forge_core::store::admin_alerts::AdminNotice; |
| 12 | 12 | use forge_core::store::advisories::AdvisoryNotice; |
| 13 | 13 | use forge_core::store::transfers::PendingTransfer; |
| 14 | -use forge_core::{Notification, Reason, Role, SubState, User, WatchLevel}; | |
| 14 | +use forge_core::{IssueState, Notification, Reason, Role, SubState, User, WatchLevel}; | |
| 15 | 15 | use futures_util::{Stream, StreamExt, future, stream}; |
| 16 | 16 | use serde::Deserialize; |
| 17 | 17 | use topcoat::Result; |
| @@ -160,11 +160,11 @@ impl Entry { | ||
| 160 | 160 | |
| 161 | 161 | /// The row for an issue or pull inbox entry. |
| 162 | 162 | fn issue_row(lang: Lang, note: &Notification, tz: &str, now: i64) -> RowView { |
| 163 | - let (kind_label, icon_class) = match (note.is_pull, note.issue_state.as_str()) { | |
| 164 | - (false, "open") => (g::t(lang, K::KindOpenIssue), "notif-icon issue-open"), | |
| 165 | - (false, _) => (g::t(lang, K::KindClosedIssue), "notif-icon issue-closed"), | |
| 166 | - (true, "open") => (g::t(lang, K::KindOpenPull), "notif-icon pull-open"), | |
| 167 | - (true, _) => (g::t(lang, K::KindClosedPull), "notif-icon pull-closed"), | |
| 163 | + let (kind_label, icon_class) = match (note.is_pull, note.issue_state) { | |
| 164 | + (false, IssueState::Open) => (g::t(lang, K::KindOpenIssue), "notif-icon issue-open"), | |
| 165 | + (false, IssueState::Closed) => (g::t(lang, K::KindClosedIssue), "notif-icon issue-closed"), | |
| 166 | + (true, IssueState::Open) => (g::t(lang, K::KindOpenPull), "notif-icon pull-open"), | |
| 167 | + (true, IssueState::Closed) => (g::t(lang, K::KindClosedPull), "notif-icon pull-closed"), | |
| 168 | 168 | }; |
| 169 | 169 | let actor = note |
| 170 | 170 | .last_actor_name |
| @@ -498,7 +498,11 @@ async fn inbox_fingerprint(state: &AppState, user: &User, all: bool) -> Result<S | ||
| 498 | 498 | { |
| 499 | 499 | lines.push(format!( |
| 500 | 500 | "issue {} {} {} {} {}", |
| 501 | - note.id, note.unread, note.updated_at, note.title, note.issue_state | |
| 501 | + note.id, | |
| 502 | + note.unread, | |
| 503 | + note.updated_at, | |
| 504 | + note.title, | |
| 505 | + note.issue_state.as_str() | |
| 502 | 506 | )); |
| 503 | 507 | } |
| 504 | 508 | for note in state |
crates/forge-web-pages/src/pages/repo.rsmodified+2 -34
| @@ -1,13 +1,10 @@ | ||
| 1 | -//! Page: repository home at `/{owner}/{repo}`. Shows the default branch's root folder in the rail | |
| 2 | -//! and the README in the sheet. An empty repo shows push instructions instead. | |
| 3 | - | |
| 4 | 1 | use std::collections::{HashMap, HashSet}; |
| 5 | 2 | use std::path::PathBuf; |
| 6 | 3 | use std::time::Duration; |
| 7 | 4 | |
| 8 | 5 | use forge_core::Repo as RepoRecord; |
| 9 | 6 | use forge_core::WatchLevel; |
| 10 | -use forge_core::time::stamp_before; | |
| 7 | +use forge_core::time::stamp_ago; | |
| 11 | 8 | use forge_git::browse; |
| 12 | 9 | use forge_git::repo::repo_path; |
| 13 | 10 | use topcoat::Result; |
| @@ -39,11 +36,6 @@ use crate::views::{ | ||
| 39 | 36 | path_param!(owner); |
| 40 | 37 | path_param!(repo); |
| 41 | 38 | |
| 42 | -/// Head of every repo page: the title with its actions right beside it, the sub line and the tabs. | |
| 43 | -/// The Code tab's head is the repo itself: its name, Clone, Star, Fork and the rest in a menu. Any | |
| 44 | -/// other tab's head is that tab (or `title`), and `child` holds the page's own actions. `sub` is | |
| 45 | -/// added to the sub line; the Code tab starts it with the description and the visibility. Built by | |
| 46 | -/// `RepoCtx::head`; every repo page passes one. | |
| 47 | 39 | #[component] |
| 48 | 40 | pub async fn repo_head( |
| 49 | 41 | cx: &Cx, |
| @@ -85,12 +77,10 @@ pub async fn repo_head( | ||
| 85 | 77 | let vis = i18n::visibility_label(lang, visibility); |
| 86 | 78 | let shown_title = title.unwrap_or_else(|| tab_title(lang, active, &name)); |
| 87 | 79 | let active = active.to_owned(); |
| 88 | - // The fork button posts with the same session CSRF token as the star form. | |
| 89 | 80 | let fork_control = match (can_fork, star.as_ref()) { |
| 90 | 81 | (true, Some(star)) => Some((repo_href(&owner, &name, "fork", ""), star.csrf.clone())), |
| 91 | 82 | _ => None, |
| 92 | 83 | }; |
| 93 | - // Signed-in viewers get a button that stars or unstars; anonymous viewers see the count only. | |
| 94 | 84 | let star_control = match star { |
| 95 | 85 | Some(star) => { |
| 96 | 86 | let (path, label) = if star.starred { |
| @@ -103,7 +93,6 @@ pub async fn repo_head( | ||
| 103 | 93 | None => None, |
| 104 | 94 | }; |
| 105 | 95 | let anon_count = format!("\u{2605} {stars}"); |
| 106 | - // Signed-in viewers get the watch level select; everyone gets the watcher count. | |
| 107 | 96 | let watch_control = watch.map(|watch| { |
| 108 | 97 | let level = match watch.level { |
| 109 | 98 | WatchLevel::Participating => "participating", |
| @@ -114,13 +103,11 @@ pub async fn repo_head( | ||
| 114 | 103 | }); |
| 115 | 104 | let watch_count = g::watching_count(lang, watchers); |
| 116 | 105 | let fork_count = g::forks_count(lang, forks); |
| 117 | - // The sub line: on the Code tab what the repo is, then what the page adds. | |
| 118 | 106 | let mut parts: Vec<SubPart> = Vec::new(); |
| 119 | 107 | if is_code { |
| 120 | 108 | if !description.is_empty() { |
| 121 | 109 | parts.push(SubPart::text(description.as_str())); |
| 122 | 110 | } |
| 123 | - // Public is the usual case and says nothing; only a private repo says so. | |
| 124 | 111 | if private { |
| 125 | 112 | parts.push(SubPart::text(vis)); |
| 126 | 113 | } |
| @@ -183,12 +170,9 @@ pub async fn repo_head( | ||
| 183 | 170 | <p class="state" role="status">(g::t(lang, K::ArchivedNotice))</p> |
| 184 | 171 | } |
| 185 | 172 | } |
| 186 | - // Boxed: this head is part of nearly every repo page's view. | |
| 187 | 173 | .boxed()) |
| 188 | 174 | } |
| 189 | 175 | |
| 190 | -/// Clone button that opens a popover with both clone URLs as selectable read-only fields and, when | |
| 191 | -/// the branch has a commit, links to its archive (`downloads`: the zip and tar.gz hrefs). | |
| 192 | 176 | #[component] |
| 193 | 177 | async fn clone_popover( |
| 194 | 178 | cx: &Cx, |
| @@ -218,8 +202,6 @@ async fn clone_popover( | ||
| 218 | 202 | }) |
| 219 | 203 | } |
| 220 | 204 | |
| 221 | -/// Shown for an empty repo (or one whose default branch is missing): the branches that exist, | |
| 222 | -/// or push instructions when there are none. | |
| 223 | 205 | #[component] |
| 224 | 206 | async fn branches_card( |
| 225 | 207 | cx: &Cx, |
| @@ -258,25 +240,16 @@ async fn default_commit(path: PathBuf, branch: String) -> Result<Option<String>> | ||
| 258 | 240 | ) |
| 259 | 241 | } |
| 260 | 242 | |
| 261 | -/// Most recent-push banners the repo home shows. | |
| 262 | 243 | const MAX_PUSH_BANNERS: usize = 3; |
| 263 | -/// How far back a push still counts as recent. | |
| 264 | 244 | const RECENT_PUSH_WINDOW: Duration = Duration::from_secs(60 * 60); |
| 265 | 245 | |
| 266 | -/// One "had recent pushes" banner: a branch the viewer pushed to, with its compare link. | |
| 267 | 246 | struct PushBanner { |
| 268 | 247 | branch: String, |
| 269 | 248 | at_unix: i64, |
| 270 | - /// The push's stamp, for the `<time>` that shows its age. | |
| 271 | 249 | at: String, |
| 272 | 250 | href: String, |
| 273 | 251 | } |
| 274 | 252 | |
| 275 | -/// Recent-push banners for the signed-in viewer. Candidates are the branches the viewer pushed to | |
| 276 | -/// in this repo and in their own forks of it, pushed within the last hour, newest first. A branch | |
| 277 | -/// is skipped when it is the default branch, is gone, or already has an open pull request. A fork | |
| 278 | -/// links to its parent's compare page when the parent is visible (`forked_from`); otherwise the | |
| 279 | -/// compare page is this repo's, with the head as `owner:branch` for a fork. | |
| 280 | 253 | async fn recent_push_banners( |
| 281 | 254 | state: &AppState, |
| 282 | 255 | ctx: &RepoCtx, |
| @@ -295,7 +268,6 @@ async fn recent_push_banners( | ||
| 295 | 268 | None => repo.clone(), |
| 296 | 269 | }; |
| 297 | 270 | |
| 298 | - // Forks the viewer owns, or that an organization they hold a role in owns. | |
| 299 | 271 | let mut forks: Vec<RepoRecord> = Vec::new(); |
| 300 | 272 | for fork in state.store.list_forks(&repo.id).await? { |
| 301 | 273 | let mine = fork.owner_id == user.id |
| @@ -311,7 +283,7 @@ async fn recent_push_banners( | ||
| 311 | 283 | let mut candidates: Vec<&RepoRecord> = vec![repo]; |
| 312 | 284 | candidates.extend(forks.iter()); |
| 313 | 285 | let ids: Vec<&str> = candidates.iter().map(|r| r.id.as_str()).collect(); |
| 314 | - let since = stamp_before(RECENT_PUSH_WINDOW); | |
| 286 | + let since = stamp_ago(RECENT_PUSH_WINDOW); | |
| 315 | 287 | let pushes = state |
| 316 | 288 | .store |
| 317 | 289 | .recent_branch_pushes(&ids, &user.id, &since) |
| @@ -371,7 +343,6 @@ async fn recent_push_banners( | ||
| 371 | 343 | Ok(banners) |
| 372 | 344 | } |
| 373 | 345 | |
| 374 | -/// The "had recent pushes" banners above the code tab. | |
| 375 | 346 | #[component] |
| 376 | 347 | async fn recent_pushes( |
| 377 | 348 | cx: &Cx, |
| @@ -415,7 +386,6 @@ async fn repo_page(cx: &Cx) -> Result<impl View> { | ||
| 415 | 386 | let push_ssh = format!("git remote add origin {ssh}\ngit push -u origin {branch}"); |
| 416 | 387 | let title = format!("{}/{}", repo.owner_name, repo.name); |
| 417 | 388 | |
| 418 | - // The tree and README exist only when the default branch has a commit. | |
| 419 | 389 | let mut tree = None; |
| 420 | 390 | let mut readme = None; |
| 421 | 391 | let mut bar = None; |
| @@ -443,7 +413,6 @@ async fn repo_page(cx: &Cx) -> Result<impl View> { | ||
| 443 | 413 | )); |
| 444 | 414 | } |
| 445 | 415 | let follows = follows_branch(&refs, &branch); |
| 446 | - // The home page follows the default branch even before its first push, so that push goes live. | |
| 447 | 416 | let live = home_live_url(&repo.owner_name, &repo.name, &branch); |
| 448 | 417 | let owner_name = repo.owner_name.clone(); |
| 449 | 418 | let repo_name = repo.name.clone(); |
| @@ -498,7 +467,6 @@ async fn repo_page(cx: &Cx) -> Result<impl View> { | ||
| 498 | 467 | }) |
| 499 | 468 | } |
| 500 | 469 | |
| 501 | -/// Other methods on a repo path get a plain 404, not a 405 that would reveal the route shape. | |
| 502 | 470 | #[route(* "/{owner}/{repo}")] |
| 503 | 471 | async fn repo_other_methods(cx: &Cx) -> Result<&'static str> { |
| 504 | 472 | Err(not_found().into()) |
crates/forge-web-repo/src/pages/authoring_tests.rsmodified+2 -2
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | //! Router-level tests for attachments, suggestions, task toggles and review requests. |
| 2 | 2 | |
| 3 | -use forge_core::Visibility; | |
| 3 | +use forge_core::{EditTarget, Visibility}; | |
| 4 | 4 | use topcoat::router::request::Request; |
| 5 | 5 | use topcoat::router::{Body, to_bytes}; |
| 6 | 6 | |
| @@ -206,7 +206,7 @@ async fn scenario_task_toggles(fx: &Fixture) { | ||
| 206 | 206 | .unwrap() |
| 207 | 207 | .unwrap(); |
| 208 | 208 | assert_eq!(now.body, "- [ ] one\n- [x] two\n"); |
| 209 | - let history = fx.store.edit_history("issue", &issue.id).await.unwrap(); | |
| 209 | + let history = fx.store.edit_history(EditTarget::Issue, &issue.id).await.unwrap(); | |
| 210 | 210 | assert_eq!(history.len(), 1); |
| 211 | 211 | assert_eq!(history[0].old_body, "- [ ] one\n- [ ] two\n"); |
| 212 | 212 |
crates/forge-web-repo/src/pages/branches.rsmodified+3 -2
| @@ -7,6 +7,7 @@ use std::time::{Duration, Instant}; | ||
| 7 | 7 | use forge_core::protection::effective; |
| 8 | 8 | use forge_git::branches; |
| 9 | 9 | use forge_git::browse::{self, RefKind}; |
| 10 | +use forge_git::history::zero_oid; | |
| 10 | 11 | use serde::Deserialize; |
| 11 | 12 | use topcoat::Result; |
| 12 | 13 | use topcoat::context::{Cx, context}; |
| @@ -372,7 +373,7 @@ async fn branch_create(cx: &Cx, Form(form): Form<CreateForm>) -> Result<SeeOther | ||
| 372 | 373 | branch = %branch, |
| 373 | 374 | "branch created from the branches page" |
| 374 | 375 | ); |
| 375 | - let zero = "0".repeat(oid.len()); | |
| 376 | + let zero = zero_oid(&oid); | |
| 376 | 377 | let refname = format!("refs/heads/{branch}"); |
| 377 | 378 | if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &zero, &oid).await { |
| 378 | 379 | tracing::error!(error = %e, "post-update work after branch create failed"); |
| @@ -430,7 +431,7 @@ async fn branch_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<SeeOther | ||
| 430 | 431 | branch = %branch, |
| 431 | 432 | "branch deleted from the branches page" |
| 432 | 433 | ); |
| 433 | - let zero = "0".repeat(tip.len()); | |
| 434 | + let zero = zero_oid(&tip); | |
| 434 | 435 | let refname = format!("refs/heads/{branch}"); |
| 435 | 436 | if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &tip, &zero).await { |
| 436 | 437 | tracing::error!(error = %e, "post-update work after branch delete failed"); |
crates/forge-web-repo/src/pages/ci_tests.rsmodified+48 -77
| @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; | ||
| 6 | 6 | use std::sync::Arc; |
| 7 | 7 | use std::time::Duration; |
| 8 | 8 | |
| 9 | -use forge_core::ci::{CiJob, CiRun, JobState, NewJob, RunState}; | |
| 9 | +use forge_core::ci::{CiJob, CiRun, JobState, NewJob, NewRun, RunState}; | |
| 10 | 10 | use forge_core::{Role, Store, Visibility}; |
| 11 | 11 | use forge_git::repo::{init_bare, repo_path}; |
| 12 | 12 | use topcoat::router::request::Request; |
| @@ -133,6 +133,14 @@ impl Reply { | ||
| 133 | 133 | } |
| 134 | 134 | } |
| 135 | 135 | |
| 136 | +fn assert_notice(res: &Reply, notice: &str) { | |
| 137 | + assert!( | |
| 138 | + res.location() | |
| 139 | + .unwrap_or_default() | |
| 140 | + .ends_with(&format!("?notice={notice}")) | |
| 141 | + ); | |
| 142 | +} | |
| 143 | + | |
| 136 | 144 | async fn get(app: &Router, uri: &str, cookie: Option<&str>) -> Reply { |
| 137 | 145 | let mut builder = Request::builder().method("GET").uri(uri); |
| 138 | 146 | if let Some(cookie) = cookie { |
| @@ -183,15 +191,17 @@ async fn run_with(fx: &Fixture, jobs: &[&str], needs_approval: bool) -> CiRun { | ||
| 183 | 191 | .collect(); |
| 184 | 192 | fx.store |
| 185 | 193 | .create_run( |
| 186 | - &fx.repo.id, | |
| 187 | - "push", | |
| 188 | - "refs/heads/main", | |
| 189 | - &fx.head, | |
| 190 | - None, | |
| 191 | - &fx.tahinli, | |
| 192 | - needs_approval, | |
| 194 | + &NewRun { | |
| 195 | + repo_id: &fx.repo.id, | |
| 196 | + trigger: "push", | |
| 197 | + git_ref: "refs/heads/main", | |
| 198 | + commit_oid: &fx.head, | |
| 199 | + pull_number: None, | |
| 200 | + actor_id: &fx.tahinli, | |
| 201 | + needs_approval, | |
| 202 | + config_error: None, | |
| 203 | + }, | |
| 193 | 204 | &specs, |
| 194 | - None, | |
| 195 | 205 | ) |
| 196 | 206 | .await |
| 197 | 207 | .expect("run") |
| @@ -1058,12 +1068,7 @@ async fn approve_only_works_while_waiting_for_approval() { | ||
| 1058 | 1068 | &[], |
| 1059 | 1069 | ) |
| 1060 | 1070 | .await; |
| 1061 | - assert!( | |
| 1062 | - approved | |
| 1063 | - .location() | |
| 1064 | - .unwrap_or_default() | |
| 1065 | - .ends_with("?notice=approved") | |
| 1066 | - ); | |
| 1071 | + assert_notice(&approved, "approved"); | |
| 1067 | 1072 | let now = fx |
| 1068 | 1073 | .store |
| 1069 | 1074 | .run_by_id(&run.id) |
| @@ -1084,12 +1089,7 @@ async fn approve_only_works_while_waiting_for_approval() { | ||
| 1084 | 1089 | &[], |
| 1085 | 1090 | ) |
| 1086 | 1091 | .await; |
| 1087 | - assert!( | |
| 1088 | - again | |
| 1089 | - .location() | |
| 1090 | - .unwrap_or_default() | |
| 1091 | - .ends_with("?notice=not-waiting") | |
| 1092 | - ); | |
| 1092 | + assert_notice(&again, "not-waiting"); | |
| 1093 | 1093 | let still = fx |
| 1094 | 1094 | .store |
| 1095 | 1095 | .run_by_id(&run.id) |
| @@ -1112,12 +1112,7 @@ async fn cancel_and_rerun_post_and_redirect() { | ||
| 1112 | 1112 | &[], |
| 1113 | 1113 | ) |
| 1114 | 1114 | .await; |
| 1115 | - assert!( | |
| 1116 | - cancelled | |
| 1117 | - .location() | |
| 1118 | - .unwrap_or_default() | |
| 1119 | - .ends_with("?notice=cancelled") | |
| 1120 | - ); | |
| 1115 | + assert_notice(&cancelled, "cancelled"); | |
| 1121 | 1116 | let now = fx |
| 1122 | 1117 | .store |
| 1123 | 1118 | .run_by_id(&run.id) |
| @@ -1132,12 +1127,7 @@ async fn cancel_and_rerun_post_and_redirect() { | ||
| 1132 | 1127 | &[], |
| 1133 | 1128 | ) |
| 1134 | 1129 | .await; |
| 1135 | - assert!( | |
| 1136 | - finished | |
| 1137 | - .location() | |
| 1138 | - .unwrap_or_default() | |
| 1139 | - .ends_with("?notice=finished") | |
| 1140 | - ); | |
| 1130 | + assert_notice(&finished, "finished"); | |
| 1141 | 1131 | |
| 1142 | 1132 | let rerun = post( |
| 1143 | 1133 | &fx.app, |
| @@ -1170,11 +1160,7 @@ async fn manual_run_refuses_an_unknown_branch() { | ||
| 1170 | 1160 | &[("branch", "no-such-branch")], |
| 1171 | 1161 | ) |
| 1172 | 1162 | .await; |
| 1173 | - assert!( | |
| 1174 | - res.location() | |
| 1175 | - .unwrap_or_default() | |
| 1176 | - .ends_with("?notice=no-branch") | |
| 1177 | - ); | |
| 1163 | + assert_notice(&res, "no-branch"); | |
| 1178 | 1164 | let reader = post( |
| 1179 | 1165 | &fx.app, |
| 1180 | 1166 | RUN_BASE, |
| @@ -1249,15 +1235,17 @@ async fn badge_follows_read_access_and_has_no_run_before_one_exists() { | ||
| 1249 | 1235 | }]; |
| 1250 | 1236 | fx.store |
| 1251 | 1237 | .create_run( |
| 1252 | - &open.id, | |
| 1253 | - "push", | |
| 1254 | - "refs/heads/main", | |
| 1255 | - SHA, | |
| 1256 | - None, | |
| 1257 | - &fx.tahinli, | |
| 1258 | - false, | |
| 1238 | + &NewRun { | |
| 1239 | + repo_id: &open.id, | |
| 1240 | + trigger: "push", | |
| 1241 | + git_ref: "refs/heads/main", | |
| 1242 | + commit_oid: SHA, | |
| 1243 | + pull_number: None, | |
| 1244 | + actor_id: &fx.tahinli, | |
| 1245 | + needs_approval: false, | |
| 1246 | + config_error: None, | |
| 1247 | + }, | |
| 1259 | 1248 | &specs, |
| 1260 | - None, | |
| 1261 | 1249 | ) |
| 1262 | 1250 | .await |
| 1263 | 1251 | .expect("run"); |
| @@ -1327,15 +1315,17 @@ async fn run_at(fx: &Fixture, commit: &str) { | ||
| 1327 | 1315 | }]; |
| 1328 | 1316 | fx.store |
| 1329 | 1317 | .create_run( |
| 1330 | - &fx.repo.id, | |
| 1331 | - "push", | |
| 1332 | - "refs/heads/main", | |
| 1333 | - commit, | |
| 1334 | - None, | |
| 1335 | - &fx.tahinli, | |
| 1336 | - false, | |
| 1318 | + &NewRun { | |
| 1319 | + repo_id: &fx.repo.id, | |
| 1320 | + trigger: "push", | |
| 1321 | + git_ref: "refs/heads/main", | |
| 1322 | + commit_oid: commit, | |
| 1323 | + pull_number: None, | |
| 1324 | + actor_id: &fx.tahinli, | |
| 1325 | + needs_approval: false, | |
| 1326 | + config_error: None, | |
| 1327 | + }, | |
| 1337 | 1328 | &specs, |
| 1338 | - None, | |
| 1339 | 1329 | ) |
| 1340 | 1330 | .await |
| 1341 | 1331 | .expect("run"); |
| @@ -1584,12 +1574,7 @@ async fn rerun_failed_and_rerun_job_start_partial_runs() { | ||
| 1584 | 1574 | let page = get(&fx.app, &run_url, Some(&writer)).await.text(); |
| 1585 | 1575 | assert!(!page.contains("Re-run failed jobs")); |
| 1586 | 1576 | let early = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await; |
| 1587 | - assert!( | |
| 1588 | - early | |
| 1589 | - .location() | |
| 1590 | - .unwrap_or_default() | |
| 1591 | - .ends_with("?notice=not-done") | |
| 1592 | - ); | |
| 1577 | + assert_notice(&early, "not-done"); | |
| 1593 | 1578 | |
| 1594 | 1579 | let cancelled = post(&fx.app, &format!("{run_url}/cancel"), &writer, &[]).await; |
| 1595 | 1580 | assert_eq!(cancelled.status, 303); |
| @@ -1647,12 +1632,7 @@ async fn rerun_failed_and_rerun_job_start_partial_runs() { | ||
| 1647 | 1632 | &[], |
| 1648 | 1633 | ) |
| 1649 | 1634 | .await; |
| 1650 | - assert!( | |
| 1651 | - early | |
| 1652 | - .location() | |
| 1653 | - .unwrap_or_default() | |
| 1654 | - .ends_with("?notice=not-done") | |
| 1655 | - ); | |
| 1635 | + assert_notice(&early, "not-done"); | |
| 1656 | 1636 | let refused = post( |
| 1657 | 1637 | &fx.app, |
| 1658 | 1638 | &format!("/tahinli/proj/ci/jobs/{}/rerun", job.id), |
| @@ -1683,12 +1663,7 @@ async fn a_run_on_an_overwritten_commit_cannot_be_rerun() { | ||
| 1683 | 1663 | assert!(!page.contains(">Re-run<")); |
| 1684 | 1664 | assert!(!page.contains(&format!("/commit/{SHA}"))); |
| 1685 | 1665 | let refused = post(&fx.app, &format!("{run_url}/rerun"), &writer, &[]).await; |
| 1686 | - assert!( | |
| 1687 | - refused | |
| 1688 | - .location() | |
| 1689 | - .unwrap_or_default() | |
| 1690 | - .ends_with("?notice=overwritten") | |
| 1691 | - ); | |
| 1666 | + assert_notice(&refused, "overwritten"); | |
| 1692 | 1667 | } |
| 1693 | 1668 | |
| 1694 | 1669 | #[tokio::test] |
| @@ -1702,11 +1677,7 @@ async fn a_run_with_no_failed_jobs_has_nothing_to_rerun() { | ||
| 1702 | 1677 | let page = get(&fx.app, &run_url, Some(&writer)).await.text(); |
| 1703 | 1678 | assert!(!page.contains("Re-run failed jobs")); |
| 1704 | 1679 | let none = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await; |
| 1705 | - assert!( | |
| 1706 | - none.location() | |
| 1707 | - .unwrap_or_default() | |
| 1708 | - .ends_with("?notice=no-failed") | |
| 1709 | - ); | |
| 1680 | + assert_notice(&none, "no-failed"); | |
| 1710 | 1681 | } |
| 1711 | 1682 | |
| 1712 | 1683 | #[tokio::test] |
crates/forge-web-repo/src/pages/pulls_merge.rsmodified+3 -3
| @@ -166,7 +166,7 @@ mod tests { | ||
| 166 | 166 | use std::path::{Path, PathBuf}; |
| 167 | 167 | use std::time::Duration; |
| 168 | 168 | |
| 169 | - use forge_core::protection::Protection; | |
| 169 | + use forge_core::protection::RuleFlags; | |
| 170 | 170 | use forge_core::store::commit_status::StatusState; |
| 171 | 171 | use forge_core::{IssueState, PullRequest, Repo, Role, Store, User, Visibility}; |
| 172 | 172 | use forge_git::repo::{init_bare, repo_path}; |
| @@ -1037,9 +1037,9 @@ mod tests { | ||
| 1037 | 1037 | checks: &[Option<StatusState>], |
| 1038 | 1038 | ) -> MergeGate { |
| 1039 | 1039 | MergeGate { |
| 1040 | - rule: Protection { | |
| 1040 | + rule: RuleFlags { | |
| 1041 | 1041 | required_approvals: need, |
| 1042 | - ..Protection::default() | |
| 1042 | + ..RuleFlags::default() | |
| 1043 | 1043 | }, |
| 1044 | 1044 | approvals, |
| 1045 | 1045 | changes_requested: false, |
crates/forge-web/src/boot.rsmodified+2 -8
| @@ -28,7 +28,7 @@ use crate::ssh_backend::SshBackend; | ||
| 28 | 28 | use crate::state::AppState; |
| 29 | 29 | |
| 30 | 30 | /// Minimum git version forge relies on (receive-pack and stateless-rpc behaviour). |
| 31 | -pub(crate) const MIN_GIT: (u32, u32, u32) = (2, 38, 0); | |
| 31 | +pub(crate) const MIN_GIT: (u32, u32, u32) = (2, 40, 0); | |
| 32 | 32 | |
| 33 | 33 | /// Boots every component and serves until shutdown. |
| 34 | 34 | pub async fn serve( |
| @@ -196,7 +196,7 @@ pub async fn serve( | ||
| 196 | 196 | user_content = %user_content_listen, |
| 197 | 197 | ssh = %ssh_listen, |
| 198 | 198 | data_dir = %data_dir.display(), |
| 199 | - git = %format_version(version), | |
| 199 | + git = %forge_git::version::fmt_version(version), | |
| 200 | 200 | "forge starting" |
| 201 | 201 | ); |
| 202 | 202 | |
| @@ -213,8 +213,6 @@ pub async fn serve( | ||
| 213 | 213 | let ssh_config = SshConfig { |
| 214 | 214 | listen: ssh_listen, |
| 215 | 215 | host_key_path: data_dir.join("ssh_host_ed25519_key"), |
| 216 | - auth_timeout: Duration::from_secs(30), | |
| 217 | - inactivity_timeout: Duration::from_secs(10 * 60), | |
| 218 | 216 | auth_rejection_time: ssh_auth_rejection_time, |
| 219 | 217 | }; |
| 220 | 218 | let ssh_backend = Arc::new(SshBackend { |
| @@ -337,7 +335,3 @@ fn random_hex() -> String { | ||
| 337 | 335 | rand::fill(&mut buf); |
| 338 | 336 | hex::encode(buf) |
| 339 | 337 | } |
| 340 | - | |
| 341 | -fn format_version((major, minor, patch): (u32, u32, u32)) -> String { | |
| 342 | - format!("{major}.{minor}.{patch}") | |
| 343 | -} |
crates/forge-web/src/page_route_tests/repo.rsmodified+17 -33
| @@ -3,7 +3,7 @@ use std::process::Command; | ||
| 3 | 3 | use std::time::Duration; |
| 4 | 4 | |
| 5 | 5 | use forge_core::Visibility; |
| 6 | -use forge_core::time::stamp_before; | |
| 6 | +use forge_core::time::stamp_ago; | |
| 7 | 7 | |
| 8 | 8 | use forge_git::repo::{init_bare, repo_path}; |
| 9 | 9 | |
| @@ -13,11 +13,6 @@ use topcoat::router::{Body, Router, to_bytes}; | ||
| 13 | 13 | use crate::auth::SESSION_COOKIE; |
| 14 | 14 | use crate::state::AppState; |
| 15 | 15 | |
| 16 | -async fn app(dir: &Path) -> (Router, AppState) { | |
| 17 | - let state = crate::test_support::test_state(dir).await; | |
| 18 | - (crate::test_support::app_router(state.clone()), state) | |
| 19 | -} | |
| 20 | - | |
| 21 | 16 | fn git(dir: &Path, args: &[&str]) { |
| 22 | 17 | let status = Command::new("git") |
| 23 | 18 | .current_dir(dir) |
| @@ -38,7 +33,8 @@ fn git(dir: &Path, args: &[&str]) { | ||
| 38 | 33 | |
| 39 | 34 | /// `tahinli/demo` (public, default branch `main` with content) and `tahinli/secret` (private, empty). |
| 40 | 35 | async fn fixture(dir: &Path) -> (Router, AppState) { |
| 41 | - let (router, state) = app(dir).await; | |
| 36 | + let state = crate::test_support::test_state(dir).await; | |
| 37 | + let router = crate::test_support::app_router(state.clone()); | |
| 42 | 38 | let tahinli = state |
| 43 | 39 | .store |
| 44 | 40 | .create_user("tahinli", None, "x", false) |
| @@ -91,18 +87,6 @@ async fn fixture(dir: &Path) -> (Router, AppState) { | ||
| 91 | 87 | (router, state) |
| 92 | 88 | } |
| 93 | 89 | |
| 94 | -async fn get(router: &Router, uri: &str) -> (u16, String) { | |
| 95 | - let req = Request::builder() | |
| 96 | - .method("GET") | |
| 97 | - .uri(uri) | |
| 98 | - .body(Body::empty()) | |
| 99 | - .unwrap(); | |
| 100 | - let res = router.handle(req).await; | |
| 101 | - let status = res.status().as_u16(); | |
| 102 | - let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); | |
| 103 | - (status, String::from_utf8_lossy(&bytes).into_owned()) | |
| 104 | -} | |
| 105 | - | |
| 106 | 90 | // The read-only tests below share one fixture: they only read the demo repo, so each scenario |
| 107 | 91 | // sees the same pristine contents. |
| 108 | 92 | |
| @@ -112,7 +96,7 @@ async fn demo_pages_render_from_the_repo_contents() { | ||
| 112 | 96 | let (router, _) = fixture(dir.path()).await; |
| 113 | 97 | |
| 114 | 98 | // Home renders the README, the tree, the clone popover and the archive links. |
| 115 | - let (status, body) = get(&router, "/tahinli/demo").await; | |
| 99 | + let (status, body) = get_as(&router, "/tahinli/demo", None).await; | |
| 116 | 100 | assert_eq!(status, 200); |
| 117 | 101 | assert!(body.contains("Hello from the README"), "README rendered"); |
| 118 | 102 | assert!( |
| @@ -134,16 +118,16 @@ async fn demo_pages_render_from_the_repo_contents() { | ||
| 134 | 118 | assert!(body.contains("data-ref-filter"), "branch switcher rendered"); |
| 135 | 119 | |
| 136 | 120 | // Trees list their entries and link to subtrees and blobs. |
| 137 | - let (status, body) = get(&router, "/tahinli/demo/tree/main/src").await; | |
| 121 | + let (status, body) = get_as(&router, "/tahinli/demo/tree/main/src", None).await; | |
| 138 | 122 | assert_eq!(status, 200); |
| 139 | 123 | assert!(body.contains("main.rs")); |
| 140 | 124 | assert!(body.contains("/tahinli/demo/blob/main/src/main.rs")); |
| 141 | - let (status, body) = get(&router, "/tahinli/demo/tree/main").await; | |
| 125 | + let (status, body) = get_as(&router, "/tahinli/demo/tree/main", None).await; | |
| 142 | 126 | assert_eq!(status, 200); |
| 143 | 127 | assert!(body.contains("/tahinli/demo/tree/main/docs")); |
| 144 | 128 | |
| 145 | 129 | // Rust source is highlighted with line anchors. |
| 146 | - let (status, body) = get(&router, "/tahinli/demo/blob/main/src/main.rs").await; | |
| 130 | + let (status, body) = get_as(&router, "/tahinli/demo/blob/main/src/main.rs", None).await; | |
| 147 | 131 | assert_eq!(status, 200); |
| 148 | 132 | assert!(body.contains("id=\"L1\"")); |
| 149 | 133 | assert!(body.contains("href=\"#L2\"")); |
| @@ -151,33 +135,33 @@ async fn demo_pages_render_from_the_repo_contents() { | ||
| 151 | 135 | assert!(body.contains("/assets/highlight.css?v=")); |
| 152 | 136 | |
| 153 | 137 | // Markdown renders unless the viewer asks for the plain source. |
| 154 | - let (status, body) = get(&router, "/tahinli/demo/blob/main/docs/guide.md").await; | |
| 138 | + let (status, body) = get_as(&router, "/tahinli/demo/blob/main/docs/guide.md", None).await; | |
| 155 | 139 | assert_eq!(status, 200); |
| 156 | 140 | assert!( |
| 157 | 141 | body.contains("markdown-body") && body.contains("<table>"), |
| 158 | 142 | "GFM table rendered" |
| 159 | 143 | ); |
| 160 | - let (status, body) = get(&router, "/tahinli/demo/blob/main/docs/guide.md?plain=1").await; | |
| 144 | + let (status, body) = get_as(&router, "/tahinli/demo/blob/main/docs/guide.md?plain=1", None).await; | |
| 161 | 145 | assert_eq!(status, 200); |
| 162 | 146 | assert!(body.contains("file-table"), "source shown as lines"); |
| 163 | 147 | assert!(!body.contains("markdown-body"), "not rendered"); |
| 164 | 148 | |
| 165 | 149 | // Binary blobs show their size instead of content. |
| 166 | - let (status, body) = get(&router, "/tahinli/demo/blob/main/data.bin").await; | |
| 150 | + let (status, body) = get_as(&router, "/tahinli/demo/blob/main/data.bin", None).await; | |
| 167 | 151 | assert_eq!(status, 200); |
| 168 | 152 | assert!(body.contains("Binary file, 3 bytes")); |
| 169 | 153 | |
| 170 | 154 | // Fixed segment routes win over the repo catch-all. |
| 171 | - let (status, body) = get(&router, "/tahinli/demo/branches").await; | |
| 155 | + let (status, body) = get_as(&router, "/tahinli/demo/branches", None).await; | |
| 172 | 156 | assert_eq!(status, 200); |
| 173 | 157 | assert!(body.contains("default"), "default branch marked"); |
| 174 | - let (status, body) = get(&router, "/tahinli/demo/tags").await; | |
| 158 | + let (status, body) = get_as(&router, "/tahinli/demo/tags", None).await; | |
| 175 | 159 | assert_eq!(status, 200); |
| 176 | 160 | assert!(body.contains("Nothing here yet.")); |
| 177 | - let (status, body) = get(&router, "/tahinli/demo/tree/main").await; | |
| 161 | + let (status, body) = get_as(&router, "/tahinli/demo/tree/main", None).await; | |
| 178 | 162 | assert_eq!(status, 200); |
| 179 | 163 | assert!(body.contains("README.md")); |
| 180 | - let (status, body) = get(&router, "/tahinli/demo").await; | |
| 164 | + let (status, body) = get_as(&router, "/tahinli/demo", None).await; | |
| 181 | 165 | assert_eq!(status, 200); |
| 182 | 166 | assert!(body.contains("Hello from the README")); |
| 183 | 167 | } |
| @@ -193,7 +177,7 @@ async fn missing_paths_and_private_repos_are_404_for_anonymous() { | ||
| 193 | 177 | "/tahinli/demo/blob/main/src", |
| 194 | 178 | "/tahinli/demo/blob/main", |
| 195 | 179 | ] { |
| 196 | - let (status, _) = get(&router, uri).await; | |
| 180 | + let (status, _) = get_as(&router, uri, None).await; | |
| 197 | 181 | assert_eq!(status, 404, "{uri}"); |
| 198 | 182 | } |
| 199 | 183 | for uri in [ |
| @@ -203,7 +187,7 @@ async fn missing_paths_and_private_repos_are_404_for_anonymous() { | ||
| 203 | 187 | "/tahinli/secret/branches", |
| 204 | 188 | "/tahinli/secret/tags", |
| 205 | 189 | ] { |
| 206 | - let (status, _) = get(&router, uri).await; | |
| 190 | + let (status, _) = get_as(&router, uri, None).await; | |
| 207 | 191 | assert_eq!(status, 404, "{uri}"); |
| 208 | 192 | } |
| 209 | 193 | } |
| @@ -237,7 +221,7 @@ fn make_branch(bare: &Path, branch: &str) { | ||
| 237 | 221 | |
| 238 | 222 | /// Records a push of `branch` to `repo_id` by `actor_id`, `age` ago. |
| 239 | 223 | async fn record_push(state: &AppState, repo_id: &str, actor_id: &str, branch: &str, age: Duration) { |
| 240 | - let at = stamp_before(age); | |
| 224 | + let at = stamp_ago(age); | |
| 241 | 225 | let full = format!("refs/heads/{branch}"); |
| 242 | 226 | state |
| 243 | 227 | .store |