forge
Explore
Log in

Don't you dare go Hollow

Forge-core, forge-ci, forge-git and forge-ssh drop dead code, duplicated helpers and redundant tests

Browse files at this commit

e587be7353fd690b22151a17ef1ff50751fd0ebaAhmet Kaan GümüşParent: 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
Show full message
♻️ 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 +1659 -3956

crates/forge-ci/src/config.rsmodified+16 -21
@@ -20,28 +20,28 @@ use serde::{Deserialize, Serialize};
20 use crate::error::ConfigError;20 use crate::error::ConfigError;
21 21
22 /// Largest accepted `ci.toml`, in bytes.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 /// Largest number of jobs in one workflow.24 /// Largest number of jobs in one workflow.
25-pub const MAX_JOBS: usize = 20;25+const MAX_JOBS: usize = 20;
26 /// Default job timeout.26 /// Default job timeout.
27-pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60;27+const DEFAULT_TIMEOUT_MINUTES: u32 = 60;
28 /// Smallest and largest allowed job timeout.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 /// Longest workflow `name`, in characters, after trimming.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 /// Largest number of `cache` entries in one job.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 /// Longest `cache` entry, in characters.34 /// Longest `cache` entry, in characters.
35-pub const MAX_CACHE_PATH_CHARS: usize = 200;35+const MAX_CACHE_PATH_CHARS: usize = 200;
36 /// Largest number of `[release] assets` entries.36 /// Largest number of `[release] assets` entries.
37-pub const MAX_RELEASE_ASSETS: usize = 32;37+const MAX_RELEASE_ASSETS: usize = 32;
38 /// Longest `[release] title` template, in characters, after trimming.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 /// Most `[on] schedule` entries.41 /// Most `[on] schedule` entries.
42-pub const MAX_SCHEDULES: usize = 8;42+const MAX_SCHEDULES: usize = 8;
43 /// Longest matrix axis value, in characters.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 /// A parsed and validated workflow.46 /// A parsed and validated workflow.
47 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]47 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -257,7 +257,7 @@ pub struct MatrixSpec {
257 }257 }
258 258
259 /// Smallest and largest `memory` a job may declare, in bytes.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 /// Reads `memory` as a size string (`"4g"`) or as a byte count (what the stored spec holds).262 /// Reads `memory` as a size string (`"4g"`) or as a byte count (what the stored spec holds).
263 fn deserialize_memory<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {263 fn deserialize_memory<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
@@ -449,9 +449,9 @@ impl CiConfig {
449 validate_trigger_glob("tag", pattern)?;449 validate_trigger_glob("tag", pattern)?;
450 }450 }
451 if self.on.schedule.len() > MAX_SCHEDULES {451 if self.on.schedule.len() > MAX_SCHEDULES {
452- return Err(ConfigError::InvalidSchedule {452+ return Err(ConfigError::TooManySchedules {
453- expr: String::new(),453+ count: self.on.schedule.len(),
454- reason: format!("at most {MAX_SCHEDULES} schedules are allowed"),454+ max: MAX_SCHEDULES,
455 });455 });
456 }456 }
457 for expr in &self.on.schedule {457 for expr in &self.on.schedule {
@@ -746,11 +746,6 @@ fn validate_release_title(title: &str) -> Result<(), ConfigError> {
746 Ok(())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 /// Whether `selected` (a job name from the config) names `job`: the job itself, or any749 /// Whether `selected` (a job name from the config) names `job`: the job itself, or any
755 /// combination of the matrix job `selected`.750 /// combination of the matrix job `selected`.
756 fn names_job(selected: &str, job: &str) -> bool {751 fn names_job(selected: &str, job: &str) -> bool {
@@ -1753,7 +1748,7 @@ artifacts = ["target/release/forge"]
1753 }1748 }
1754 let many = ["\"0 3 * * *\""; MAX_SCHEDULES + 1].join(", ");1749 let many = ["\"0 3 * * *\""; MAX_SCHEDULES + 1].join(", ");
1755 let text = format!("[on]\nschedule = [{many}]\n{}", job_toml(""));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 #[test]1754 #[test]
crates/forge-ci/src/error.rsmodified+3 -0
@@ -32,6 +32,9 @@ pub enum ConfigError {
32 #[error("invalid schedule {expr:?}: {reason}")]32 #[error("invalid schedule {expr:?}: {reason}")]
33 InvalidSchedule { expr: String, reason: String },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 #[error("invalid job name {0:?}: must match ^[a-z0-9][a-z0-9_-]{{0,39}}$")]38 #[error("invalid job name {0:?}: must match ^[a-z0-9][a-z0-9_-]{{0,39}}$")]
36 InvalidJobName(String),39 InvalidJobName(String),
37 40
crates/forge-ci/src/mask.rsmodified+18 -31
@@ -44,17 +44,6 @@ impl Masker {
44 patterns.sort_by_key(|p| std::cmp::Reverse(p.len()));44 patterns.sort_by_key(|p| std::cmp::Reverse(p.len()));
45 Self { patterns }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 /// Masks a byte stream that arrives in chunks.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 let mut i = 0;87 let mut i = 0;
99 while i < input.len() {88 while i < input.len() {
100 let tail = &input[i..];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 if !last90 if !last
107 && patterns91 && patterns
108 .iter()92 .iter()
@@ -110,19 +94,17 @@ fn scan(patterns: &[Vec<u8>], input: &[u8], last: bool) -> (Vec<u8>, Vec<u8>) {
110 {94 {
111 return (out, tail.to_vec());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 out.push(input[i]);102 out.push(input[i]);
114 i += 1;103 i += 1;
115 }104 }
116 (out, Vec::new())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 #[cfg(test)]108 #[cfg(test)]
127 mod tests {109 mod tests {
128 use super::*;110 use super::*;
@@ -132,7 +114,7 @@ mod tests {
132 }114 }
133 115
134 fn stream_all(m: &Masker, chunks: &[&[u8]]) -> String {116 fn stream_all(m: &Masker, chunks: &[&[u8]]) -> String {
135- let mut s = m.stream();117+ let mut s = MaskStream::new(m.clone());
136 let mut out = Vec::new();118 let mut out = Vec::new();
137 for c in chunks {119 for c in chunks {
138 out.extend(s.push(c));120 out.extend(s.push(c));
@@ -146,31 +128,36 @@ mod tests {
146 let secret = "hunter2-secret";128 let secret = "hunter2-secret";
147 let encoded = STANDARD.encode(secret.as_bytes());129 let encoded = STANDARD.encode(secret.as_bytes());
148 let m = masker(&[secret]);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 let other = masker(&["abcdefgh"]);132 let other = masker(&["abcdefgh"]);
151 let enc = STANDARD.encode("abcdefgh");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 #[test]137 #[test]
156 fn short_values_are_ignored() {138 fn short_values_are_ignored() {
157 let m = masker(&["abc", "", "ab"]);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 // 4 chars is the minimum that is masked.141 // 4 chars is the minimum that is masked.
160 let m = masker(&["abcd"]);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 #[test]146 #[test]
165 fn longest_match_wins() {147 fn longest_match_wins() {
166 let m = masker(&["secret-value", "secret"]);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 #[test]158 #[test]
171 fn empty_secret_set_is_a_no_op() {159 fn empty_secret_set_is_a_no_op() {
172 let m = Masker::new(std::iter::empty());160 let m = Masker::new(std::iter::empty());
173- assert_eq!(m.mask("anything"), "anything");
174 assert_eq!(stream_all(&m, &[b"anything"]), "anything");161 assert_eq!(stream_all(&m, &[b"anything"]), "anything");
175 }162 }
176 163
@@ -218,7 +205,7 @@ mod tests {
218 #[test]205 #[test]
219 fn held_bytes_are_bounded() {206 fn held_bytes_are_bounded() {
220 let m = masker(&["0123456789"]);207 let m = masker(&["0123456789"]);
221- let mut s = m.stream();208+ let mut s = MaskStream::new(m);
222 let out = s.push(b"0123456");209 let out = s.push(b"0123456");
223 assert!(out.is_empty());210 assert!(out.is_empty());
224 assert!(s.held.len() <= 9);211 assert!(s.held.len() <= 9);
crates/forge-ci/src/steps.rsmodified+23 -6
@@ -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.62+/// Drops the ANSI escape sequences and the other control characters (a tab stays) of a log line.
63-fn strip_ansi(line: &str) -> String {63+pub fn strip_ansi(line: &str) -> String {
64 let mut out = String::with_capacity(line.len());64 let mut out = String::with_capacity(line.len());
65 let mut chars = line.chars().peekable();65 let mut chars = line.chars().peekable();
66 while let Some(c) = chars.next() {66 while let Some(c) = chars.next() {
67- if c == '\u{1b}' && chars.peek() == Some(&'[') {67+ if c == '\u{1b}' {
68+ match chars.peek() {
69+ Some('[') => {
68 chars.next();70 chars.next();
69- for f in chars.by_ref() {71+ for n in chars.by_ref() {
70- if ('\u{40}'..='\u{7e}').contains(&f) {72+ if ('@'..='~').contains(&n) {
71 break;73 break;
72 }74 }
73 }75 }
74- } else {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+ _ => {}
90+ }
91+ } else if c == '\t' || !c.is_control() {
75 out.push(c);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 /// `fixed` (exclusive) or `last_affected` (inclusive). `introduced` of `0` starts at the beginning.256 /// `fixed` (exclusive) or `last_affected` (inclusive). `introduced` of `0` starts at the beginning.
257 /// An interval still open at the end runs forever.257 /// An interval still open at the end runs forever.
258 fn range_affects(range: &Range, version: &semver::Version) -> bool {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 let mut open: Option<Option<semver::Version>> = None;259 let mut open: Option<Option<semver::Version>> = None;
261 for event in &range.events {260 for event in &range.events {
262 match event {261 match event {
@@ -264,7 +263,6 @@ fn range_affects(range: &Range, version: &semver::Version) -> bool {
264 open = Some(if raw == "0" {263 open = Some(if raw == "0" {
265 None264 None
266 } else {265 } else {
267- // An unreadable start is treated as "from the beginning": more alerts, never fewer.
268 parse_version(raw)266 parse_version(raw)
269 });267 });
270 }268 }
crates/forge-core/src/alerts.rsmodified+0 -26
@@ -18,32 +18,6 @@ pub enum AlertKind {
18 Replication,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 /// Whether a job's result looks like the process was killed: SIGKILL (`signal: 9`, `SIGKILL`,21 /// Whether a job's result looks like the process was killed: SIGKILL (`signal: 9`, `SIGKILL`,
48 /// `Killed`), the shell's `128 + 9` exit code, or an out-of-memory message.22 /// `Killed`), the shell's `128 + 9` exit code, or an out-of-memory message.
49 pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool {23 pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool {
crates/forge-core/src/audit.rsmodified+120 -325
@@ -6,339 +6,135 @@ use ulid::Ulid;
6 6
7 use crate::time::now_stamp;7 use crate::time::now_stamp;
8 8
9-/// Every security-relevant action that is recorded. The `as_str` names are stored and shown.9+macro_rules! audit_actions {
10+ ($($variant:ident => $name:literal,)*) => {
10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]11 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
11 pub enum AuditAction {12 pub enum AuditAction {
12- LoginSuccess,13+ $($variant,)*
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 }14 }
119 15
120 impl AuditAction {16 impl AuditAction {
121- /// Every action, in declaration order. Used to parse filter values.17+ pub const ALL: &'static [AuditAction] = &[$(AuditAction::$variant,)*];
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- ];
230 18
231 pub fn as_str(self) -> &'static str {19 pub fn as_str(self) -> &'static str {
232 match self {20 match self {
233- AuditAction::LoginSuccess => "login_success",21+ $(AuditAction::$variant => $name,)*
234- AuditAction::LoginFailed => "login_failed",22+ }
235- AuditAction::Login2faFailed => "login_2fa_failed",23+ }
236- AuditAction::Logout => "logout",24+ }
237- AuditAction::PasswordChanged => "password_changed",25+ };
238- AuditAction::EmailChanged => "email_changed",26+}
239- AuditAction::PasswordResetByAdmin => "password_reset_by_admin",27+
240- AuditAction::TotpEnabled => "totp_enabled",28+audit_actions! {
241- AuditAction::TotpDisabled => "totp_disabled",29+ LoginSuccess => "login_success",
242- AuditAction::RecoveryCodesRegenerated => "recovery_codes_regenerated",30+ LoginFailed => "login_failed",
243- AuditAction::SshKeyAdded => "ssh_key_added",31+ Login2faFailed => "login_2fa_failed",
244- AuditAction::SshKeyRemoved => "ssh_key_removed",32+ Logout => "logout",
245- AuditAction::GpgKeyAdded => "gpg_key_added",33+ PasswordChanged => "password_changed",
246- AuditAction::GpgKeyDeleted => "gpg_key_deleted",34+ EmailChanged => "email_changed",
247- AuditAction::TokenCreated => "token_created",35+ PasswordResetByAdmin => "password_reset_by_admin",
248- AuditAction::TokenRevoked => "token_revoked",36+ TotpEnabled => "totp_enabled",
249- AuditAction::SessionRevoked => "session_revoked",37+ TotpDisabled => "totp_disabled",
250- AuditAction::UserCreated => "user_created",38+ RecoveryCodesRegenerated => "recovery_codes_regenerated",
251- AuditAction::UsernameChanged => "username_changed",39+ SshKeyAdded => "ssh_key_added",
252- AuditAction::UserDeleted => "user_deleted",40+ SshKeyRemoved => "ssh_key_removed",
253- AuditAction::RepoCreated => "repo_created",41+ GpgKeyAdded => "gpg_key_added",
254- AuditAction::RepoDeleted => "repo_deleted",42+ GpgKeyDeleted => "gpg_key_deleted",
255- AuditAction::RepoRenamed => "repo_renamed",43+ TokenCreated => "token_created",
256- AuditAction::RepoTransferred => "repo_transferred",44+ TokenRevoked => "token_revoked",
257- AuditAction::RepoTransferInitiated => "repo_transfer_initiated",45+ SessionRevoked => "session_revoked",
258- AuditAction::RepoTransferAccepted => "repo_transfer_accepted",46+ UserCreated => "user_created",
259- AuditAction::RepoTransferDeclined => "repo_transfer_declined",47+ UsernameChanged => "username_changed",
260- AuditAction::RepoTransferCancelled => "repo_transfer_cancelled",48+ UserDeleted => "user_deleted",
261- AuditAction::RepoVisibilityChanged => "repo_visibility_changed",49+ RepoCreated => "repo_created",
262- AuditAction::CollaboratorAdded => "collaborator_added",50+ RepoDeleted => "repo_deleted",
263- AuditAction::CollaboratorRemoved => "collaborator_removed",51+ RepoRenamed => "repo_renamed",
264- AuditAction::CollaboratorRoleChanged => "collaborator_role_changed",52+ RepoTransferred => "repo_transferred",
265- AuditAction::BranchRuleCreated => "branch_rule_created",53+ RepoTransferInitiated => "repo_transfer_initiated",
266- AuditAction::BranchRuleUpdated => "branch_rule_updated",54+ RepoTransferAccepted => "repo_transfer_accepted",
267- AuditAction::BranchRuleDeleted => "branch_rule_deleted",55+ RepoTransferDeclined => "repo_transfer_declined",
268- AuditAction::RepoArchived => "repo_archived",56+ RepoTransferCancelled => "repo_transfer_cancelled",
269- AuditAction::RepoUnarchived => "repo_unarchived",57+ RepoVisibilityChanged => "repo_visibility_changed",
270- AuditAction::WebhookCreated => "webhook_created",58+ CollaboratorAdded => "collaborator_added",
271- AuditAction::WebhookUpdated => "webhook_updated",59+ CollaboratorRemoved => "collaborator_removed",
272- AuditAction::WebhookDeleted => "webhook_deleted",60+ CollaboratorRoleChanged => "collaborator_role_changed",
273- AuditAction::MirrorCreated => "mirror_created",61+ BranchRuleCreated => "branch_rule_created",
274- AuditAction::MirrorUpdated => "mirror_updated",62+ BranchRuleUpdated => "branch_rule_updated",
275- AuditAction::MirrorDeleted => "mirror_deleted",63+ BranchRuleDeleted => "branch_rule_deleted",
276- AuditAction::MirrorSyncFailed => "mirror_sync_failed",64+ RepoArchived => "repo_archived",
277- AuditAction::BackupStarted => "backup_started",65+ RepoUnarchived => "repo_unarchived",
278- AuditAction::FsckStarted => "fsck_started",66+ WebhookCreated => "webhook_created",
279- AuditAction::ReplicationReconcileStarted => "replication_reconcile_started",67+ WebhookUpdated => "webhook_updated",
280- AuditAction::CiSecretSet => "ci_secret_set",68+ WebhookDeleted => "webhook_deleted",
281- AuditAction::CiSecretDeleted => "ci_secret_deleted",69+ MirrorCreated => "mirror_created",
282- AuditAction::CiRunnerRegistered => "ci_runner_registered",70+ MirrorUpdated => "mirror_updated",
283- AuditAction::CiRunnerDeleted => "ci_runner_deleted",71+ MirrorDeleted => "mirror_deleted",
284- AuditAction::CiRunnerRestartRequested => "ci_runner_restart_requested",72+ MirrorSyncFailed => "mirror_sync_failed",
285- AuditAction::CiRunnerConfigChanged => "ci_runner_config_changed",73+ BackupStarted => "backup_started",
286- AuditAction::CiRegistrationTokenCreated => "ci_registration_token_created",74+ FsckStarted => "fsck_started",
287- AuditAction::AdvisoryAlertDismissed => "advisory_alert_dismissed",75+ ReplicationReconcileStarted => "replication_reconcile_started",
288- AuditAction::AdvisoryAlertReopened => "advisory_alert_reopened",76+ CiSecretSet => "ci_secret_set",
289- AuditAction::UiPrefsChanged => "ui_prefs_changed",77+ CiSecretDeleted => "ci_secret_deleted",
290- AuditAction::DiscussionsEnabled => "discussions_enabled",78+ CiRunnerRegistered => "ci_runner_registered",
291- AuditAction::DiscussionsDisabled => "discussions_disabled",79+ CiRunnerDeleted => "ci_runner_deleted",
292- AuditAction::DiscussionCreated => "discussion_created",80+ CiRunnerRestartRequested => "ci_runner_restart_requested",
293- AuditAction::DiscussionEdited => "discussion_edited",81+ CiRunnerConfigChanged => "ci_runner_config_changed",
294- AuditAction::DiscussionDeleted => "discussion_deleted",82+ CiRegistrationTokenCreated => "ci_registration_token_created",
295- AuditAction::DiscussionLocked => "discussion_locked",83+ AdvisoryAlertDismissed => "advisory_alert_dismissed",
296- AuditAction::DiscussionUnlocked => "discussion_unlocked",84+ AdvisoryAlertReopened => "advisory_alert_reopened",
297- AuditAction::DiscussionAnswered => "discussion_answered",85+ UiPrefsChanged => "ui_prefs_changed",
298- AuditAction::DiscussionCommentCreated => "discussion_comment_created",86+ DiscussionsEnabled => "discussions_enabled",
299- AuditAction::DiscussionCommentEdited => "discussion_comment_edited",87+ DiscussionsDisabled => "discussions_disabled",
300- AuditAction::DiscussionCommentDeleted => "discussion_comment_deleted",88+ DiscussionCreated => "discussion_created",
301- AuditAction::MailSettingsUpdated => "mail_settings_updated",89+ DiscussionEdited => "discussion_edited",
302- AuditAction::MailTestQueued => "mail_test_queued",90+ DiscussionDeleted => "discussion_deleted",
303- AuditAction::ServerSettingsUpdated => "server_settings_updated",91+ DiscussionLocked => "discussion_locked",
304- AuditAction::ServerRestarted => "server_restarted",92+ DiscussionUnlocked => "discussion_unlocked",
305- AuditAction::SnippetCreated => "snippet_created",93+ DiscussionAnswered => "discussion_answered",
306- AuditAction::SnippetUpdated => "snippet_updated",94+ DiscussionCommentCreated => "discussion_comment_created",
307- AuditAction::SnippetDeleted => "snippet_deleted",95+ DiscussionCommentEdited => "discussion_comment_edited",
308- AuditAction::WikiPageSaved => "wiki_page_saved",96+ DiscussionCommentDeleted => "discussion_comment_deleted",
309- AuditAction::WikiEnabled => "wiki_enabled",97+ MailSettingsUpdated => "mail_settings_updated",
310- AuditAction::WikiDisabled => "wiki_disabled",98+ MailTestQueued => "mail_test_queued",
311- AuditAction::WikiPushed => "wiki_pushed",99+ ServerSettingsUpdated => "server_settings_updated",
312- AuditAction::OrgCreated => "org_created",100+ ServerRestarted => "server_restarted",
313- AuditAction::OrgDeleted => "org_deleted",101+ SnippetCreated => "snippet_created",
314- AuditAction::OrgSettingsUpdated => "org_settings_updated",102+ SnippetUpdated => "snippet_updated",
315- AuditAction::OrgMemberAdded => "org_member_added",103+ SnippetDeleted => "snippet_deleted",
316- AuditAction::OrgMemberRemoved => "org_member_removed",104+ WikiPageSaved => "wiki_page_saved",
317- AuditAction::OrgMemberRoleChanged => "org_member_role_changed",105+ WikiEnabled => "wiki_enabled",
318- AuditAction::TeamCreated => "team_created",106+ WikiDisabled => "wiki_disabled",
319- AuditAction::TeamUpdated => "team_updated",107+ WikiPushed => "wiki_pushed",
320- AuditAction::TeamDeleted => "team_deleted",108+ OrgCreated => "org_created",
321- AuditAction::TeamMemberAdded => "team_member_added",109+ OrgDeleted => "org_deleted",
322- AuditAction::TeamMemberRemoved => "team_member_removed",110+ OrgSettingsUpdated => "org_settings_updated",
323- AuditAction::TeamRepoAdded => "team_repo_added",111+ OrgMemberAdded => "org_member_added",
324- AuditAction::TeamRepoRemoved => "team_repo_removed",112+ OrgMemberRemoved => "org_member_removed",
325- AuditAction::PasswordResetCompleted => "password_reset_completed",113+ OrgMemberRoleChanged => "org_member_role_changed",
326- AuditAction::EmailVerified => "email_verified",114+ TeamCreated => "team_created",
327- AuditAction::InviteSent => "invite_sent",115+ TeamUpdated => "team_updated",
328- AuditAction::InviteAccepted => "invite_accepted",116+ TeamDeleted => "team_deleted",
329- AuditAction::UserSuspended => "user_suspended",117+ TeamMemberAdded => "team_member_added",
330- AuditAction::UserUnsuspended => "user_unsuspended",118+ TeamMemberRemoved => "team_member_removed",
331- AuditAction::AdminGranted => "admin_granted",119+ TeamRepoAdded => "team_repo_added",
332- AuditAction::AdminRevoked => "admin_revoked",120+ TeamRepoRemoved => "team_repo_removed",
333- AuditAction::TotpDisabledByAdmin => "totp_disabled_by_admin",121+ PasswordResetCompleted => "password_reset_completed",
334- AuditAction::PasskeyAdded => "passkey_added",122+ EmailVerified => "email_verified",
335- AuditAction::PasskeyRenamed => "passkey_renamed",123+ InviteSent => "invite_sent",
336- AuditAction::PasskeyDeleted => "passkey_deleted",124+ InviteAccepted => "invite_accepted",
337- AuditAction::PasskeysRemovedByAdmin => "passkeys_removed_by_admin",125+ UserSuspended => "user_suspended",
338- AuditAction::PasskeyLogin => "passkey_login",126+ UserUnsuspended => "user_unsuspended",
339- }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",
340 }135 }
341 136
137+impl AuditAction {
342 /// The action with this stored name, if any.138 /// The action with this stored name, if any.
343 pub fn parse(name: &str) -> Option<AuditAction> {139 pub fn parse(name: &str) -> Option<AuditAction> {
344 AuditAction::ALL140 AuditAction::ALL
@@ -436,13 +232,12 @@ mod tests {
436 #[test]232 #[test]
437 fn names_are_unique_and_round_trip() {233 fn names_are_unique_and_round_trip() {
438 let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect();234 let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect();
439- assert_eq!(names.len(), 106);
440 for action in AuditAction::ALL {235 for action in AuditAction::ALL {
441 assert_eq!(AuditAction::parse(action.as_str()), Some(*action));236 assert_eq!(AuditAction::parse(action.as_str()), Some(*action));
442 }237 }
443 names.sort();238 names.sort();
444 names.dedup();239 names.dedup();
445- assert_eq!(names.len(), 106);240+ assert_eq!(names.len(), AuditAction::ALL.len());
446 assert_eq!(AuditAction::parse("nope"), None);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 /// The higher of two optional roles. `Read < Triage < Write < Maintain < Admin`.24 /// The higher of two optional roles. `Read < Triage < Write < Maintain < Admin`.
25 pub fn max_role(a: Option<Role>, b: Option<Role>) -> Option<Role> {25 pub fn max_role(a: Option<Role>, b: Option<Role>) -> Option<Role> {
26- fn rank(role: Role) -> u8 {26+ a.max(b)
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- }
40 }27 }
41 28
42 /// Owner or instance admin: all actions. Public repo: Read for anyone.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 let entry = entry.ok()?;193 let entry = entry.ok()?;
194 let path = entry.path().ok()?.into_owned();194 let path = entry.path().ok()?.into_owned();
195 let mut parts = path.components();195 let mut parts = path.components();
196- parts.next()?;196+ let (Some(_), Some(file)) = (parts.next(), parts.next()) else {
197- let file = parts.next()?;197+ continue;
198+ };
198 let is_top = parts.next().is_none();199 let is_top = parts.next().is_none();
199 let file_name = file.as_os_str().to_string_lossy().to_ascii_lowercase();200 let file_name = file.as_os_str().to_string_lossy().to_ascii_lowercase();
200 if is_top && file_name.starts_with("readme") && entry.header().entry_type().is_file() {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 //! migrations/0024_ci.sql; the store functions live in store/ci.rs.2 //! migrations/0024_ci.sql; the store functions live in store/ci.rs.
3 //!3 //!
4 //! Job specs are kept as JSON text (`CiJob::spec_json`). The store reads only the `needs` and4 //! 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 use std::collections::BTreeMap;7 use std::collections::BTreeMap;
8 use std::str::FromStr;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 use crate::error::{Error, Result};14 use crate::error::{Error, Result};
11 15
12 /// State of a run. Stored as the `as_str` name.16 /// State of a run. Stored as the `as_str` name.
@@ -142,35 +146,6 @@ pub struct CiRunner {
142 pub config_overrides: BTreeMap<String, serde_json::Value>,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 /// A pending runner restart: asked for, not yet seen to happen.149 /// A pending runner restart: asked for, not yet seen to happen.
175 #[derive(Debug, Clone, PartialEq, Eq)]150 #[derive(Debug, Clone, PartialEq, Eq)]
176 pub struct RunnerRestart {151 pub struct RunnerRestart {
@@ -319,8 +294,8 @@ pub fn validate_runner_field(
319 match key {294 match key {
320 "concurrency" => int_in(295 "concurrency" => int_in(
321 raw,296 raw,
322- i64::from(MIN_RUNNER_CONCURRENCY),297+ i64::from(MIN_CONCURRENCY),
323- i64::from(MAX_RUNNER_CONCURRENCY),298+ i64::from(MAX_CONCURRENCY),
324 "concurrency",299 "concurrency",
325 ),300 ),
326 "labels" => {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 /// One run of the workflow for a commit.507 /// One run of the workflow for a commit.
537 #[derive(Debug, Clone, PartialEq, Eq)]508 #[derive(Debug, Clone, PartialEq, Eq)]
538 pub struct CiRun {509 pub struct CiRun {
@@ -673,6 +644,17 @@ pub struct NewJob<'a> {
673 pub needs: &'a [String],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 #[cfg(test)]658 #[cfg(test)]
677 mod memory_tests {659 mod memory_tests {
678 use super::*;660 use super::*;
crates/forge-core/src/config.rsmodified+20 -22
@@ -233,30 +233,12 @@ impl BannerConfig {
233 233
234 /// Parses `YYYY-MM-DD HH:MM` (UTC) into unix seconds.234 /// Parses `YYYY-MM-DD HH:MM` (UTC) into unix seconds.
235 pub fn parse_banner_expiry(raw: &str) -> Option<i64> {235 pub fn parse_banner_expiry(raw: &str) -> Option<i64> {
236- let raw = raw.trim();236+ let dt = jiff::civil::DateTime::strptime("%Y-%m-%d %H:%M", raw.trim()).ok()?;
237- let (date, time) = raw.split_once(' ')?;237+ if dt.year() < 1970 {
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) {
245- return None;
246- }
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;238 return None;
251 }239 }
252- // Days from civil (Howard Hinnant).240+ let zoned = dt.to_zoned_datetime(jiff::tz::TimeZone::UTC).ok()?;
253- let y2 = if m <= 2 { y - 1 } else { y };241+ Some(zoned.timestamp().as_second())
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)
260 }242 }
261 243
262 /// Self-update, from the `[self_update]` section. When enabled, a successful push run of `repo`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 /// Git LFS limits, from the `[lfs]` section.423 /// Git LFS limits, from the `[lfs]` section.
427 #[derive(Debug, Clone, Deserialize)]424 #[derive(Debug, Clone, Deserialize)]
428 #[serde(deny_unknown_fields, default)]425 #[serde(deny_unknown_fields, default)]
@@ -804,6 +801,7 @@ impl Config {
804 self.backup.validate()?;801 self.backup.validate()?;
805 self.replication.validate()?;802 self.replication.validate()?;
806 self.self_update.validate()?;803 self.self_update.validate()?;
804+ self.advisories.validate()?;
807 self.storage.validate()?;805 self.storage.validate()?;
808 Ok(())806 Ok(())
809 }807 }
crates/forge-core/src/issue_refs.rsmodified+14 -19
@@ -11,25 +11,13 @@ const CLOSING_KEYWORDS: [&str; 9] = [
11 /// Maximum number of digits in an issue number.11 /// Maximum number of digits in an issue number.
12 const MAX_DIGITS: usize = 9;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 /// Every `#N` reference in `text`, deduplicated, in order of first appearance.14 /// Every `#N` reference in `text`, deduplicated, in order of first appearance.
21 ///15 ///
22 /// A reference is `#` followed by 1 to 9 digits. It is not recognised when the `#` is preceded by16 /// A reference is `#` followed by 1 to 9 digits. It is not recognised when the `#` is preceded by
23 /// an alphanumeric char, `&` or `/`, or when the digits are followed by an alphanumeric char.17 /// an alphanumeric char, `&` or `/`, or when the digits are followed by an alphanumeric char.
24 /// `#0` is not an issue number and is ignored.18 /// `#0` is not an issue number and is ignored.
25 pub fn find_issue_refs(text: &str) -> Vec<i64> {19 pub fn find_issue_refs(text: &str) -> Vec<i64> {
26- let mut out: Vec<i64> = Vec::new();20+ dedup(issue_ref_spans(text).into_iter().map(|(_, n)| n))
27- for (_, n) in scan_refs(text) {
28- if !out.contains(&n) {
29- out.push(n);
30- }
31- }
32- out
33 }21 }
34 22
35 /// Issue numbers closed by closing keywords in `text`, deduplicated, in order.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 /// separated by a `:`, with at least one whitespace char between the keyword (or colon) and `#`.26 /// separated by a `:`, with at least one whitespace char between the keyword (or colon) and `#`.
39 /// Example: `"Fixes: #3, closes #4"` gives `[3, 4]`; `"unfixes #2"` gives nothing.27 /// Example: `"Fixes: #3, closes #4"` gives `[3, 4]`; `"unfixes #2"` gives nothing.
40 pub fn find_closing_refs(text: &str) -> Vec<i64> {28 pub fn find_closing_refs(text: &str) -> Vec<i64> {
41- let mut out: Vec<i64> = Vec::new();29+ dedup(
42- for (range, n) in scan_refs(text) {30+ issue_ref_spans(text)
43- if !preceded_by_closing_keyword(&text[..range.start]) {31+ .into_iter()
44- continue;32+ .filter(|(range, _)| preceded_by_closing_keyword(&text[..range.start]))
33+ .map(|(_, n)| n),
34+ )
45 }35 }
36+
37+fn dedup(values: impl Iterator<Item = i64>) -> Vec<i64> {
38+ let mut out: Vec<i64> = Vec::new();
39+ for n in values {
46 if !out.contains(&n) {40 if !out.contains(&n) {
47 out.push(n);41 out.push(n);
48 }42 }
@@ -50,8 +44,9 @@ pub fn find_closing_refs(text: &str) -> Vec<i64> {
50 out44 out
51 }45 }
52 46
53-/// Byte range of each valid `#N` reference and its value, in order of appearance.47+/// Byte range (including the `#`) and value of every valid `#N` reference in `text`, in order.
54-fn scan_refs(text: &str) -> Vec<(Range<usize>, i64)> {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 let bytes = text.as_bytes();50 let bytes = text.as_bytes();
56 let mut refs = Vec::new();51 let mut refs = Vec::new();
57 let mut i = 0;52 let mut i = 0;
crates/forge-core/src/lib.rsmodified+1 -2
@@ -30,7 +30,6 @@ pub mod releases;
30 pub mod reviews;30 pub mod reviews;
31 pub mod secret;31 pub mod secret;
32 pub mod server_settings;32 pub mod server_settings;
33-pub mod session;
34 pub mod store;33 pub mod store;
35 pub mod suggestions;34 pub mod suggestions;
36 pub mod time;35 pub mod time;
@@ -50,4 +49,4 @@ pub use pulls::*;
50 pub use reactions::{Reaction, ReactionMap, ReactionSummary, ReactionTarget};49 pub use reactions::{Reaction, ReactionMap, ReactionSummary, ReactionTarget};
51 pub use reviews::*;50 pub use reviews::*;
52 pub use store::Store;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 pub last_error: Option<String>,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 impl OutboxEntry {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 /// The state of the row at `now` (an RFC 3339-style stamp, compared as text).275 /// The state of the row at `now` (an RFC 3339-style stamp, compared as text).
304 pub fn state_at(&self, now: &str) -> MailState {276 pub fn state_at(&self, now: &str) -> MailState {
305 if self.sent_at.is_some() {277 if self.sent_at.is_some() {
@@ -527,31 +499,4 @@ mod tests {
527 entry.sent_at = Some(now.into());499 entry.sent_at = Some(now.into());
528 assert_eq!(entry.state_at(now), MailState::Sent);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 QueueState::Removed => "removed",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 impl std::str::FromStr for QueueState {30 impl std::str::FromStr for QueueState {
crates/forge-core/src/model.rsmodified+1 -1
@@ -9,7 +9,7 @@ pub enum Visibility {
9 Private,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 #[serde(rename_all = "lowercase")]13 #[serde(rename_all = "lowercase")]
14 pub enum Role {14 pub enum Role {
15 Read,15 Read,
crates/forge-core/src/names.rsmodified+0 -4
@@ -43,10 +43,6 @@ pub const RESERVED: &[&str] = &[
43 "favicon.ico",43 "favicon.ico",
44 "robots.txt",44 "robots.txt",
45 "security.txt",45 "security.txt",
46- ".well-known",
47- "-",
48- ".",
49- "..",
50 ];46 ];
51 47
52 /// NFKC normalization plus case fold.48 /// NFKC normalization plus case fold.
crates/forge-core/src/notifications.rsmodified+2 -2
@@ -1,5 +1,6 @@
1 //! Notification models: repo watch levels, issue subscriptions and inbox entries.1 //! Notification models: repo watch levels, issue subscriptions and inbox entries.
2 2
3+use crate::issues::IssueState;
3 use crate::model::Id;4 use crate::model::Id;
4 5
5 /// How much activity a user hears about in a repo. A user with no row is `Participating`.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 /// True for pull requests (`issues.kind = 'pull'`).127 /// True for pull requests (`issues.kind = 'pull'`).
127 pub is_pull: bool,128 pub is_pull: bool,
128 pub title: String,129 pub title: String,
129- /// `open` or `closed`.130+ pub issue_state: IssueState,
130- pub issue_state: String,
131 pub reason: Reason,131 pub reason: Reason,
132 pub last_activity: String,132 pub last_activity: String,
133 /// `None` when the actor was deleted without a ghost reassignment or the activity had none.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 pub created_at: String,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 #[derive(Debug, Clone, Default, PartialEq, Eq)]51 #[derive(Debug, Clone, Default, PartialEq, Eq)]
37 pub struct RuleFlags {52 pub struct RuleFlags {
38 pub allow_force_push: bool,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 /// Rejects `required_approvals` above `MAX_REQUIRED_APPROVALS`.74 /// Rejects `required_approvals` above `MAX_REQUIRED_APPROVALS`.
73 pub fn validate_required_approvals(n: u32) -> Result<()> {75 pub fn validate_required_approvals(n: u32) -> Result<()> {
74 if n > MAX_REQUIRED_APPROVALS {76 if n > MAX_REQUIRED_APPROVALS {
@@ -219,7 +221,7 @@ fn is_literal(pattern: &str) -> bool {
219 /// longest pattern wins, and ties go to the earliest created_at.221 /// longest pattern wins, and ties go to the earliest created_at.
220 /// 2. Otherwise, if `branch == default_branch`: built-in protection {force_push: false, deletion: false}.222 /// 2. Otherwise, if `branch == default_branch`: built-in protection {force_push: false, deletion: false}.
221 /// 3. Otherwise: unprotected {force_push: true, deletion: true}.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 let best = rules225 let best = rules
224 .iter()226 .iter()
225 .filter(|r| pattern_matches(&r.pattern, branch))227 .filter(|r| pattern_matches(&r.pattern, branch))
@@ -233,29 +235,12 @@ pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> Pr
233 .then_with(|| a.pattern.cmp(&b.pattern))235 .then_with(|| a.pattern.cmp(&b.pattern))
234 });236 });
235 if let Some(rule) = best {237 if let Some(rule) = best {
236- return Protection {238+ return rule.flags();
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- };
246 }239 }
247 if branch == default_branch {240 if branch == default_branch {
248- Protection {241+ RuleFlags::basic(false, false)
249- allow_force_push: false,
250- allow_deletion: false,
251- ..Protection::default()
252- }
253 } else {242 } else {
254- Protection {243+ RuleFlags::basic(true, true)
255- allow_force_push: true,
256- allow_deletion: true,
257- ..Protection::default()
258- }
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 #[test]268 #[test]
292 fn pattern_matches_cases() {269 fn pattern_matches_cases() {
293 assert!(pattern_matches("main", "main"));270 assert!(pattern_matches("main", "main"));
@@ -335,27 +312,27 @@ mod tests {
335 #[test]312 #[test]
336 fn effective_without_rules_protects_only_default() {313 fn effective_without_rules_protects_only_default() {
337 let none: &[BranchRule] = &[];314 let none: &[BranchRule] = &[];
338- assert_eq!(effective(none, "main", "main"), flags(false, false));315+ assert_eq!(effective(none, "main", "main"), RuleFlags::basic(false, false));
339- assert_eq!(effective(none, "main", "feature"), flags(true, true));316+ assert_eq!(effective(none, "main", "feature"), RuleFlags::basic(true, true));
340 }317 }
341 318
342 #[test]319 #[test]
343 fn effective_literal_allows_force_push_on_main() {320 fn effective_literal_allows_force_push_on_main() {
344 let rules = [rule("main", true, false, "1")];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 #[test]325 #[test]
349 fn effective_literal_beats_glob() {326 fn effective_literal_beats_glob() {
350 let rules = [rule("*", false, false, "1"), rule("main", true, true, "2")];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 #[test]331 #[test]
355 fn effective_longer_glob_wins() {332 fn effective_longer_glob_wins() {
356 // Both `*` and `rel*` match `release`; the longer `rel*` wins even though `*` is older.333 // Both `*` and `rel*` match `release`; the longer `rel*` wins even though `*` is older.
357 let rules = [rule("*", true, true, "0"), rule("rel*", false, false, "1")];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 // `release/**` is longer than `release/*`, so it wins for nested names.336 // `release/**` is longer than `release/*`, so it wins for nested names.
360 let rules = [337 let rules = [
361 rule("release/*", true, true, "1"),338 rule("release/*", true, true, "1"),
@@ -363,7 +340,7 @@ mod tests {
363 ];340 ];
364 assert_eq!(341 assert_eq!(
365 effective(&rules, "main", "release/a/b"),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 let rules = [gated];354 let rules = [gated];
378 assert_eq!(355 assert_eq!(
379 effective(&rules, "main", "main"),356 effective(&rules, "main", "main"),
380- Protection {357+ RuleFlags {
381 allow_force_push: false,358 allow_force_push: false,
382 allow_deletion: false,359 allow_deletion: false,
383 required_approvals: 2,360 required_approvals: 2,
crates/forge-core/src/reactions.rsmodified+0 -9
@@ -1,7 +1,6 @@
1 //! Emoji reactions: the fixed set a user can put on an issue, a pull request or a comment, and1 //! Emoji reactions: the fixed set a user can put on an issue, a pull request or a comment, and
2 //! the summaries the pages show. Stored as the short name (`+1`, `heart`, ...).2 //! the summaries the pages show. Stored as the short name (`+1`, `heart`, ...).
3 3
4-use crate::error::{Error, Result};
5 use crate::model::Id;4 use crate::model::Id;
6 5
7 /// The fixed reaction set, in the order the pages list them.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 /// What a reaction is attached to. Pull requests are issue rows, so they use `Issue`.66 /// What a reaction is attached to. Pull requests are issue rows, so they use `Issue`.
76 #[derive(Debug, Clone, Copy, PartialEq, Eq)]67 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
77 pub enum ReactionTarget {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 fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {26 fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {
27- use std::io::Write;
28-
29 use rand::TryRng;27 use rand::TryRng;
30 28
31 let mut key = [0u8; 32];29 let mut key = [0u8; 32];
@@ -33,6 +31,16 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {
33 .try_fill_bytes(&mut key)31 .try_fill_bytes(&mut key)
34 .map_err(std::io::Error::other)?;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 let mut options = std::fs::OpenOptions::new();44 let mut options = std::fs::OpenOptions::new();
37 options.write(true).create_new(true);45 options.write(true).create_new(true);
38 #[cfg(unix)]46 #[cfg(unix)]
@@ -41,14 +49,8 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {
41 options.mode(0o600);49 options.mode(0o600);
42 }50 }
43 let mut file = options.open(path)?;51 let mut file = options.open(path)?;
44- let written = file.write_all(&key).and_then(|()| file.sync_all());52+ file.write_all(key)?;
45- if let Err(e) = written {53+ file.sync_all()
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 }54 }
53 55
54 fn read_key(path: &Path) -> Result<[u8; 32]> {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 use std::collections::{BTreeMap, BTreeSet};1 use std::collections::{BTreeMap, BTreeSet};
18 use std::net::IpAddr;2 use std::net::IpAddr;
19 use std::sync::{Arc, RwLock};3 use std::sync::{Arc, RwLock};
20 4
21 use ipnet::IpNet;5 use ipnet::IpNet;
22 6
7+use crate::advisories::KNOWN_ECOSYSTEMS;
23 use crate::config::{Config, MailTransport, OrgCreation, Registration, StorageBackend};8 use crate::config::{Config, MailTransport, OrgCreation, Registration, StorageBackend};
24 use crate::error::{Error, Result};9 use crate::error::{Error, Result};
25 10
26-/// How a field reaches the running process.
27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]11 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
28 pub enum Kind {12 pub enum Kind {
29 Live,13 Live,
@@ -31,7 +15,6 @@ pub enum Kind {
31 ReadOnly,15 ReadOnly,
32 }16 }
33 17
34-/// The page tab a field belongs to.
35 #[derive(Debug, Clone, Copy, PartialEq, Eq)]18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
36 pub enum Group {19 pub enum Group {
37 General,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 #[derive(Debug, Clone, Copy, PartialEq, Eq)]54 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
73 pub enum Ty {55 pub enum Ty {
74 Bool,56 Bool,
75- /// Whole number in `min..=max`.
76 Uint(u64, u64),57 Uint(u64, u64),
77 Text,58 Text,
78- /// A filesystem path. Empty is allowed and usually means "off".
79 Path,59 Path,
80 Choice(&'static [&'static str]),60 Choice(&'static [&'static str]),
81- /// Comma separated entries.
82 List,61 List,
83- /// Write-only text.
84 Secret,62 Secret,
85- /// Socket address (read-only fields only).
86 Addr,63 Addr,
87 }64 }
88 65
@@ -132,7 +109,6 @@ const JURISDICTION: &[&str] = &["", "eu", "fedramp"];
132 const MB: Ty = Ty::Uint(1, 1_048_576);109 const MB: Ty = Ty::Uint(1, 1_048_576);
133 const PORT: Ty = Ty::Uint(1, 65_535);110 const PORT: Ty = Ty::Uint(1, 65_535);
134 111
135-/// Every setting, in display order.
136 pub static FIELDS: &[Field] = &[112 pub static FIELDS: &[Field] = &[
137 f(113 f(
138 "registration",114 "registration",
@@ -723,7 +699,6 @@ pub static FIELDS: &[Field] = &[
723 ),699 ),
724 ];700 ];
725 701
726-/// The field for a dotted key.
727 pub fn field(key: &str) -> Option<&'static Field> {702 pub fn field(key: &str) -> Option<&'static Field> {
728 FIELDS.iter().find(|f| f.key == key)703 FIELDS.iter().find(|f| f.key == key)
729 }704 }
@@ -740,7 +715,6 @@ fn split_list(raw: &str) -> Vec<String> {
740 .collect()715 .collect()
741 }716 }
742 717
743-/// Checks `raw` against the field's type and returns its canonical string.
744 pub fn normalize(field: &Field, raw: &str) -> Result<String> {718 pub fn normalize(field: &Field, raw: &str) -> Result<String> {
745 let raw = raw.trim();719 let raw = raw.trim();
746 match field.ty {720 match field.ty {
@@ -807,7 +781,7 @@ pub fn normalize(field: &Field, raw: &str) -> Result<String> {
807 }781 }
808 if field.key == "advisories.ecosystems" {782 if field.key == "advisories.ecosystems" {
809 for item in &items {783 for item in &items {
810- if !matches!(item.as_str(), "crates.io" | "npm" | "Go") {784+ if !KNOWN_ECOSYSTEMS.contains(&item.as_str()) {
811 return Err(invalid(field, &format!("unknown ecosystem `{item}`")));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 pub fn get(cfg: &Config, key: &str) -> String {817 pub fn get(cfg: &Config, key: &str) -> String {
846 let path = |p: &std::path::Path| p.to_string_lossy().into_owned();818 let path = |p: &std::path::Path| p.to_string_lossy().into_owned();
847 let list = |v: &[String]| v.join(", ");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 pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> {919 pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> {
949 let field = field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?;920 let field = field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?;
950 if field.kind == Kind::ReadOnly {921 if field.kind == Kind::ReadOnly {
@@ -1072,8 +1043,6 @@ pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> {
1072 Ok(())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 pub fn apply(file: &Config, overrides: &BTreeMap<String, String>) -> Result<Config> {1046 pub fn apply(file: &Config, overrides: &BTreeMap<String, String>) -> Result<Config> {
1078 let mut cfg = file.clone();1047 let mut cfg = file.clone();
1079 for (key, value) in overrides {1048 for (key, value) in overrides {
@@ -1084,9 +1053,6 @@ pub fn apply(file: &Config, overrides: &BTreeMap<String, String>) -> Result<Conf
1084 Ok(cfg)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 pub fn boot_config(file: &Config, overrides: &BTreeMap<String, String>) -> (Config, Option<Error>) {1056 pub fn boot_config(file: &Config, overrides: &BTreeMap<String, String>) -> (Config, Option<Error>) {
1091 match apply(file, overrides).and_then(|c| c.validate().map(|()| c)) {1057 match apply(file, overrides).and_then(|c| c.validate().map(|()| c)) {
1092 Ok(config) => (config, None),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 pub fn live_view(boot: &Config, pending: &Config) -> Config {1063 pub fn live_view(boot: &Config, pending: &Config) -> Config {
1099 let mut cfg = boot.clone();1064 let mut cfg = boot.clone();
1100 for f in FIELDS.iter().filter(|f| f.kind == Kind::Live) {1065 for f in FIELDS.iter().filter(|f| f.kind == Kind::Live) {
1101- // Values from `get` always pass `normalize`, so this cannot fail.
1102 let _ = set(&mut cfg, f.key, &get(pending, f.key));1066 let _ = set(&mut cfg, f.key, &get(pending, f.key));
1103 }1067 }
1104 cfg1068 cfg
1105 }1069 }
1106 1070
1107-/// Where a field's effective value comes from.
1108 #[derive(Debug, Clone, Copy, PartialEq, Eq)]1071 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1109 pub enum Source {1072 pub enum Source {
1110 Default,1073 Default,
@@ -1112,23 +1075,16 @@ pub enum Source {
1112 Ui,1075 Ui,
1113 }1076 }
1114 1077
1115-/// One field as the page shows it.
1116 #[derive(Debug, Clone)]1078 #[derive(Debug, Clone)]
1117 pub struct FieldView {1079 pub struct FieldView {
1118 pub field: &'static Field,1080 pub field: &'static Field,
1119- /// Effective value. Empty for a secret.
1120 pub value: String,1081 pub value: String,
1121- /// The value the file (or default) gives. Empty for a secret.
1122 pub file_value: String,1082 pub file_value: String,
1123 pub source: Source,1083 pub source: Source,
1124- /// For a secret: whether a value is set.
1125 pub secret_set: bool,1084 pub secret_set: bool,
1126- /// Saved but not yet running: a restart field whose value differs from the running one.
1127 pub restart_pending: bool,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 pub struct Live {1088 pub struct Live {
1133 file: Arc<Config>,1089 file: Arc<Config>,
1134 file_keys: BTreeSet<String>,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 pub fn current(&self) -> Arc<Config> {1105 pub fn current(&self) -> Arc<Config> {
1151 self.current1106 self.current
1152 .read()1107 .read()
@@ -1154,15 +1109,6 @@ impl Live {
1154 .clone()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 pub fn publish(&self, overrides: &BTreeMap<String, String>) -> Result<()> {1112 pub fn publish(&self, overrides: &BTreeMap<String, String>) -> Result<()> {
1167 let pending = apply(&self.file, overrides)?;1113 let pending = apply(&self.file, overrides)?;
1168 pending.validate()?;1114 pending.validate()?;
@@ -1174,7 +1120,6 @@ impl Live {
1174 Ok(())1120 Ok(())
1175 }1121 }
1176 1122
1177- /// Every field with its effective value and source.
1178 pub fn views(&self, overrides: &BTreeMap<String, String>) -> Vec<FieldView> {1123 pub fn views(&self, overrides: &BTreeMap<String, String>) -> Vec<FieldView> {
1179 let pending = apply(&self.file, overrides).unwrap_or_else(|_| (*self.file).clone());1124 let pending = apply(&self.file, overrides).unwrap_or_else(|_| (*self.file).clone());
1180 FIELDS1125 FIELDS
@@ -1210,9 +1155,6 @@ impl Live {
1210 .collect()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 pub fn plan_save(1158 pub fn plan_save(
1217 &self,1159 &self,
1218 existing: &BTreeMap<String, String>,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 pub fn plan_reset(1207 pub fn plan_reset(
1267 &self,1208 &self,
1268 existing: &BTreeMap<String, String>,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 #[derive(Debug)]1220 #[derive(Debug)]
1281 pub struct SavePlan {1221 pub struct SavePlan {
1282 pub sets: Vec<(String, String)>,1222 pub sets: Vec<(String, String)>,
1283 pub clears: Vec<String>,1223 pub clears: Vec<String>,
1284- /// All overrides once the plan is applied.
1285 pub overrides: BTreeMap<String, String>,1224 pub overrides: BTreeMap<String, String>,
1286 }1225 }
1287 1226
@@ -1379,7 +1318,7 @@ max_log_mb = 20
1379 let v = live.views(&over);1318 let v = live.views(&over);
1380 let v = v.iter().find(|v| v.field.key == "base_url").unwrap();1319 let v = v.iter().find(|v| v.field.key == "base_url").unwrap();
1381 assert!(v.restart_pending);1320 assert!(v.restart_pending);
1382- let (boot, err) = boot_config(live.file(), &over);1321+ let (boot, err) = boot_config(&base(), &over);
1383 assert!(err.is_none());1322 assert!(err.is_none());
1384 assert_eq!(boot.base_url, "https://new.example");1323 assert_eq!(boot.base_url, "https://new.example");
1385 let after = Live::new(Arc::new(base()), Default::default(), Arc::new(boot));1324 let after = Live::new(Arc::new(base()), Default::default(), Arc::new(boot));
@@ -1402,7 +1341,6 @@ max_log_mb = 20
1402 let mut cfg = base();1341 let mut cfg = base();
1403 assert!(set(&mut cfg, key, value).is_err(), "{key}={value}");1342 assert!(set(&mut cfg, key, value).is_err(), "{key}={value}");
1404 }1343 }
1405- // Cross-field loader rules apply to a whole save.
1406 let group_form = form(&[("storage.backend", "r2")]);1344 let group_form = form(&[("storage.backend", "r2")]);
1407 assert!(1345 assert!(
1408 live.plan_save(&BTreeMap::new(), Group::Storage, &group_form)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 use std::time::Duration;6 use std::time::Duration;
7 7
8-use super::issues::finish;8+use super::finish;
9 use super::{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 use crate::error::{Error, Result};13 use crate::error::{Error, Result};
13 use crate::model::{AccountKind, User};14 use crate::model::{AccountKind, User};
@@ -98,10 +99,10 @@ impl Store {
98 let conn = self.read_conn().await;99 let conn = self.read_conn().await;
99 fetch_opt(100 fetch_opt(
100 &conn,101 &conn,
101- "SELECT id, username, email, password_hash, is_admin, created_at, about, timezone, \102+ &format!(
102- (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \103+ "SELECT {USER_COLS} FROM users WHERE LOWER(email) = LOWER(?1) \
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"
104- AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1",105+ ),
105 (email.to_owned(),),106 (email.to_owned(),),
106 map_user,107 map_user,
107 )108 )
crates/forge-core/src/store/admin_alerts.rsmodified+2 -6
@@ -6,8 +6,8 @@
6 6
7 use turso::{Row, Value};7 use turso::{Row, Value};
8 8
9-use super::issues::finish;9+use super::finish;
10-use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id};10+use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id, text};
11 use crate::error::Result;11 use crate::error::Result;
12 use crate::time::now_stamp;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 impl Store {62 impl Store {
67 /// Marks the condition `key` active. Returns true when it was not active before, which is63 /// Marks the condition `key` active. Returns true when it was not active before, which is
68 /// when the admins are told. An alert already active keeps its first `raised_at`; only its64 /// 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 outcome.opened += 1;302 outcome.opened += 1;
303 }303 }
304 Some(AlertState::Fixed) => {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 outcome.opened += 1;306 outcome.opened += 1;
307 }307 }
308 Some(AlertState::Open | AlertState::Dismissed) => {}308 Some(AlertState::Open | AlertState::Dismissed) => {}
@@ -310,7 +310,7 @@ impl Store {
310 }310 }
311 for (key, state) in &existing {311 for (key, state) in &existing {
312 if *state == AlertState::Open && !matched.contains(key) {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 outcome.fixed += 1;314 outcome.fixed += 1;
315 }315 }
316 }316 }
@@ -333,21 +333,7 @@ impl Store {
333 let rid = repo_id.to_string();333 let rid = repo_id.to_string();
334 let now = now_stamp();334 let now = now_stamp();
335 let outcome: Result<bool> = async {335 let outcome: Result<bool> = async {
336- let mut params = key_params(&rid, key);336+ let changed = set_state(&tx, &rid, key, from, to, &now).await?;
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)?;
351 Ok(changed > 0)337 Ok(changed > 0)
352 }338 }
353 .await;339 .await;
@@ -531,22 +517,23 @@ async fn set_state(
531 tx: &turso::transaction::Transaction<'_>,517 tx: &turso::transaction::Transaction<'_>,
532 repo_id: &str,518 repo_id: &str,
533 key: &AlertKey,519 key: &AlertKey,
534- state: AlertState,520+ from: AlertState,
521+ to: AlertState,
535 now: &str,522 now: &str,
536-) -> Result<()> {523+) -> Result<u64> {
537 let mut params = key_params(repo_id, key);524 let mut params = key_params(repo_id, key);
538 params.extend([525 params.extend([
539- Value::Text(state.as_str().to_string()),526+ Value::Text(to.as_str().to_string()),
540 Value::Text(now.to_string()),527 Value::Text(now.to_string()),
528+ Value::Text(from.as_str().to_string()),
541 ]);529 ]);
542 tx.execute(530 tx.execute(
543 "UPDATE repo_alerts SET state = ?6, updated_at = ?7 WHERE repo_id = ?1 AND advisory_id = ?2 \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 params,533 params,
546 )534 )
547 .await535 .await
548- .map_err(db_err)?;536+ .map_err(db_err)
549- Ok(())
550 }537 }
551 538
552 #[cfg(test)]539 #[cfg(test)]
crates/forge-core/src/store/audit.rsmodified+1 -10
@@ -2,7 +2,7 @@
2 2
3 use turso::{Row, Value};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 use crate::audit::{AuditAction, AuditCursor, AuditEntry, AuditFilter};6 use crate::audit::{AuditAction, AuditCursor, AuditEntry, AuditFilter};
7 use crate::error::{Error, Result};7 use crate::error::{Error, Result};
8 8
@@ -142,15 +142,6 @@ impl Store {
142 fetch_all(&conn, &sql, params, map_audit).await142 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 /// Retention: deletes entries stamped before `cutoff` (an RFC 3339 UTC stamp). Returns the145 /// Retention: deletes entries stamped before `cutoff` (an RFC 3339 UTC stamp). Returns the
155 /// number of entries removed. This is the only delete on the audit log.146 /// number of entries removed. This is the only delete on the audit log.
156 pub async fn purge_audit_before(&self, cutoff: &str) -> Result<u64> {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 use turso::{Row, Value};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 use crate::error::{Error, Result};7 use crate::error::{Error, Result};
8 use crate::time::now_stamp;8 use crate::time::now_stamp;
9 9
@@ -76,29 +76,12 @@ pub struct BackupRun {
76 pub error: Option<String>,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 fn map_run(row: &Row) -> Result<BackupRun> {79 fn map_run(row: &Row) -> Result<BackupRun> {
96 let kind = col_text(row, 1)?;80 let kind = col_text(row, 1)?;
97 let trigger = col_text(row, 8)?;81 let trigger = col_text(row, 8)?;
98- let bytes = match opt_int(row, 6)? {82+ let bytes = col_opt_int(row, 6)?
99- Some(n) => Some(u64::try_from(n).map_err(|_| Error::Database("negative run size".into()))?),83+ .map(|n| u64::try_from(n).map_err(|_| Error::Database("negative run size".into())))
100- None => None,84+ .transpose()?;
101- };
102 Ok(BackupRun {85 Ok(BackupRun {
103 id: col_text(row, 0)?,86 id: col_text(row, 0)?,
104 kind: RunKind::parse(&kind)87 kind: RunKind::parse(&kind)
@@ -106,11 +89,11 @@ fn map_run(row: &Row) -> Result<BackupRun> {
106 trigger: RunTrigger::parse(&trigger)89 trigger: RunTrigger::parse(&trigger)
107 .ok_or_else(|| Error::Database(format!("unknown run trigger {trigger:?}")))?,90 .ok_or_else(|| Error::Database(format!("unknown run trigger {trigger:?}")))?,
108 started_at: col_text(row, 2)?,91 started_at: col_text(row, 2)?,
109- finished_at: opt_text(row, 3)?,92+ finished_at: col_opt_text(row, 3)?,
110- ok: opt_int(row, 4)?.map(|n| n != 0),93+ ok: col_opt_int(row, 4)?.map(|n| n != 0),
111- path: opt_text(row, 5)?,94+ path: col_opt_text(row, 5)?,
112 bytes,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+149 -236
@@ -10,19 +10,19 @@ use std::time::Duration;
10 use turso::{Connection, Row, Value};10 use turso::{Connection, Row, Value};
11 11
12 use super::{12 use super::{
13- Store, col_blob, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt,13+ Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all,
14- finish, insert_err, missing_row, new_id,14+ fetch_opt, finish, insert_err, missing_row, new_id, opt_int_value, opt_text, text,
15 };15 };
16 use crate::ci::{16 use crate::ci::{
17 CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, JobStep,17 CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, JobStep,
18- MAX_RUNNER_CONCURRENCY, MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode,18+ MemoryOffer, NewJob, NewRun, QueueSkips, RestartMode, RunState, RunnerJob, RunnerReport,
19- RunState, RunnerJob, RunnerReport, RunnerRestart, STARVE_AFTER_SECS, StepSample,19+ RunnerRestart, STARVE_AFTER_SECS, StepSample, pick_by_memory, validate_runner_field,
20- pick_by_memory, validate_runner_field,
21 };20 };
22 use crate::error::{Error, Result};21 use crate::error::{Error, Result};
23 use crate::secret;22 use crate::secret;
24 use crate::time::{now_stamp, stamp_after, stamp_to_unix};23 use crate::time::{now_stamp, stamp_after, stamp_to_unix};
25 use crate::token::{generate_token, hash_token};24 use crate::token::{generate_token, hash_token};
25+use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY};
26 use forge_ci::steps::{MAX_STEPS, StepMark};26 use forge_ci::steps::{MAX_STEPS, StepMark};
27 27
28 const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, message, queued_at, \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 /// Longest page `list_runs` returns.50 /// Longest page `list_runs` returns.
51 const MAX_PER_PAGE: u32 = 100;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 fn map_runner(row: &Row) -> Result<CiRunner> {53 fn map_runner(row: &Row) -> Result<CiRunner> {
75 let labels = serde_json::from_str::<Vec<String>>(&col_text(row, 2)?)54 let labels = serde_json::from_str::<Vec<String>>(&col_text(row, 2)?)
76 .map_err(|e| Error::Database(format!("runner labels are not a string list: {e}")))?;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 concurrency: opt_u32(row, 7)?,65 concurrency: opt_u32(row, 7)?,
87 version: col_opt_text(row, 8)?,66 version: col_opt_text(row, 8)?,
88 cpus: opt_u32(row, 9)?,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 build: col_opt_text(row, 14)?,69 build: col_opt_text(row, 14)?,
91 boot_id: col_opt_text(row, 15)?,70 boot_id: col_opt_text(row, 15)?,
92 capabilities: col_opt_text(row, 18)?71 capabilities: col_opt_text(row, 18)?
@@ -97,15 +76,14 @@ fn map_runner(row: &Row) -> Result<CiRunner> {
97 .collect()76 .collect()
98 })77 })
99 .unwrap_or_default(),78 .unwrap_or_default(),
100- memory_budget: opt_int(row, 19)?.and_then(|n| u64::try_from(n).ok()),79+ memory_budget: col_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()),80+ memory_free: col_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()),81+ memory_reserve: col_opt_int(row, 21)?.and_then(|n| u64::try_from(n).ok()),
103 },82 },
104 restart: match (col_opt_text(row, 16)?, col_opt_text(row, 17)?) {83 restart: match (col_opt_text(row, 16)?, col_opt_text(row, 17)?) {
105- (Some(mode), Some(requested_at)) => mode84+ (Some(mode), Some(requested_at)) => {
106- .parse::<RestartMode>()85+ RestartMode::parse(&mode).map(|mode| RunnerRestart { mode, requested_at })
107- .ok()86+ }
108- .map(|mode| RunnerRestart { mode, requested_at }),
109 _ => None,87 _ => None,
110 },88 },
111 running_jobs: opt_u32(row, 13)?.unwrap_or(0),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 /// A NULL-able integer column that holds a count.102 /// A NULL-able integer column that holds a count.
125 fn opt_u32(row: &Row, i: usize) -> Result<Option<u32>> {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 fn map_run(row: &Row) -> Result<CiRun> {107 fn map_run(row: &Row) -> Result<CiRun> {
@@ -134,7 +112,7 @@ fn map_run(row: &Row) -> Result<CiRun> {
134 trigger: col_text(row, 3)?,112 trigger: col_text(row, 3)?,
135 git_ref: col_text(row, 4)?,113 git_ref: col_text(row, 4)?,
136 commit_oid: col_text(row, 5)?,114 commit_oid: col_text(row, 5)?,
137- pull_number: opt_int(row, 6)?,115+ pull_number: col_opt_int(row, 6)?,
138 actor_id: col_text(row, 7)?,116 actor_id: col_text(row, 7)?,
139 state: col_text(row, 8)?.parse::<RunState>()?,117 state: col_text(row, 8)?.parse::<RunState>()?,
140 config_error: col_opt_text(row, 9)?,118 config_error: col_opt_text(row, 9)?,
@@ -151,7 +129,7 @@ fn map_job(row: &Row) -> Result<CiJob> {
151 spec_json: col_text(row, 3)?,129 spec_json: col_text(row, 3)?,
152 state: col_text(row, 4)?.parse::<JobState>()?,130 state: col_text(row, 4)?.parse::<JobState>()?,
153 runner_id: col_opt_text(row, 5)?,131 runner_id: col_opt_text(row, 5)?,
154- exit_code: opt_int(row, 6)?,132+ exit_code: col_opt_int(row, 6)?,
155 message: col_opt_text(row, 7)?,133 message: col_opt_text(row, 7)?,
156 queued_at: col_opt_text(row, 8)?,134 queued_at: col_opt_text(row, 8)?,
157 started_at: col_opt_text(row, 9)?,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 Ok(())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 impl Store {437 impl Store {
415 fn seal_ci_secret(&self, plain: &[u8]) -> Result<Vec<u8>> {438 fn seal_ci_secret(&self, plain: &[u8]) -> Result<Vec<u8>> {
416- let key = self439+ Ok(secret::seal(self.secret_key()?, plain)?.into_bytes())
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())
422 }440 }
423 441
424 /// Creates a single-use registration token valid for `ttl_hours`. Returns the plaintext,442 /// Creates a single-use registration token valid for `ttl_hours`. Returns the plaintext,
@@ -457,8 +475,9 @@ impl Store {
457 let conn = self.inner.conn.lock().await;475 let conn = self.inner.conn.lock().await;
458 let mut rows = conn476 let mut rows = conn
459 .query(477 .query(
460- "SELECT 1 FROM ci_registration_tokens WHERE token_hash = ?1 AND used_at IS NULL",478+ "SELECT 1 FROM ci_registration_tokens \
461- vec![text(token_hash)],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 .await482 .await
464 .map_err(db_err)?;483 .map_err(db_err)?;
@@ -655,10 +674,10 @@ impl Store {
655 /// must be 1 to 64, else `Invalid`. `NotFound` if the runner does not exist.674 /// must be 1 to 64, else `Invalid`. `NotFound` if the runner does not exist.
656 pub async fn set_runner_concurrency(&self, id: &str, value: Option<u32>) -> Result<()> {675 pub async fn set_runner_concurrency(&self, id: &str, value: Option<u32>) -> Result<()> {
657 if let Some(n) = value676 if let Some(n) = value
658- && !(MIN_RUNNER_CONCURRENCY..=MAX_RUNNER_CONCURRENCY).contains(&n)677+ && !(MIN_CONCURRENCY..=MAX_CONCURRENCY).contains(&n)
659 {678 {
660 return Err(Error::Invalid(format!(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 let conn = self.inner.conn.lock().await;683 let conn = self.inner.conn.lock().await;
@@ -695,14 +714,7 @@ impl Store {
695 .await;714 .await;
696 }715 }
697 let conn = self.inner.conn.lock().await;716 let conn = self.inner.conn.lock().await;
698- let mut runner = fetch_opt(717+ let mut runner = load_runner(&conn, id).await?.ok_or(Error::NotFound)?;
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)?;
706 match parsed {718 match parsed {
707 Some(v) => {719 Some(v) => {
708 runner.config_overrides.insert(key.to_owned(), v);720 runner.config_overrides.insert(key.to_owned(), v);
@@ -719,7 +731,6 @@ impl Store {
719 .map_err(|e| Error::Database(e.to_string()))?,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 let labels = if key == "labels" {734 let labels = if key == "labels" {
724 let chosen = runner735 let chosen = runner
725 .config_overrides736 .config_overrides
@@ -762,14 +773,7 @@ impl Store {
762 config: &BTreeMap<String, serde_json::Value>,773 config: &BTreeMap<String, serde_json::Value>,
763 ) -> Result<bool> {774 ) -> Result<bool> {
764 let conn = self.inner.conn.lock().await;775 let conn = self.inner.conn.lock().await;
765- let current = fetch_opt(776+ let Some(current) = load_runner(&conn, id).await? else {
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 {
773 return Ok(false);777 return Ok(false);
774 };778 };
775 if &current.reported_config == config {779 if &current.reported_config == config {
@@ -831,14 +835,7 @@ impl Store {
831 /// value. Returns true when a stored value changed, so the caller can tell live pages.835 /// value. Returns true when a stored value changed, so the caller can tell live pages.
832 pub async fn record_runner_report(&self, id: &str, report: &RunnerReport) -> Result<bool> {836 pub async fn record_runner_report(&self, id: &str, report: &RunnerReport) -> Result<bool> {
833 let conn = self.inner.conn.lock().await;837 let conn = self.inner.conn.lock().await;
834- let current = fetch_opt(838+ let Some(current) = load_runner(&conn, id).await? else {
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 {
842 return Ok(false);839 return Ok(false);
843 };840 };
844 let merged = RunnerReport {841 let merged = RunnerReport {
@@ -860,7 +857,6 @@ impl Store {
860 if merged == current.reported {857 if merged == current.reported {
861 return Ok(false);858 return Ok(false);
862 }859 }
863- // A new boot id while a restart is pending means the runner came back.
864 if merged.boot_id != current.reported.boot_id && current.restart.is_some() {860 if merged.boot_id != current.reported.boot_id && current.restart.is_some() {
865 conn.execute(861 conn.execute(
866 "UPDATE ci_runners SET restart_mode = NULL, restart_requested_at = NULL \862 "UPDATE ci_runners SET restart_mode = NULL, restart_requested_at = NULL \
@@ -924,7 +920,7 @@ impl Store {
924 |row| col_opt_text(row, 0),920 |row| col_opt_text(row, 0),
925 )921 )
926 .await?;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 /// Removes a runner. `NotFound` if it does not exist.926 /// Removes a runner. `NotFound` if it does not exist.
@@ -947,18 +943,17 @@ impl Store {
947 /// `Blocked` until `approve_run`. Otherwise need-less jobs are `Queued` and the run is943 /// `Blocked` until `approve_run`. Otherwise need-less jobs are `Queued` and the run is
948 /// `Queued`. Jobs with needs are always `Blocked` at first.944 /// `Queued`. Jobs with needs are always `Blocked` at first.
949 #[allow(clippy::too_many_arguments)]945 #[allow(clippy::too_many_arguments)]
950- pub async fn create_run(946+ pub async fn create_run(&self, run: &NewRun<'_>, jobs: &[NewJob<'_>]) -> Result<CiRun> {
951- &self,947+ let NewRun {
952- repo_id: &str,948+ repo_id,
953- trigger: &str,949+ trigger,
954- git_ref: &str,950+ git_ref,
955- commit_oid: &str,951+ commit_oid,
956- pull_number: Option<i64>,952+ pull_number,
957- actor_id: &str,953+ actor_id,
958- needs_approval: bool,954+ needs_approval,
959- jobs: &[NewJob<'_>],955+ config_error,
960- config_error: Option<&str>,956+ } = *run;
961- ) -> Result<CiRun> {
962 let id = new_id();957 let id = new_id();
963 let now = now_stamp();958 let now = now_stamp();
964 let conn = self.inner.conn.lock().await;959 let conn = self.inner.conn.lock().await;
@@ -1099,11 +1094,10 @@ impl Store {
1099 let candidates: Vec<(Option<u64>, u64)> = compatible1094 let candidates: Vec<(Option<u64>, u64)> = compatible
1100 .iter()1095 .iter()
1101 .map(|(_, spec, queued_at)| {1096 .map(|(_, spec, queued_at)| {
1102- let waited = queued_at1097+ (
1103- .as_deref()1098+ declared_memory(spec),
1104- .and_then(stamp_to_unix)1099+ waited_secs(queued_at.as_deref(), now),
1105- .map_or(0, |at| u64::try_from(now - at).unwrap_or(0));1100+ )
1106- (declared_memory(spec), waited)
1107 })1101 })
1108 .collect();1102 .collect();
1109 compatible = pick_by_memory(&candidates, &offer, STARVE_AFTER_SECS)1103 compatible = pick_by_memory(&candidates, &offer, STARVE_AFTER_SECS)
@@ -1168,7 +1162,6 @@ impl Store {
1168 ..QueueSkips::default()1162 ..QueueSkips::default()
1169 };1163 };
1170 let mut missing = BTreeSet::new();1164 let mut missing = BTreeSet::new();
1171- // The same walk as `pick_by_memory`, oldest first, counting instead of picking.
1172 for (spec, queued_at) in &queued {1165 for (spec, queued_at) in &queued {
1173 if !runs_on_covered(spec, &runner.labels) {1166 if !runs_on_covered(spec, &runner.labels) {
1174 skips.lacking_labels += 1;1167 skips.lacking_labels += 1;
@@ -1191,11 +1184,7 @@ impl Store {
1191 let need = offer.reservation(declared);1184 let need = offer.reservation(declared);
1192 skips.too_big += 1;1185 skips.too_big += 1;
1193 skips.smallest_need = Some(skips.smallest_need.map_or(need, |n| n.min(need)));1186 skips.smallest_need = Some(skips.smallest_need.map_or(need, |n| n.min(need)));
1194- let waited = queued_at1187+ if waited_secs(queued_at.as_deref(), now) >= STARVE_AFTER_SECS {
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 {
1199 skips.starved_need = Some(need);1188 skips.starved_need = Some(need);
1200 }1189 }
1201 }1190 }
@@ -1280,7 +1269,8 @@ impl Store {
1280 1269
1281 /// Finishes a job with a terminal state. Dependants are then unblocked or skipped, and the1270 /// Finishes a job with a terminal state. Dependants are then unblocked or skipped, and the
1282 /// run state is recomputed. A `Failure` or `Error` fails the run fast: the run's queued and1271 /// 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 pub async fn finish_job(1274 pub async fn finish_job(
1285 &self,1275 &self,
1286 job_id: &str,1276 job_id: &str,
@@ -1316,21 +1306,7 @@ impl Store {
1316 .map_err(db_err)?;1306 .map_err(db_err)?;
1317 propagate(&tx, &job.run_id, &now).await?;1307 propagate(&tx, &job.run_id, &now).await?;
1318 if matches!(state, JobState::Failure | JobState::Error) {1308 if matches!(state, JobState::Failure | JobState::Error) {
1319- // Fail fast: the run cannot succeed any more, so stop the sibling jobs now.1309+ cancel_open_jobs(&tx, &job.run_id, &now).await?;
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)?;
1334 }1310 }
1335 recompute_run(&tx, &job.run_id, &now).await?;1311 recompute_run(&tx, &job.run_id, &now).await?;
1336 load_run(&tx, &job.run_id).await?.ok_or_else(missing_row)1312 load_run(&tx, &job.run_id).await?.ok_or_else(missing_row)
@@ -1388,19 +1364,7 @@ impl Store {
1388 if run.state.is_terminal() {1364 if run.state.is_terminal() {
1389 return Ok(());1365 return Ok(());
1390 }1366 }
1391- tx.execute(1367+ cancel_open_jobs(&tx, run_id, &now).await?;
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)?;
1404 recompute_run(&tx, run_id, &now).await1368 recompute_run(&tx, run_id, &now).await
1405 }1369 }
1406 .await;1370 .await;
@@ -1507,15 +1471,17 @@ impl Store {
1507 .collect();1471 .collect();
1508 let created = self1472 let created = self
1509 .create_run(1473 .create_run(
1510- &run.repo_id,1474+ &NewRun {
1511- &run.trigger,1475+ repo_id: &run.repo_id,
1512- &run.git_ref,1476+ trigger: &run.trigger,
1513- &run.commit_oid,1477+ git_ref: &run.git_ref,
1514- run.pull_number,1478+ commit_oid: &run.commit_oid,
1479+ pull_number: run.pull_number,
1515 actor_id,1480 actor_id,
1516- false,1481+ needs_approval: false,
1482+ config_error: run.config_error.as_deref(),
1483+ },
1517 &new_jobs,1484 &new_jobs,
1518- run.config_error.as_deref(),
1519 )1485 )
1520 .await?;1486 .await?;
1521 let warnings = self.run_warnings(&run.id).await?;1487 let warnings = self.run_warnings(&run.id).await?;
@@ -1527,7 +1493,11 @@ impl Store {
1527 1493
1528 /// Stores the config warnings of a run, replacing any earlier ones.1494 /// Stores the config warnings of a run, replacing any earlier ones.
1529 pub async fn set_run_warnings(&self, run_id: &str, warnings: &[String]) -> Result<()> {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 let conn = self.inner.conn.lock().await;1501 let conn = self.inner.conn.lock().await;
1532 conn.execute(1502 conn.execute(
1533 "UPDATE ci_runs SET config_warnings = ?2 WHERE id = ?1",1503 "UPDATE ci_runs SET config_warnings = ?2 WHERE id = ?1",
@@ -1599,6 +1569,7 @@ impl Store {
1599 )1569 )
1600 .await?;1570 .await?;
1601 let mut runs: Vec<String> = Vec::new();1571 let mut runs: Vec<String> = Vec::new();
1572+ let mut failed_runs: Vec<String> = Vec::new();
1602 for job in &lost {1573 for job in &lost {
1603 tx.execute(1574 tx.execute(
1604 "UPDATE ci_jobs SET \1575 "UPDATE ci_jobs SET \
@@ -1613,9 +1584,15 @@ impl Store {
1613 if !runs.contains(&job.run_id) {1584 if !runs.contains(&job.run_id) {
1614 runs.push(job.run_id.clone());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 for run_id in &runs {1591 for run_id in &runs {
1618 propagate(&tx, run_id, &now).await?;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 recompute_run(&tx, run_id, &now).await?;1596 recompute_run(&tx, run_id, &now).await?;
1620 }1597 }
1621 let mut out = Vec::with_capacity(lost.len());1598 let mut out = Vec::with_capacity(lost.len());
@@ -1708,27 +1685,10 @@ impl Store {
1708 repo_id: &str,1685 repo_id: &str,
1709 git_refs: &[String],1686 git_refs: &[String],
1710 ) -> Result<Vec<JobSample>> {1687 ) -> Result<Vec<JobSample>> {
1711- let mut params: Vec<Value> = Vec::with_capacity(git_refs.len() + 1);1688+ let (params, scope) = recent_done_scope(repo_id, git_refs);
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- };
1723 let sql = format!(1689 let sql = format!(
1724- "WITH done AS ( \1690+ "{DONE_RUNS} SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, \
1725- SELECT id, git_ref, \1691+ j.started_at, j.finished_at \
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 \
1732 FROM done JOIN ci_jobs j ON j.run_id = done.id \1692 FROM done JOIN ci_jobs j ON j.run_id = done.id \
1733 WHERE ({scope}) \1693 WHERE ({scope}) \
1734 AND j.state = 'success' AND j.started_at IS NOT NULL AND j.finished_at IS NOT NULL"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 repo_id: &str,1828 repo_id: &str,
1869 git_refs: &[String],1829 git_refs: &[String],
1870 ) -> Result<Vec<StepSample>> {1830 ) -> Result<Vec<StepSample>> {
1871- let mut params: Vec<Value> = Vec::with_capacity(git_refs.len() + 1);1831+ let (params, scope) = recent_done_scope(repo_id, git_refs);
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- };
1883 let sql = format!(1832 let sql = format!(
1884- "WITH done AS ( \1833+ "{DONE_RUNS} SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, s.name, \
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, \
1891 s.started_at, s.finished_at \1834 s.started_at, s.finished_at \
1892 FROM done JOIN ci_jobs j ON j.run_id = done.id \1835 FROM done JOIN ci_jobs j ON j.run_id = done.id \
1893 JOIN ci_job_steps s ON s.job_id = j.id \1836 JOIN ci_job_steps s ON s.job_id = j.id \
@@ -2031,7 +1974,6 @@ impl Store {
2031 let conn = self.inner.conn.lock().await;1974 let conn = self.inner.conn.lock().await;
2032 let tx = conn.unchecked_transaction().await.map_err(db_err)?;1975 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
2033 let outcome: Result<(Vec<String>, Vec<String>, Vec<String>)> = async {1976 let outcome: Result<(Vec<String>, Vec<String>, Vec<String>)> = async {
2034- // Which run owns each artifact, read before the rows go.
2035 let owners: BTreeMap<String, String> = fetch_all(1977 let owners: BTreeMap<String, String> = fetch_all(
2036 &tx,1978 &tx,
2037 "SELECT a.id, j.run_id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id",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 .await2015 .await
2074 .map_err(db_err)?;2016 .map_err(db_err)?;
2075 2017
2076- // Keep only the newest `keep_runs` runs (per repo) that still have artifacts.
2077 if keep_runs > 0 {2018 if keep_runs > 0 {
2078 let old = fetch_all(2019 let old = fetch_all(
2079 &tx,2020 &tx,
2080 "SELECT a.id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id \2021 "SELECT a.id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id \
2081 WHERE j.run_id NOT IN ( \2022 WHERE j.run_id NOT IN ( \
2082 SELECT id FROM ( \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 AS rn \2025 AS rn \
2085 FROM ci_runs r \2026 FROM ci_runs r \
2086 WHERE EXISTS (SELECT 1 FROM ci_artifacts a2 JOIN ci_jobs j2 \2027 WHERE EXISTS (SELECT 1 FROM ci_artifacts a2 JOIN ci_jobs j2 \
@@ -2099,10 +2040,8 @@ impl Store {
2099 artifact_ids.extend(old);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 if max_total_bytes > 0 {2043 if max_total_bytes > 0 {
2104 let limit = i64::try_from(max_total_bytes).unwrap_or(i64::MAX);2044 let limit = i64::try_from(max_total_bytes).unwrap_or(i64::MAX);
2105- // (artifact id, run id, size), oldest run first.
2106 let rows = fetch_all(2045 let rows = fetch_all(
2107 &tx,2046 &tx,
2108 "SELECT a.id, j.run_id, a.size FROM ci_artifacts a \2047 "SELECT a.id, j.run_id, a.size FROM ci_artifacts a \
@@ -2215,14 +2154,9 @@ impl Store {
2215 if !names.contains(&name) {2154 if !names.contains(&name) {
2216 continue;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 let sealed = String::from_utf8(sealed)2157 let sealed = String::from_utf8(sealed)
2224 .map_err(|_| Error::Crypto("sealed CI secret is not UTF-8".into()))?;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 let value = String::from_utf8(plain)2160 let value = String::from_utf8(plain)
2227 .map_err(|_| Error::Crypto("CI secret is not UTF-8".into()))?;2161 .map_err(|_| Error::Crypto("CI secret is not UTF-8".into()))?;
2228 out.insert(name, value);2162 out.insert(name, value);
@@ -2305,15 +2239,17 @@ mod tests {
2305 .collect();2239 .collect();
2306 store2240 store
2307 .create_run(2241 .create_run(
2242+ &NewRun {
2308 repo_id,2243 repo_id,
2309- "push",2244+ trigger: "push",
2310- "refs/heads/main",2245+ git_ref: "refs/heads/main",
2311- "abc123",2246+ commit_oid: "abc123",
2312- None,2247+ pull_number: None,
2313- actor,2248+ actor_id: actor,
2314- approval,2249+ needs_approval: approval,
2250+ config_error: None,
2251+ },
2315 &new,2252 &new,
2316- None,
2317 )2253 )
2318 .await2254 .await
2319 .unwrap()2255 .unwrap()
@@ -2363,7 +2299,6 @@ mod tests {
2363 .create_registration_token(&fx.tahinli.id, 1)2299 .create_registration_token(&fx.tahinli.id, 1)
2364 .await2300 .await
2365 .unwrap();2301 .unwrap();
2366- // Only the hash is stored.
2367 {2302 {
2368 let conn = fx.store.inner.conn.lock().await;2303 let conn = fx.store.inner.conn.lock().await;
2369 let n = fetch_opt(2304 let n = fetch_opt(
@@ -2511,7 +2446,6 @@ mod tests {
2511 assert_eq!(found.config_overrides["limits.memory"], "8g");2446 assert_eq!(found.config_overrides["limits.memory"], "8g");
2512 assert_eq!(found.reported_config["limits.memory"], "4g");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 fx.store2449 fx.store
2516 .set_runner_field(&runner.id, "labels", Some("linux, arm"))2450 .set_runner_field(&runner.id, "labels", Some("linux, arm"))
2517 .await2451 .await
@@ -2530,7 +2464,6 @@ mod tests {
2530 assert_eq!(after.labels, vec!["linux".to_string()]);2464 assert_eq!(after.labels, vec!["linux".to_string()]);
2531 assert!(after.config_overrides.is_empty());2465 assert!(after.config_overrides.is_empty());
2532 2466
2533- // Concurrency goes through the same entry point.
2534 fx.store2467 fx.store
2535 .set_runner_field(&runner.id, "concurrency", Some("6"))2468 .set_runner_field(&runner.id, "concurrency", Some("6"))
2536 .await2469 .await
@@ -2566,7 +2499,6 @@ mod tests {
2566 .await,2499 .await,
2567 Err(Error::Invalid(_))2500 Err(Error::Invalid(_))
2568 ));2501 ));
2569- // A boot id alone is not enough, the version is the same for every build.
2570 fx.store2502 fx.store
2571 .record_runner_report(&runner.id, &boot_report("b1", &[]))2503 .record_runner_report(&runner.id, &boot_report("b1", &[]))
2572 .await2504 .await
@@ -2606,13 +2538,11 @@ mod tests {
2606 assert_eq!(listed.restart.as_ref().unwrap().mode, RestartMode::Drain);2538 assert_eq!(listed.restart.as_ref().unwrap().mode, RestartMode::Drain);
2607 assert!(listed.supports_restart());2539 assert!(listed.supports_restart());
2608 2540
2609- // The same process reporting again changes nothing.
2610 fx.store2541 fx.store
2611 .record_runner_report(&runner.id, &boot_report("b1", &["restart"]))2542 .record_runner_report(&runner.id, &boot_report("b1", &["restart"]))
2612 .await2543 .await
2613 .unwrap();2544 .unwrap();
2614 assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some());2545 assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some());
2615- // A heartbeat without a boot id changes nothing either.
2616 let beat = RunnerReport {2546 let beat = RunnerReport {
2617 concurrency: Some(2),2547 concurrency: Some(2),
2618 ..RunnerReport::default()2548 ..RunnerReport::default()
@@ -2623,7 +2553,6 @@ mod tests {
2623 .unwrap();2553 .unwrap();
2624 assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some());2554 assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some());
2625 2555
2626- // "Restart now" replaces the pending drain.
2627 fx.store2556 fx.store
2628 .request_runner_restart(&runner.id, RestartMode::Now)2557 .request_runner_restart(&runner.id, RestartMode::Now)
2629 .await2558 .await
@@ -2633,7 +2562,6 @@ mod tests {
2633 Some(RestartMode::Now)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 assert!(2565 assert!(
2638 fx.store2566 fx.store
2639 .record_runner_report(&runner.id, &boot_report("b2", &["restart"]))2567 .record_runner_report(&runner.id, &boot_report("b2", &["restart"]))
@@ -2678,7 +2606,6 @@ mod tests {
2678 .unwrap(),2606 .unwrap(),
2679 "an identical report is not a change"2607 "an identical report is not a change"
2680 );2608 );
2681- // A heartbeat reports only the concurrency and keeps the host facts.
2682 let beat = RunnerReport {2609 let beat = RunnerReport {
2683 concurrency: Some(3),2610 concurrency: Some(3),
2684 ..RunnerReport::default()2611 ..RunnerReport::default()
@@ -2699,7 +2626,6 @@ mod tests {
2699 );2626 );
2700 assert_eq!(listed.running_jobs, 0);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 create(2629 create(
2704 &fx.store,2630 &fx.store,
2705 &fx.repo.id,2631 &fx.repo.id,
@@ -2801,15 +2727,17 @@ mod tests {
2801 let broken = fx2727 let broken = fx
2802 .store2728 .store
2803 .create_run(2729 .create_run(
2804- &repo.id,2730+ &NewRun {
2805- "push",2731+ repo_id: &repo.id,
2806- "refs/heads/main",2732+ trigger: "push",
2807- "abc123",2733+ git_ref: "refs/heads/main",
2808- None,2734+ commit_oid: "abc123",
2809- &fx.tahinli.id,2735+ pull_number: None,
2810- false,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 .await2742 .await
2815 .unwrap();2743 .unwrap();
@@ -2842,15 +2770,17 @@ mod tests {
2842 let dev = fx2770 let dev = fx
2843 .store2771 .store
2844 .create_run(2772 .create_run(
2845- &repo.id,2773+ &NewRun {
2846- "push",2774+ repo_id: &repo.id,
2847- "refs/heads/dev",2775+ trigger: "push",
2848- "abc123",2776+ git_ref: "refs/heads/dev",
2849- None,2777+ commit_oid: "abc123",
2850- &fx.tahinli.id,2778+ pull_number: None,
2851- false,2779+ actor_id: &fx.tahinli.id,
2780+ needs_approval: false,
2781+ config_error: Some("broken"),
2782+ },
2852 &[],2783 &[],
2853- Some("broken"),
2854 )2784 )
2855 .await2785 .await
2856 .unwrap();2786 .unwrap();
@@ -2922,7 +2852,7 @@ mod tests {
2922 let run = create(store, repo_id, actor, jobs, approval).await;2852 let run = create(store, repo_id, actor, jobs, approval).await;
2923 let conn = store.inner.conn.lock().await;2853 let conn = store.inner.conn.lock().await;
2924 for (i, j) in jobs.iter().enumerate() {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 conn.execute(2856 conn.execute(
2927 "UPDATE ci_jobs SET queued_at = ?1 WHERE name = ?2",2857 "UPDATE ci_jobs SET queued_at = ?1 WHERE name = ?2",
2928 (at, j.name.clone()),2858 (at, j.name.clone()),
@@ -2971,7 +2901,6 @@ mod tests {
2971 )2901 )
2972 .await;2902 .await;
2973 let runner = bare_runner(&["linux"]);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 let first = fx2904 let first = fx
2976 .store2905 .store
2977 .claim_job_fitting(&runner, offer(2))2906 .claim_job_fitting(&runner, offer(2))
@@ -2979,7 +2908,6 @@ mod tests {
2979 .unwrap()2908 .unwrap()
2980 .unwrap();2909 .unwrap();
2981 assert_eq!(first.0.name, "small");2910 assert_eq!(first.0.name, "small");
2982- // 1 GiB left: a job with no memory reserves the default 1 GiB and fits.
2983 let second = fx2911 let second = fx
2984 .store2912 .store
2985 .claim_job_fitting(&runner, offer(1))2913 .claim_job_fitting(&runner, offer(1))
@@ -2987,7 +2915,6 @@ mod tests {
2987 .unwrap()2915 .unwrap()
2988 .unwrap();2916 .unwrap();
2989 assert_eq!(second.0.name, "plain");2917 assert_eq!(second.0.name, "plain");
2990- // Nothing fits in 0 GiB, and the big job is still queued.
2991 assert!(2918 assert!(
2992 fx.store2919 fx.store
2993 .claim_job_fitting(&runner, offer(0))2920 .claim_job_fitting(&runner, offer(0))
@@ -2995,7 +2922,6 @@ mod tests {
2995 .unwrap()2922 .unwrap()
2996 .is_none()2923 .is_none()
2997 );2924 );
2998- // An idle runner takes it.
2999 let big = fx2925 let big = fx
3000 .store2926 .store
3001 .claim_job_fitting(&runner, offer(6))2927 .claim_job_fitting(&runner, offer(6))
@@ -3068,7 +2994,7 @@ mod tests {
3068 false,2994 false,
3069 )2995 )
3070 .await;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 let conn = fx.store.inner.conn.lock().await;2999 let conn = fx.store.inner.conn.lock().await;
3074 conn.execute(3000 conn.execute(
@@ -3087,7 +3013,6 @@ mod tests {
3087 .is_none(),3013 .is_none(),
3088 "the old big job holds the line"3014 "the old big job holds the line"
3089 );3015 );
3090- // Once enough memory is free the big job goes first.
3091 let claimed = fx3016 let claimed = fx
3092 .store3017 .store
3093 .claim_job_fitting(&runner, offer(5))3018 .claim_job_fitting(&runner, offer(5))
@@ -3128,7 +3053,6 @@ mod tests {
3128 assert_eq!(back.oom_kills, None);3053 assert_eq!(back.oom_kills, None);
3129 let run = fx.store.run_by_id(&run.id).await.unwrap().unwrap();3054 let run = fx.store.run_by_id(&run.id).await.unwrap().unwrap();
3130 assert_eq!(run.state, RunState::Running);3055 assert_eq!(run.state, RunState::Running);
3131- // The old token no longer matches, and only a running job can be requeued.
3132 assert!(!fx.store.requeue_job(&claimed.id).await.unwrap());3056 assert!(!fx.store.requeue_job(&claimed.id).await.unwrap());
3133 assert!(!fx.store.requeue_job("missing").await.unwrap());3057 assert!(!fx.store.requeue_job("missing").await.unwrap());
3134 let (again, _, token) = fx3058 let (again, _, token) = fx
@@ -3292,7 +3216,6 @@ mod tests {
3292 second.0.id.clone()3216 second.0.id.clone()
3293 };3217 };
3294 3218
3295- // Success unblocks b; c still waits on b.
3296 let after_a = fx3219 let after_a = fx
3297 .store3220 .store
3298 .finish_job(&a_id, JobState::Success, Some(0), None)3221 .finish_job(&a_id, JobState::Success, Some(0), None)
@@ -3308,7 +3231,6 @@ mod tests {
3308 JobState::Blocked3231 JobState::Blocked
3309 );3232 );
3310 3233
3311- // Failure of b skips c transitively once b is done.
3312 let b_claim = fx.store.claim_job(&runner).await.unwrap().unwrap();3234 let b_claim = fx.store.claim_job(&runner).await.unwrap().unwrap();
3313 assert_eq!(b_claim.0.name, "b");3235 assert_eq!(b_claim.0.name, "b");
3314 fx.store3236 fx.store
@@ -3467,7 +3389,6 @@ mod tests {
3467 .unwrap();3389 .unwrap();
3468 assert_eq!(done.state, RunState::Cancelled);3390 assert_eq!(done.state, RunState::Cancelled);
3469 assert!(done.finished_at.is_some());3391 assert!(done.finished_at.is_some());
3470- // A finished run does not change again.
3471 fx.store.request_cancel(&run.id).await.unwrap();3392 fx.store.request_cancel(&run.id).await.unwrap();
3472 assert_eq!(3393 assert_eq!(
3473 fx.store.run_by_id(&run.id).await.unwrap().unwrap().state,3394 fx.store.run_by_id(&run.id).await.unwrap().unwrap().state,
@@ -3528,7 +3449,6 @@ mod tests {
3528 .finish_job(&b.id, JobState::Failure, Some(1), None)3449 .finish_job(&b.id, JobState::Failure, Some(1), None)
3529 .await3450 .await
3530 .unwrap();3451 .unwrap();
3531- // Fail fast cancels the queued `d` and skips `c`.
3532 let done = fx.store.run_by_id(&first.id).await.unwrap().unwrap();3452 let done = fx.store.run_by_id(&first.id).await.unwrap().unwrap();
3533 assert_eq!(done.state, RunState::Failure);3453 assert_eq!(done.state, RunState::Failure);
3534 assert_eq!(3454 assert_eq!(
@@ -3557,7 +3477,6 @@ mod tests {
3557 assert_eq!(c2.state, JobState::Blocked);3477 assert_eq!(c2.state, JobState::Blocked);
3558 assert_eq!(spec_needs(&c2.spec_json), ["b"]);3478 assert_eq!(spec_needs(&c2.spec_json), ["b"]);
3559 3479
3560- // One finished job brings its dependants; a live one is refused.
3561 let single = fx3480 let single = fx
3562 .store3481 .store
3563 .rerun_job(&first.id, &a.id, &fx.tahinli.id)3482 .rerun_job(&first.id, &a.id, &fx.tahinli.id)
@@ -3628,7 +3547,6 @@ mod tests {
3628 .await3547 .await
3629 .unwrap()3548 .unwrap()
3630 .unwrap();3549 .unwrap();
3631- // Nothing is older than the epoch.
3632 assert!(fx.store.reap_lost_jobs(DAWN).await.unwrap().is_empty());3550 assert!(fx.store.reap_lost_jobs(DAWN).await.unwrap().is_empty());
3633 let future = stamp_after(Duration::from_secs(3600));3551 let future = stamp_after(Duration::from_secs(3600));
3634 let reaped = fx.store.reap_lost_jobs(&future).await.unwrap();3552 let reaped = fx.store.reap_lost_jobs(&future).await.unwrap();
@@ -3739,13 +3657,10 @@ mod tests {
3739 .await3657 .await
3740 .unwrap();3658 .unwrap();
3741 artifacts.push(made.id);3659 artifacts.push(made.id);
3742- // ULIDs made in the same millisecond do not sort by creation order.
3743 tokio::time::sleep(Duration::from_millis(2)).await;3660 tokio::time::sleep(Duration::from_millis(2)).await;
3744 }3661 }
3745- // Keep the newest two runs: the oldest run's artifact goes.
3746 let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap();3662 let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap();
3747 assert_eq!(deleted, vec![artifacts[0].clone()]);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 let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();3664 let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();
3750 assert_eq!(deleted, vec![artifacts[1].clone()]);3665 assert_eq!(deleted, vec![artifacts[1].clone()]);
3751 let (_, again, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();3666 let (_, again, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();
@@ -3795,7 +3710,6 @@ mod tests {
3795 .await3710 .await
3796 .unwrap();3711 .unwrap();
3797 3712
3798- // Raw storage is sealed, not plaintext.
3799 {3713 {
3800 let conn = fx.store.inner.conn.lock().await;3714 let conn = fx.store.inner.conn.lock().await;
3801 let raw = fetch_opt(3715 let raw = fetch_opt(
@@ -3827,7 +3741,6 @@ mod tests {
3827 assert_eq!(values.len(), 1);3741 assert_eq!(values.len(), 1);
3828 assert_eq!(values.get("DEPLOY_KEY").map(String::as_str), Some(plain));3742 assert_eq!(values.get("DEPLOY_KEY").map(String::as_str), Some(plain));
3829 3743
3830- // Replacing keeps one row.
3831 fx.store3744 fx.store
3832 .set_ci_secret(&repo.id, "DEPLOY_KEY", b"rotated")3745 .set_ci_secret(&repo.id, "DEPLOY_KEY", b"rotated")
3833 .await3746 .await
crates/forge-core/src/store/contributions.rsmodified+36 -54
@@ -13,6 +13,27 @@ use crate::tz::local_date;
13 /// Most contributions `contributions_between` returns for one day.13 /// Most contributions `contributions_between` returns for one day.
14 const DAY_LIMIT: u32 = 200;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 /// What a contribution was: a branch push, an issue, pull request or comment the user wrote, or37 /// What a contribution was: a branch push, an issue, pull request or comment the user wrote, or
17 /// a commit the user was credited with as a co-author.38 /// a commit the user was credited with as a co-author.
18 #[derive(Clone, Copy, Debug, PartialEq, Eq)]39 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -81,35 +102,21 @@ impl Store {
81 since: &str,102 since: &str,
82 tz: &str,103 tz: &str,
83 ) -> Result<Vec<(String, u32)>> {104 ) -> Result<Vec<(String, u32)>> {
84- // Parameters: ?1 user, ?2 since, ?3 and ?4 zero oids.105+ let sql = format!(
85- let sql = "SELECT minute, COUNT(*) FROM ( \106+ "SELECT substr(created_at, 1, 16) AS minute, COUNT(*) FROM ({}) \
86- SELECT substr(created_at, 1, 16) AS minute FROM push_events \107+ WHERE user_id = ?1 AND created_at >= ?2 GROUP BY minute",
87- WHERE actor_id = ?1 AND created_at >= ?2 AND new_oid NOT IN (?3, ?4) \108+ activity_sql()
88- AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \109+ );
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";
100 let params = vec![110 let params = vec![
101 Value::Text(user_id.to_string()),111 Value::Text(user_id.to_string()),
102 Value::Text(since.to_string()),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 let conn = self.read_conn().await;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 Ok((col_text(row, 0)?, col_int(row, 1)?))117 Ok((col_text(row, 0)?, col_int(row, 1)?))
110 })118 })
111 .await?;119 .await?;
112- // `minute` is `YYYY-MM-DDTHH:MM` in UTC; the stamp is completed with seconds to parse.
113 let mut days: BTreeMap<String, u32> = BTreeMap::new();120 let mut days: BTreeMap<String, u32> = BTreeMap::new();
114 for (minute, count) in rows {121 for (minute, count) in rows {
115 let Ok(ts) = format!("{minute}:00Z").parse::<Timestamp>() else {122 let Ok(ts) = format!("{minute}:00Z").parse::<Timestamp>() else {
@@ -131,41 +138,23 @@ impl Store {
131 from: &str,138 from: &str,
132 to: &str,139 to: &str,
133 ) -> Result<Vec<ContributionItem>> {140 ) -> Result<Vec<ContributionItem>> {
134- // Parameters: ?1 user, ?2 from, ?3 to, ?4 and ?5 zero oids.141+ let sql = format!(
135- let sql = "SELECT 'push' AS created_kind, o.username, r.name, p.created_at, p.ref_name, \142+ "SELECT a.kind, o.username, r.name, a.created_at, a.ref_name, a.number, a.title, \
136- 0, '', '' FROM push_events p \143+ a.commit_oid FROM ({}) a \
137- JOIN repos r ON r.id = p.repo_id JOIN users o ON o.id = r.owner_id \144+ JOIN repos r ON r.id = a.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 \145+ WHERE a.user_id = ?1 AND a.created_at >= ?2 AND a.created_at < ?3 \
139- AND p.new_oid NOT IN (?4, ?5) AND r.visibility = 'public' \146+ ORDER BY a.created_at DESC LIMIT ?4",
140- UNION ALL \147+ activity_sql()
141- SELECT i.kind, o.username, r.name, i.created_at, '', i.number, i.title, '' FROM issues i \148+ );
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";
158 let params = vec![149 let params = vec![
159 Value::Text(user_id.to_string()),150 Value::Text(user_id.to_string()),
160 Value::Text(from.to_string()),151 Value::Text(from.to_string()),
161 Value::Text(to.to_string()),152 Value::Text(to.to_string()),
162- Value::Text(ZERO_OID_SHA1.to_string()),
163- Value::Text(ZERO_OID_SHA256.to_string()),
164 Value::Integer(i64::from(DAY_LIMIT)),153 Value::Integer(i64::from(DAY_LIMIT)),
165 ];154 ];
166 155
167 let conn = self.read_conn().await;156 let conn = self.read_conn().await;
168- fetch_all(&conn, sql, params, map_item).await157+ fetch_all(&conn, &sql, params, map_item).await
169 }158 }
170 159
171 /// Credits `user_id` with a co-authored commit in `repo_id`. A commit is recorded once per160 /// Credits `user_id` with a co-authored commit in `repo_id`. A commit is recorded once per
@@ -311,7 +300,6 @@ mod tests {
311 .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at)300 .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at)
312 .await301 .await
313 .unwrap();302 .unwrap();
314- // A repeat of the same commit is ignored.
315 store303 store
316 .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at)304 .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at)
317 .await305 .await
@@ -349,7 +337,6 @@ mod tests {
349 .await337 .await
350 .unwrap();338 .unwrap();
351 339
352- // Day one: a push and an issue.
353 let day1 = "2026-03-01T10:00:00.000000000Z";340 let day1 = "2026-03-01T10:00:00.000000000Z";
354 let day2 = "2026-03-02T10:00:00.000000000Z";341 let day2 = "2026-03-02T10:00:00.000000000Z";
355 let before = "2026-02-28T10:00:00.000000000Z";342 let before = "2026-02-28T10:00:00.000000000Z";
@@ -363,7 +350,6 @@ mod tests {
363 .unwrap();350 .unwrap();
364 set_created_at(&store, "issues", &issue.id, day1).await;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 store353 store
368 .record_push_event_at(&demo.id, &tahinli.id, "refs/heads/main", OID, OID, day2)354 .record_push_event_at(&demo.id, &tahinli.id, "refs/heads/main", OID, OID, day2)
369 .await355 .await
@@ -393,7 +379,6 @@ mod tests {
393 .unwrap();379 .unwrap();
394 set_created_at(&store, "comments", &comment.id, day2).await;380 set_created_at(&store, "comments", &comment.id, day2).await;
395 381
396- // Before `since`, and someone else's activity: left out.
397 store382 store
398 .record_push_event_at(&demo.id, &tahinli.id, "refs/heads/main", OID, OID, before)383 .record_push_event_at(&demo.id, &tahinli.id, "refs/heads/main", OID, OID, before)
399 .await384 .await
@@ -413,8 +398,6 @@ mod tests {
413 vec![("2026-03-01".to_string(), 2), ("2026-03-02".to_string(), 3)]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 let later = store401 let later = store
419 .contribution_counts(402 .contribution_counts(
420 &tahinli.id,403 &tahinli.id,
@@ -425,7 +408,6 @@ mod tests {
425 .unwrap();408 .unwrap();
426 assert_eq!(later, vec![("2026-03-03".to_string(), 3)]);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 assert!(411 assert!(
430 store412 store
431 .contribution_counts(&bob.id, "2026-03-03T00:00:00.000000000Z", "UTC")413 .contribution_counts(&bob.id, "2026-03-03T00:00:00.000000000Z", "UTC")
crates/forge-core/src/store/discussions.rsmodified+50 -42
@@ -5,7 +5,7 @@
5 use turso::transaction::Transaction;5 use turso::transaction::Transaction;
6 use turso::{Connection, Row, Value};6 use turso::{Connection, Row, Value};
7 7
8-use super::issues::finish;8+use super::finish;
9 use super::{9 use super::{
10 Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id,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 .await452 .await
453 .map_err(db_err)?;453 .map_err(db_err)?;
454 if discussion.author_id != author_id {454 if discussion.author_id != author_id {
455- tx.execute(455+ upsert_discussion_notification(
456- "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \456+ &tx,
457- last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, 'reply', ?4, 1, ?5) \457+ &discussion.author_id,
458- ON CONFLICT (user_id, discussion_id) DO UPDATE SET \458+ &discussion.repo_id,
459- reason = CASE WHEN discussion_notifications.reason = 'mention' THEN 'mention' \459+ discussion_id,
460- ELSE 'reply' END, last_actor_id = excluded.last_actor_id, unread = 1, \460+ "reply",
461- updated_at = excluded.updated_at",461+ author_id,
462- (462+ &now,
463- discussion.author_id.clone(),
464- discussion_id.to_string(),
465- discussion.repo_id.clone(),
466- author_id.to_string(),
467- now,
468- ),
469 )463 )
470- .await464+ .await?;
471- .map_err(db_err)?;
472 }465 }
473 Ok(comment)466 Ok(comment)
474 }467 }
@@ -598,21 +591,16 @@ impl Store {
598 let conn = self.inner.conn.lock().await;591 let conn = self.inner.conn.lock().await;
599 let now = now_stamp();592 let now = now_stamp();
600 for user_id in user_ids {593 for user_id in user_ids {
601- conn.execute(594+ upsert_discussion_notification(
602- "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \595+ &conn,
603- last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, 'mention', ?4, 1, ?5) \596+ user_id,
604- ON CONFLICT (user_id, discussion_id) DO UPDATE SET reason = 'mention', \597+ repo_id,
605- last_actor_id = excluded.last_actor_id, unread = 1, updated_at = excluded.updated_at",598+ discussion_id,
606- (599+ "mention",
607- user_id.clone(),600+ actor_id,
608- discussion_id.to_string(),601+ &now,
609- repo_id.to_string(),
610- actor_id.to_string(),
611- now.clone(),
612- ),
613 )602 )
614- .await603+ .await?;
615- .map_err(db_err)?;
616 }604 }
617 Ok(())605 Ok(())
618 }606 }
@@ -696,26 +684,46 @@ impl Store {
696 repo_id: Option<&str>,684 repo_id: Option<&str>,
697 ) -> Result<()> {685 ) -> Result<()> {
698 let conn = self.inner.conn.lock().await;686 let conn = self.inner.conn.lock().await;
699- let result = match repo_id {
700- Some(repo) => {
701 conn.execute(687 conn.execute(
702- "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND repo_id = ?2 AND unread = 1",688+ "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1 \
703- (user_id.to_string(), repo.to_string()),689+ AND (?2 IS NULL OR repo_id = ?2)",
690+ (user_id.to_string(), repo_id.map(str::to_string)),
704 )691 )
705 .await692 .await
693+ .map_err(db_err)?;
694+ Ok(())
706 }695 }
707- None => {696+}
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<()> {
708 conn.execute(707 conn.execute(
709- "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1",708+ "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \
710- (user_id.to_string(),),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+ ),
711 )722 )
712 .await723 .await
713- }724+ .map_err(db_err)?;
714- };
715- result.map_err(db_err)?;
716 Ok(())725 Ok(())
717 }726 }
718-}
719 727
720 #[cfg(test)]728 #[cfg(test)]
721 mod tests {729 mod tests {
crates/forge-core/src/store/edit_history_read.rsmodified+29 -17
@@ -4,11 +4,26 @@
4 4
5 use std::collections::HashMap;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 use crate::error::Result;8 use crate::error::Result;
9 9
10-/// Longest id list sent in one `IN (...)` query.10+/// The kinds of target that have edit history. `as_str` is the stored text.
11-const CHUNK: usize = 500;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 /// One previous version of an issue, pull request, comment or review comment.28 /// One previous version of an issue, pull request, comment or review comment.
14 #[derive(Debug, Clone, PartialEq)]29 #[derive(Debug, Clone, PartialEq)]
@@ -22,15 +37,11 @@ pub struct EditVersion {
22 pub old_body: String,37 pub old_body: String,
23 }38 }
24 39
25-fn placeholders(n: usize) -> String {
26- vec!["?"; n].join(",")
27-}
28-
29 impl Store {40 impl Store {
30 /// The previous versions of one target, newest first.41 /// The previous versions of one target, newest first.
31 pub async fn edit_history(42 pub async fn edit_history(
32 &self,43 &self,
33- target_kind: &str,44+ target_kind: EditTarget,
34 target_id: &str,45 target_id: &str,
35 ) -> Result<Vec<EditVersion>> {46 ) -> Result<Vec<EditVersion>> {
36 let conn = self.read_conn().await;47 let conn = self.read_conn().await;
@@ -40,7 +51,7 @@ impl Store {
40 FROM edit_history h JOIN users u ON u.id = h.editor_id \51 FROM edit_history h JOIN users u ON u.id = h.editor_id \
41 WHERE h.target_kind = ?1 AND h.target_id = ?2 \52 WHERE h.target_kind = ?1 AND h.target_id = ?2 \
42 ORDER BY h.edited_at DESC, h.id DESC",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 |row| {55 |row| {
45 Ok(EditVersion {56 Ok(EditVersion {
46 id: col_text(row, 0)?,57 id: col_text(row, 0)?,
@@ -58,7 +69,7 @@ impl Store {
58 /// absent from the map. One query per 500 ids.69 /// absent from the map. One query per 500 ids.
59 pub async fn edit_count(70 pub async fn edit_count(
60 &self,71 &self,
61- target_kind: &str,72+ target_kind: EditTarget,
62 target_ids: &[&str],73 target_ids: &[&str],
63 ) -> Result<HashMap<String, u64>> {74 ) -> Result<HashMap<String, u64>> {
64 let mut out = HashMap::new();75 let mut out = HashMap::new();
@@ -66,14 +77,14 @@ impl Store {
66 return Ok(out);77 return Ok(out);
67 }78 }
68 let conn = self.read_conn().await;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 let sql = format!(81 let sql = format!(
71 "SELECT target_id, COUNT(*) FROM edit_history \82 "SELECT target_id, COUNT(*) FROM edit_history \
72 WHERE target_kind = ?1 AND target_id IN ({}) GROUP BY target_id",83 WHERE target_kind = ?1 AND target_id IN ({}) GROUP BY target_id",
73 placeholders(chunk.len())84 placeholders(chunk.len())
74 );85 );
75 let mut params: Vec<turso::Value> = Vec::with_capacity(chunk.len() + 1);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 params.extend(chunk.iter().map(|id| turso::Value::Text((*id).to_string())));88 params.extend(chunk.iter().map(|id| turso::Value::Text((*id).to_string())));
78 let rows = fetch_all(&conn, &sql, params, |row| {89 let rows = fetch_all(&conn, &sql, params, |row| {
79 let count = u64::try_from(col_int(row, 1)?).unwrap_or(0);90 let count = u64::try_from(col_int(row, 1)?).unwrap_or(0);
@@ -89,14 +100,15 @@ impl Store {
89 /// target does not exist (a deleted comment has no history either).100 /// target does not exist (a deleted comment has no history either).
90 pub async fn edit_target_issue(101 pub async fn edit_target_issue(
91 &self,102 &self,
92- target_kind: &str,103+ target_kind: EditTarget,
93 target_id: &str,104 target_id: &str,
94 ) -> Result<Option<String>> {105 ) -> Result<Option<String>> {
95 let sql = match target_kind {106 let sql = match target_kind {
96- "issue" => "SELECT id FROM issues WHERE id = ?1 LIMIT 1",107+ EditTarget::Issue => "SELECT id FROM issues WHERE id = ?1 LIMIT 1",
97- "comment" => "SELECT issue_id FROM comments WHERE id = ?1 LIMIT 1",108+ EditTarget::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",109+ EditTarget::ReviewComment => {
99- _ => return Ok(None),110+ "SELECT issue_id FROM review_comments WHERE id = ?1 LIMIT 1"
111+ }
100 };112 };
101 let conn = self.read_conn().await;113 let conn = self.read_conn().await;
102 fetch_opt(&conn, sql, (target_id.to_string(),), |row| col_text(row, 0)).await114 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 use crate::time::{stamp_ago, stamp_to_unix};5 use crate::time::{stamp_ago, stamp_to_unix};
6 6
7 /// Window in which a runner's last report counts as online.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 /// Whether a runner counts as online at `now_unix`: enabled, and its last report within10 /// Whether a runner counts as online at `now_unix`: enabled, and its last report within
11 /// [`RUNNER_ONLINE_SECS`]. The runners page dot and the live signal of the runners page both use11 /// [`RUNNER_ONLINE_SECS`]. The runners page dot and the live signal of the runners page both use
12 /// this one rule.12 /// this one rule.
13 pub fn runner_is_online(disabled: bool, last_seen_at: Option<&str>, now_unix: i64) -> bool {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 !disabled14 !disabled
16 && last_seen_at15 && last_seen_at
17 .and_then(stamp_to_unix)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 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]20 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -31,7 +30,7 @@ impl Store {
31 /// Counts of repos, users, queued CI jobs and runners. Five indexed `COUNT(*)` queries.30 /// Counts of repos, users, queued CI jobs and runners. Five indexed `COUNT(*)` queries.
32 pub async fn health_counts(&self) -> Result<HealthCounts> {31 pub async fn health_counts(&self) -> Result<HealthCounts> {
33 let conn = self.read_conn().await;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 let plain = |sql: &'static str| {34 let plain = |sql: &'static str| {
36 let conn = &conn;35 let conn = &conn;
37 async move {36 async move {
crates/forge-core/src/store/imports.rsmodified+7 -7
@@ -3,7 +3,7 @@
3 3
4 use turso::{Row, Value};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 use crate::error::{Error, Result};7 use crate::error::{Error, Result};
8 use crate::time::now_stamp;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 impl Store {103 impl Store {
108 /// Creates a queued job. `source_ref` must not hold a credential.104 /// Creates a queued job. `source_ref` must not hold a credential.
109 pub async fn create_import_job(105 pub async fn create_import_job(
@@ -186,7 +182,11 @@ impl Store {
186 error: Option<&str>,182 error: Option<&str>,
187 ) -> Result<()> {183 ) -> Result<()> {
188 let now = now_stamp();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 let conn = self.inner.conn.lock().await;190 let conn = self.inner.conn.lock().await;
191 conn.execute(191 conn.execute(
192 "UPDATE import_jobs SET state = ?2, error = ?3, updated_at = ?4, finished_at = ?5 \192 "UPDATE import_jobs SET state = ?2, error = ?3, updated_at = ?4, finished_at = ?5 \
@@ -196,7 +196,7 @@ impl Store {
196 text(state.as_str()),196 text(state.as_str()),
197 error.map_or(Value::Null, text),197 error.map_or(Value::Null, text),
198 text(&now),198 text(&now),
199- finished.as_deref().map_or(Value::Null, text),199+ finished,
200 ],200 ],
201 )201 )
202 .await202 .await
crates/forge-core/src/store/issues.rsmodified+12 -120
@@ -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 use std::collections::HashMap;1 use std::collections::HashMap;
5 2
6 use serde_json::{Map, Value as Json};3 use serde_json::{Map, Value as Json};
@@ -8,8 +5,8 @@ use turso::transaction::Transaction;
8 use turso::{Connection, Row, Value};5 use turso::{Connection, Row, Value};
9 6
10 use super::{7 use super::{
11- Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, missing_row,8+ IN_CHUNK, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish,
12- new_id,9+ insert_err, missing_row, new_id, placeholders,
13 };10 };
14 use crate::error::{Error, Result};11 use crate::error::{Error, Result};
15 use crate::issues::{12 use crate::issues::{
@@ -19,7 +16,6 @@ use crate::issues::{
19 use crate::names::normalize_name;16 use crate::names::normalize_name;
20 use crate::time::now_stamp;17 use crate::time::now_stamp;
21 18
22-/// Event kinds the timeline knows. Anything else is rejected by `add_event`.
23 const EVENT_KINDS: &[&str] = &[19 const EVENT_KINDS: &[&str] = &[
24 "closed",20 "closed",
25 "reopened",21 "reopened",
@@ -33,7 +29,6 @@ const EVENT_KINDS: &[&str] = &[
33 "referenced",29 "referenced",
34 "locked",30 "locked",
35 "unlocked",31 "unlocked",
36- // Pull requests (store/pulls.rs).
37 "merged",32 "merged",
38 "head_updated",33 "head_updated",
39 "base_changed",34 "base_changed",
@@ -44,11 +39,9 @@ const EVENT_KINDS: &[&str] = &[
44 "converted_to_draft",39 "converted_to_draft",
45 "auto_merge_enabled",40 "auto_merge_enabled",
46 "auto_merge_disabled",41 "auto_merge_disabled",
47- // Pull request reviews (store/reviews.rs).
48 "review_dismissed",42 "review_dismissed",
49 "thread_resolved",43 "thread_resolved",
50 "thread_unresolved",44 "thread_unresolved",
51- // Pinned issues (store/pinned.rs).
52 "pinned",45 "pinned",
53 "unpinned",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 const COMMENT_COLS: &str = "id, issue_id, author_id, body, created_at, updated_at, edited";52 const COMMENT_COLS: &str = "id, issue_id, author_id, body, created_at, updated_at, edited";
60 const LABEL_COLS: &str = "l.id, l.repo_id, l.name, l.color, l.description";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 pub(super) fn parse_db<T: std::str::FromStr<Err = Error>>(s: &str) -> Result<T> {55 pub(super) fn parse_db<T: std::str::FromStr<Err = Error>>(s: &str) -> Result<T> {
66 s.parse::<T>()56 s.parse::<T>()
67 .map_err(|e| Error::Database(format!("stored value {s:?}: {e}")))57 .map_err(|e| Error::Database(format!("stored value {s:?}: {e}")))
68 }58 }
69 59
70-/// Reads `ISSUE_COLS` (columns 0 to 14).
71 pub(super) fn map_issue(row: &Row) -> Result<Issue> {60 pub(super) fn map_issue(row: &Row) -> Result<Issue> {
72 Ok(Issue {61 Ok(Issue {
73 id: col_text(row, 0)?,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 fn map_label(row: &Row, base: usize) -> Result<Label> {109 fn map_label(row: &Row, base: usize) -> Result<Label> {
122 Ok(Label {110 Ok(Label {
123 id: col_text(row, base)?,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 pub(crate) fn like_pattern(query: &str) -> String {119 pub(crate) fn like_pattern(query: &str) -> String {
136 let mut out = String::with_capacity(query.len() + 2);120 let mut out = String::with_capacity(query.len() + 2);
137 out.push('%');121 out.push('%');
@@ -145,32 +129,16 @@ pub(crate) fn like_pattern(query: &str) -> String {
145 out129 out
146 }130 }
147 131
148-/// Validates a `YYYY-MM-DD` due date.132+fn event_data(data: Json) -> Result<Map<String, Json>> {
149-pub fn validate_due_on(due_on: &str) -> Result<()> {133+ match data {
150- let format = time::macros::format_description!("[year]-[month]-[day]");134+ Json::Object(map) => Ok(map),
151- match time::Date::parse(due_on, &format) {135+ Json::Null => Ok(Map::new()),
152- Ok(_) => Ok(()),136+ _ => Err(Error::Invalid(
153- Err(_) => Err(Error::Invalid(format!(137+ "event data must be a JSON object".to_string(),
154- "due date {due_on:?} is not YYYY-MM-DD"138+ )),
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- }
170 }139 }
171 }140 }
172 141
173-/// Inserts a timeline event. `data` must be a JSON object or null (stored as `{}`).
174 pub(super) async fn insert_event(142 pub(super) async fn insert_event(
175 conn: &Connection,143 conn: &Connection,
176 issue_id: &str,144 issue_id: &str,
@@ -195,9 +163,6 @@ pub(super) async fn insert_event(
195 Ok(())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 pub(super) async fn load_issue(conn: &Connection, issue_id: &str) -> Result<Issue> {166 pub(super) async fn load_issue(conn: &Connection, issue_id: &str) -> Result<Issue> {
202 fetch_opt(167 fetch_opt(
203 conn,168 conn,
@@ -209,7 +174,6 @@ pub(super) async fn load_issue(conn: &Connection, issue_id: &str) -> Result<Issu
209 .ok_or(Error::NotFound)174 .ok_or(Error::NotFound)
210 }175 }
211 176
212-/// Labels of an issue, read through `issue_labels`, keyed by issue id.
213 async fn labels_for_issues(177 async fn labels_for_issues(
214 conn: &Connection,178 conn: &Connection,
215 issue_ids: &[String],179 issue_ids: &[String],
@@ -233,7 +197,6 @@ async fn labels_for_issues(
233 Ok(out)197 Ok(out)
234 }198 }
235 199
236-/// Display usernames of assignees, keyed by issue id.
237 async fn assignees_for_issues(200 async fn assignees_for_issues(
238 conn: &Connection,201 conn: &Connection,
239 issue_ids: &[String],202 issue_ids: &[String],
@@ -257,10 +220,7 @@ async fn assignees_for_issues(
257 Ok(out)220 Ok(out)
258 }221 }
259 222
260-// issues
261 impl Store {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 pub async fn create_issue(224 pub async fn create_issue(
265 &self,225 &self,
266 repo_id: &str,226 repo_id: &str,
@@ -341,8 +301,6 @@ impl Store {
341 .await301 .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 pub async fn list_issues(304 pub async fn list_issues(
347 &self,305 &self,
348 repo_id: &str,306 repo_id: &str,
@@ -351,7 +309,6 @@ impl Store {
351 self.list_of_kind(repo_id, f, "issue").await309 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 pub(super) async fn list_of_kind(312 pub(super) async fn list_of_kind(
356 &self,313 &self,
357 repo_id: &str,314 repo_id: &str,
@@ -401,19 +358,16 @@ impl Store {
401 params.push(Value::Text(normalize_name(reviewer)));358 params.push(Value::Text(normalize_name(reviewer)));
402 }359 }
403 if let Some(query) = non_empty(f.query.as_deref()) {360 if let Some(query) = non_empty(f.query.as_deref()) {
404- // Escape the LIKE wildcards and the escape character itself.
405 clauses.push("i.title LIKE ? ESCAPE '\\'");361 clauses.push("i.title LIKE ? ESCAPE '\\'");
406 params.push(Value::Text(like_pattern(query)));362 params.push(Value::Text(like_pattern(query)));
407 }363 }
408- if let (true, Some(draft)) = (kind == "pull", f.draft) {364+ if kind == "pull" && let Some(draft) = f.draft {
409- {
410 clauses.push(if draft {365 clauses.push(if draft {
411 "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 1)"366 "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 1)"
412 } else {367 } else {
413 "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 0)"368 "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 0)"
414 });369 });
415 }370 }
416- }
417 let where_sql = clauses.join(" AND ");371 let where_sql = clauses.join(" AND ");
418 let order = match f.sort {372 let order = match f.sort {
419 IssueSort::Newest => "i.number DESC",373 IssueSort::Newest => "i.number DESC",
@@ -468,12 +422,10 @@ impl Store {
468 Ok((items, total))422 Ok((items, total))
469 }423 }
470 424
471- /// Open and closed issue counts of the repo (issues only, not pulls).
472 pub async fn issue_counts(&self, repo_id: &str) -> Result<(u64, u64)> {425 pub async fn issue_counts(&self, repo_id: &str) -> Result<(u64, u64)> {
473 self.counts_of_kind(repo_id, "issue").await426 self.counts_of_kind(repo_id, "issue").await
474 }427 }
475 428
476- /// Open and closed counts for one `kind` ('issue' or 'pull').
477 pub(super) async fn counts_of_kind(&self, repo_id: &str, kind: &str) -> Result<(u64, u64)> {429 pub(super) async fn counts_of_kind(&self, repo_id: &str, kind: &str) -> Result<(u64, u64)> {
478 let conn = self.read_conn().await;430 let conn = self.read_conn().await;
479 let row = fetch_opt(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 pub async fn edit_issue(447 pub async fn edit_issue(
498 &self,448 &self,
499 issue_id: &str,449 issue_id: &str,
@@ -543,9 +493,6 @@ impl Store {
543 finish(tx, outcome).await493 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 pub async fn set_issue_state(496 pub async fn set_issue_state(
550 &self,497 &self,
551 issue_id: &str,498 issue_id: &str,
@@ -554,15 +501,7 @@ impl Store {
554 reason: Option<StateReason>,501 reason: Option<StateReason>,
555 data: Json,502 data: Json,
556 ) -> Result<bool> {503 ) -> Result<bool> {
557- let mut data = match data {504+ let mut data = event_data(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- };
566 let conn = self.inner.conn.lock().await;505 let conn = self.inner.conn.lock().await;
567 let tx = conn.unchecked_transaction().await.map_err(db_err)?;506 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
568 let outcome: Result<bool> = async {507 let outcome: Result<bool> = async {
@@ -604,9 +543,6 @@ impl Store {
604 finish(tx, outcome).await543 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 pub async fn set_issue_locked(546 pub async fn set_issue_locked(
611 &self,547 &self,
612 issue_id: &str,548 issue_id: &str,
@@ -653,10 +589,6 @@ impl Store {
653 finish(tx, outcome).await589 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 pub async fn add_comment(592 pub async fn add_comment(
661 &self,593 &self,
662 issue_id: &str,594 issue_id: &str,
@@ -718,7 +650,6 @@ impl Store {
718 .await650 .await
719 }651 }
720 652
721- /// Saves the previous body to the edit history and marks the comment edited.
722 pub async fn edit_comment(&self, comment_id: &str, editor_id: &str, body: &str) -> Result<()> {653 pub async fn edit_comment(&self, comment_id: &str, editor_id: &str, body: &str) -> Result<()> {
723 validate_body(body)?;654 validate_body(body)?;
724 if body.trim().is_empty() {655 if body.trim().is_empty() {
@@ -761,7 +692,6 @@ impl Store {
761 finish(tx, outcome).await692 finish(tx, outcome).await
762 }693 }
763 694
764- /// Deletes the comment with its edit history and decrements the issue's `comment_count`.
765 pub async fn delete_comment(&self, comment_id: &str) -> Result<()> {695 pub async fn delete_comment(&self, comment_id: &str) -> Result<()> {
766 let conn = self.inner.conn.lock().await;696 let conn = self.inner.conn.lock().await;
767 let tx = conn.unchecked_transaction().await.map_err(db_err)?;697 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -817,8 +747,6 @@ impl Store {
817 .await747 .await
818 }748 }
819 749
820- // events
821-
822 pub async fn list_events(&self, issue_id: &str) -> Result<Vec<IssueEvent>> {750 pub async fn list_events(&self, issue_id: &str) -> Result<Vec<IssueEvent>> {
823 let conn = self.read_conn().await;751 let conn = self.read_conn().await;
824 fetch_all(752 fetch_all(
@@ -831,8 +759,6 @@ impl Store {
831 .await759 .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 pub async fn add_event(762 pub async fn add_event(
837 &self,763 &self,
838 issue_id: &str,764 issue_id: &str,
@@ -843,23 +769,12 @@ impl Store {
843 if !EVENT_KINDS.contains(&kind) {769 if !EVENT_KINDS.contains(&kind) {
844 return Err(Error::Invalid(format!("event kind {kind:?}")));770 return Err(Error::Invalid(format!("event kind {kind:?}")));
845 }771 }
846- let data = match data {772+ let data = Json::Object(event_data(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- };
855 let conn = self.inner.conn.lock().await;773 let conn = self.inner.conn.lock().await;
856 load_issue(&conn, issue_id).await?;774 load_issue(&conn, issue_id).await?;
857 insert_event(&conn, issue_id, actor_id, kind, &data).await775 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 pub async fn usernames_by_ids(778 pub async fn usernames_by_ids(
864 &self,779 &self,
865 ids: &[String],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 pub(super) async fn delete_repo_issue_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {813 pub(super) async fn delete_repo_issue_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {
900 let id = repo_id.to_string();814 let id = repo_id.to_string();
901 for sql in [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 async fn fresh_repo(store: &Store, owner: &str, name: &str) -> String {871 async fn fresh_repo(store: &Store, owner: &str, name: &str) -> String {
959 store872 store
960 .create_repo(owner, name, "", Visibility::Public, "main")873 .create_repo(owner, name, "", Visibility::Public, "main")
@@ -975,13 +888,11 @@ mod tests {
975 items.into_iter().map(|i| i.issue.title).collect()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 #[tokio::test]891 #[tokio::test]
980 async fn issue_create_and_list_rules_hold_in_each_scenario() {892 async fn issue_create_and_list_rules_hold_in_each_scenario() {
981 let fx = fixture().await;893 let fx = fixture().await;
982 let s = &fx.store;894 let s = &fx.store;
983 895
984- // Scenario 1: numbers start at one and advance; lookup by number.
985 let repo = fresh_repo(s, &fx.tahinli.id, "numbers").await;896 let repo = fresh_repo(s, &fx.tahinli.id, "numbers").await;
986 let a = s897 let a = s
987 .create_issue(&repo, &fx.tahinli.id, " First ", "body")898 .create_issue(&repo, &fx.tahinli.id, " First ", "body")
@@ -1002,7 +913,6 @@ mod tests {
1002 "numbers: no third issue"913 "numbers: no third issue"
1003 );914 );
1004 915
1005- // Scenario 2: invalid input and missing repos are refused without taking a number.
1006 let repo = fresh_repo(s, &fx.tahinli.id, "validate").await;916 let repo = fresh_repo(s, &fx.tahinli.id, "validate").await;
1007 assert!(917 assert!(
1008 matches!(918 matches!(
@@ -1032,7 +942,6 @@ mod tests {
1032 .unwrap();942 .unwrap();
1033 assert_eq!(ok.number, 1, "validate: failed creates kept no number");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 let repo = fresh_repo(s, &fx.tahinli.id, "concurrent").await;945 let repo = fresh_repo(s, &fx.tahinli.id, "concurrent").await;
1037 let mut handles = Vec::new();946 let mut handles = Vec::new();
1038 for i in 0..20 {947 for i in 0..20 {
@@ -1061,7 +970,6 @@ mod tests {
1061 "concurrent: all open"970 "concurrent: all open"
1062 );971 );
1063 972
1064- // Scenario 4: state, author and text filters.
1065 let repo = fresh_repo(s, &fx.tahinli.id, "filters").await;973 let repo = fresh_repo(s, &fx.tahinli.id, "filters").await;
1066 let a = s974 let a = s
1067 .create_issue(&repo, &fx.tahinli.id, "Crash on start", "")975 .create_issue(&repo, &fx.tahinli.id, "Crash on start", "")
@@ -1080,7 +988,6 @@ mod tests {
1080 .await988 .await
1081 .unwrap();989 .unwrap();
1082 990
1083- // Default filter (open only).
1084 assert_eq!(991 assert_eq!(
1085 titles(s, &repo, &IssueFilter::default()).await,992 titles(s, &repo, &IssueFilter::default()).await,
1086 vec!["Typo in docs"],993 vec!["Typo in docs"],
@@ -1116,7 +1023,6 @@ mod tests {
1116 "filters: text is case-insensitive"1023 "filters: text is case-insensitive"
1117 );1024 );
1118 1025
1119- // Scenario 5: wildcards in the text query are literal.
1120 let repo = fresh_repo(s, &fx.tahinli.id, "wildcards").await;1026 let repo = fresh_repo(s, &fx.tahinli.id, "wildcards").await;
1121 for t in [1027 for t in [
1122 "100% done",1028 "100% done",
@@ -1158,7 +1064,6 @@ mod tests {
1158 "wildcards: blank query matches everything"1064 "wildcards: blank query matches everything"
1159 );1065 );
1160 1066
1161- // Scenario 6: paging and clamping.
1162 let repo = fresh_repo(s, &fx.tahinli.id, "pages").await;1067 let repo = fresh_repo(s, &fx.tahinli.id, "pages").await;
1163 for i in 0..30 {1068 for i in 0..30 {
1164 s.create_issue(&repo, &fx.tahinli.id, &format!("issue {i}"), "")1069 s.create_issue(&repo, &fx.tahinli.id, &format!("issue {i}"), "")
@@ -1176,14 +1081,12 @@ mod tests {
1176 let (second, _) = s.list_issues(&repo, &page(2, 25)).await.unwrap();1081 let (second, _) = s.list_issues(&repo, &page(2, 25)).await.unwrap();
1177 assert_eq!(second.len(), 5, "pages: second page size");1082 assert_eq!(second.len(), 5, "pages: second page size");
1178 assert_eq!(second[4].issue.number, 1, "pages: oldest last");1083 assert_eq!(second[4].issue.number, 1, "pages: oldest last");
1179- // per_page clamps to 1..=100, page to 1..=1000.
1180 let (one, _) = s.list_issues(&repo, &page(0, 0)).await.unwrap();1084 let (one, _) = s.list_issues(&repo, &page(0, 0)).await.unwrap();
1181 assert_eq!(one.len(), 1, "pages: per_page and page clamp up");1085 assert_eq!(one.len(), 1, "pages: per_page and page clamp up");
1182 assert_eq!(one[0].issue.number, 30, "pages: clamped to first page");1086 assert_eq!(one[0].issue.number, 30, "pages: clamped to first page");
1183 let (big, _) = s.list_issues(&repo, &page(5000, 1000)).await.unwrap();1087 let (big, _) = s.list_issues(&repo, &page(5000, 1000)).await.unwrap();
1184 assert!(big.is_empty(), "pages: far past the end");1088 assert!(big.is_empty(), "pages: far past the end");
1185 1089
1186- // Scenario 7: sorting by number and by last update.
1187 let repo = fresh_repo(s, &fx.tahinli.id, "sorts").await;1090 let repo = fresh_repo(s, &fx.tahinli.id, "sorts").await;
1188 let first = s1091 let first = s
1189 .create_issue(&repo, &fx.tahinli.id, "one", "")1092 .create_issue(&repo, &fx.tahinli.id, "one", "")
@@ -1212,7 +1115,6 @@ mod tests {
1212 "sorts: recently updated"1115 "sorts: recently updated"
1213 );1116 );
1214 1117
1215- // Scenario 8: labels and assignees are attached, and filterable by name.
1216 let repo = fresh_repo(s, &fx.tahinli.id, "labels").await;1118 let repo = fresh_repo(s, &fx.tahinli.id, "labels").await;
1217 let issue = s1119 let issue = s
1218 .create_issue(&repo, &fx.tahinli.id, "labelled", "")1120 .create_issue(&repo, &fx.tahinli.id, "labelled", "")
@@ -1264,7 +1166,6 @@ mod tests {
1264 "labels: filter by assignee"1166 "labels: filter by assignee"
1265 );1167 );
1266 1168
1267- // Scenario 9: counts split open and closed.
1268 let repo = fresh_repo(s, &fx.tahinli.id, "counts").await;1169 let repo = fresh_repo(s, &fx.tahinli.id, "counts").await;
1269 let a = s1170 let a = s
1270 .create_issue(&repo, &fx.tahinli.id, "a", "")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 #[tokio::test]1187 #[tokio::test]
1288 async fn issue_edit_and_thread_rules_hold_in_each_scenario() {1188 async fn issue_edit_and_thread_rules_hold_in_each_scenario() {
1289 let fx = fixture().await;1189 let fx = fixture().await;
1290 let s = &fx.store;1190 let s = &fx.store;
1291 1191
1292- // Scenario 1: an edit saves history and records a rename, body-only edits do not.
1293 let repo = fresh_repo(s, &fx.tahinli.id, "edit").await;1192 let repo = fresh_repo(s, &fx.tahinli.id, "edit").await;
1294 let issue = s1193 let issue = s
1295 .create_issue(&repo, &fx.tahinli.id, "old", "old body")1194 .create_issue(&repo, &fx.tahinli.id, "old", "old body")
@@ -1339,7 +1238,6 @@ mod tests {
1339 "edit: rename actor"1238 "edit: rename actor"
1340 );1239 );
1341 1240
1342- // Body-only edit: history yes, no rename event.
1343 s.edit_issue(&issue.id, &fx.bob.id, "new", "newer")1241 s.edit_issue(&issue.id, &fx.bob.id, "new", "newer")
1344 .await1242 .await
1345 .unwrap();1243 .unwrap();
@@ -1356,7 +1254,6 @@ mod tests {
1356 "edit: unknown issue"1254 "edit: unknown issue"
1357 );1255 );
1358 1256
1359- // Scenario 2: locking toggles the reason and records events.
1360 let repo = fresh_repo(s, &fx.tahinli.id, "locks").await;1257 let repo = fresh_repo(s, &fx.tahinli.id, "locks").await;
1361 let issue = s1258 let issue = s
1362 .create_issue(&repo, &fx.tahinli.id, "t", "")1259 .create_issue(&repo, &fx.tahinli.id, "t", "")
@@ -1414,7 +1311,6 @@ mod tests {
1414 .collect();1311 .collect();
1415 assert_eq!(kinds, vec!["locked", "unlocked"], "lock: events");1312 assert_eq!(kinds, vec!["locked", "unlocked"], "lock: events");
1416 1313
1417- // Scenario 3: closing and reopening record events and stamps.
1418 let repo = fresh_repo(s, &fx.tahinli.id, "state").await;1314 let repo = fresh_repo(s, &fx.tahinli.id, "state").await;
1419 let issue = s1315 let issue = s
1420 .create_issue(&repo, &fx.tahinli.id, "t", "")1316 .create_issue(&repo, &fx.tahinli.id, "t", "")
@@ -1504,7 +1400,6 @@ mod tests {
1504 "state: payload must be an object"1400 "state: payload must be an object"
1505 );1401 );
1506 1402
1507- // Scenario 4: comments keep the count, timestamps and ordering in step.
1508 let repo = fresh_repo(s, &fx.tahinli.id, "comments").await;1403 let repo = fresh_repo(s, &fx.tahinli.id, "comments").await;
1509 let issue = s1404 let issue = s
1510 .create_issue(&repo, &fx.tahinli.id, "t", "")1405 .create_issue(&repo, &fx.tahinli.id, "t", "")
@@ -1580,7 +1475,6 @@ mod tests {
1580 "comments: delete twice"1475 "comments: delete twice"
1581 );1476 );
1582 1477
1583- // Scenario 5: events validate their kind and their issue.
1584 let repo = fresh_repo(s, &fx.tahinli.id, "events").await;1478 let repo = fresh_repo(s, &fx.tahinli.id, "events").await;
1585 let issue = s1479 let issue = s
1586 .create_issue(&repo, &fx.tahinli.id, "t", "")1480 .create_issue(&repo, &fx.tahinli.id, "t", "")
@@ -1632,7 +1526,6 @@ mod tests {
1632 "events: unknown issue"1526 "events: unknown issue"
1633 );1527 );
1634 1528
1635- // Scenario 6: usernames are batched and unknown ids are skipped.
1636 let ids = vec![1529 let ids = vec![
1637 fx.tahinli.id.clone(),1530 fx.tahinli.id.clone(),
1638 fx.bob.id.clone(),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 #[tokio::test]1544 #[tokio::test]
1653 async fn delete_repo_leaves_no_m3_rows() {1545 async fn delete_repo_leaves_no_m3_rows() {
1654 let fx = fixture().await;1546 let fx = fixture().await;
crates/forge-core/src/store/labels.rsmodified+19 -56
@@ -4,22 +4,23 @@
4 use std::collections::{BTreeMap, BTreeSet};4 use std::collections::{BTreeMap, BTreeSet};
5 5
6 use jiff::civil::Date;6 use jiff::civil::Date;
7-use serde_json::{Value, json};7+use serde_json::json;
8-use turso::transaction::Transaction;
9 use turso::{Connection, Row};8 use turso::{Connection, Row};
10 9
10+use super::issues::insert_event;
11 use super::{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 use crate::authz::{Action, authorize};15 use crate::authz::{Action, authorize};
15 use crate::error::{Error, Result};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 use crate::model::User;20 use crate::model::User;
18 use crate::names::normalize_name;21 use crate::names::normalize_name;
19 use crate::time::now_stamp;22 use crate::time::now_stamp;
20 23
21-/// Most assignees one issue can have.
22-pub const MAX_ASSIGNEES: usize = 10;
23 /// Most labels one repo can have.24 /// Most labels one repo can have.
24 pub const MAX_LABELS: i64 = 500;25 pub const MAX_LABELS: i64 = 500;
25 26
@@ -53,7 +54,8 @@ const LABEL_COLS: &str = "id, repo_id, name, color, description";
53 const MILESTONE_SELECT: &str = "SELECT m.id, m.repo_id, m.title, m.description, m.due_on, m.state, \54 const MILESTONE_SELECT: &str = "SELECT m.id, m.repo_id, m.title, m.description, m.due_on, m.state, \
54 m.created_at, m.closed_at, \55 m.created_at, m.closed_at, \
55 COUNT(CASE WHEN i.state = 'open' THEN 1 END), COUNT(CASE WHEN i.state = 'closed' THEN 1 END) \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 // labels60 // labels
59 61
@@ -206,7 +208,7 @@ impl Store {
206 Ok(())208 Ok(())
207 }209 }
208 .await;210 .await;
209- commit_or_rollback(tx, outcome).await211+ finish(tx, outcome).await
210 }212 }
211 213
212 /// The labels on one issue, ordered by case-folded name.214 /// The labels on one issue, ordered by case-folded name.
@@ -309,7 +311,7 @@ impl Store {
309 Ok(())311 Ok(())
310 }312 }
311 .await;313 .await;
312- commit_or_rollback(tx, outcome).await314+ finish(tx, outcome).await
313 }315 }
314 316
315 /// The issue's assignees as `(user id, display username)`, ordered by name.317 /// The issue's assignees as `(user id, display username)`, ordered by name.
@@ -426,7 +428,7 @@ impl Store {
426 Ok(())428 Ok(())
427 }429 }
428 .await;430 .await;
429- commit_or_rollback(tx, outcome).await431+ finish(tx, outcome).await
430 }432 }
431 433
432 // milestones434 // milestones
@@ -528,8 +530,8 @@ impl Store {
528 (530 (
529 id.to_string(),531 id.to_string(),
530 repo_id.to_string(),532 repo_id.to_string(),
533+ title.clone(),
531 normalize_name(&title),534 normalize_name(&title),
532- title,
533 description.to_string(),535 description.to_string(),
534 due_on.map(str::to_owned),536 due_on.map(str::to_owned),
535 state.as_str().to_string(),537 state.as_str().to_string(),
@@ -569,7 +571,7 @@ impl Store {
569 Ok(())571 Ok(())
570 }572 }
571 .await;573 .await;
572- commit_or_rollback(tx, outcome).await574+ finish(tx, outcome).await
573 }575 }
574 576
575 /// Sets or clears the issue's milestone. The milestone must belong to the issue's repo577 /// Sets or clears the issue's milestone. The milestone must belong to the issue's repo
@@ -646,7 +648,7 @@ impl Store {
646 Ok(())648 Ok(())
647 }649 }
648 .await;650 .await;
649- commit_or_rollback(tx, outcome).await651+ 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 .ok_or(Error::NotFound)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 #[cfg(test)]715 #[cfg(test)]
754 mod tests {716 mod tests {
755 use super::*;717 use super::*;
718+ use serde_json::Value;
756 use crate::issues::{IssueEvent, StateReason};719 use crate::issues::{IssueEvent, StateReason};
757 use crate::model::{Role, Visibility};720 use crate::model::{Role, Visibility};
758 721
@@ -1259,17 +1222,17 @@ mod tests {
1259 ),1222 ),
1260 "update: other repo refused"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 .await1226 .await
1264 .unwrap();1227 .unwrap();
1265 let closed = s.milestone_by_id(&repo, &v1.id).await.unwrap().unwrap();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 assert_eq!(closed.description, "done", "update: description");1230 assert_eq!(closed.description, "done", "update: description");
1268 assert!(closed.due_on.is_none(), "update: due date cleared");1231 assert!(closed.due_on.is_none(), "update: due date cleared");
1269 assert!(matches!(closed.state, IssueState::Closed), "update: closed");1232 assert!(matches!(closed.state, IssueState::Closed), "update: closed");
1270 assert!(closed.closed_at.is_some(), "update: closed stamp set");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 .await1236 .await
1274 .unwrap();1237 .unwrap();
1275 let reopened = s.milestone_by_id(&repo, &v1.id).await.unwrap().unwrap();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 validate_settings(update)?;106 validate_settings(update)?;
107 let sealed = match update.password {107 let sealed = match update.password {
108 Some(password) => {108 Some(password) => {
109- let key = self109+ Some(secret::seal(self.secret_key()?, password.as_bytes())?.into_bytes())
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())
115 }110 }
116 None => None,111 None => None,
117 };112 };
@@ -161,11 +156,7 @@ impl Store {
161 let Some(bytes) = sealed else {156 let Some(bytes) = sealed else {
162 return Ok(None);157 return Ok(None);
163 };158 };
164- let key = self159+ let key = self.secret_key()?;
165- .inner
166- .secret_key
167- .get()
168- .ok_or_else(|| Error::Crypto("the instance key is not set".into()))?;
169 let text = String::from_utf8(bytes)160 let text = String::from_utf8(bytes)
170 .map_err(|_| Error::Crypto("sealed mail password is not text".into()))?;161 .map_err(|_| Error::Crypto("sealed mail password is not text".into()))?;
171 let plain = secret::open(key, &text)?;162 let plain = secret::open(key, &text)?;
@@ -317,20 +308,22 @@ impl Store {
317 /// How many outbox rows stand in each state at `now`, in `MailState::ALL` order.308 /// How many outbox rows stand in each state at `now`, in `MailState::ALL` order.
318 pub async fn mail_state_counts(&self, now: &str) -> Result<Vec<(MailState, u32)>> {309 pub async fn mail_state_counts(&self, now: &str) -> Result<Vec<(MailState, u32)>> {
319 let conn = self.read_conn().await;310 let conn = self.read_conn().await;
320- let mut counts = Vec::with_capacity(MailState::ALL.len());311+ let columns = MailState::ALL
321- for state in MailState::ALL {312+ .map(|state| format!("COUNT(CASE WHEN {} THEN 1 END)", state_clause(state)))
322- let clause = state_clause(state);313+ .join(", ");
323- let sql = format!("SELECT COUNT(*) FROM mail_outbox WHERE {clause}");314+ let sql = format!("SELECT {columns} FROM mail_outbox");
324- // A clause without `?1` must be bound with no parameters at all.315+ let counts = fetch_opt(&conn, &sql, (now.to_owned(),), |row| {
325- let n = if clause.contains("?1") {316+ MailState::ALL
326- fetch_opt(&conn, &sql, (now.to_owned(),), |row| col_int(row, 0)).await?317+ .into_iter()
327- } else {318+ .enumerate()
328- fetch_opt(&conn, &sql, (), |row| col_int(row, 0)).await?319+ .map(|(i, state)| {
329- }320+ let n = col_int(row, i)?;
330- .unwrap_or(0);321+ Ok((state, u32::try_from(n).unwrap_or(u32::MAX)))
331- counts.push((state, u32::try_from(n).unwrap_or(u32::MAX)));322+ })
332- }323+ .collect::<Result<Vec<_>>>()
333- Ok(counts)324+ })
325+ .await?;
326+ Ok(counts.unwrap_or_default())
334 }327 }
335 328
336 /// Gives a failed message a fresh set of tries, due at `now`. Returns `false` when the row is329 /// 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 use std::time::Duration;419 use std::time::Duration;
427 420
428 use super::*;421 use super::*;
429- use crate::mail::OutboxStatus;422+ use crate::mail::MailState;
430 use crate::time::{now_stamp, stamp_after};423 use crate::time::{now_stamp, stamp_after};
431 424
432 const KEY: [u8; 32] = [7u8; 32];425 const KEY: [u8; 32] = [7u8; 32];
@@ -562,7 +555,7 @@ mod tests {
562 .is_empty()555 .is_empty()
563 );556 );
564 let rows = store.recent_mail(10).await.expect("rows");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 assert_eq!(rows[0].attempts, 1);559 assert_eq!(rows[0].attempts, 1);
567 }560 }
568 561
@@ -598,14 +591,14 @@ mod tests {
598 let row = store.recent_mail(10).await.expect("rows").remove(0);591 let row = store.recent_mail(10).await.expect("rows").remove(0);
599 assert_eq!(row.attempts, 1);592 assert_eq!(row.attempts, 1);
600 assert_eq!(row.last_error.as_deref(), Some("timeout"));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 store596 store
604 .mark_mail_failed(&row.id, "gone", None)597 .mark_mail_failed(&row.id, "gone", None)
605 .await598 .await
606 .expect("gave up");599 .expect("gave up");
607 let row = store.recent_mail(10).await.expect("rows").remove(0);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 assert_eq!(store.next_mail_due().await.expect("none"), None);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 use turso::Value;4 use turso::Value;
5 5
6-use super::issues::finish;6+use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
7-use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
8 use crate::error::{Error, Result};7 use crate::error::{Error, Result};
9 use crate::merge_queue::{QueueEntry, QueueState};8 use crate::merge_queue::{QueueEntry, QueueState};
10 use crate::pulls::MergeStyle;9 use crate::pulls::MergeStyle;
@@ -178,20 +177,6 @@ impl Store {
178 .await177 .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 /// Moves a tested entry to `merging`. False when another event already took it.180 /// Moves a tested entry to `merging`. False when another event already took it.
196 pub async fn queue_set_merging(&self, id: &str) -> Result<bool> {181 pub async fn queue_set_merging(&self, id: &str) -> Result<bool> {
197 self.queue_update(182 self.queue_update(
crates/forge-core/src/store/migrate.rsmodified+33 -136
@@ -192,9 +192,7 @@ async fn applied_versions(conn: &Connection) -> Result<Vec<i64>> {
192 mod tests {192 mod tests {
193 use super::*;193 use super::*;
194 194
195- #[tokio::test]195+ async fn open_at(dir: &tempfile::TempDir, version: u32) -> (turso::Database, Connection) {
196- async fn database_at_0001_gains_profile_columns_with_defaults() {
197- let dir = tempfile::tempdir().unwrap();
198 let path = dir.path().join("old.db");196 let path = dir.path().join("old.db");
199 let db = turso::Builder::new_local(path.to_str().unwrap())197 let db = turso::Builder::new_local(path.to_str().unwrap())
200 .build()198 .build()
@@ -206,13 +204,22 @@ mod tests {
206 )204 )
207 .await205 .await
208 .unwrap();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();
210 conn.execute(209 conn.execute(
211- "INSERT INTO schema_migrations (version, applied_at) VALUES (1, 'then')",210+ "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, 'then')",
212- (),211+ (i64::from(v),),
213 )212 )
214 .await213 .await
215 .unwrap();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;
216 conn.execute(223 conn.execute(
217 "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \224 "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \
218 VALUES ('u1', 'Old', 'old', 'h', 0, 'then')",225 VALUES ('u1', 'Old', 'old', 'h', 0, 'then')",
@@ -220,6 +227,13 @@ mod tests {
220 )227 )
221 .await228 .await
222 .unwrap();229 .unwrap();
230+ conn.execute(
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')",
233+ (),
234+ )
235+ .await
236+ .unwrap();
223 237
224 migrate(&conn).await.unwrap();238 migrate(&conn).await.unwrap();
225 239
@@ -230,6 +244,7 @@ mod tests {
230 let row = rows.next().await.unwrap().expect("user row");244 let row = rows.next().await.unwrap().expect("user row");
231 assert_eq!(row.get_value(0).unwrap(), turso::Value::Text(String::new()));245 assert_eq!(row.get_value(0).unwrap(), turso::Value::Text(String::new()));
232 assert_eq!(row.get_value(1).unwrap(), turso::Value::Text("UTC".into()));246 assert_eq!(row.get_value(1).unwrap(), turso::Value::Text("UTC".into()));
247+ drop(rows);
233 let mut rows = conn248 let mut rows = conn
234 .query("SELECT version FROM schema_migrations ORDER BY version", ())249 .query("SELECT version FROM schema_migrations ORDER BY version", ())
235 .await250 .await
@@ -243,102 +258,7 @@ mod tests {
243 .map(|(v, _)| turso::Value::Integer(i64::from(*v)))258 .map(|(v, _)| turso::Value::Integer(i64::from(*v)))
244 .collect();259 .collect();
245 assert_eq!(versions, expected);260 assert_eq!(versions, expected);
246- }261+ drop(rows);
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();
342 262
343 let mut rows = conn263 let mut rows = conn
344 .query("SELECT next_issue_number FROM repos WHERE id = 'r1'", ())264 .query("SELECT next_issue_number FROM repos WHERE id = 'r1'", ())
@@ -361,44 +281,14 @@ mod tests {
361 )281 )
362 .await282 .await
363 .unwrap();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 conn.execute(284 conn.execute(
393- "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \285+ "INSERT INTO branch_protections (id, repo_id, pattern, allow_force_push, allow_deletion, created_at) \
394- VALUES ('u1', 'Old', 'old', 'h', 0, 'then')",286+ VALUES ('b1', 'r1', 'main', 1, 0, 'then')",
395 (),287 (),
396 )288 )
397 .await289 .await
398 .unwrap();290 .unwrap();
399 291
400- migrate(&conn).await.unwrap();
401-
402 let mut rows = conn292 let mut rows = conn
403 .query(293 .query(
404 "SELECT totp_secret_sealed, totp_enabled, totp_last_step FROM users WHERE id = 'u1'",294 "SELECT totp_secret_sealed, totp_enabled, totp_last_step FROM users WHERE id = 'u1'",
@@ -413,7 +303,14 @@ mod tests {
413 drop(rows);303 drop(rows);
414 304
415 conn.execute(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 .await316 .await
@@ -421,7 +318,7 @@ mod tests {
421 conn.execute_batch("PRAGMA foreign_keys = ON")318 conn.execute_batch("PRAGMA foreign_keys = ON")
422 .await319 .await
423 .unwrap();320 .unwrap();
424- conn.execute("DELETE FROM users WHERE id = 'u1'", ())321+ conn.execute("DELETE FROM users WHERE id = 'u2'", ())
425 .await322 .await
426 .unwrap();323 .unwrap();
427 let mut rows = conn324 let mut rows = conn
crates/forge-core/src/store/mirrors.rsmodified+13 -69
@@ -7,8 +7,8 @@
7 use turso::{Row, Value};7 use turso::{Row, Value};
8 8
9 use super::{9 use super::{
10- Store, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish,10+ Store, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt,
11- insert_err, missing_row, new_id,11+ finish, insert_err, missing_row, new_id, opt_text,
12 };12 };
13 use crate::error::{Error, Result};13 use crate::error::{Error, Result};
14 use crate::mirrors::{14 use crate::mirrors::{
@@ -38,29 +38,12 @@ fn map_mirror(row: &Row) -> Result<Mirror> {
38 enabled: col_bool(row, 7)?,38 enabled: col_bool(row, 7)?,
39 next_sync_at: col_text(row, 8)?,39 next_sync_at: col_text(row, 8)?,
40 last_sync_at: col_opt_text(row, 9)?,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 last_error: col_opt_text(row, 11)?,42 last_error: col_opt_text(row, 11)?,
43 created_at: col_text(row, 12)?,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 /// Rejects an interval that is neither `0` (manual only) nor at least the minimum.47 /// Rejects an interval that is neither `0` (manual only) nor at least the minimum.
65 fn validate_interval(minutes: u32) -> Result<()> {48 fn validate_interval(minutes: u32) -> Result<()> {
66 if minutes != 0 && minutes < MIN_INTERVAL_MINUTES {49 if minutes != 0 && minutes < MIN_INTERVAL_MINUTES {
@@ -74,12 +57,7 @@ fn validate_interval(minutes: u32) -> Result<()> {
74 impl Store {57 impl Store {
75 /// Seals a plaintext mirror secret with the instance key.58 /// Seals a plaintext mirror secret with the instance key.
76 fn seal_mirror_secret(&self, plain: &[u8]) -> Result<Vec<u8>> {59 fn seal_mirror_secret(&self, plain: &[u8]) -> Result<Vec<u8>> {
77- let key = self60+ Ok(secret::seal(self.secret_key()?, plain)?.into_bytes())
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())
83 }61 }
84 62
85 /// Creates a mirror. The repo has at most one pull mirror (`Conflict` for a second) and at63 /// 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 let sealed = String::from_utf8(sealed)242 let sealed = String::from_utf8(sealed)
265 .map_err(|_| Error::Crypto("sealed mirror secret is not UTF-8".into()))?;243 .map_err(|_| Error::Crypto("sealed mirror secret is not UTF-8".into()))?;
266- let key = self244+ Ok(Some(secret::open(self.secret_key()?, &sealed)?))
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)?))
272 }245 }
273 246
274 /// Enabled mirrors due at or before `now`, earliest first, at most `limit` (capped at 200).247 /// Enabled mirrors due at or before `now`, earliest first, at most `limit` (capped at 200).
@@ -328,7 +301,7 @@ impl Store {
328 let params = vec![301 let params = vec![
329 Value::Text(id.to_string()),302 Value::Text(id.to_string()),
330 Value::Text(now_stamp()),303 Value::Text(now_stamp()),
331- opt_int_value(Some(ok)),304+ Value::Integer(i64::from(ok)),
332 opt_text(error),305 opt_text(error),
333 Value::Text(next_sync_at.to_string()),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 async fn add_repo(store: &Store, owner: &User, name: &str) -> Repo {365 async fn add_repo(store: &Store, owner: &User, name: &str) -> Repo {
428 store366 store
429 .create_repo(&owner.id, name, "", Visibility::Public, "main")367 .create_repo(&owner.id, name, "", Visibility::Public, "main")
@@ -653,6 +591,7 @@ mod tests {
653 #[tokio::test]591 #[tokio::test]
654 async fn due_mirrors_are_earliest_first_and_skip_disabled() {592 async fn due_mirrors_are_earliest_first_and_skip_disabled() {
655 let (store, _tahinli, repo, _dir) = setup().await;593 let (store, _tahinli, repo, _dir) = setup().await;
594+ assert_eq!(store.next_mirror_due().await.unwrap(), None);
656 let late = store595 let late = store
657 .create_mirror(&push(&repo, "https://late.example/r.git"))596 .create_mirror(&push(&repo, "https://late.example/r.git"))
658 .await597 .await
@@ -678,7 +617,7 @@ mod tests {
678 .await617 .await
679 .unwrap();618 .unwrap();
680 store619 store
681- .schedule_mirror(&off.id, "2020-01-01T00:00:00.000000000Z")620+ .schedule_mirror(&off.id, "2019-12-31T00:00:00.000000000Z")
682 .await621 .await
683 .unwrap();622 .unwrap();
684 store623 store
@@ -696,6 +635,11 @@ mod tests {
696 )635 )
697 .await636 .await
698 .unwrap();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 let now = now_stamp();644 let now = now_stamp();
701 let due: Vec<String> = store645 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 use crate::time::now_stamp;71 use crate::time::now_stamp;
72 72
73 const BUSY_TIMEOUT: Duration = Duration::from_millis(5000);73 const BUSY_TIMEOUT: Duration = Duration::from_millis(5000);
74+
75+const IN_CHUNK: usize = 500;
74 /// Longest accepted `about` text, in characters.76 /// Longest accepted `about` text, in characters.
75 pub const MAX_ABOUT_CHARS: usize = 2000;77 pub const MAX_ABOUT_CHARS: usize = 2000;
76 /// Longest accepted display name, in characters.78 /// Longest accepted display name, in characters.
@@ -152,13 +154,12 @@ impl Store {
152 let conn = db.connect().map_err(db_err)?;154 let conn = db.connect().map_err(db_err)?;
153 apply_pragmas(&conn).await;155 apply_pragmas(&conn).await;
154 migrate::migrate(&conn).await?;156 migrate::migrate(&conn).await?;
155- // Readers are opened after migrations so their schema view is current.
156 let mut readers = Vec::with_capacity(READER_COUNT);157 let mut readers = Vec::with_capacity(READER_COUNT);
157 for _ in 0..READER_COUNT {158 for _ in 0..READER_COUNT {
158 let reader = db.connect().map_err(db_err)?;159 let reader = db.connect().map_err(db_err)?;
159 apply_pragmas(&reader).await;160 apply_pragmas(&reader).await;
160- apply_query_only(&reader).await?;161+ run_pragma(&reader, "PRAGMA query_only = 1").await.map_err(db_err)?;
161- apply_reader_cache_size(&reader).await?;162+ run_pragma(&reader, "PRAGMA cache_size = -2048").await.map_err(db_err)?;
162 readers.push(Mutex::new(reader));163 readers.push(Mutex::new(reader));
163 }164 }
164 Ok(Store {165 Ok(Store {
@@ -193,7 +194,13 @@ impl Store {
193 let _ = self.inner.secret_key.set(key);194 let _ = self.inner.secret_key.set(key);
194 }195 }
195 196
196- // users197+ 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 pub async fn user_count(&self) -> Result<u64> {204 pub async fn user_count(&self) -> Result<u64> {
198 let conn = self.read_conn().await;205 let conn = self.read_conn().await;
199 let mut rows = conn206 let mut rows = conn
@@ -212,27 +219,7 @@ impl Store {
212 password_hash: &str,219 password_hash: &str,
213 is_admin: bool,220 is_admin: bool,
214 ) -> Result<User> {221 ) -> Result<User> {
215- let user = User {222+ let user = new_user(username, email, password_hash, is_admin);
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- };
236 let conn = self.inner.conn.lock().await;223 let conn = self.inner.conn.lock().await;
237 conn.execute(224 conn.execute(
238 "INSERT INTO users (id, username, username_folded, email, password_hash, is_admin, created_at, theme) \225 "INSERT INTO users (id, username, username_folded, email, password_hash, is_admin, created_at, theme) \
@@ -260,27 +247,7 @@ impl Store {
260 email: Option<&str>,247 email: Option<&str>,
261 password_hash: &str,248 password_hash: &str,
262 ) -> Result<Option<User>> {249 ) -> Result<Option<User>> {
263- let user = User {250+ let user = new_user(username, email, password_hash, true);
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- };
284 let conn = self.inner.conn.lock().await;251 let conn = self.inner.conn.lock().await;
285 let inserted = conn252 let inserted = conn
286 .execute(253 .execute(
@@ -334,7 +301,6 @@ impl Store {
334 .await301 .await
335 }302 }
336 303
337- // sessions
338 /// Changes only the display casing of a username. `display` must validate and fold to the304 /// Changes only the display casing of a username. `display` must validate and fold to the
339 /// user's current `username_folded`; anything else is rejected and nothing is written.305 /// user's current `username_folded`; anything else is rejected and nothing is written.
340 pub async fn set_username_display(&self, user_id: &str, display: &str) -> Result<()> {306 pub async fn set_username_display(&self, user_id: &str, display: &str) -> Result<()> {
@@ -454,7 +420,6 @@ impl Store {
454 .await420 .await
455 }421 }
456 422
457- // ssh keys
458 pub async fn add_ssh_key(423 pub async fn add_ssh_key(
459 &self,424 &self,
460 user_id: &str,425 user_id: &str,
@@ -479,7 +444,7 @@ impl Store {
479 "SELECT COUNT(*) FROM ssh_keys WHERE user_id = ?1",444 "SELECT COUNT(*) FROM ssh_keys WHERE user_id = ?1",
480 user_id,445 user_id,
481 MAX_SSH_KEYS,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 .await?;449 .await?;
485 conn.execute(450 conn.execute(
@@ -549,7 +514,6 @@ impl Store {
549 Ok(())514 Ok(())
550 }515 }
551 516
552- // tokens
553 pub async fn create_token(517 pub async fn create_token(
554 &self,518 &self,
555 user_id: &str,519 user_id: &str,
@@ -575,7 +539,7 @@ impl Store {
575 "SELECT COUNT(*) FROM access_tokens WHERE user_id = ?1",539 "SELECT COUNT(*) FROM access_tokens WHERE user_id = ?1",
576 user_id,540 user_id,
577 MAX_TOKENS,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 .await?;544 .await?;
581 conn.execute(545 conn.execute(
@@ -648,7 +612,6 @@ impl Store {
648 Ok(())612 Ok(())
649 }613 }
650 614
651- // repos
652 pub async fn create_repo(615 pub async fn create_repo(
653 &self,616 &self,
654 owner_id: &str,617 owner_id: &str,
@@ -683,7 +646,6 @@ impl Store {
683 let conn = self.inner.conn.lock().await;646 let conn = self.inner.conn.lock().await;
684 let tx = conn.unchecked_transaction().await.map_err(db_err)?;647 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
685 let outcome: Result<Option<Repo>> = async {648 let outcome: Result<Option<Repo>> = async {
686- // A new repo takes over an old name, so any redirect for it is dropped.
687 tx.execute(649 tx.execute(
688 "DELETE FROM repo_redirects WHERE owner_folded = (SELECT username_folded FROM users WHERE id = ?1) AND name_folded = ?2",650 "DELETE FROM repo_redirects WHERE owner_folded = (SELECT username_folded FROM users WHERE id = ?1) AND name_folded = ?2",
689 (owner_id.to_string(), normalize_name(name)),651 (owner_id.to_string(), normalize_name(name)),
@@ -716,20 +678,7 @@ impl Store {
716 .await678 .await
717 }679 }
718 .await;680 .await;
719- match outcome {681+ finish(tx, outcome.and_then(|repo| repo.ok_or_else(missing_row))).await
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- }
733 }682 }
734 683
735 /// Normalized. The caller strips a trailing ".git" from `name`.684 /// Normalized. The caller strips a trailing ".git" from `name`.
@@ -778,10 +727,7 @@ impl Store {
778 )727 )
779 .await728 .await
780 .map_err(db_err)?;729 .map_err(db_err)?;
781- if n == 0 {730+ affected(n)
782- return Err(Error::NotFound);
783- }
784- Ok(())
785 }731 }
786 732
787 pub async fn collaborator_role(&self, repo_id: &str, user_id: &str) -> Result<Option<Role>> {733 pub async fn collaborator_role(&self, repo_id: &str, user_id: &str) -> Result<Option<Role>> {
@@ -811,7 +757,6 @@ impl Store {
811 Ok(())757 Ok(())
812 }758 }
813 759
814- // events
815 pub async fn record_push_event(760 pub async fn record_push_event(
816 &self,761 &self,
817 repo_id: &str,762 repo_id: &str,
@@ -840,7 +785,7 @@ impl Store {
840 .map_err(db_err)?;785 .map_err(db_err)?;
841 Ok(())786 Ok(())
842 }787 }
843- // profile788+
844 /// Sets the about text and timezone. `about` is at most 2000 characters and `timezone`789 /// Sets the about text and timezone. `about` is at most 2000 characters and `timezone`
845 /// must be a known IANA name; anything else is rejected and nothing is written.790 /// must be a known IANA name; anything else is rejected and nothing is written.
846 pub async fn set_profile(&self, user_id: &str, about: &str, timezone: &str) -> Result<()> {791 pub async fn set_profile(&self, user_id: &str, about: &str, timezone: &str) -> Result<()> {
@@ -858,10 +803,7 @@ impl Store {
858 )803 )
859 .await804 .await
860 .map_err(db_err)?;805 .map_err(db_err)?;
861- if n == 0 {806+ affected(n)
862- return Err(Error::NotFound);
863- }
864- Ok(())
865 }807 }
866 808
867 /// Sets the display name. `name` goes through `validate_display_name`; an empty name clears809 /// Sets the display name. `name` goes through `validate_display_name`; an empty name clears
@@ -879,10 +821,7 @@ impl Store {
879 )821 )
880 .await822 .await
881 .map_err(db_err)?;823 .map_err(db_err)?;
882- if n == 0 {824+ affected(n)
883- return Err(Error::NotFound);
884- }
885- Ok(())
886 }825 }
887 826
888 /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest.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 fn new_id() -> String {882 fn new_id() -> String {
946 Ulid::generate().to_string()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 fn db_err(e: turso::Error) -> Error {922 fn db_err(e: turso::Error) -> Error {
950 Error::Database(e.to_string())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 fn missing_row() -> Error {933 fn missing_row() -> Error {
954 Error::Database("expected a row that is not there".into())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 a947+async fn run_pragma(conn: &Connection, sql: &str) -> std::result::Result<(), turso::Error> {
968-/// reader that can write would break the pool's rule.948+ let mut rows = conn.query(sql, ()).await?;
969-async fn apply_query_only(conn: &Connection) -> Result<()> {949+ while rows.next().await?.is_some() {}
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() {}
986 Ok(())950 Ok(())
987 }951 }
988 952
@@ -994,13 +958,7 @@ async fn apply_pragmas(conn: &Connection) {
994 "PRAGMA synchronous = FULL",958 "PRAGMA synchronous = FULL",
995 "PRAGMA foreign_keys = ON",959 "PRAGMA foreign_keys = ON",
996 ] {960 ] {
997- let applied = async {961+ if let Err(e) = run_pragma(conn, sql).await {
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 {
1004 tracing::warn!(pragma = sql, error = %e, "database pragma not applied");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 fn col_blob(row: &Row, i: usize) -> Result<Vec<u8>> {1054 fn col_blob(row: &Row, i: usize) -> Result<Vec<u8>> {
1089 match row.get_value(i).map_err(db_err)? {1055 match row.get_value(i).map_err(db_err)? {
1090 Value::Blob(b) => Ok(b),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 pub(crate) fn col_int(row: &Row, i: usize) -> Result<i64> {1065 pub(crate) fn col_int(row: &Row, i: usize) -> Result<i64> {
1096 match row.get_value(i).map_err(db_err)? {1066 match row.get_value(i).map_err(db_err)? {
1097 Value::Integer(n) => Ok(n),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 impl Store {1211 impl Store {
1243 /// Deletes a repo row and every row that references it (webhooks and their deliveries, issues and their children, labels,1212 /// Deletes a repo row and every row that references it (webhooks and their deliveries, issues and their children, labels,
1244 /// milestones, pull requests, notifications, watches and issue subscriptions, redirects, collaborators, push events,1213 /// milestones, pull requests, notifications, watches and issue subscriptions, redirects, collaborators, push events,
@@ -1252,8 +1221,6 @@ impl Store {
1252 let tx = conn.unchecked_transaction().await.map_err(db_err)?;1221 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
1253 let id = repo_id.to_string();1222 let id = repo_id.to_string();
1254 let outcome: Result<u64> = async {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 notifications::delete_repo_notification_rows(&tx, &id).await?;1224 notifications::delete_repo_notification_rows(&tx, &id).await?;
1258 reviews::delete_repo_review_rows(&tx, &id).await?;1225 reviews::delete_repo_review_rows(&tx, &id).await?;
1259 pulls::delete_repo_pull_rows(&tx, &id).await?;1226 pulls::delete_repo_pull_rows(&tx, &id).await?;
@@ -1261,7 +1228,6 @@ impl Store {
1261 discussions::delete_repo_discussion_rows(&tx, &id).await?;1228 discussions::delete_repo_discussion_rows(&tx, &id).await?;
1262 releases::delete_repo_release_rows(&tx, &id).await?;1229 releases::delete_repo_release_rows(&tx, &id).await?;
1263 for sql in [1230 for sql in [
1264- // Deliveries before hooks, hooks before the repo.
1265 "DELETE FROM webhook_deliveries WHERE hook_id IN (SELECT id FROM webhooks WHERE repo_id = ?1)",1231 "DELETE FROM webhook_deliveries WHERE hook_id IN (SELECT id FROM webhooks WHERE repo_id = ?1)",
1266 "DELETE FROM webhooks WHERE repo_id = ?1",1232 "DELETE FROM webhooks WHERE repo_id = ?1",
1267 "DELETE FROM repo_mirrors WHERE repo_id = ?1",1233 "DELETE FROM repo_mirrors WHERE repo_id = ?1",
@@ -1279,13 +1245,11 @@ impl Store {
1279 "DELETE FROM advisory_notifications WHERE repo_id = ?1",1245 "DELETE FROM advisory_notifications WHERE repo_id = ?1",
1280 "DELETE FROM repo_alerts WHERE repo_id = ?1",1246 "DELETE FROM repo_alerts WHERE repo_id = ?1",
1281 "DELETE FROM repo_dependencies WHERE repo_id = ?1",1247 "DELETE FROM repo_dependencies WHERE repo_id = ?1",
1282- // CI: artifacts and jobs before runs, runs before the repo.
1283 "DELETE FROM ci_artifacts WHERE job_id IN (SELECT ci_jobs.id FROM ci_jobs \1248 "DELETE FROM ci_artifacts WHERE job_id IN (SELECT ci_jobs.id FROM ci_jobs \
1284 JOIN ci_runs ON ci_runs.id = ci_jobs.run_id WHERE ci_runs.repo_id = ?1)",1249 JOIN ci_runs ON ci_runs.id = ci_jobs.run_id WHERE ci_runs.repo_id = ?1)",
1285 "DELETE FROM ci_jobs WHERE run_id IN (SELECT id FROM ci_runs WHERE repo_id = ?1)",1250 "DELETE FROM ci_jobs WHERE run_id IN (SELECT id FROM ci_runs WHERE repo_id = ?1)",
1286 "DELETE FROM ci_runs WHERE repo_id = ?1",1251 "DELETE FROM ci_runs WHERE repo_id = ?1",
1287 "DELETE FROM ci_secrets WHERE repo_id = ?1",1252 "DELETE FROM ci_secrets WHERE repo_id = ?1",
1288- // Forks of this repo stay, detached from it.
1289 "UPDATE repos SET fork_of = NULL WHERE fork_of = ?1",1253 "UPDATE repos SET fork_of = NULL WHERE fork_of = ?1",
1290 ] {1254 ] {
1291 tx.execute(sql, (id.clone(),)).await.map_err(db_err)?;1255 tx.execute(sql, (id.clone(),)).await.map_err(db_err)?;
@@ -1295,20 +1259,11 @@ impl Store {
1295 .map_err(db_err)1259 .map_err(db_err)
1296 }1260 }
1297 .await;1261 .await;
1298- match outcome {1262+ finish(
1299- Ok(1) => {1263+ tx,
1300- tx.commit().await.map_err(db_err)?;1264+ outcome.and_then(|n| if n == 1 { Ok(()) } else { Err(Error::NotFound) }),
1301- Ok(())1265+ )
1302- }1266+ .await
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- }
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 required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks, \1271 required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks, \
1317 require_merge_queue";1272 require_merge_queue";
1318 1273
1319-// branch protection
1320 impl Store {1274 impl Store {
1321 /// The repo's branch rules, ordered by pattern.1275 /// The repo's branch rules, ordered by pattern.
1322 pub async fn list_branch_rules(&self, repo_id: &str) -> Result<Vec<BranchRule>> {1276 pub async fn list_branch_rules(&self, repo_id: &str) -> Result<Vec<BranchRule>> {
@@ -1395,10 +1349,7 @@ impl Store {
1395 )1349 )
1396 .await1350 .await
1397 .map_err(db_err)?;1351 .map_err(db_err)?;
1398- if n == 0 {1352+ affected(n)
1399- return Err(Error::NotFound);
1400- }
1401- Ok(())
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 impl Store {1375 impl Store {
1426 /// The repo a past owner/name points at (both folded). Chains work because a redirect always1376 /// The repo a past owner/name points at (both folded). Chains work because a redirect always
1427 /// points at the repo id, not at an intermediate name.1377 /// points at the repo id, not at an intermediate name.
@@ -1443,65 +1393,60 @@ impl Store {
1443 /// Renames a repo under its current owner. The old name keeps working through a redirect.1393 /// Renames a repo under its current owner. The old name keeps working through a redirect.
1444 /// A name taken by another repo of the same owner gives `Conflict`.1394 /// A name taken by another repo of the same owner gives `Conflict`.
1445 pub async fn rename_repo(&self, repo_id: &str, new_name: &str) -> Result<()> {1395 pub async fn rename_repo(&self, repo_id: &str, new_name: &str) -> Result<()> {
1446- let folded = validate_name(new_name)?;1396+ validate_name(new_name)?;
1447- let owner_id = self.repo_owner_id(repo_id).await?.ok_or(Error::NotFound)?;1397+ self.move_repo(repo_id, None, Some(new_name)).await
1448- self.move_repo(repo_id, &owner_id, new_name, &folded).await
1449 }1398 }
1450 1399
1451 /// Moves a repo to another owner under the same name. The old owner/name keeps working through1400 /// Moves a repo to another owner under the same name. The old owner/name keeps working through
1452 /// a redirect. Collaborator rows stay, except the new owner's, which is removed. A name taken1401 /// a redirect. Collaborator rows stay, except the new owner's, which is removed. A name taken
1453 /// by the new owner gives `Conflict`.1402 /// by the new owner gives `Conflict`.
1454 pub async fn transfer_repo(&self, repo_id: &str, new_owner_id: &str) -> Result<()> {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)?;1404+ self.move_repo(repo_id, Some(new_owner_id), None).await
1456- self.move_repo(
1457- repo_id,
1458- new_owner_id,
1459- &repo.name,
1460- &normalize_name(&repo.name),
1461- )
1462- .await
1463- }
1464-
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 }1405 }
1476 1406
1477- /// Shared body of rename and transfer, in one transaction: updates owner, name and folded1407+ /// Shared body of rename and transfer, in one transaction. `None` keeps the current owner or
1478- /// name, records a redirect from the old owner/name to this repo, drops any redirect for the1408+ /// name, which is read here under the writer lock so a concurrent move is not written back.
1479- /// new owner/name, and removes the new owner's collaborator row when the owner changes.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 async fn move_repo(1412 async fn move_repo(
1481 &self,1413 &self,
1482 repo_id: &str,1414 repo_id: &str,
1483- new_owner_id: &str,1415+ new_owner_id: Option<&str>,
1484- new_name: &str,1416+ new_name: Option<&str>,
1485- new_folded: &str,
1486 ) -> Result<()> {1417 ) -> Result<()> {
1487 let conn = self.inner.conn.lock().await;1418 let conn = self.inner.conn.lock().await;
1488 let tx = conn.unchecked_transaction().await.map_err(db_err)?;1419 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
1489 let id = repo_id.to_string();1420 let id = repo_id.to_string();
1490 let outcome: Result<()> = async {1421 let outcome: Result<()> = async {
1491- // Old owner folded, old owner id, and old folded name.1422+ let (old_owner_id, old_owner_folded, old_name, old_folded): (
1492- let (old_owner_id, old_owner_folded, old_folded): (String, String, String) = fetch_opt(1423+ String,
1424+ String,
1425+ String,
1426+ String,
1427+ ) = fetch_opt(
1493 &tx,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 JOIN users u ON u.id = r.owner_id WHERE r.id = ?1",1430 JOIN users u ON u.id = r.owner_id WHERE r.id = ?1",
1496 (id.clone(),),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 .await?1441 .await?
1500 .ok_or(Error::NotFound)?;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 let new_owner_folded: String = fetch_opt(1446 let new_owner_folded: String = fetch_opt(
1502 &tx,1447 &tx,
1503 "SELECT username_folded FROM users WHERE id = ?1",1448 "SELECT username_folded FROM users WHERE id = ?1",
1504- (new_owner_id.to_string(),),1449+ (new_owner_id.clone(),),
1505 |row| col_text(row, 0),1450 |row| col_text(row, 0),
1506 )1451 )
1507 .await?1452 .await?
@@ -1519,7 +1464,6 @@ impl Store {
1519 .await1464 .await
1520 .map_err(|e| insert_err(e, "a repository with this name already exists"))?;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 tx.execute(1467 tx.execute(
1524 "DELETE FROM repo_redirects WHERE owner_folded = ?1 AND name_folded = ?2",1468 "DELETE FROM repo_redirects WHERE owner_folded = ?1 AND name_folded = ?2",
1525 (new_owner_folded.clone(), new_folded.to_string()),1469 (new_owner_folded.clone(), new_folded.to_string()),
@@ -1550,8 +1494,6 @@ impl Store {
1550 )1494 )
1551 .await1495 .await
1552 .map_err(db_err)?;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 tx.execute(1497 tx.execute(
1556 "DELETE FROM repo_transfers WHERE repo_id = ?1",1498 "DELETE FROM repo_transfers WHERE repo_id = ?1",
1557 (id.clone(),),1499 (id.clone(),),
@@ -1562,21 +1504,10 @@ impl Store {
1562 Ok(())1504 Ok(())
1563 }1505 }
1564 .await;1506 .await;
1565- match outcome {1507+ finish(tx, outcome).await
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- }
1575 }1508 }
1576 }1509 }
1577 1510
1578-// ---- account security: email, password, two-factor ----
1579-
1580 /// The two-factor state of a user.1511 /// The two-factor state of a user.
1581 #[derive(Debug, Clone, PartialEq)]1512 #[derive(Debug, Clone, PartialEq)]
1582 pub struct TotpState {1513 pub struct TotpState {
@@ -1623,10 +1554,7 @@ impl Store {
1623 )1554 )
1624 .await1555 .await
1625 .map_err(db_err)?;1556 .map_err(db_err)?;
1626- if n == 0 {1557+ affected(n)
1627- return Err(Error::NotFound);
1628- }
1629- Ok(())
1630 }1558 }
1631 1559
1632 /// Replaces the stored password hash. The caller hashes the password.1560 /// Replaces the stored password hash. The caller hashes the password.
@@ -1639,10 +1567,7 @@ impl Store {
1639 )1567 )
1640 .await1568 .await
1641 .map_err(db_err)?;1569 .map_err(db_err)?;
1642- if n == 0 {1570+ affected(n)
1643- return Err(Error::NotFound);
1644- }
1645- Ok(())
1646 }1571 }
1647 1572
1648 /// Deletes every session of the user except `keep_session_id`. Returns how many were removed.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 .await1629 .await
1705 .map_err(db_err)?;1630 .map_err(db_err)?;
1706- if n == 0 {1631+ affected(n)
1707- return Err(Error::NotFound);
1708- }
1709- Ok(())
1710 }1632 }
1711 1633
1712 /// Turns two-factor on after a confirmed code, and replaces the recovery codes with1634 /// Turns two-factor on after a confirmed code, and replaces the recovery codes with
@@ -1733,9 +1655,7 @@ impl Store {
1733 )1655 )
1734 .await1656 .await
1735 .map_err(db_err)?;1657 .map_err(db_err)?;
1736- if n == 0 {1658+ affected(n)?;
1737- return Err(Error::NotFound);
1738- }
1739 replace_codes_in(&tx, &uid, code_hashes).await1659 replace_codes_in(&tx, &uid, code_hashes).await
1740 }1660 }
1741 .await;1661 .await;
@@ -1908,14 +1828,12 @@ mod tests {
1908 let dir = tempfile::tempdir().unwrap();1828 let dir = tempfile::tempdir().unwrap();
1909 let (store, user) = store_with_user(&dir).await;1829 let (store, user) = store_with_user(&dir).await;
1910 1830
1911- // Scenario: a new user has an empty bio and UTC.
1912 assert_eq!(user.about, "");1831 assert_eq!(user.about, "");
1913 assert_eq!(user.timezone, "UTC");1832 assert_eq!(user.timezone, "UTC");
1914 let fetched = store.user_by_id(&user.id).await.unwrap().unwrap();1833 let fetched = store.user_by_id(&user.id).await.unwrap().unwrap();
1915 assert_eq!(fetched.about, "");1834 assert_eq!(fetched.about, "");
1916 assert_eq!(fetched.timezone, "UTC");1835 assert_eq!(fetched.timezone, "UTC");
1917 1836
1918- // Scenario: a valid profile is saved; invalid input is refused and changes nothing.
1919 store1837 store
1920 .set_profile(&user.id, "Hello *world*", "Europe/Istanbul")1838 .set_profile(&user.id, "Hello *world*", "Europe/Istanbul")
1921 .await1839 .await
@@ -1949,7 +1867,6 @@ mod tests {
1949 validate_display_name(" Ahmet Kaan Gümüş ").unwrap(),1867 validate_display_name(" Ahmet Kaan Gümüş ").unwrap(),
1950 Some("Ahmet Kaan Gümüş".to_string())1868 Some("Ahmet Kaan Gümüş".to_string())
1951 );1869 );
1952- // The limit counts characters: 80 two-byte letters fit, 81 do not.
1953 assert!(validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS)).is_ok());1870 assert!(validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS)).is_ok());
1954 assert!(matches!(1871 assert!(matches!(
1955 validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS + 1)),1872 validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS + 1)),
@@ -1982,12 +1899,10 @@ mod tests {
1982 let fetched = store.user_by_id(&user.id).await.unwrap().unwrap();1899 let fetched = store.user_by_id(&user.id).await.unwrap().unwrap();
1983 assert_eq!(fetched.display_name.as_deref(), Some("Ahmet Kaan Gümüş"));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 store.set_display_name(&user.id, " ").await.unwrap();1902 store.set_display_name(&user.id, " ").await.unwrap();
1987 let cleared = store.user_by_id(&user.id).await.unwrap().unwrap();1903 let cleared = store.user_by_id(&user.id).await.unwrap().unwrap();
1988 assert_eq!(cleared.display_name, None);1904 assert_eq!(cleared.display_name, None);
1989 1905
1990- // A rejected name leaves the stored value alone.
1991 store.set_display_name(&user.id, "Kept").await.unwrap();1906 store.set_display_name(&user.id, "Kept").await.unwrap();
1992 let long = "x".repeat(MAX_DISPLAY_NAME_CHARS + 1);1907 let long = "x".repeat(MAX_DISPLAY_NAME_CHARS + 1);
1993 assert!(matches!(1908 assert!(matches!(
@@ -2007,7 +1922,6 @@ mod tests {
2007 let dir = tempfile::tempdir().unwrap();1922 let dir = tempfile::tempdir().unwrap();
2008 let (store, user) = store_with_user(&dir).await;1923 let (store, user) = store_with_user(&dir).await;
2009 1924
2010- // Scenario: upsert replaces the image and its hash; delete is idempotent.
2011 assert_eq!(store.avatar(&user.id).await.unwrap(), None);1925 assert_eq!(store.avatar(&user.id).await.unwrap(), None);
2012 assert_eq!(store.avatar_hash(&user.id).await.unwrap(), None);1926 assert_eq!(store.avatar_hash(&user.id).await.unwrap(), None);
2013 store.set_avatar(&user.id, b"png-1", "aaaa").await.unwrap();1927 store.set_avatar(&user.id, b"png-1", "aaaa").await.unwrap();
@@ -2024,7 +1938,6 @@ mod tests {
2024 store.delete_avatar(&user.id).await.unwrap();1938 store.delete_avatar(&user.id).await.unwrap();
2025 assert_eq!(store.avatar(&user.id).await.unwrap(), None);1939 assert_eq!(store.avatar(&user.id).await.unwrap(), None);
2026 1940
2027- // Scenario: deleting the user row removes its avatar with it.
2028 let doomed = store1941 let doomed = store
2029 .create_user("Doomed", None, "hash", false)1942 .create_user("Doomed", None, "hash", false)
2030 .await1943 .await
@@ -2045,8 +1958,6 @@ mod tests {
2045 let (store, tahinli) = store_with_user(&dir).await;1958 let (store, tahinli) = store_with_user(&dir).await;
2046 let bob = store.create_user("Bob", None, "hash", false).await.unwrap();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 let keep = store1961 let keep = store
2051 .create_repo(&tahinli.id, "keep", "", Visibility::Public, "main")1962 .create_repo(&tahinli.id, "keep", "", Visibility::Public, "main")
2052 .await1963 .await
@@ -2107,7 +2018,6 @@ mod tests {
2107 assert_eq!(col_int(&row, 0).unwrap(), 1);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 let later = store2021 let later = store
2112 .create_repo(&tahinli.id, "later", "", Visibility::Public, "main")2022 .create_repo(&tahinli.id, "later", "", Visibility::Public, "main")
2113 .await2023 .await
@@ -2129,8 +2039,6 @@ mod tests {
2129 let dir = tempfile::tempdir().unwrap();2039 let dir = tempfile::tempdir().unwrap();
2130 let (store, owner) = store_with_user(&dir).await;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 let repo = store2043 let repo = store
2136 .create_repo(&owner.id, "checks", "", Visibility::Public, "main")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 let repo = store2081 let repo = store
2175 .create_repo(&owner.id, "list", "", Visibility::Public, "main")2082 .create_repo(&owner.id, "list", "", Visibility::Public, "main")
@@ -2189,7 +2096,6 @@ mod tests {
2189 let patterns: Vec<&str> = rules.iter().map(|r| r.pattern.as_str()).collect();2096 let patterns: Vec<&str> = rules.iter().map(|r| r.pattern.as_str()).collect();
2190 assert_eq!(patterns, ["main", "release/*"]);2097 assert_eq!(patterns, ["main", "release/*"]);
2191 2098
2192- // Same pattern updates the flags in place and keeps the id and created_at.
2193 let updated = store2099 let updated = store
2194 .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(true, true))2100 .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(true, true))
2195 .await2101 .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 let repo = store2119 let repo = store
2215 .create_repo(&owner.id, "fields", "", Visibility::Public, "main")2120 .create_repo(&owner.id, "fields", "", Visibility::Public, "main")
@@ -2238,7 +2143,6 @@ mod tests {
2238 vec![saved]2143 vec![saved]
2239 );2144 );
2240 2145
2241- // Out of range is refused and stores nothing new.
2242 let too_many = RuleFlags {2146 let too_many = RuleFlags {
2243 required_approvals: 21,2147 required_approvals: 21,
2244 ..flags2148 ..flags
@@ -2251,7 +2155,6 @@ mod tests {
2251 assert_eq!(rules[0].required_approvals, 20);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 let a = store2159 let a = store
2257 .create_repo(&owner.id, "scope-a", "", Visibility::Public, "main")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 impl Store {2228 impl Store {
2327 /// Every collaborator on a repo with their role, ordered by username (case-insensitive).2229 /// Every collaborator on a repo with their role, ordered by username (case-insensitive).
2328 pub async fn list_collaborators(&self, repo_id: &str) -> Result<Vec<(User, Role)>> {2230 pub async fn list_collaborators(&self, repo_id: &str) -> Result<Vec<(User, Role)>> {
@@ -2357,7 +2259,6 @@ impl Store {
2357 /// Longest accepted repo description, in characters.2259 /// Longest accepted repo description, in characters.
2358 pub const MAX_DESCRIPTION_CHARS: usize = 350;2260 pub const MAX_DESCRIPTION_CHARS: usize = 350;
2359 2261
2360-// general repo settings (description, default branch, visibility)
2361 impl Store {2262 impl Store {
2362 /// Saves the description and the default branch in one statement. The description must be at2263 /// Saves the description and the default branch in one statement. The description must be at
2363 /// most `MAX_DESCRIPTION_CHARS` characters with no control characters. The branch is not checked2264 /// most `MAX_DESCRIPTION_CHARS` characters with no control characters. The branch is not checked
@@ -2393,10 +2294,7 @@ impl Store {
2393 )2294 )
2394 .await2295 .await
2395 .map_err(db_err)?;2296 .map_err(db_err)?;
2396- if n == 0 {2297+ affected(n)
2397- return Err(Error::NotFound);
2398- }
2399- Ok(())
2400 }2298 }
2401 2299
2402 /// Sets the repo's visibility. `NotFound` when the repo is gone.2300 /// Sets the repo's visibility. `NotFound` when the repo is gone.
@@ -2409,10 +2307,7 @@ impl Store {
2409 )2307 )
2410 .await2308 .await
2411 .map_err(db_err)?;2309 .map_err(db_err)?;
2412- if n == 0 {2310+ affected(n)
2413- return Err(Error::NotFound);
2414- }
2415- Ok(())
2416 }2311 }
2417 }2312 }
2418 2313
@@ -2444,7 +2339,6 @@ mod collaborator_tests {
2444 .set_collaborator(&repo.id, &amy.id, Role::Write)2339 .set_collaborator(&repo.id, &amy.id, Role::Write)
2445 .await2340 .await
2446 .unwrap();2341 .unwrap();
2447- // Setting an existing collaborator again replaces the role.
2448 store2342 store
2449 .set_collaborator(&repo.id, &zed.id, Role::Triage)2343 .set_collaborator(&repo.id, &zed.id, Role::Triage)
2450 .await2344 .await
@@ -2462,7 +2356,6 @@ mod collaborator_tests {
2462 "ordered by username, one row per user"2356 "ordered by username, one row per user"
2463 );2357 );
2464 2358
2465- // Push rights follow the role through authorize.
2466 assert!(authorize(Some(&amy), &repo, Some(Role::Write), None, Action::Write).is_ok());2359 assert!(authorize(Some(&amy), &repo, Some(Role::Write), None, Action::Write).is_ok());
2467 assert_eq!(2360 assert_eq!(
2468 authorize(Some(&zed), &repo, Some(Role::Read), None, Action::Write),2361 authorize(Some(&zed), &repo, Some(Role::Read), None, Action::Write),
@@ -2493,7 +2386,6 @@ pub enum RepoSort {
2493 /// A row of the public listing: the repo, its star count and its last activity time.2386 /// A row of the public listing: the repo, its star count and its last activity time.
2494 pub type ListedRepo = (Repo, u64, String);2387 pub type ListedRepo = (Repo, u64, String);
2495 2388
2496-// stars and the public repo listing
2497 impl Store {2389 impl Store {
2498 /// Stars a repo for a user. Starring a repo twice changes nothing.2390 /// Stars a repo for a user. Starring a repo twice changes nothing.
2499 pub async fn star(&self, user_id: &str, repo_id: &str) -> Result<()> {2391 pub async fn star(&self, user_id: &str, repo_id: &str) -> Result<()> {
@@ -2546,23 +2438,6 @@ impl Store {
2546 Ok(u64::try_from(n).unwrap_or(0))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 /// One page of public repos, optionally filtered by `query`. The query matches the repo name2441 /// One page of public repos, optionally filtered by `query`. The query matches the repo name
2567 /// or description, case-insensitively, as a plain substring: `%`, `_` and `\` are literal.2442 /// or description, case-insensitively, as a plain substring: `%`, `_` and `\` are literal.
2568 /// Each row carries the star count and the last activity time (the latest push, or the2443 /// Each row carries the star count and the last activity time (the latest push, or the
@@ -2633,7 +2508,6 @@ mod security_tests {
2633 async fn account_email_password_and_session_scenarios() {2508 async fn account_email_password_and_session_scenarios() {
2634 let (store, user, _dir) = store_with_user().await;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 store2511 store
2638 .set_email(&user.id, "tahinli@example.com")2512 .set_email(&user.id, "tahinli@example.com")
2639 .await2513 .await
@@ -2648,7 +2522,6 @@ mod security_tests {
2648 Err(Error::NotFound)2522 Err(Error::NotFound)
2649 ));2523 ));
2650 2524
2651- // Scenario: deleting sessions except one keeps only the named session.
2652 let expiry = crate::time::stamp_after(std::time::Duration::from_secs(3600));2525 let expiry = crate::time::stamp_after(std::time::Duration::from_secs(3600));
2653 let keep = store2526 let keep = store
2654 .create_session(&user.id, "h1", "c1", &expiry, None, None)2527 .create_session(&user.id, "h1", "c1", &expiry, None, None)
@@ -2678,12 +2551,10 @@ mod security_tests {
2678 async fn totp_scenarios() {2551 async fn totp_scenarios() {
2679 let (store, user, _dir) = store_with_user().await;2552 let (store, user, _dir) = store_with_user().await;
2680 2553
2681- // Scenario: enabling without a secret is refused and leaves TOTP off.
2682 let err = store.enable_totp(&user.id, 1, &[]).await;2554 let err = store.enable_totp(&user.id, 1, &[]).await;
2683 assert!(matches!(err, Err(Error::NotFound)));2555 assert!(matches!(err, Err(Error::NotFound)));
2684 assert!(!store.totp_state(&user.id).await.unwrap().unwrap().enabled);2556 assert!(!store.totp_state(&user.id).await.unwrap().unwrap().enabled);
2685 2557
2686- // Scenario: enrollment, then replay and recovery-code rules.
2687 let fresh = store.totp_state(&user.id).await.unwrap().unwrap();2558 let fresh = store.totp_state(&user.id).await.unwrap().unwrap();
2688 assert_eq!(fresh.sealed_secret, None);2559 assert_eq!(fresh.sealed_secret, None);
2689 assert!(!fresh.enabled);2560 assert!(!fresh.enabled);
@@ -2700,7 +2571,6 @@ mod security_tests {
2700 assert_eq!(on.last_step, 100);2571 assert_eq!(on.last_step, 100);
2701 assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 2);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 assert!(!store.accept_totp_step(&user.id, 100).await.unwrap());2574 assert!(!store.accept_totp_step(&user.id, 100).await.unwrap());
2705 assert!(!store.accept_totp_step(&user.id, 99).await.unwrap());2575 assert!(!store.accept_totp_step(&user.id, 99).await.unwrap());
2706 assert!(store.accept_totp_step(&user.id, 101).await.unwrap());2576 assert!(store.accept_totp_step(&user.id, 101).await.unwrap());
@@ -2738,7 +2608,6 @@ mod security_tests {
2738 assert_eq!(off.last_step, 0);2608 assert_eq!(off.last_step, 0);
2739 assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 0);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 let device = store2611 let device = store
2743 .create_user("device-owner", None, "h", false)2612 .create_user("device-owner", None, "h", false)
2744 .await2613 .await
@@ -2775,14 +2644,12 @@ mod security_tests {
2775 Some("Work phone")2644 Some("Work phone")
2776 );2645 );
2777 2646
2778- // Stamps have nanosecond precision and sort as text, so a later use compares greater.
2779 std::thread::sleep(std::time::Duration::from_millis(5));2647 std::thread::sleep(std::time::Duration::from_millis(5));
2780 assert!(store.accept_totp_step(&device.id, 101).await.unwrap());2648 assert!(store.accept_totp_step(&device.id, 101).await.unwrap());
2781 let used = store.totp_state(&device.id).await.unwrap().unwrap();2649 let used = store.totp_state(&device.id).await.unwrap().unwrap();
2782 assert!(used.last_used_at.as_deref().unwrap() > added.as_str());2650 assert!(used.last_used_at.as_deref().unwrap() > added.as_str());
2783 assert_eq!(used.created_at.as_deref(), Some(added.as_str()));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 std::thread::sleep(std::time::Duration::from_millis(5));2653 std::thread::sleep(std::time::Duration::from_millis(5));
2787 assert!(!store.accept_totp_step(&device.id, 101).await.unwrap());2654 assert!(!store.accept_totp_step(&device.id, 101).await.unwrap());
2788 assert_eq!(2655 assert_eq!(
crates/forge-core/src/store/notifications.rsmodified+52 -214
@@ -3,9 +3,8 @@
3 use turso::transaction::Transaction;3 use turso::transaction::Transaction;
4 use turso::{Row, Value};4 use turso::{Row, Value};
5 5
6-use super::issues::finish;6+use super::repo_listing::VIEWER_ACCESS;
7-use super::repo_listing::READABLE_BY_VIEWER;7+use super::{Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, finish, map_user, new_id};
8-use super::{Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, map_user, new_id};
9 use crate::error::{Error, Result};8 use crate::error::{Error, Result};
10 use crate::model::{Id, User};9 use crate::model::{Id, User};
11 use crate::notifications::{Notification, Reason, SubState, WatchLevel};10 use crate::notifications::{Notification, Reason, SubState, WatchLevel};
@@ -19,7 +18,7 @@ const MAX_NOTIFICATION_PAGE: u32 = 200;
19 /// from, drops out of the inbox, the dashboard and the unread count at once.18 /// from, drops out of the inbox, the dashboard and the unread count at once.
20 pub(super) fn readable_repo() -> String {19 pub(super) fn readable_repo() -> String {
21 format!(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 number: col_int(row, 5)?,60 number: col_int(row, 5)?,
62 is_pull: kind == "pull",61 is_pull: kind == "pull",
63 title: col_text(row, 7)?,62 title: col_text(row, 7)?,
64- issue_state: col_text(row, 8)?,63+ issue_state: col_text(row, 8)?.parse()?,
65 reason: reason_from(&col_text(row, 9)?)?,64 reason: reason_from(&col_text(row, 9)?)?,
66 last_activity: col_text(row, 10)?,65 last_activity: col_text(row, 10)?,
67 last_actor_name: match row.get_value(11).map_err(db_err)? {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 impl Store {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 /// Sets the user's watch level on a repo, creating the row if needed.101 /// Sets the user's watch level on a repo, creating the row if needed.
95 pub async fn set_watch(&self, user_id: &str, repo_id: &str, level: WatchLevel) -> Result<()> {102 pub async fn set_watch(&self, user_id: &str, repo_id: &str, level: WatchLevel) -> Result<()> {
96 let conn = self.inner.conn.lock().await;103 let conn = self.inner.conn.lock().await;
@@ -405,23 +412,12 @@ impl Store {
405 /// them.412 /// them.
406 pub async fn mark_all_read(&self, user_id: &str, repo_id: Option<&str>) -> Result<()> {413 pub async fn mark_all_read(&self, user_id: &str, repo_id: Option<&str>) -> Result<()> {
407 let conn = self.inner.conn.lock().await;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(415 conn.execute(
418- "UPDATE notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1",416+ "UPDATE notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1 AND (?2 IS NULL OR repo_id = ?2)",
419- (user_id.to_string(),),417+ (user_id.to_string(), repo_id.map(str::to_string)),
420 )418 )
421 .await419 .await
422- }420+ .map_err(db_err)?;
423- };
424- result.map_err(db_err)?;
425 Ok(())421 Ok(())
426 }422 }
427 423
@@ -441,6 +437,7 @@ impl Store {
441 #[cfg(test)]437 #[cfg(test)]
442 mod tests {438 mod tests {
443 use super::*;439 use super::*;
440+ use crate::issues::IssueState;
444 use crate::model::Visibility;441 use crate::model::Visibility;
445 442
446 struct Fixture {443 struct Fixture {
@@ -517,14 +514,25 @@ mod tests {
517 .id514 .id
518 }515 }
519 516
520- // Scenarios share one store. Each one uses its own issue, repo or fresh users517+ async fn notify(
521- // wherever the assertions read repo-wide or per-user state.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 #[tokio::test]531 #[tokio::test]
523- async fn watch_and_subscription_rules_hold_in_each_scenario() {532+ async fn watch_and_subscription_rules() {
524 let fx = fixture().await;533 let fx = fixture().await;
525 let s = &fx.store;534 let s = &fx.store;
526 535
527- // Scenario 1: watch levels default to participating; watchers lists only watchers.
528 let repo = s536 let repo = s
529 .create_repo(&fx.owner, "watch", "", Visibility::Public, "main")537 .create_repo(&fx.owner, "watch", "", Visibility::Public, "main")
530 .await538 .await
@@ -560,7 +568,6 @@ mod tests {
560 expected.sort();568 expected.sort();
561 assert_eq!(watchers, expected, "watch: only watching users listed");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 let issue = s571 let issue = s
565 .create_issue(&fx.repo, &fx.owner, "Third", "")572 .create_issue(&fx.repo, &fx.owner, "Third", "")
566 .await573 .await
@@ -574,7 +581,6 @@ mod tests {
574 Some((SubState::Subscribed, Reason::Comment)),581 Some((SubState::Subscribed, Reason::Comment)),
575 "auto: first subscription"582 "auto: first subscription"
576 );583 );
577- // Existing row stays as it was.
578 s.auto_subscribe(&fx.tahinli, &issue, Reason::Mention)584 s.auto_subscribe(&fx.tahinli, &issue, Reason::Mention)
579 .await585 .await
580 .unwrap();586 .unwrap();
@@ -583,7 +589,6 @@ mod tests {
583 Some((SubState::Subscribed, Reason::Comment)),589 Some((SubState::Subscribed, Reason::Comment)),
584 "auto: existing row kept"590 "auto: existing row kept"
585 );591 );
586- // An explicit ignore is never replaced by auto-subscribe.
587 s.subscribe(&fx.bob, &issue, SubState::Ignored, Reason::Subscribed)592 s.subscribe(&fx.bob, &issue, SubState::Ignored, Reason::Subscribed)
588 .await593 .await
589 .unwrap();594 .unwrap();
@@ -595,7 +600,6 @@ mod tests {
595 Some((SubState::Ignored, Reason::Subscribed)),600 Some((SubState::Ignored, Reason::Subscribed)),
596 "auto: ignore kept"601 "auto: ignore kept"
597 );602 );
598- // Explicit subscribe does replace.
599 s.subscribe(&fx.bob, &issue, SubState::Subscribed, Reason::Author)603 s.subscribe(&fx.bob, &issue, SubState::Subscribed, Reason::Author)
600 .await604 .await
601 .unwrap();605 .unwrap();
@@ -610,7 +614,6 @@ mod tests {
610 "auto: untouched user has no row"614 "auto: untouched user has no row"
611 );615 );
612 616
613- // Scenario 3: subscribers lists only subscribed users of one issue.
614 let issue = s617 let issue = s
615 .create_issue(&fx.repo, &fx.owner, "Fourth", "")618 .create_issue(&fx.repo, &fx.owner, "Fourth", "")
616 .await619 .await
@@ -634,32 +637,13 @@ mod tests {
634 }637 }
635 638
636 #[tokio::test]639 #[tokio::test]
637- async fn inbox_rules_hold_in_each_scenario() {640+ async fn inbox_rules() {
638 let fx = fixture().await;641 let fx = fixture().await;
639 let s = &fx.store;642 let s = &fx.store;
640 643
641- // Scenario 1: a stronger reason wins while unread; a read row is replaced.
642 let ivy = user(s, "Ivy").await;644 let ivy = user(s, "Ivy").await;
643- s.upsert_notification(645+ notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Mention, "mentioned", Some(&fx.bob)).await;
644- &ivy,646+ notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&fx.bob)).await;
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();
663 assert_eq!(647 assert_eq!(
664 reason_of(s, &ivy, &fx.issue_a).await,648 reason_of(s, &ivy, &fx.issue_a).await,
665 Reason::Mention,649 Reason::Mention,
@@ -668,43 +652,16 @@ mod tests {
668 assert_eq!(s.unread_count(&ivy).await.unwrap(), 1, "upsert: one unread");652 assert_eq!(s.unread_count(&ivy).await.unwrap(), 1, "upsert: one unread");
669 653
670 s.mark_issue_read(&ivy, &fx.issue_a).await.unwrap();654 s.mark_issue_read(&ivy, &fx.issue_a).await.unwrap();
671- assert_eq!(655+ assert_eq!(s.unread_count(&ivy).await.unwrap(), 0, "upsert: marked read");
672- s.unread_count(&ivy).await.unwrap(),656+ notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&fx.bob)).await;
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();
686 assert_eq!(657 assert_eq!(
687 reason_of(s, &ivy, &fx.issue_a).await,658 reason_of(s, &ivy, &fx.issue_a).await,
688 Reason::Comment,659 Reason::Comment,
689 "upsert: read row replaced"660 "upsert: read row replaced"
690 );661 );
691- assert_eq!(662+ assert_eq!(s.unread_count(&ivy).await.unwrap(), 1, "upsert: unread again");
692- s.unread_count(&ivy).await.unwrap(),
693- 1,
694- "upsert: unread again"
695- );
696 663
697- // A stronger reason while unread still wins.664+ notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Assign, "assigned", None).await;
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();
708 let inbox = s.list_notifications(&ivy, false, None, 10).await.unwrap();665 let inbox = s.list_notifications(&ivy, false, None, 10).await.unwrap();
709 assert_eq!(inbox.len(), 1, "upsert: still one row");666 assert_eq!(inbox.len(), 1, "upsert: still one row");
710 assert_eq!(667 assert_eq!(
@@ -715,28 +672,9 @@ mod tests {
715 assert_eq!(inbox[0].last_activity, "assigned", "upsert: activity text");672 assert_eq!(inbox[0].last_activity, "assigned", "upsert: activity text");
716 assert_eq!(inbox[0].last_actor_name, None, "upsert: no actor given");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 let kim = user(s, "Kim").await;675 let kim = user(s, "Kim").await;
720- s.upsert_notification(676+ notify(s, &kim, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&fx.bob)).await;
721- &kim,677+ notify(s, &kim, &fx.repo, &fx.issue_b, Reason::Comment, "comment", Some(&fx.bob)).await;
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();
740 s.mark_issue_read(&kim, &fx.issue_b).await.unwrap();678 s.mark_issue_read(&kim, &fx.issue_b).await.unwrap();
741 679
742 let all = s.list_notifications(&kim, false, None, 50).await.unwrap();680 let all = s.list_notifications(&kim, false, None, 50).await.unwrap();
@@ -746,7 +684,7 @@ mod tests {
746 assert_eq!(all[0].repo_owner, "Owen", "list: repo owner");684 assert_eq!(all[0].repo_owner, "Owen", "list: repo owner");
747 assert_eq!(all[0].repo_name, "proj", "list: repo name");685 assert_eq!(all[0].repo_name, "proj", "list: repo name");
748 assert_eq!(all[0].number, 2, "list: issue number");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 assert!(!all[0].is_pull, "list: issue, not a pull request");688 assert!(!all[0].is_pull, "list: issue, not a pull request");
751 assert_eq!(689 assert_eq!(
752 all[0].last_actor_name.as_deref(),690 all[0].last_actor_name.as_deref(),
@@ -758,7 +696,6 @@ mod tests {
758 assert_eq!(unread.len(), 1, "list: unread filter");696 assert_eq!(unread.len(), 1, "list: unread filter");
759 assert_eq!(unread[0].issue_id, fx.issue_a, "list: unread row");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 let first = s.list_notifications(&kim, false, None, 1).await.unwrap();699 let first = s.list_notifications(&kim, false, None, 1).await.unwrap();
763 assert_eq!(first[0].issue_id, fx.issue_b, "cursor: first page");700 assert_eq!(first[0].issue_id, fx.issue_b, "cursor: first page");
764 let second = s701 let second = s
@@ -773,7 +710,6 @@ mod tests {
773 .unwrap();710 .unwrap();
774 assert!(none.is_empty(), "cursor: past the end");711 assert!(none.is_empty(), "cursor: past the end");
775 712
776- // Other users see nothing.
777 assert!(713 assert!(
778 s.list_notifications(&fx.bob, false, None, 50)714 s.list_notifications(&fx.bob, false, None, 50)
779 .await715 .await
@@ -782,42 +718,13 @@ mod tests {
782 "list: other user sees nothing"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 let ned = user(s, "Ned").await;721 let ned = user(s, "Ned").await;
787 let olive = user(s, "Olive").await;722 let olive = user(s, "Olive").await;
788- s.upsert_notification(723+ notify(s, &ned, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await;
789- &ned,724+ notify(s, &ned, &fx.repo, &fx.issue_b, Reason::Comment, "comment", None).await;
790- &fx.repo,725+ notify(s, &olive, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await;
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();
818 assert_eq!(s.unread_count(&ned).await.unwrap(), 2, "read: two unread");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 let inbox = s.list_notifications(&ned, false, None, 50).await.unwrap();728 let inbox = s.list_notifications(&ned, false, None, 50).await.unwrap();
822 let olive_inbox = s.list_notifications(&olive, false, None, 50).await.unwrap();729 let olive_inbox = s.list_notifications(&olive, false, None, 50).await.unwrap();
823 s.mark_read(&ned, &olive_inbox[0].id).await.unwrap();730 s.mark_read(&ned, &olive_inbox[0].id).await.unwrap();
@@ -831,17 +738,7 @@ mod tests {
831 s.mark_read(&ned, &inbox[1].id).await.unwrap();738 s.mark_read(&ned, &inbox[1].id).await.unwrap();
832 assert_eq!(s.unread_count(&ned).await.unwrap(), 0, "read: second by id");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.741+ notify(s, &ned, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await;
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();
845 s.mark_all_read(&ned, Some(&fx.repo)).await.unwrap();742 s.mark_all_read(&ned, Some(&fx.repo)).await.unwrap();
846 assert_eq!(s.unread_count(&ned).await.unwrap(), 0, "read: all in repo");743 assert_eq!(s.unread_count(&ned).await.unwrap(), 0, "read: all in repo");
847 assert_eq!(744 assert_eq!(
@@ -850,16 +747,7 @@ mod tests {
850 "read: other user kept"747 "read: other user kept"
851 );748 );
852 749
853- s.upsert_notification(750+ notify(s, &ned, &fx.repo, &fx.issue_b, Reason::Comment, "comment", None).await;
854- &ned,
855- &fx.repo,
856- &fx.issue_b,
857- Reason::Comment,
858- "comment",
859- None,
860- )
861- .await
862- .unwrap();
863 s.mark_all_read(&ned, None).await.unwrap();751 s.mark_all_read(&ned, None).await.unwrap();
864 assert_eq!(s.unread_count(&ned).await.unwrap(), 0, "read: all, no repo");752 assert_eq!(s.unread_count(&ned).await.unwrap(), 0, "read: all, no repo");
865 s.mark_all_read(&olive, Some("no-such-repo")).await.unwrap();753 s.mark_all_read(&olive, Some("no-such-repo")).await.unwrap();
@@ -869,28 +757,9 @@ mod tests {
869 "read: unknown repo"757 "read: unknown repo"
870 );758 );
871 759
872- // Scenario 4: mark_issue_read only touches that issue.
873 let max = user(s, "Max").await;760 let max = user(s, "Max").await;
874- s.upsert_notification(761+ notify(s, &max, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await;
875- &max,762+ notify(s, &max, &fx.repo, &fx.issue_b, Reason::Comment, "comment", None).await;
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();
894 s.mark_issue_read(&max, &fx.issue_a).await.unwrap();763 s.mark_issue_read(&max, &fx.issue_a).await.unwrap();
895 assert_eq!(764 assert_eq!(
896 s.unread_count(&max).await.unwrap(),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 #[tokio::test]776 #[tokio::test]
909- async fn delete_rules_hold_in_each_scenario() {777+ async fn delete_rules() {
910 let fx = fixture().await;778 let fx = fixture().await;
911 let s = &fx.store;779 let s = &fx.store;
912 780
913- // Scenario 1: deleting a repo removes its notification rows, subs and watches.
914 let pat = user(s, "Pat").await;781 let pat = user(s, "Pat").await;
915 let doomed = s782 let doomed = s
916 .create_repo(&fx.owner, "doomed", "", Visibility::Public, "main")783 .create_repo(&fx.owner, "doomed", "", Visibility::Public, "main")
@@ -928,16 +795,7 @@ mod tests {
928 s.subscribe(&pat, &doomed_issue, SubState::Subscribed, Reason::Author)795 s.subscribe(&pat, &doomed_issue, SubState::Subscribed, Reason::Author)
929 .await796 .await
930 .unwrap();797 .unwrap();
931- s.upsert_notification(798+ notify(s, &pat, &doomed, &doomed_issue, Reason::Comment, "comment", Some(&fx.bob)).await;
932- &pat,
933- &doomed,
934- &doomed_issue,
935- Reason::Comment,
936- "comment",
937- Some(&fx.bob),
938- )
939- .await
940- .unwrap();
941 799
942 s.delete_repo(&doomed).await.unwrap();800 s.delete_repo(&doomed).await.unwrap();
943 assert_eq!(801 assert_eq!(
@@ -976,7 +834,6 @@ mod tests {
976 "repo: nothing unread"834 "repo: nothing unread"
977 );835 );
978 836
979- // Scenario 2: deleting a user removes their rows and reassigns last actor to ghost.
980 let ghost = s.ensure_ghost_user().await.unwrap();837 let ghost = s.ensure_ghost_user().await.unwrap();
981 let quin = user(s, "Quin").await;838 let quin = user(s, "Quin").await;
982 let ray = user(s, "Ray").await;839 let ray = user(s, "Ray").await;
@@ -986,27 +843,8 @@ mod tests {
986 s.subscribe(&quin, &fx.issue_a, SubState::Subscribed, Reason::Author)843 s.subscribe(&quin, &fx.issue_a, SubState::Subscribed, Reason::Author)
987 .await844 .await
988 .unwrap();845 .unwrap();
989- // Ray's inbox row whose last actor is Quin, and Quin's own inbox row.846+ notify(s, &ray, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&quin)).await;
990- s.upsert_notification(847+ notify(s, &quin, &fx.repo, &fx.issue_b, Reason::Comment, "comment", Some(&fx.bob)).await;
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();
1010 848
1011 s.delete_user(&quin, &ghost.id).await.unwrap();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 // A link made again starts its grace period over: the sweep keeps a recent link (see33 // A link made again starts its grace period over: the sweep keeps a recent link (see
34 // `oci_sweep_unreferenced`), and the push that made it is still on its way to a manifest.34 // `oci_sweep_unreferenced`), and the push that made it is still on its way to a manifest.
35 conn.execute(35 conn.execute(
36- "DELETE FROM oci_blobs WHERE package_id = ?1 AND digest = ?2",36+ "INSERT INTO oci_blobs (package_id, digest, size, created_at) VALUES (?1, ?2, ?3, ?4) \
37- (package_id.to_string(), digest.to_string()),37+ ON CONFLICT(package_id, digest) DO UPDATE SET size = excluded.size, \
38- )38+ created_at = excluded.created_at",
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)",
43 (39 (
44 package_id.to_string(),40 package_id.to_string(),
45 digest.to_string(),41 digest.to_string(),
@@ -163,15 +159,10 @@ impl Store {
163 /// Points `tag` of `package_id` at `manifest_id`, replacing any earlier target.159 /// Points `tag` of `package_id` at `manifest_id`, replacing any earlier target.
164 pub async fn oci_set_tag(&self, package_id: &str, tag: &str, manifest_id: &str) -> Result<()> {160 pub async fn oci_set_tag(&self, package_id: &str, tag: &str, manifest_id: &str) -> Result<()> {
165 let conn = self.inner.conn.lock().await;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 conn.execute(162 conn.execute(
173 "INSERT INTO oci_tags (package_id, tag, manifest_id, updated_at) \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 package_id.to_string(),167 package_id.to_string(),
177 tag.to_string(),168 tag.to_string(),
crates/forge-core/src/store/orgs.rsmodified+1 -14
@@ -7,7 +7,7 @@
7 7
8 use turso::{Connection, IntoParams};8 use turso::{Connection, IntoParams};
9 9
10-use super::issues::finish;10+use super::finish;
11 use super::{11 use super::{
12 REPO_COLS, Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, insert_err,12 REPO_COLS, Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, insert_err,
13 map_repo, map_user, missing_row, new_id, parse_role, role_str,13 map_repo, map_user, missing_row, new_id, parse_role, role_str,
@@ -1117,17 +1117,4 @@ mod tests {
1117 store.delete_org(&cyberdyne.id).await.unwrap();1117 store.delete_org(&cyberdyne.id).await.unwrap();
1118 assert_eq!(store.orgs_for_user(&quinn.id).await.unwrap().len(), 1);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 //! string; the web crate owns the format. Sign counts live inside that string, so an update2 //! string; the web crate owns the format. Sign counts live inside that string, so an update
3 //! replaces it.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 use crate::error::{Error, Result};8 use crate::error::{Error, Result};
7 use crate::time::now_stamp;9 use crate::time::now_stamp;
8 10
@@ -27,6 +29,17 @@ pub struct PasskeyRow {
27 29
28 const COLS: &str = "id, user_id, credential_id, passkey, name, created_at, last_used_at";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 fn map_row(row: &turso::Row) -> Result<PasskeyRow> {43 fn map_row(row: &turso::Row) -> Result<PasskeyRow> {
31 Ok(PasskeyRow {44 Ok(PasskeyRow {
32 id: col_text(row, 0)?,45 id: col_text(row, 0)?,
@@ -68,14 +81,7 @@ impl Store {
68 81
69 pub async fn passkey_count(&self, user_id: &str) -> Result<i64> {82 pub async fn passkey_count(&self, user_id: &str) -> Result<i64> {
70 let conn = self.read_conn().await;83 let conn = self.read_conn().await;
71- Ok(fetch_opt(84+ count_passkeys(&conn, user_id).await
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))
79 }85 }
80 86
81 /// The passkey with this credential id, whoever owns it.87 /// The passkey with this credential id, whoever owns it.
@@ -100,29 +106,12 @@ impl Store {
100 ) -> Result<PasskeyRow> {106 ) -> Result<PasskeyRow> {
101 let name = clean_name(name)?;107 let name = clean_name(name)?;
102 let conn = self.inner.conn.lock().await;108 let conn = self.inner.conn.lock().await;
103- let held = fetch_opt(109+ let held = count_passkeys(&conn, user_id).await?;
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);
111 if usize::try_from(held).unwrap_or(usize::MAX) >= MAX_PASSKEYS {110 if usize::try_from(held).unwrap_or(usize::MAX) >= MAX_PASSKEYS {
112 return Err(Error::Invalid(format!(111 return Err(Error::Invalid(format!(
113 "an account can hold at most {MAX_PASSKEYS} passkeys"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 let row = PasskeyRow {115 let row = PasskeyRow {
127 id: new_id(),116 id: new_id(),
128 user_id: user_id.to_string(),117 user_id: user_id.to_string(),
@@ -145,7 +134,7 @@ impl Store {
145 ),134 ),
146 )135 )
147 .await136 .await
148- .map_err(db_err)?;137+ .map_err(|e| insert_err(e, "this passkey is already registered"))?;
149 Ok(row)138 Ok(row)
150 }139 }
151 140
crates/forge-core/src/store/pulls.rsmodified+27 -127
@@ -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 use turso::transaction::Transaction;1 use turso::transaction::Transaction;
6 use turso::{Connection, Row};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 use super::{5 use super::{
6+ finish,
10 REPO_COLS, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err,7 REPO_COLS, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err,
11 map_repo, new_id,8 map_repo, new_id,
12 };9 };
13 use crate::error::{Error, Result};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 use crate::model::{Id, Repo};12 use crate::model::{Id, Repo};
16 use crate::pulls::{AutoMerge, MergeStyle, Mergeable, PullRequest};13 use crate::pulls::{AutoMerge, MergeStyle, Mergeable, PullRequest};
17 use crate::time::now_stamp;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 const PULL_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, i.state, i.state_reason, \16 const PULL_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, i.state, i.state_reason, \
21 i.author_id, i.milestone_id, i.comment_count, i.created_at, i.updated_at, \17 i.author_id, i.milestone_id, i.comment_count, i.created_at, i.updated_at, \
22 i.closed_at, i.locked, i.lock_reason, p.base_branch, p.head_repo_id, p.head_branch, p.head_oid, \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 const MERGED_MSG: &str = "pull request is already merged";22 const MERGED_MSG: &str = "pull request is already merged";
27 23
28-/// Reads `PULL_COLS`.
29 fn map_pull(row: &Row) -> Result<PullRequest> {24 fn map_pull(row: &Row) -> Result<PullRequest> {
30 let conflicts_raw = col_text(row, 22)?;25 let conflicts_raw = col_text(row, 22)?;
31 let conflict_files: Vec<String> = serde_json::from_str(&conflicts_raw)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 async fn load_pull(conn: &Connection, issue_id: &str) -> Result<PullRequest> {52 async fn load_pull(conn: &Connection, issue_id: &str) -> Result<PullRequest> {
59 fetch_opt(53 fetch_opt(
60 conn,54 conn,
@@ -69,9 +63,16 @@ async fn load_pull(conn: &Connection, issue_id: &str) -> Result<PullRequest> {
69 .ok_or(Error::NotFound)63 .ok_or(Error::NotFound)
70 }64 }
71 65
72-/// Repo deletion for pull requests. Called from `Store::delete_repo` inside its transaction,66+fn ensure_open(pull: &PullRequest) -> Result<()> {
73-/// before the issue rows go. Pull request rows whose head was this repo keep their row, with67+ if pull.merged_at.is_some() {
74-/// `head_repo_id` set to NULL.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 pub(super) async fn delete_repo_pull_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {76 pub(super) async fn delete_repo_pull_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {
76 let id = repo_id.to_string();77 let id = repo_id.to_string();
77 tx.execute(78 tx.execute(
@@ -89,11 +90,7 @@ pub(super) async fn delete_repo_pull_rows(tx: &Transaction<'_>, repo_id: &str) -
89 Ok(())90 Ok(())
90 }91 }
91 92
92-// pull requests
93 impl Store {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 #[allow(clippy::too_many_arguments)]94 #[allow(clippy::too_many_arguments)]
98 pub async fn create_pull(95 pub async fn create_pull(
99 &self,96 &self,
@@ -112,7 +109,6 @@ impl Store {
112 let conn = self.inner.conn.lock().await;109 let conn = self.inner.conn.lock().await;
113 let tx = conn.unchecked_transaction().await.map_err(db_err)?;110 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
114 let outcome: Result<PullRequest> = async {111 let outcome: Result<PullRequest> = async {
115- // Checked here, inside the transaction, so two requests cannot both open the pull.
116 if let Some(number) =112 if let Some(number) =
117 open_pull_number(&tx, repo_id, base_branch, head_repo_id, head_branch).await?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 .await163 .await
168 .map_err(db_err)?;164 .map_err(db_err)?;
169- Ok(PullRequest {165+ load_pull(&tx, &id).await
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- })
201 }166 }
202 .await;167 .await;
203 finish(tx, outcome).await168 finish(tx, outcome).await
204 }169 }
205 170
206- /// The pull request with this number in the repo, if any.
207 pub async fn pull_by_number(&self, repo_id: &str, number: i64) -> Result<Option<PullRequest>> {171 pub async fn pull_by_number(&self, repo_id: &str, number: i64) -> Result<Option<PullRequest>> {
208 let conn = self.read_conn().await;172 let conn = self.read_conn().await;
209 fetch_opt(173 fetch_opt(
@@ -218,7 +182,6 @@ impl Store {
218 .await182 .await
219 }183 }
220 184
221- /// One page of pull requests, filtered and sorted like `list_issues`, plus the total.
222 pub async fn list_pulls(185 pub async fn list_pulls(
223 &self,186 &self,
224 repo_id: &str,187 repo_id: &str,
@@ -227,13 +190,10 @@ impl Store {
227 self.list_of_kind(repo_id, f, "pull").await190 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 pub async fn pull_counts(&self, repo_id: &str) -> Result<(u64, u64)> {193 pub async fn pull_counts(&self, repo_id: &str) -> Result<(u64, u64)> {
232 self.counts_of_kind(repo_id, "pull").await194 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 pub async fn open_pulls_for_head(197 pub async fn open_pulls_for_head(
238 &self,198 &self,
239 head_repo_id: &str,199 head_repo_id: &str,
@@ -252,7 +212,6 @@ impl Store {
252 .await212 .await
253 }213 }
254 214
255- /// Open pull requests into this branch of this repo, as `(number, issue id)`.
256 pub async fn open_pulls_for_base(215 pub async fn open_pulls_for_base(
257 &self,216 &self,
258 repo_id: &str,217 repo_id: &str,
@@ -270,8 +229,6 @@ impl Store {
270 .await229 .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 pub async fn pull_refs(&self, repo_id: &str) -> Result<Vec<(Id, i64)>> {232 pub async fn pull_refs(&self, repo_id: &str) -> Result<Vec<(Id, i64)>> {
276 let conn = self.read_conn().await;233 let conn = self.read_conn().await;
277 fetch_all(234 fetch_all(
@@ -284,7 +241,6 @@ impl Store {
284 .await241 .await
285 }242 }
286 243
287- /// The pull requests of a repo whose head is `sha`, open or closed, as `(issue id, number)`.
288 pub async fn pulls_for_head_oid(&self, repo_id: &str, sha: &str) -> Result<Vec<(Id, i64)>> {244 pub async fn pulls_for_head_oid(&self, repo_id: &str, sha: &str) -> Result<Vec<(Id, i64)>> {
289 let conn = self.read_conn().await;245 let conn = self.read_conn().await;
290 fetch_all(246 fetch_all(
@@ -298,27 +254,32 @@ impl Store {
298 .await254 .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 pub async fn update_pull_head(&self, issue_id: &str, head_oid: &str) -> Result<()> {257 pub async fn update_pull_head(&self, issue_id: &str, head_oid: &str) -> Result<()> {
304 let conn = self.inner.conn.lock().await;258 let conn = self.inner.conn.lock().await;
305 let changed = conn259 let changed = conn
306 .execute(260 .execute(
307 "UPDATE pull_requests SET head_oid = ?2, merge_base = NULL, mergeable = 'unknown', \261 "UPDATE pull_requests SET head_oid = ?2, merge_base = NULL, mergeable = 'unknown', \
308 conflict_files = '[]', auto_merge_style = NULL, auto_merge_user = NULL \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 (issue_id.to_string(), head_oid.to_string()),264 (issue_id.to_string(), head_oid.to_string()),
311 )265 )
312 .await266 .await
313 .map_err(db_err)?;267 .map_err(db_err)?;
314 if changed == 0 {268 if changed == 0 {
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() {
315 return Err(Error::NotFound);277 return Err(Error::NotFound);
316 }278 }
279+ }
317 Ok(())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 pub async fn set_mergeability(283 pub async fn set_mergeability(
323 &self,284 &self,
324 issue_id: &str,285 issue_id: &str,
@@ -348,7 +309,6 @@ impl Store {
348 .await309 .await
349 .map_err(db_err)?;310 .map_err(db_err)?;
350 if changed == 0 {311 if changed == 0 {
351- // Either the pull request is missing, or it is already merged and therefore final.
352 let exists = fetch_opt(312 let exists = fetch_opt(
353 &conn,313 &conn,
354 "SELECT merged_at FROM pull_requests WHERE issue_id = ?1 LIMIT 1",314 "SELECT merged_at FROM pull_requests WHERE issue_id = ?1 LIMIT 1",
@@ -363,9 +323,6 @@ impl Store {
363 Ok(())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 pub async fn set_pull_draft(326 pub async fn set_pull_draft(
370 &self,327 &self,
371 issue_id: &str,328 issue_id: &str,
@@ -376,12 +333,7 @@ impl Store {
376 let tx = conn.unchecked_transaction().await.map_err(db_err)?;333 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
377 let outcome: Result<bool> = async {334 let outcome: Result<bool> = async {
378 let current = load_pull(&tx, issue_id).await?;335 let current = load_pull(&tx, issue_id).await?;
379- if current.merged_at.is_some() {336+ ensure_open(&current)?;
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- }
385 if current.draft == draft {337 if current.draft == draft {
386 return Ok(false);338 return Ok(false);
387 }339 }
@@ -405,8 +357,6 @@ impl Store {
405 finish(tx, outcome).await357 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 pub async fn enable_auto_merge(360 pub async fn enable_auto_merge(
411 &self,361 &self,
412 issue_id: &str,362 issue_id: &str,
@@ -417,12 +367,7 @@ impl Store {
417 let tx = conn.unchecked_transaction().await.map_err(db_err)?;367 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
418 let outcome: Result<()> = async {368 let outcome: Result<()> = async {
419 let current = load_pull(&tx, issue_id).await?;369 let current = load_pull(&tx, issue_id).await?;
420- if current.merged_at.is_some() {370+ ensure_open(&current)?;
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- }
426 tx.execute(371 tx.execute(
427 "UPDATE pull_requests SET auto_merge_style = ?2, auto_merge_user = ?3 \372 "UPDATE pull_requests SET auto_merge_style = ?2, auto_merge_user = ?3 \
428 WHERE issue_id = ?1",373 WHERE issue_id = ?1",
@@ -442,8 +387,6 @@ impl Store {
442 finish(tx, outcome).await387 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 pub async fn disable_auto_merge(390 pub async fn disable_auto_merge(
448 &self,391 &self,
449 issue_id: &str,392 issue_id: &str,
@@ -472,7 +415,6 @@ impl Store {
472 finish(tx, outcome).await415 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 pub async fn auto_merge_pulls_for_head(418 pub async fn auto_merge_pulls_for_head(
477 &self,419 &self,
478 repo_id: &str,420 repo_id: &str,
@@ -492,9 +434,6 @@ impl Store {
492 .await434 .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 pub async fn mark_merged(437 pub async fn mark_merged(
499 &self,438 &self,
500 issue_id: &str,439 issue_id: &str,
@@ -505,12 +444,7 @@ impl Store {
505 let tx = conn.unchecked_transaction().await.map_err(db_err)?;444 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
506 let outcome: Result<()> = async {445 let outcome: Result<()> = async {
507 let current = load_pull(&tx, issue_id).await?;446 let current = load_pull(&tx, issue_id).await?;
508- if current.merged_at.is_some() {447+ ensure_open(&current)?;
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- }
514 let now = now_stamp();448 let now = now_stamp();
515 tx.execute(449 tx.execute(
516 "UPDATE issues SET state = 'closed', state_reason = 'completed', closed_at = ?2, \450 "UPDATE issues SET state = 'closed', state_reason = 'completed', closed_at = ?2, \
@@ -540,8 +474,6 @@ impl Store {
540 finish(tx, outcome).await474 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 pub async fn find_open_pull(477 pub async fn find_open_pull(
546 &self,478 &self,
547 base_repo: &str,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 async fn open_pull_number(489 async fn open_pull_number(
560 conn: &Connection,490 conn: &Connection,
561 base_repo: &str,491 base_repo: &str,
@@ -579,11 +509,7 @@ async fn open_pull_number(
579 .await509 .await
580 }510 }
581 511
582-// forks
583 impl Store {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 pub async fn create_fork(&self, source: &Repo, owner_id: &str, name: &str) -> Result<Repo> {513 pub async fn create_fork(&self, source: &Repo, owner_id: &str, name: &str) -> Result<Repo> {
588 self.insert_repo(514 self.insert_repo(
589 owner_id,515 owner_id,
@@ -596,7 +522,6 @@ impl Store {
596 .await522 .await
597 }523 }
598 524
599- /// Repos forked from `repo_id`, by name.
600 pub async fn list_forks(&self, repo_id: &str) -> Result<Vec<Repo>> {525 pub async fn list_forks(&self, repo_id: &str) -> Result<Vec<Repo>> {
601 let conn = self.read_conn().await;526 let conn = self.read_conn().await;
602 fetch_all(527 fetch_all(
@@ -611,7 +536,6 @@ impl Store {
611 .await536 .await
612 }537 }
613 538
614- /// How many public forks the repo has (the count of `list_forks` filtered to public).
615 pub async fn public_fork_count(&self, repo_id: &str) -> Result<u64> {539 pub async fn public_fork_count(&self, repo_id: &str) -> Result<u64> {
616 let conn = self.read_conn().await;540 let conn = self.read_conn().await;
617 let n = fetch_opt(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 async fn new_repo(fx: &Fixture, name: &str) -> Repo {589 async fn new_repo(fx: &Fixture, name: &str) -> Repo {
667 fx.store590 fx.store
668 .create_repo(&fx.tahinli.id, name, "", Visibility::Public, "main")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 async fn open_pull(604 async fn open_pull(
683 fx: &Fixture,605 fx: &Fixture,
684 repo: &Repo,606 repo: &Repo,
@@ -702,13 +624,10 @@ mod tests {
702 .unwrap()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 #[tokio::test]627 #[tokio::test]
708 async fn pull_scenarios_share_one_store() {628 async fn pull_scenarios_share_one_store() {
709 let fx = fixture().await;629 let fx = fixture().await;
710 630
711- // Issues and pulls share one numbering; each list shows only its kind.
712 let repo = new_repo(&fx, "numbering").await;631 let repo = new_repo(&fx, "numbering").await;
713 let issue1 = fx632 let issue1 = fx
714 .store633 .store
@@ -765,7 +684,6 @@ mod tests {
765 "numbering: pull reads back"684 "numbering: pull reads back"
766 );685 );
767 686
768- // Counts: a merged pull counts as closed; issue counts are untouched.
769 let repo = new_repo(&fx, "counts").await;687 let repo = new_repo(&fx, "counts").await;
770 fx.store688 fx.store
771 .create_issue(&repo.id, &fx.tahinli.id, "issue", "")689 .create_issue(&repo.id, &fx.tahinli.id, "issue", "")
@@ -804,7 +722,6 @@ mod tests {
804 assert_eq!(total, 1, "counts: open filter total");722 assert_eq!(total, 1, "counts: open filter total");
805 assert_eq!(open[0].issue.title, "pull two", "counts: open filter row");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 let repo = new_repo(&fx, "head").await;725 let repo = new_repo(&fx, "head").await;
809 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;726 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;
810 let id = pull.issue.id.clone();727 let id = pull.issue.id.clone();
@@ -832,7 +749,6 @@ mod tests {
832 assert!(after.conflict_files.is_empty(), "head: conflicts cleared");749 assert!(after.conflict_files.is_empty(), "head: conflicts cleared");
833 assert_eq!(after.base_oid, "b".repeat(40), "head: base untouched");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 let repo = new_repo(&fx, "mergeability").await;752 let repo = new_repo(&fx, "mergeability").await;
837 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;753 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;
838 let id = pull.issue.id.clone();754 let id = pull.issue.id.clone();
@@ -896,7 +812,6 @@ mod tests {
896 "mergeability: missing pull"812 "mergeability: missing pull"
897 );813 );
898 814
899- // Merging closes the pull, records an event, and is final.
900 let repo = new_repo(&fx, "merge").await;815 let repo = new_repo(&fx, "merge").await;
901 let issue = fx816 let issue = fx
902 .store817 .store
@@ -961,7 +876,6 @@ mod tests {
961 "merge: event actor"876 "merge: event actor"
962 );877 );
963 878
964- // A second merge is refused, and a late mergeability recompute is a no-op.
965 assert!(879 assert!(
966 matches!(880 matches!(
967 fx.store.mark_merged(&id, &fx.bob.id, &merge_commit).await,881 fx.store.mark_merged(&id, &fx.bob.id, &merge_commit).await,
@@ -981,7 +895,6 @@ mod tests {
981 .unwrap();895 .unwrap();
982 assert_eq!(still.mergeable, Mergeable::Merged, "merge: stays merged");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 let repo = new_repo(&fx, "refuse").await;898 let repo = new_repo(&fx, "refuse").await;
986 let first = open_pull(&fx, &repo, &repo.id, "feature", "first").await;899 let first = open_pull(&fx, &repo, &repo.id, "feature", "first").await;
987 let second = fx900 let second = fx
@@ -1012,7 +925,6 @@ mod tests {
1012 "refuse: no number taken"925 "refuse: no number taken"
1013 );926 );
1014 927
1015- // find_open_pull matches base and head, and a merged pull stops matching.
1016 let repo = new_repo(&fx, "find").await;928 let repo = new_repo(&fx, "find").await;
1017 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;929 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;
1018 let found = fx930 let found = fx
@@ -1051,7 +963,6 @@ mod tests {
1051 "find: merged pull no longer blocks"963 "find: merged pull no longer blocks"
1052 );964 );
1053 965
1054- // Draft flag: round trip, events, list filter and draft numbers.
1055 let repo = new_repo(&fx, "draft").await;966 let repo = new_repo(&fx, "draft").await;
1056 let pr = open_pull(&fx, &repo, &repo.id, "feature", "wip").await;967 let pr = open_pull(&fx, &repo, &repo.id, "feature", "wip").await;
1057 let _ready = open_pull(&fx, &repo, &repo.id, "other", "ready").await;968 let _ready = open_pull(&fx, &repo, &repo.id, "other", "ready").await;
@@ -1064,7 +975,6 @@ mod tests {
1064 .unwrap(),975 .unwrap(),
1065 "draft: set changes the flag"976 "draft: set changes the flag"
1066 );977 );
1067- // Setting the same value again changes nothing and records no event.
1068 assert!(978 assert!(
1069 !fx.store979 !fx.store
1070 .set_pull_draft(&pr.issue.id, Some(&fx.tahinli.id), true)980 .set_pull_draft(&pr.issue.id, Some(&fx.tahinli.id), true)
@@ -1132,7 +1042,6 @@ mod tests {
1132 "draft: events"1042 "draft: events"
1133 );1043 );
1134 1044
1135- // Auto merge is cleared by a new head, a draft, or a merge.
1136 let repo = new_repo(&fx, "auto").await;1045 let repo = new_repo(&fx, "auto").await;
1137 let pr = open_pull(&fx, &repo, &repo.id, "feature", "auto").await;1046 let pr = open_pull(&fx, &repo, &repo.id, "feature", "auto").await;
1138 let head = "a".repeat(40);1047 let head = "a".repeat(40);
@@ -1233,7 +1142,6 @@ mod tests {
1233 "auto: merged pull refuses auto merge"1142 "auto: merged pull refuses auto merge"
1234 );1143 );
1235 1144
1236- // Pull event kinds are accepted on pulls.
1237 let repo = new_repo(&fx, "events").await;1145 let repo = new_repo(&fx, "events").await;
1238 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;1146 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;
1239 for kind in ["head_updated", "base_changed", "head_deleted"] {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 #[tokio::test]1168 #[tokio::test]
1263 async fn fork_scenarios_share_one_store() {1169 async fn fork_scenarios_share_one_store() {
1264 let fx = fixture().await;1170 let fx = fixture().await;
1265 1171
1266- // A fork copies the source settings and lists under its source.
1267 let fork = fx1172 let fork = fx
1268 .store1173 .store
1269 .create_fork(&fx.repo, &fx.bob.id, "proj-1")1174 .create_fork(&fx.repo, &fx.bob.id, "proj-1")
@@ -1286,7 +1191,6 @@ mod tests {
1286 );1191 );
1287 assert_eq!(fx.repo.fork_of, None, "fork: source is not a fork");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 let read = fx.store.repo_by_id(&fork.id).await.unwrap().unwrap();1194 let read = fx.store.repo_by_id(&fork.id).await.unwrap().unwrap();
1291 assert_eq!(read.fork_of, Some(fx.repo.id.clone()), "fork: read by id");1195 assert_eq!(read.fork_of, Some(fx.repo.id.clone()), "fork: read by id");
1292 let read = fx1196 let read = fx
@@ -1319,7 +1223,6 @@ mod tests {
1319 "fork: name clash is a conflict"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 let private = fx1226 let private = fx
1324 .store1227 .store
1325 .create_repo(&fx.tahinli.id, "secret", "", Visibility::Private, "trunk")1228 .create_repo(&fx.tahinli.id, "secret", "", Visibility::Private, "trunk")
@@ -1337,7 +1240,6 @@ mod tests {
1337 );1240 );
1338 assert_eq!(secret_fork.default_branch, "trunk", "private fork: branch");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 let source = new_repo(&fx, "fork-src").await;1243 let source = new_repo(&fx, "fork-src").await;
1342 let fork = fx1244 let fork = fx
1343 .store1245 .store
@@ -1399,8 +1301,6 @@ mod tests {
1399 "bases: fork pull remains"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 let source = new_repo(&fx, "detach-src").await;1304 let source = new_repo(&fx, "detach-src").await;
1405 let fork = fx1305 let fork = fx
1406 .store1306 .store
crates/forge-core/src/store/pulls_list_extra.rsmodified+11 -18
@@ -10,40 +10,33 @@ use crate::error::Result;
10 impl Store {10 impl Store {
11 /// Which of `numbers` are draft pull requests of this repo.11 /// Which of `numbers` are draft pull requests of this repo.
12 pub async fn draft_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> {12 pub async fn draft_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> {
13- if numbers.is_empty() {13+ self.pull_numbers_where(repo_id, numbers, "p.draft = 1").await
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())
28 }14 }
29 15
30 /// Which of `numbers` are merged pull requests of this repo. Numbers that are issues, open16 /// Which of `numbers` are merged pull requests of this repo. Numbers that are issues, open
31 /// or closed without a merge are left out.17 /// or closed without a merge are left out.
32 pub async fn merged_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> {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 if numbers.is_empty() {28 if numbers.is_empty() {
34 return Ok(HashSet::new());29 return Ok(HashSet::new());
35 }30 }
36 let placeholders: Vec<String> = (2..=numbers.len() + 1).map(|i| format!("?{i}")).collect();31 let placeholders: Vec<String> = (2..=numbers.len() + 1).map(|i| format!("?{i}")).collect();
37 let sql = format!(32 let sql = format!(
38 "SELECT i.number FROM pull_requests p JOIN issues i ON i.id = p.issue_id \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 \34+ WHERE i.repo_id = ?1 AND i.kind = 'pull' AND {predicate} AND i.number IN ({})",
40- AND i.number IN ({})",
41 placeholders.join(", ")35 placeholders.join(", ")
42 );36 );
43 let mut params: Vec<Value> = Vec::with_capacity(numbers.len() + 1);37 let mut params: Vec<Value> = Vec::with_capacity(numbers.len() + 1);
44 params.push(Value::Text(repo_id.to_string()));38 params.push(Value::Text(repo_id.to_string()));
45 params.extend(numbers.iter().map(|n| Value::Integer(*n)));39 params.extend(numbers.iter().map(|n| Value::Integer(*n)));
46-
47 let conn = self.read_conn().await;40 let conn = self.read_conn().await;
48 let found = fetch_all(&conn, &sql, params, |row| col_int(row, 0)).await?;41 let found = fetch_all(&conn, &sql, params, |row| col_int(row, 0)).await?;
49 Ok(found.into_iter().collect())42 Ok(found.into_iter().collect())
crates/forge-core/src/store/push_recent.rsmodified+6 -6
@@ -89,7 +89,7 @@ impl Store {
89 #[cfg(test)]89 #[cfg(test)]
90 mod tests {90 mod tests {
91 use crate::model::Visibility;91 use crate::model::Visibility;
92- use crate::time::{stamp_after, stamp_before};92+ use crate::time::{stamp_after, stamp_ago};
93 use std::time::Duration;93 use std::time::Duration;
94 94
95 use super::*;95 use super::*;
@@ -121,9 +121,9 @@ mod tests {
121 #[tokio::test]121 #[tokio::test]
122 async fn recent_branch_pushes_rules_and_empty_inputs() {122 async fn recent_branch_pushes_rules_and_empty_inputs() {
123 let (_dir, store, tahinli, bob, demo, other) = store_with_repos().await;123 let (_dir, store, tahinli, bob, demo, other) = store_with_repos().await;
124- let since = stamp_before(Duration::from_secs(3600));124+ let since = stamp_ago(Duration::from_secs(3600));
125- let older = stamp_before(Duration::from_secs(600));125+ let older = stamp_ago(Duration::from_secs(600));
126- let newer = stamp_before(Duration::from_secs(60));126+ let newer = stamp_ago(Duration::from_secs(60));
127 127
128 store128 store
129 .record_push_event_at(&demo, &tahinli, "refs/heads/feature", ZERO, OID, &older)129 .record_push_event_at(&demo, &tahinli, "refs/heads/feature", ZERO, OID, &older)
@@ -155,7 +155,7 @@ mod tests {
155 "refs/heads/stale",155 "refs/heads/stale",
156 ZERO,156 ZERO,
157 OID,157 OID,
158- &stamp_before(Duration::from_secs(7200)),158+ &stamp_ago(Duration::from_secs(7200)),
159 )159 )
160 .await160 .await
161 .unwrap();161 .unwrap();
@@ -181,7 +181,7 @@ mod tests {
181 .await181 .await
182 .unwrap();182 .unwrap();
183 let none = store183 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 .await185 .await
186 .unwrap();186 .unwrap();
187 assert!(none.is_empty(), "empty repo list");187 assert!(none.is_empty(), "empty repo list");
crates/forge-core/src/store/reactions.rsmodified+3 -7
@@ -4,17 +4,13 @@
4 4
5 use std::collections::{BTreeMap, HashMap};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 use crate::error::{Error, Result};10 use crate::error::{Error, Result};
9 use crate::reactions::{Reaction, ReactionMap, ReactionSummary, ReactionTarget, SUMMARY_USERS};11 use crate::reactions::{Reaction, ReactionMap, ReactionSummary, ReactionTarget, SUMMARY_USERS};
10 use crate::time::now_stamp;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 impl Store {14 impl Store {
19 /// Adds the reaction when the user has not put it on the target yet, removes it when they have.15 /// Adds the reaction when the user has not put it on the target yet, removes it when they have.
20 /// Returns whether it is on afterwards. A target that does not exist is `NotFound`.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 //! user's repos, a user's stars). Read access is decided in the query with the same rules as2 //! user's repos, a user's stars). Read access is decided in the query with the same rules as
3 //! `authz::authorize` for `Action::Read`, so no per-repo role lookup is needed.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 use super::{7 use super::{
8 ListedRepo, REPO_COLS, RepoSort, Store, col_int, col_text, fetch_all, fetch_opt, issues,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 /// The star count of `r`.26 /// The star count of `r`.
27 const STARS: &str = "(SELECT COUNT(*) FROM stars s WHERE s.repo_id = r.id)";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 the29+/// The SQL condition under which a signed-in, non-admin viewer may read a private repo `r`, taking
30-/// viewer id four times (bind it as four `?` parameters). It mirrors `authorize` for Read:30+/// the 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 an31+/// the viewer's own repos, repos where the viewer is a collaborator, and repos of an org where the
32-/// org where the viewer's org role (`Store::org_repo_role`) is some role: an org owner, a member32+/// viewer's org role (`Store::org_repo_role`) is some role: an org owner, a member when the default
33-/// when the default repo role is not `none`, or a member of a team covering the repo.33+/// repo role is not `none`, or a member of a team covering the repo. Public repos are added by
34-pub(crate) const READABLE_BY_VIEWER: &str = "(r.visibility = 'public' OR r.owner_id = ? \34+/// the callers.
35+pub(crate) const VIEWER_ACCESS: &str = "(r.owner_id = ? \
35 OR EXISTS (SELECT 1 FROM collaborators c WHERE c.repo_id = r.id AND c.user_id = ?) \36 OR EXISTS (SELECT 1 FROM collaborators c WHERE c.repo_id = r.id AND c.user_id = ?) \
36 OR EXISTS (SELECT 1 FROM org_members m WHERE m.org_id = r.owner_id AND m.user_id = ? AND ( \37 OR EXISTS (SELECT 1 FROM org_members m WHERE m.org_id = r.owner_id AND m.user_id = ? AND ( \
37 m.role = 'owner' \38 m.role = 'owner' \
@@ -58,7 +59,7 @@ impl Store {
58 ) -> Result<(Vec<ListedRepo>, u64)> {59 ) -> Result<(Vec<ListedRepo>, u64)> {
59 let (from_sql, mut clauses, mut params) = scoped(scope, viewer);60 let (from_sql, mut clauses, mut params) = scoped(scope, viewer);
60 if let Some(q) = query.map(str::trim).filter(|q| !q.is_empty()) {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 params.push(Value::Text(issues::like_pattern(&q.to_lowercase())));63 params.push(Value::Text(issues::like_pattern(&q.to_lowercase())));
63 }64 }
64 self.page_of_repos(65 self.page_of_repos(
@@ -80,37 +81,23 @@ impl Store {
80 ) -> Result<u64> {81 ) -> Result<u64> {
81 let (from_sql, clauses, params) = scoped(scope, viewer);82 let (from_sql, clauses, params) = scoped(scope, viewer);
82 let conn = self.read_conn().await;83 let conn = self.read_conn().await;
83- let n = fetch_opt(84+ count_repos(&conn, from_sql, &clauses.join(" AND "), params).await
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))
95 }85 }
96 86
97 /// Up to `limit` repos the signed-in `viewer` is part of: their own, ones they collaborate on, and87 /// Up to `limit` repos the signed-in `viewer` is part of: their own, ones they collaborate on, and
98 /// org repos they reach. Sorted by owner and name, for the command palette. Other public repos are88 /// org repos they reach. Sorted by owner and name, for the command palette. Other public repos are
99 /// left out (Explore lists them), and so are an admin's: on a big instance they would push the89 /// 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 pub async fn list_viewer_repos(&self, viewer: &User, limit: u64) -> Result<Vec<Repo>> {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);92+ let mut params: Vec<Value> = (0..4).map(|_| Value::Text(viewer.id.clone())).collect();
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();
105 let limit = i64::try_from(limit).unwrap_or(i64::MAX);93 let limit = i64::try_from(limit).unwrap_or(i64::MAX);
106- let mut params = params;
107 params.push(Value::Integer(limit));94 params.push(Value::Integer(limit));
108 let conn = self.read_conn().await;95 let conn = self.read_conn().await;
109 fetch_all(96 fetch_all(
110 &conn,97 &conn,
111 &format!(98 &format!(
112 "SELECT {REPO_COLS} FROM repos r JOIN users u ON u.id = r.owner_id \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 params,102 params,
116 map_repo,103 map_repo,
@@ -138,15 +125,7 @@ impl Store {
138 let per_page = per_page.clamp(1, 100);125 let per_page = per_page.clamp(1, 100);
139 126
140 let conn = self.read_conn().await;127 let conn = self.read_conn().await;
141- let total = fetch_opt(128+ let total = count_repos(&conn, from_sql, where_sql, params.clone()).await?;
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);
150 let pages = total.div_ceil(per_page).max(1);129 let pages = total.div_ceil(per_page).max(1);
151 let page = page.clamp(1, pages);130 let page = page.clamp(1, pages);
152 let offset = i64::try_from((page - 1) * per_page).unwrap_or(i64::MAX);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 /// The FROM clause, the WHERE clauses and their parameters for `scope` as seen by `viewer`.170 /// The FROM clause, the WHERE clauses and their parameters for `scope` as seen by `viewer`.
175-fn scoped(171+fn scoped(scope: RepoScope<'_>, viewer: Option<&User>) -> (&'static str, Vec<String>, Vec<Value>) {
176- scope: RepoScope<'_>,
177- viewer: Option<&User>,
178-) -> (&'static str, Vec<&'static str>, Vec<Value>) {
179 let (from_sql, scope_id) = match scope {172 let (from_sql, scope_id) = match scope {
180 RepoScope::OwnedBy(id) => ("repos r JOIN users u ON u.id = r.owner_id", id),173 RepoScope::OwnedBy(id) => ("repos r JOIN users u ON u.id = r.owner_id", id),
181 RepoScope::StarredBy(id) => (174 RepoScope::StarredBy(id) => (
@@ -184,20 +177,20 @@ fn scoped(
184 ),177 ),
185 };178 };
186 let mut clauses = vec![match scope {179 let mut clauses = vec![match scope {
187- RepoScope::OwnedBy(_) => "r.owner_id = ?",180+ RepoScope::OwnedBy(_) => "r.owner_id = ?".to_owned(),
188- RepoScope::StarredBy(_) => "st.user_id = ?",181+ RepoScope::StarredBy(_) => "st.user_id = ?".to_owned(),
189 }];182 }];
190 let mut params = vec![Value::Text(scope_id.to_owned())];183 let mut params = vec![Value::Text(scope_id.to_owned())];
191 match viewer {184 match viewer {
192 // Admins read everything.185 // Admins read everything.
193 Some(user) if user.is_admin => {}186 Some(user) if user.is_admin => {}
194 Some(user) => {187 Some(user) => {
195- clauses.push(READABLE_BY_VIEWER);188+ clauses.push(format!("(r.visibility = 'public' OR {VIEWER_ACCESS})"));
196 for _ in 0..4 {189 for _ in 0..4 {
197 params.push(Value::Text(user.id.clone()));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 (from_sql, clauses, params)195 (from_sql, clauses, params)
203 }196 }
crates/forge-core/src/store/review_requests.rsmodified+7 -16
@@ -4,7 +4,7 @@
4 4
5 use std::collections::HashMap;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 use crate::error::Result;8 use crate::error::Result;
9 use crate::time::now_stamp;9 use crate::time::now_stamp;
10 10
@@ -28,19 +28,10 @@ impl Store {
28 requested_by: &str,28 requested_by: &str,
29 ) -> Result<bool> {29 ) -> Result<bool> {
30 let conn = self.inner.conn.lock().await;30 let conn = self.inner.conn.lock().await;
31- let exists = fetch_opt(31+ let n = conn
32- &conn,32+ .execute(
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) \33 "INSERT INTO review_requests (issue_id, reviewer_id, requested_by, created_at) \
43- VALUES (?1, ?2, ?3, ?4)",34+ VALUES (?1, ?2, ?3, ?4) ON CONFLICT (issue_id, reviewer_id) DO NOTHING",
44 (35 (
45 issue_id.to_string(),36 issue_id.to_string(),
46 reviewer_id.to_string(),37 reviewer_id.to_string(),
@@ -50,7 +41,7 @@ impl Store {
50 )41 )
51 .await42 .await
52 .map_err(db_err)?;43 .map_err(db_err)?;
53- Ok(true)44+ Ok(n == 1)
54 }45 }
55 46
56 /// Withdraws a pending request. Returns whether there was one.47 /// Withdraws a pending request. Returns whether there was one.
@@ -85,8 +76,8 @@ impl Store {
85 return Ok(out);76 return Ok(out);
86 }77 }
87 let conn = self.read_conn().await;78 let conn = self.read_conn().await;
88- for chunk in ids.chunks(500) {79+ for chunk in ids.chunks(IN_CHUNK) {
89- let marks = vec!["?"; chunk.len()].join(",");80+ let marks = placeholders(chunk.len());
90 let rows = fetch_all(81 let rows = fetch_all(
91 &conn,82 &conn,
92 &format!(83 &format!(
crates/forge-core/src/store/reviews.rsmodified+6 -34
@@ -2,14 +2,15 @@
2 //! with `kind = 'pull'`). Every multi-row write runs in one transaction. Replies are submitted2 //! with `kind = 'pull'`). Every multi-row write runs in one transaction. Replies are submitted
3 //! at once through an auto-created `commented` review with no body.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 use serde_json::json;7 use serde_json::json;
8 use turso::transaction::Transaction;8 use turso::transaction::Transaction;
9 use turso::{Connection, Row};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 use super::{12 use super::{
13+ finish,
13 Store, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing_row,14 Store, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing_row,
14 new_id,15 new_id,
15 };16 };
@@ -287,7 +288,6 @@ pub(super) async fn delete_repo_review_rows(tx: &Transaction<'_>, repo_id: &str)
287 Ok(())288 Ok(())
288 }289 }
289 290
290-// reviews
291 impl Store {291 impl Store {
292 /// The author's pending review on a pull request, if any.292 /// The author's pending review on a pull request, if any.
293 pub async fn pending_review(&self, issue_id: &str, author_id: &str) -> Result<Option<Review>> {293 pub async fn pending_review(&self, issue_id: &str, author_id: &str) -> Result<Option<Review>> {
@@ -487,7 +487,6 @@ impl Store {
487 insert_review(&tx, issue_id, author_id, state, body, head_oid, &now).await?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 tx.execute(490 tx.execute(
492 "DELETE FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2",491 "DELETE FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2",
493 (issue_id.to_string(), author_id.to_string()),492 (issue_id.to_string(), author_id.to_string()),
@@ -585,7 +584,6 @@ impl Store {
585 issue_id: &str,584 issue_id: &str,
586 viewer_id: Option<&str>,585 viewer_id: Option<&str>,
587 ) -> Result<Vec<Thread>> {586 ) -> Result<Vec<Thread>> {
588- // No user id is empty, so `None` matches no pending comment.
589 let viewer = viewer_id.unwrap_or("").to_string();587 let viewer = viewer_id.unwrap_or("").to_string();
590 let conn = self.read_conn().await;588 let conn = self.read_conn().await;
591 let comments = fetch_all(589 let comments = fetch_all(
@@ -839,17 +837,14 @@ impl Store {
839 },837 },
840 )838 )
841 .await?;839 .await?;
842- // Rows are in submission order, so the last one per reviewer is the latest.840+ let mut latest: BTreeMap<String, (String, ReviewState, String)> = BTreeMap::new();
843- let mut latest: HashMap<String, (String, ReviewState, String)> = HashMap::new();
844 for (author_id, name, state, commit) in rows {841 for (author_id, name, state, commit) in rows {
845 latest.insert(author_id, (name, state, commit));842 latest.insert(author_id, (name, state, commit));
846 }843 }
847- let mut out: Vec<(String, String, ReviewState, String)> = latest844+ Ok(latest
848 .into_iter()845 .into_iter()
849 .map(|(id, (name, state, commit))| (id, name, state, commit))846 .map(|(id, (name, state, commit))| (id, name, state, commit))
850- .collect();847+ .collect())
851- out.sort_unstable_by(|a, b| a.0.cmp(&b.0));
852- Ok(out)
853 }848 }
854 }849 }
855 850
@@ -965,13 +960,10 @@ mod tests {
965 .unwrap()960 .unwrap()
966 }961 }
967 962
968- // Comment, reply, edit, delete, resolve, outdated and relocate. Each
969- // scenario has its own pull request.
970 #[tokio::test]963 #[tokio::test]
971 async fn comment_scenarios_share_one_store() {964 async fn comment_scenarios_share_one_store() {
972 let fx = fixture().await;965 let fx = fixture().await;
973 966
974- // A pending comment is visible only to its author and joins one draft.
975 let issue = new_pull(&fx, "pending").await;967 let issue = new_pull(&fx, "pending").await;
976 let draft = comment(&fx, &issue, &fx.bob.id, true, "draft").await;968 let draft = comment(&fx, &issue, &fx.bob.id, true, "draft").await;
977 assert!(draft.pending, "pending: draft is pending");969 assert!(draft.pending, "pending: draft is pending");
@@ -1010,7 +1002,6 @@ mod tests {
1010 "pending: same draft review"1002 "pending: same draft review"
1011 );1003 );
1012 1004
1013- // A single submitted comment creates its own commented review.
1014 let issue = new_pull(&fx, "single").await;1005 let issue = new_pull(&fx, "single").await;
1015 let c = comment(&fx, &issue, &fx.bob.id, false, "nit").await;1006 let c = comment(&fx, &issue, &fx.bob.id, false, "nit").await;
1016 assert!(!c.pending, "single: submitted");1007 assert!(!c.pending, "single: submitted");
@@ -1040,7 +1031,6 @@ mod tests {
1040 assert_eq!(threads.len(), 1, "single: one thread");1031 assert_eq!(threads.len(), 1, "single: one thread");
1041 assert!(threads[0].replies.is_empty(), "single: no replies");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 let issue = new_pull(&fx, "reply").await;1034 let issue = new_pull(&fx, "reply").await;
1045 let root = comment(&fx, &issue, &fx.bob.id, false, "question").await;1035 let root = comment(&fx, &issue, &fx.bob.id, false, "question").await;
1046 let answer = reply(&fx, &issue, &fx.carol.id, &root.id, "answer").await;1036 let answer = reply(&fx, &issue, &fx.carol.id, &root.id, "answer").await;
@@ -1055,7 +1045,6 @@ mod tests {
1055 );1045 );
1056 assert!(!answer.pending, "reply: submitted");1046 assert!(!answer.pending, "reply: submitted");
1057 1047
1058- // Each reply is submitted through its own commented review.
1059 assert_eq!(1048 assert_eq!(
1060 fx.store.list_reviews(&issue).await.unwrap().len(),1049 fx.store.list_reviews(&issue).await.unwrap().len(),
1061 2,1050 2,
@@ -1089,7 +1078,6 @@ mod tests {
1089 );1078 );
1090 }1079 }
1091 1080
1092- // Edits record the previous body.
1093 let issue = new_pull(&fx, "edit").await;1081 let issue = new_pull(&fx, "edit").await;
1094 let c = comment(&fx, &issue, &fx.bob.id, false, "old text").await;1082 let c = comment(&fx, &issue, &fx.bob.id, false, "old text").await;
1095 fx.store1083 fx.store
@@ -1135,7 +1123,6 @@ mod tests {
1135 "edit: missing refused: {err:?}"1123 "edit: missing refused: {err:?}"
1136 );1124 );
1137 1125
1138- // Deleting a root removes its replies; deleting a reply keeps the root.
1139 let issue = new_pull(&fx, "delete").await;1126 let issue = new_pull(&fx, "delete").await;
1140 let root = comment(&fx, &issue, &fx.bob.id, false, "root").await;1127 let root = comment(&fx, &issue, &fx.bob.id, false, "root").await;
1141 let r1 = reply(&fx, &issue, &fx.carol.id, &root.id, "one").await;1128 let r1 = reply(&fx, &issue, &fx.carol.id, &root.id, "one").await;
@@ -1158,7 +1145,6 @@ mod tests {
1158 let threads = fx.store.review_threads(&issue, None).await.unwrap();1145 let threads = fx.store.review_threads(&issue, None).await.unwrap();
1159 assert_eq!(threads.len(), 1, "delete root: other thread remains");1146 assert_eq!(threads.len(), 1, "delete root: other thread remains");
1160 assert_eq!(threads[0].root.id, other.id, "delete root: other root kept");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 let reviews = fx.store.list_reviews(&issue).await.unwrap();1148 let reviews = fx.store.list_reviews(&issue).await.unwrap();
1163 assert_eq!(reviews.len(), 1, "delete root: emptied reviews removed");1149 assert_eq!(reviews.len(), 1, "delete root: emptied reviews removed");
1164 assert_eq!(1150 assert_eq!(
@@ -1186,7 +1172,6 @@ mod tests {
1186 "delete: missing refused: {err:?}"1172 "delete: missing refused: {err:?}"
1187 );1173 );
1188 1174
1189- // Resolving records events, and only submitted roots can be resolved.
1190 let issue = new_pull(&fx, "resolve").await;1175 let issue = new_pull(&fx, "resolve").await;
1191 let root = comment(&fx, &issue, &fx.bob.id, false, "fix this").await;1176 let root = comment(&fx, &issue, &fx.bob.id, false, "fix this").await;
1192 1177
@@ -1203,7 +1188,6 @@ mod tests {
1203 .resolved,1188 .resolved,
1204 "resolve: resolved"1189 "resolve: resolved"
1205 );1190 );
1206- // Already resolved: no second event.
1207 fx.store1191 fx.store
1208 .set_thread_resolved(&root.id, &fx.carol.id, true)1192 .set_thread_resolved(&root.id, &fx.carol.id, true)
1209 .await1193 .await
@@ -1266,7 +1250,6 @@ mod tests {
1266 );1250 );
1267 }1251 }
1268 1252
1269- // Outdated marks only submitted roots.
1270 let issue = new_pull(&fx, "outdated").await;1253 let issue = new_pull(&fx, "outdated").await;
1271 let root = comment(&fx, &issue, &fx.bob.id, false, "a").await;1254 let root = comment(&fx, &issue, &fx.bob.id, false, "a").await;
1272 let r = reply(&fx, &issue, &fx.carol.id, &root.id, "b").await;1255 let r = reply(&fx, &issue, &fx.carol.id, &root.id, "b").await;
@@ -1289,7 +1272,6 @@ mod tests {
1289 let draft_thread = own.iter().find(|t| t.root.id == draft.id).unwrap();1272 let draft_thread = own.iter().find(|t| t.root.id == draft.id).unwrap();
1290 assert!(!draft_thread.root.outdated, "outdated: draft untouched");1273 assert!(!draft_thread.root.outdated, "outdated: draft untouched");
1291 1274
1292- // Relocation moves the root and its replies, keeping the hunk.
1293 let issue = new_pull(&fx, "relocate").await;1275 let issue = new_pull(&fx, "relocate").await;
1294 let root = comment(&fx, &issue, &fx.bob.id, false, "root").await;1276 let root = comment(&fx, &issue, &fx.bob.id, false, "root").await;
1295 let answer = reply(&fx, &issue, &fx.tahinli.id, &root.id, "answer").await;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 #[tokio::test]1321 #[tokio::test]
1342 async fn review_scenarios_share_one_store() {1322 async fn review_scenarios_share_one_store() {
1343 let fx = fixture().await;1323 let fx = fixture().await;
@@ -1347,7 +1327,6 @@ mod tests {
1347 .await1327 .await
1348 .unwrap();1328 .unwrap();
1349 1329
1350- // A pending draft becomes an approved review.
1351 let issue = new_pull(&fx, "approve").await;1330 let issue = new_pull(&fx, "approve").await;
1352 let draft = comment(&fx, &issue, &fx.bob.id, true, "draft").await;1331 let draft = comment(&fx, &issue, &fx.bob.id, true, "draft").await;
1353 let review = fx1332 let review = fx
@@ -1393,7 +1372,6 @@ mod tests {
1393 "approve: no requests"1372 "approve: no requests"
1394 );1373 );
1395 1374
1396- // The pull request author may comment but not approve or request changes.
1397 let issue = new_pull(&fx, "author").await;1375 let issue = new_pull(&fx, "author").await;
1398 for state in [ReviewState::Approved, ReviewState::ChangesRequested] {1376 for state in [ReviewState::Approved, ReviewState::ChangesRequested] {
1399 let err = fx1377 let err = fx
@@ -1427,7 +1405,6 @@ mod tests {
1427 "author: comment allowed"1405 "author: comment allowed"
1428 );1406 );
1429 1407
1430- // A commented review needs text unless it carries a pending comment.
1431 let issue = new_pull(&fx, "empty").await;1408 let issue = new_pull(&fx, "empty").await;
1432 let err = fx1409 let err = fx
1433 .store1410 .store
@@ -1455,7 +1432,6 @@ mod tests {
1455 "empty: approval without body and comment review with draft"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 let issue = new_pull(&fx, "summary").await;1435 let issue = new_pull(&fx, "summary").await;
1460 fx.store1436 fx.store
1461 .submit_review(&issue, &fx.bob.id, ReviewState::Approved, "", &oid('a'))1437 .submit_review(&issue, &fx.bob.id, ReviewState::Approved, "", &oid('a'))
@@ -1524,7 +1500,6 @@ mod tests {
1524 "summary: dismissed request gone"1500 "summary: dismissed request gone"
1525 );1501 );
1526 1502
1527- // Only approvals and change requests can be dismissed, and only once.
1528 let issue = new_pull(&fx, "dismiss").await;1503 let issue = new_pull(&fx, "dismiss").await;
1529 let note = comment(&fx, &issue, &fx.bob.id, false, "note").await;1504 let note = comment(&fx, &issue, &fx.bob.id, false, "note").await;
1530 let err = fx1505 let err = fx
@@ -1609,7 +1584,6 @@ mod tests {
1609 "dismiss: twice refused: {err:?}"1584 "dismiss: twice refused: {err:?}"
1610 );1585 );
1611 1586
1612- // A review written before the previous-state column has none.
1613 {1587 {
1614 let conn = fx.store.inner.conn.lock().await;1588 let conn = fx.store.inner.conn.lock().await;
1615 conn.execute(1589 conn.execute(
@@ -1623,7 +1597,6 @@ mod tests {
1623 let legacy = listed.iter().find(|r| r.id == approved.id).unwrap();1597 let legacy = listed.iter().find(|r| r.id == approved.id).unwrap();
1624 assert_eq!(legacy.dismissed_from, None, "legacy: no previous state");1598 assert_eq!(legacy.dismissed_from, None, "legacy: no previous state");
1625 1599
1626- // Discarding a draft keeps submitted comments.
1627 let issue = new_pull(&fx, "discard").await;1600 let issue = new_pull(&fx, "discard").await;
1628 let submitted = comment(&fx, &issue, &fx.bob.id, false, "done").await;1601 let submitted = comment(&fx, &issue, &fx.bob.id, false, "done").await;
1629 let d1 = comment(&fx, &issue, &fx.bob.id, true, "d1").await;1602 let d1 = comment(&fx, &issue, &fx.bob.id, true, "d1").await;
@@ -1664,7 +1637,6 @@ mod tests {
1664 .unwrap();1637 .unwrap();
1665 assert_eq!(own.len(), 1, "discard: only the submitted thread");1638 assert_eq!(own.len(), 1, "discard: only the submitted thread");
1666 1639
1667- // Nothing pending left: discarding again is fine.
1668 fx.store1640 fx.store
1669 .discard_pending_review(&issue, &fx.bob.id)1641 .discard_pending_review(&issue, &fx.bob.id)
1670 .await1642 .await
crates/forge-core/src/store/server_settings.rsmodified+8 -7
@@ -4,17 +4,13 @@
4 4
5 use std::collections::BTreeMap;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 use crate::error::{Error, Result};8 use crate::error::{Error, Result};
9 use crate::{secret, server_settings};9 use crate::{secret, server_settings};
10 10
11 impl Store {11 impl Store {
12 fn settings_key(&self) -> Result<[u8; 32]> {12 fn settings_key(&self) -> Result<[u8; 32]> {
13- self.inner13+ self.secret_key().map(|key| *key)
14- .secret_key
15- .get()
16- .copied()
17- .ok_or_else(|| Error::Crypto("the instance key is not set".into()))
18 }14 }
19 15
20 /// Every stored override, with secret values opened. A key this binary does not know is16 /// Every stored override, with secret values opened. A key this binary does not know is
@@ -59,8 +55,10 @@ impl Store {
59 prepared.push((key.clone(), stored));55 prepared.push((key.clone(), stored));
60 }56 }
61 let conn = self.inner.conn.lock().await;57 let conn = self.inner.conn.lock().await;
58+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
59+ let outcome: Result<()> = async {
62 for (key, stored) in prepared {60 for (key, stored) in prepared {
63- conn.execute(61+ tx.execute(
64 "INSERT INTO server_settings (key, value, updated_at) VALUES (?1, ?2, ?3) \62 "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",63 ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
66 (key, stored, now.clone()),64 (key, stored, now.clone()),
@@ -70,6 +68,9 @@ impl Store {
70 }68 }
71 Ok(())69 Ok(())
72 }70 }
71+ .await;
72+ finish(tx, outcome).await
73+ }
73 74
74 /// Removes the override of `key`, so the file value (or the default) applies again.75 /// Removes the override of `key`, so the file value (or the default) applies again.
75 pub async fn clear_server_override(&self, key: &str) -> Result<()> {76 pub async fn clear_server_override(&self, key: &str) -> Result<()> {
crates/forge-core/src/store/snapshot.rsmodified+11 -12
@@ -33,6 +33,11 @@ fn sql_string_literal(text: &str) -> Result<String> {
33 Ok(format!("'{}'", text.replace('\'', "''")))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 impl Store {41 impl Store {
37 /// Writes a consistent copy of the database to `dest` with `VACUUM INTO`, then fsyncs it.42 /// Writes a consistent copy of the database to `dest` with `VACUUM INTO`, then fsyncs it.
38 /// `dest` must not exist. The store's connection is held for the whole copy.43 /// `dest` must not exist. The store's connection is held for the whole copy.
@@ -43,10 +48,7 @@ impl Store {
43 dest.display()48 dest.display()
44 )));49 )));
45 }50 }
46- let text = dest.to_str().ok_or_else(|| {51+ let sql = format!("VACUUM INTO {}", sql_string_literal(utf8_path(dest)?)?);
47- Error::Config(format!("snapshot path is not UTF-8: {}", dest.display()))
48- })?;
49- let sql = format!("VACUUM INTO {}", sql_string_literal(text)?);
50 {52 {
51 let conn = self.inner.conn.lock().await;53 let conn = self.inner.conn.lock().await;
52 conn.execute(&sql, ()).await.map_err(db_err)?;54 conn.execute(&sql, ()).await.map_err(db_err)?;
@@ -74,10 +76,10 @@ impl Store {
74 /// until every frame is in the main file, and then removes sidecars that are empty. A sidecar that76 /// until every frame is in the main file, and then removes sidecars that are empty. A sidecar that
75 /// still has bytes is an error. The main file alone is then the whole database.77 /// still has bytes is an error. The main file alone is then the whole database.
76 async fn make_self_contained(dest: &Path) -> Result<()> {78 async fn make_self_contained(dest: &Path) -> Result<()> {
77- let text = dest79+ let db = Builder::new_local(utf8_path(dest)?)
78- .to_str()80+ .build()
79- .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", dest.display())))?;81+ .await
80- let db = Builder::new_local(text).build().await.map_err(db_err)?;82+ .map_err(db_err)?;
81 let conn = db.connect().map_err(db_err)?;83 let conn = db.connect().map_err(db_err)?;
82 // Columns: busy, frames in the log, frames checkpointed.84 // Columns: busy, frames in the log, frames checkpointed.
83 let status = fetch_all(&conn, "PRAGMA wal_checkpoint(TRUNCATE)", (), |row| {85 let status = fetch_all(&conn, "PRAGMA wal_checkpoint(TRUNCATE)", (), |row| {
@@ -116,10 +118,7 @@ async fn make_self_contained(dest: &Path) -> Result<()> {
116 /// Opens a snapshot read-only with a fresh connection, runs `PRAGMA integrity_check`, checks the118 /// Opens a snapshot read-only with a fresh connection, runs `PRAGMA integrity_check`, checks the
117 /// migration history and the repo rows, and returns what it found. Any problem is an error.119 /// migration history and the repo rows, and returns what it found. Any problem is an error.
118 pub async fn verify_snapshot(path: &Path) -> Result<SnapshotInfo> {120 pub async fn verify_snapshot(path: &Path) -> Result<SnapshotInfo> {
119- let text = path121+ let db = Builder::new_local(utf8_path(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)
123 .read_only(true)122 .read_only(true)
124 .build()123 .build()
125 .await124 .await
crates/forge-core/src/store/suggest.rsmodified+12 -32
@@ -33,42 +33,22 @@ impl Store {
33 };33 };
34 // `like_pattern` wraps in `%..%`; for a prefix match drop the leading one (done above).34 // `like_pattern` wraps in `%..%`; for a prefix match drop the leading one (done above).
35 let cap = Value::Integer(i64::try_from(limit).unwrap_or(8));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 let conn = self.read_conn().await;36 let conn = self.read_conn().await;
52- let mut out: Vec<String> = Vec::new();37+ fetch_all(
53- for sql in queries {
54- let names = fetch_all(
55 &conn,38 &conn,
56- sql,39+ "SELECT username FROM (SELECT u.username, u.username_folded, CASE \
57- vec![40+ WHEN u.id = (SELECT owner_id FROM repos WHERE id = ?1) OR \
58- Value::Text(repo_id.to_string()),41+ u.id IN (SELECT user_id FROM collaborators WHERE repo_id = ?1) THEN 0 \
59- Value::Text(pattern.clone()),42+ WHEN u.id IN (SELECT author_id FROM issues WHERE repo_id = ?1) OR \
60- cap.clone(),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 \
61- ],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],
62 |row| col_text(row, 0),49 |row| col_text(row, 0),
63 )50 )
64- .await?;51+ .await
65- for name in names {
66- if out.len() < limit && !out.contains(&name) {
67- out.push(name);
68- }
69- }
70- }
71- Ok(out)
72 }52 }
73 53
74 /// Issues and pull requests of the repo whose number starts with `q` (when it is digits) or54 /// 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 //! A suspended user keeps their data but cannot sign in. The session, token and SSH key lookups3 //! A suspended user keeps their data but cannot sign in. The session, token and SSH key lookups
4 //! in `store/mod.rs` skip a suspended owner, so every transport stops at once.4 //! in `store/mod.rs` skip a suspended owner, so every transport stops at once.
5 5
6+use turso::Connection;
7+
6 use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_opt};8 use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_opt};
7 use crate::error::{Error, Result};9 use crate::error::{Error, Result};
8 use crate::time::now_stamp;10 use crate::time::now_stamp;
@@ -67,16 +69,7 @@ impl Store {
67 return Err(Error::Invalid("an organization cannot be suspended".into()));69 return Err(Error::Invalid("an organization cannot be suspended".into()));
68 }70 }
69 if row.0 {71 if row.0 {
70- let others = fetch_opt(72+ if other_active_admins(&conn, &uid).await? == 0 {
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 {
80 return Err(Error::Conflict(73 return Err(Error::Conflict(
81 "cannot suspend the last active administrator".into(),74 "cannot suspend the last active administrator".into(),
82 ));75 ));
@@ -116,14 +109,7 @@ impl Store {
116 /// Administrators other than `user_id`: zero means `user_id` is the last one and cannot be demoted.109 /// Administrators other than `user_id`: zero means `user_id` is the last one and cannot be demoted.
117 pub async fn other_admin_count(&self, user_id: &str) -> Result<i64> {110 pub async fn other_admin_count(&self, user_id: &str) -> Result<i64> {
118 let conn = self.read_conn().await;111 let conn = self.read_conn().await;
119- Ok(fetch_opt(112+ other_active_admins(&conn, user_id).await
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))
127 }113 }
128 114
129 /// Grants or revokes the admin flag. Revoking is refused for the last administrator.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 if !admin {132 if !admin {
147- let others = fetch_opt(133+ if other_active_admins(&conn, &uid).await? == 0 {
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 {
156 return Err(Error::Conflict(134 return Err(Error::Conflict(
157 "cannot remove the last administrator".into(),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 #[cfg(test)]196 #[cfg(test)]
207 mod tests {197 mod tests {
208 use super::*;198 use super::*;
crates/forge-core/src/store/transfers.rsmodified+1 -1
@@ -8,7 +8,7 @@
8 8
9 use turso::Row;9 use turso::Row;
10 10
11-use super::issues::finish;11+use super::finish;
12 use super::orgs::OrgMemberRole;12 use super::orgs::OrgMemberRole;
13 use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt};13 use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt};
14 use crate::error::{Error, Result};14 use crate::error::{Error, Result};
crates/forge-core/src/store/ui_prefs.rsmodified+21 -54
@@ -4,6 +4,8 @@
4 //! 0042 and 0043). The web layer decides which values it offers; the store only checks that a4 //! 0042 and 0043). The web layer decides which values it offers; the store only checks that a
5 //! value is well formed, so a new language, accent or base needs no store change.5 //! value is well formed, so a new language, accent or base needs no store change.
6 6
7+use turso::IntoParams;
8+
7 use super::{Store, db_err};9 use super::{Store, db_err};
8 use crate::error::{Error, Result};10 use crate::error::{Error, Result};
9 11
@@ -51,7 +53,7 @@ pub fn valid_language(code: &str) -> bool {
51 53
52 /// True for a short lowercase slug such as `sage` or `rose-2`: 1 to 24 ASCII letters, digits or54 /// True for a short lowercase slug such as `sage` or `rose-2`: 1 to 24 ASCII letters, digits or
53 /// hyphens. Whether forge offers the id is the web layer's call.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 (1..=MAX_ACCENT_LEN).contains(&id.len())57 (1..=MAX_ACCENT_LEN).contains(&id.len())
56 && id58 && id
57 .bytes()59 .bytes()
@@ -64,6 +66,15 @@ pub fn valid_sidebar(side: &str) -> bool {
64 }66 }
65 67
66 impl Store {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 /// Sets the user's theme and language. Anything malformed is rejected and nothing is written.78 /// Sets the user's theme and language. Anything malformed is rejected and nothing is written.
68 pub async fn set_ui_prefs(&self, user_id: &str, theme: &str, language: &str) -> Result<()> {79 pub async fn set_ui_prefs(&self, user_id: &str, theme: &str, language: &str) -> Result<()> {
69 if !THEMES.contains(&theme) {80 if !THEMES.contains(&theme) {
@@ -72,38 +83,24 @@ impl Store {
72 if !valid_language(language) {83 if !valid_language(language) {
73 return Err(Error::Invalid(format!("language {language:?}")));84 return Err(Error::Invalid(format!("language {language:?}")));
74 }85 }
75- let conn = self.inner.conn.lock().await;86+ self.update_user(
76- let n = conn
77- .execute(
78 "UPDATE users SET theme = ?2, language = ?3 WHERE id = ?1",87 "UPDATE users SET theme = ?2, language = ?3 WHERE id = ?1",
79 (user_id.to_string(), theme.to_string(), language.to_string()),88 (user_id.to_string(), theme.to_string(), language.to_string()),
80 )89 )
81 .await90 .await
82- .map_err(db_err)?;
83- if n == 0 {
84- return Err(Error::NotFound);
85- }
86- Ok(())
87 }91 }
88 92
89 /// Sets the user's accent colour id for both themes. A malformed id is rejected and nothing is93 /// Sets the user's accent colour id for both themes. A malformed id is rejected and nothing is
90 /// written.94 /// written.
91 pub async fn set_accent(&self, user_id: &str, accent: &str) -> Result<()> {95 pub async fn set_accent(&self, user_id: &str, accent: &str) -> Result<()> {
92- if !valid_accent(accent) {96+ if !valid_slug(accent) {
93 return Err(Error::Invalid(format!("accent {accent:?}")));97 return Err(Error::Invalid(format!("accent {accent:?}")));
94 }98 }
95- let conn = self.inner.conn.lock().await;99+ self.update_user(
96- let n = conn
97- .execute(
98 "UPDATE users SET accent = ?2, accent_dark = ?2 WHERE id = ?1",100 "UPDATE users SET accent = ?2, accent_dark = ?2 WHERE id = ?1",
99 (user_id.to_string(), accent.to_string()),101 (user_id.to_string(), accent.to_string()),
100 )102 )
101 .await103 .await
102- .map_err(db_err)?;
103- if n == 0 {
104- return Err(Error::NotFound);
105- }
106- Ok(())
107 }104 }
108 105
109 /// Sets the four colour choices: the accent and the base for the light theme, then the accent106 /// Sets the four colour choices: the accent and the base for the light theme, then the accent
@@ -117,18 +114,16 @@ impl Store {
117 base_dark: &str,114 base_dark: &str,
118 ) -> Result<()> {115 ) -> Result<()> {
119 for accent in [accent_light, accent_dark] {116 for accent in [accent_light, accent_dark] {
120- if !valid_accent(accent) {117+ if !valid_slug(accent) {
121 return Err(Error::Invalid(format!("accent {accent:?}")));118 return Err(Error::Invalid(format!("accent {accent:?}")));
122 }119 }
123 }120 }
124 for base in [base_light, base_dark] {121 for base in [base_light, base_dark] {
125- if !valid_accent(base) {122+ if !valid_slug(base) {
126 return Err(Error::Invalid(format!("base {base:?}")));123 return Err(Error::Invalid(format!("base {base:?}")));
127 }124 }
128 }125 }
129- let conn = self.inner.conn.lock().await;126+ self.update_user(
130- let n = conn
131- .execute(
132 "UPDATE users SET accent = ?2, accent_dark = ?3, base_light = ?4, base_dark = ?5 \127 "UPDATE users SET accent = ?2, accent_dark = ?3, base_light = ?4, base_dark = ?5 \
133 WHERE id = ?1",128 WHERE id = ?1",
134 (129 (
@@ -140,11 +135,6 @@ impl Store {
140 ),135 ),
141 )136 )
142 .await137 .await
143- .map_err(db_err)?;
144- if n == 0 {
145- return Err(Error::NotFound);
146- }
147- Ok(())
148 }138 }
149 139
150 /// Sets the side the shell sidebar sits on. Anything but `left` or `right` is rejected and140 /// Sets the side the shell sidebar sits on. Anything but `left` or `right` is rejected and
@@ -153,34 +143,11 @@ impl Store {
153 if !valid_sidebar(side) {143 if !valid_sidebar(side) {
154 return Err(Error::Invalid(format!("sidebar {side:?}")));144 return Err(Error::Invalid(format!("sidebar {side:?}")));
155 }145 }
156- let conn = self.inner.conn.lock().await;146+ self.update_user(
157- let n = conn
158- .execute(
159 "UPDATE users SET sidebar_side = ?2 WHERE id = ?1",147 "UPDATE users SET sidebar_side = ?2 WHERE id = ?1",
160 (user_id.to_string(), side.to_string()),148 (user_id.to_string(), side.to_string()),
161 )149 )
162 .await150 .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(())
184 }151 }
185 }152 }
186 153
@@ -208,10 +175,10 @@ mod tests {
208 let longest = "a".repeat(MAX_ACCENT_LEN);175 let longest = "a".repeat(MAX_ACCENT_LEN);
209 let too_long = "a".repeat(MAX_ACCENT_LEN + 1);176 let too_long = "a".repeat(MAX_ACCENT_LEN + 1);
210 for ok in ["sage", "rose-2", "a", longest.as_str()] {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 for bad in ["", "Sage", "sage_2", "../x", "a b", too_long.as_str()] {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 // Sidebar sides.184 // Sidebar sides.
crates/forge-core/src/store/user_delete.rsmodified+17 -40
@@ -6,10 +6,10 @@
6 use turso::Connection;6 use turso::Connection;
7 use turso::transaction::Transaction;7 use turso::transaction::Transaction;
8 8
9-use super::issues::finish;9+use super::finish;
10 use super::{Store, USER_COLS, col_bool, col_int, col_text, db_err, fetch_opt, map_user, new_id};10 use super::{Store, USER_COLS, col_bool, col_int, col_text, db_err, fetch_opt, map_user, new_id};
11 use crate::error::{Error, Result};11 use crate::error::{Error, Result};
12-use crate::model::{AccountKind, User};12+use crate::model::User;
13 use crate::time::now_stamp;13 use crate::time::now_stamp;
14 14
15 /// Login name of the reserved ghost account. `names::RESERVED` contains it, so nobody can15 /// 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 "created_by",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 "notification actors",92 "notification actors",
92 "notifications",93 "notifications",
@@ -165,41 +166,28 @@ impl Store {
165 if let Some(user) = existing {166 if let Some(user) = existing {
166 return Ok(user);167 return Ok(user);
167 }168 }
168- let user = User {169+ let id = new_id();
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- };
189 conn.execute(170 conn.execute(
190 "INSERT INTO users (id, username, username_folded, email, password_hash, is_admin, created_at, theme) \171 "INSERT INTO users (id, username, username_folded, email, password_hash, is_admin, created_at, theme) \
191 VALUES (?1, ?2, ?3, NULL, ?4, 0, ?5, 'light')",172 VALUES (?1, ?2, ?3, NULL, ?4, 0, ?5, 'light')",
192 (173 (
193- user.id.clone(),174+ id.clone(),
194- user.username.clone(),
195 GHOST_USERNAME.to_string(),175 GHOST_USERNAME.to_string(),
196- user.password_hash.clone(),176+ GHOST_USERNAME.to_string(),
197- user.created_at.clone(),177+ GHOST_PASSWORD_HASH.to_string(),
178+ now_stamp(),
198 ),179 ),
199 )180 )
200 .await181 .await
201 .map_err(db_err)?;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 /// Checks whether `user_id` can be deleted and reports what would happen. Changes nothing.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 let uid = user_id.to_string();306 let uid = user_id.to_string();
319 let gid = ghost_id.to_string();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 let draft_edits = format!(309 let draft_edits = format!(
323 "DELETE FROM edit_history WHERE target_kind = 'review_comment' AND target_id IN ({DRAFT_COMMENTS})"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 let sql = format!("DELETE FROM {table} WHERE {column} = ?1");329 let sql = format!("DELETE FROM {table} WHERE {column} = ?1");
343 tx.execute(&sql, (uid.clone(),)).await.map_err(db_err)?;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 tx.execute(332 tx.execute(
347 "DELETE FROM commit_signatures WHERE signer_user_id = ?1",333 "DELETE FROM commit_signatures WHERE signer_user_id = ?1",
348 (uid.clone(),),334 (uid.clone(),),
@@ -434,7 +420,6 @@ mod tests {
434 async fn ghost_account_and_refused_deletions() {420 async fn ghost_account_and_refused_deletions() {
435 let fx = fixture().await;421 let fx = fixture().await;
436 422
437- // Scenario: the ghost is created once and cannot log in.
438 let again = fx.store.ensure_ghost_user().await.unwrap();423 let again = fx.store.ensure_ghost_user().await.unwrap();
439 assert_eq!(again.id, fx.ghost.id);424 assert_eq!(again.id, fx.ghost.id);
440 assert_eq!(fx.ghost.username, "ghost");425 assert_eq!(fx.ghost.username, "ghost");
@@ -447,13 +432,11 @@ mod tests {
447 &fx.ghost.password_hash432 &fx.ghost.password_hash
448 ));433 ));
449 434
450- // Scenario: the ghost itself cannot be deleted.
451 assert!(matches!(435 assert!(matches!(
452 fx.store.delete_user(&fx.ghost.id, &fx.ghost.id).await,436 fx.store.delete_user(&fx.ghost.id, &fx.ghost.id).await,
453 Err(Error::Forbidden(_))437 Err(Error::Forbidden(_))
454 ));438 ));
455 439
456- // Scenario: a user who owns a repo is refused and nothing changes.
457 let err = fx.store.delete_user(&fx.bob.id, &fx.ghost.id).await;440 let err = fx.store.delete_user(&fx.bob.id, &fx.ghost.id).await;
458 assert!(441 assert!(
459 matches!(err, Err(Error::Conflict(ref m)) if m == "transfer or delete their repositories first"),442 matches!(err, Err(Error::Conflict(ref m)) if m == "transfer or delete their repositories first"),
@@ -462,7 +445,6 @@ mod tests {
462 assert!(fx.store.user_by_id(&fx.bob.id).await.unwrap().is_some());445 assert!(fx.store.user_by_id(&fx.bob.id).await.unwrap().is_some());
463 assert!(fx.store.repo_by_id(&fx.repo_id).await.unwrap().is_some());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 let err = fx.store.delete_user(&fx.admin.id, &fx.ghost.id).await;448 let err = fx.store.delete_user(&fx.admin.id, &fx.ghost.id).await;
467 assert!(matches!(err, Err(Error::Conflict(_))), "{err:?}");449 assert!(matches!(err, Err(Error::Conflict(_))), "{err:?}");
468 assert!(fx.store.user_by_id(&fx.admin.id).await.unwrap().is_some());450 assert!(fx.store.user_by_id(&fx.admin.id).await.unwrap().is_some());
@@ -472,7 +454,6 @@ mod tests {
472 async fn authored_content_moves_to_ghost_and_preview_changes_nothing() {454 async fn authored_content_moves_to_ghost_and_preview_changes_nothing() {
473 let fx = fixture().await;455 let fx = fixture().await;
474 456
475- // Scenario: authored content moves to the ghost and stays readable.
476 let issue = fx457 let issue = fx
477 .store458 .store
478 .create_issue(&fx.repo_id, &fx.tahinli.id, "Bug", "body")459 .create_issue(&fx.repo_id, &fx.tahinli.id, "Bug", "body")
@@ -483,7 +464,6 @@ mod tests {
483 .add_comment(&issue.id, &fx.tahinli.id, "a comment")464 .add_comment(&issue.id, &fx.tahinli.id, "a comment")
484 .await465 .await
485 .unwrap();466 .unwrap();
486- // A submitted review and a pending draft, both by Tahinli on the issue row.
487 {467 {
488 let conn = fx.store.inner.conn.lock().await;468 let conn = fx.store.inner.conn.lock().await;
489 for (id, state) in [("rev-done", "commented"), ("rev-draft", "pending")] {469 for (id, state) in [("rev-done", "commented"), ("rev-draft", "pending")] {
@@ -545,7 +525,6 @@ mod tests {
545 );525 );
546 assert!(fx.store.user_by_id(&fx.tahinli.id).await.unwrap().is_none());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 let second_admin = fx528 let second_admin = fx
550 .store529 .store
551 .create_user("Carol", None, "hash", true)530 .create_user("Carol", None, "hash", true)
@@ -631,7 +610,6 @@ mod tests {
631 #[tokio::test]610 #[tokio::test]
632 async fn discussions_and_comments_move_to_ghost() {611 async fn discussions_and_comments_move_to_ghost() {
633 let fx = fixture().await;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 let mine = fx613 let mine = fx
636 .store614 .store
637 .create_discussion(615 .create_discussion(
@@ -652,7 +630,6 @@ mod tests {
652 .add_discussion_comment(&mine.id, &fx.bob.id, None, "a reply", false)630 .add_discussion_comment(&mine.id, &fx.bob.id, None, "a reply", false)
653 .await631 .await
654 .unwrap();632 .unwrap();
655- // Bob's discussion that Tahinli commented on: Bob's inbox row names Tahinli as last actor.
656 let theirs = fx633 let theirs = fx
657 .store634 .store
658 .create_discussion(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 /// Most devices one account may hold. A subscription past this is refused, so a client cannot8 /// Most devices one account may hold. A subscription past this is refused, so a client cannot
9 /// grow the table without bound.9 /// grow the table without bound.
10-pub const MAX_DEVICES: usize = 20;10+pub const MAX_DEVICES: i64 = 20;
11 11
12 /// One browser or installed app that receives pushes for `user_id`.12 /// One browser or installed app that receives pushes for `user_id`.
13 #[derive(Debug, Clone, PartialEq, Eq)]13 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -118,7 +118,7 @@ impl Store {
118 )118 )
119 .await?119 .await?
120 .unwrap_or(0);120 .unwrap_or(0);
121- if usize::try_from(held).unwrap_or(usize::MAX) >= MAX_DEVICES {121+ if held >= MAX_DEVICES {
122 return Err(Error::Invalid(format!(122 return Err(Error::Invalid(format!(
123 "an account can enable push on at most {MAX_DEVICES} devices"123 "an account can enable push on at most {MAX_DEVICES} devices"
124 )));124 )));
crates/forge-core/src/store/webhooks.rsmodified+53 -84
@@ -9,8 +9,8 @@ use std::time::Duration;
9 use turso::{Connection, Row, Value};9 use turso::{Connection, Row, Value};
10 10
11 use super::{11 use super::{
12- Store, col_blob, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt,12+ Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all,
13- finish, new_id,13+ fetch_opt, finish, new_id, opt_int_value, opt_text,
14 };14 };
15 use crate::error::{Error, Result};15 use crate::error::{Error, Result};
16 use crate::secret;16 use crate::secret;
@@ -68,13 +68,13 @@ fn map_delivery(row: &Row) -> Result<Delivery> {
68 attempt: u32::try_from(col_int(row, 8)?)68 attempt: u32::try_from(col_int(row, 8)?)
69 .map_err(|_| Error::Database("negative delivery attempt count".into()))?,69 .map_err(|_| Error::Database("negative delivery attempt count".into()))?,
70 next_attempt_at: col_opt_text(row, 9)?,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 .map(|n| u16::try_from(n).map_err(|_| Error::Database("bad response status".into())))72 .map(|n| u16::try_from(n).map_err(|_| Error::Database("bad response status".into())))
73 .transpose()?,73 .transpose()?,
74 response_headers: col_opt_text(row, 11)?,74 response_headers: col_opt_text(row, 11)?,
75 response_body: col_opt_text(row, 12)?,75 response_body: col_opt_text(row, 12)?,
76 error: col_opt_text(row, 13)?,76 error: col_opt_text(row, 13)?,
77- duration_ms: opt_int(row, 14)?77+ duration_ms: col_opt_int(row, 14)?
78 .map(|n| u64::try_from(n).map_err(|_| Error::Database("bad duration".into())))78 .map(|n| u64::try_from(n).map_err(|_| Error::Database("bad duration".into())))
79 .transpose()?,79 .transpose()?,
80 created_at: col_text(row, 15)?,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 /// Headers the worker adds at send time. They are never kept in the stored request headers, so a85 /// Headers the worker adds at send time. They are never kept in the stored request headers, so a
95 /// redelivery gets a fresh GUID and signature. Keep this list in step with `WORKER_HEADERS` in86 /// redelivery gets a fresh GUID and signature. Keep this list in step with `WORKER_HEADERS` in
96 /// forge-web's webhook worker.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 /// JSON array of event names, in the order given.106 /// JSON array of event names, in the order given.
124 fn events_json(events: &[WebhookEvent]) -> String {107 fn events_json(events: &[WebhookEvent]) -> String {
125 let names: Vec<&str> = events.iter().map(|e| e.as_str()).collect();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 Ok(())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 /// Most webhooks one repository can have.187 /// Most webhooks one repository can have.
176 pub const MAX_WEBHOOKS: i64 = 20;188 pub const MAX_WEBHOOKS: i64 = 20;
177 189
@@ -214,7 +226,7 @@ impl Store {
214 "SELECT COUNT(*) FROM webhooks WHERE repo_id = ?1",226 "SELECT COUNT(*) FROM webhooks WHERE repo_id = ?1",
215 repo_id,227 repo_id,
216 MAX_WEBHOOKS,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 .await?;231 .await?;
220 conn.execute(232 conn.execute(
@@ -240,37 +252,21 @@ impl Store {
240 let now = now_stamp();252 let now = now_stamp();
241 {253 {
242 let conn = self.inner.conn.lock().await;254 let conn = self.inner.conn.lock().await;
243- let n = match secret_sealed {255+ let sealed = secret_sealed.map_or(Value::Null, |s| Value::Blob(s.to_vec()));
244- Some(sealed) => {256+ let n = conn
245- conn.execute(257+ .execute(
246- "UPDATE webhooks SET url = ?2, secret_sealed = ?3, events = ?4, \258+ "UPDATE webhooks SET url = ?2, secret_sealed = COALESCE(?3, secret_sealed), \
247- active = ?5, updated_at = ?6 WHERE id = ?1",259+ events = ?4, 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![260 vec![
264 Value::Text(id.to_string()),261 Value::Text(id.to_string()),
265 Value::Text(url.to_string()),262 Value::Text(url.to_string()),
263+ sealed,
266 Value::Text(events_json(events)),264 Value::Text(events_json(events)),
267 Value::Integer(i64::from(active)),265 Value::Integer(i64::from(active)),
268 Value::Text(now),266 Value::Text(now),
269 ],267 ],
270 )268 )
271 .await269 .await
272- }
273- }
274 .map_err(db_err)?;270 .map_err(db_err)?;
275 if n == 0 {271 if n == 0 {
276 return Err(Error::NotFound);272 return Err(Error::NotFound);
@@ -391,26 +387,13 @@ impl Store {
391 headers_json: &str,387 headers_json: &str,
392 body: &str,388 body: &str,
393 ) -> Result<Delivery> {389 ) -> Result<Delivery> {
394- let now = now_stamp();390+ let delivery = pending_delivery(
395- let delivery = Delivery {391+ hook_id,
396- id: new_id(),
397- hook_id: hook_id.to_string(),
398- guid: new_guid(),
399 event,392 event,
400- action: action.to_string(),393+ action.to_string(),
401- request_headers: headers_json.to_string(),394+ headers_json.to_string(),
402- request_body: body.to_string(),395+ body.to_string(),
403- state: DeliveryState::Pending,396+ );
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- };
414 let conn = self.inner.conn.lock().await;397 let conn = self.inner.conn.lock().await;
415 insert_delivery(&conn, &delivery).await?;398 insert_delivery(&conn, &delivery).await?;
416 Ok(delivery)399 Ok(delivery)
@@ -570,27 +553,13 @@ impl Store {
570 )553 )
571 .await?554 .await?
572 .ok_or(Error::NotFound)?;555 .ok_or(Error::NotFound)?;
573- let guid = new_guid();556+ let copy = pending_delivery(
574- let now = now_stamp();557+ &original.hook_id,
575- let copy = Delivery {558+ original.event,
576- id: new_id(),559+ original.action,
577- hook_id: original.hook_id,560+ strip_worker_headers(&original.request_headers),
578- guid: guid.clone(),561+ original.request_body,
579- event: original.event,562+ );
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- };
594 insert_delivery(&conn, &copy).await?;563 insert_delivery(&conn, &copy).await?;
595 Ok(copy)564 Ok(copy)
596 }565 }
crates/forge-core/src/suggestions.rsmodified+2 -1
@@ -99,7 +99,7 @@ pub fn replace_line(
99 let replacement: Vec<&str> = replacement.iter().map(String::as_str).collect();99 let replacement: Vec<&str> = replacement.iter().map(String::as_str).collect();
100 lines.splice(index..=index, replacement);100 lines.splice(index..=index, replacement);
101 let mut out = lines.join("\n");101 let mut out = lines.join("\n");
102- if ends_with_newline {102+ if ends_with_newline && !lines.is_empty() {
103 out.push('\n');103 out.push('\n');
104 }104 }
105 Ok(out)105 Ok(out)
@@ -168,6 +168,7 @@ mod tests {
168 ("a\nb\nc\n", 2, "b", &["B"], Ok("a\nB\nc\n")),168 ("a\nb\nc\n", 2, "b", &["B"], Ok("a\nB\nc\n")),
169 ("a\nb", 2, "b", &["b1", "b2"], Ok("a\nb1\nb2")),169 ("a\nb", 2, "b", &["b1", "b2"], Ok("a\nb1\nb2")),
170 ("a\nb\nc\n", 2, "b", &[], Ok("a\nc\n")),170 ("a\nb\nc\n", 2, "b", &[], Ok("a\nc\n")),
171+ ("a\n", 1, "a", &[], Ok("")),
171 ("a\nb\n", 2, "old", &["x"], Err(ApplyError::Changed)),172 ("a\nb\n", 2, "old", &["x"], Err(ApplyError::Changed)),
172 ("a\nb\n", 3, "b", &["x"], Err(ApplyError::OutOfRange)),173 ("a\nb\n", 3, "b", &["x"], Err(ApplyError::OutOfRange)),
173 ("a\n", 0, "a", &["x"], Err(ApplyError::OutOfRange)),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 format_stamp(OffsetDateTime::now_utc().saturating_add(delta))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 /// The stamp for `now - ago`, in the same format as [`now_stamp`]. Saturates at the minimum29 /// The stamp for `now - ago`, in the same format as [`now_stamp`]. Saturates at the minimum
37 /// representable time instead of panicking.30 /// representable time instead of panicking.
38 pub fn stamp_ago(ago: Duration) -> String {31 pub fn stamp_ago(ago: Duration) -> String {
@@ -75,6 +68,7 @@ mod tests {
75 #[test]68 #[test]
76 fn stamps_sort_lexicographically_in_time_order() {69 fn stamps_sort_lexicographically_in_time_order() {
77 let a = now_stamp();70 let a = now_stamp();
71+ assert!(is_valid_stamp(&a), "bad stamp: {a}");
78 let b = stamp_after(Duration::from_secs(3600));72 let b = stamp_after(Duration::from_secs(3600));
79 assert!(is_valid_stamp(&b), "bad stamp: {b}");73 assert!(is_valid_stamp(&b), "bad stamp: {b}");
80 assert!(a < b);74 assert!(a < b);
crates/forge-core/src/token.rsmodified+5 -1
@@ -26,8 +26,12 @@ pub fn random_readable(len: usize) -> String {
26 .collect()26 .collect()
27 }27 }
28 28
29+pub fn random_b64url() -> String {
30+ BASE64_URL_SAFE_NO_PAD.encode(random_32())
31+}
32+
29 pub fn generate_token() -> String {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 /// Hex-encoded sha256 of the token.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 1101 1
102 );102 );
103 103
104- // Bob is involved in three entries: his own key, the reset of him, and nothing else.
105 let involving = AuditFilter {104 let involving = AuditFilter {
106 involving_user: Some(bob.id.clone()),105 involving_user: Some(bob.id.clone()),
107 ..Default::default()106 ..Default::default()
crates/forge-core/tests/integration/main.rsmodified+0 -2
@@ -1,9 +1,7 @@
1 //! Store integration tests for forge-core, built as one test binary.1 //! Store integration tests for forge-core, built as one test binary.
2 2
3-#[allow(dead_code)]
4 mod common;3 mod common;
5 4
6 mod audit_store;5 mod audit_store;
7-mod read_pool;
8 mod stars_store;6 mod stars_store;
9 mod store_basic;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 use forge_core::Visibility;1 use forge_core::Visibility;
4 use forge_core::store::RepoSort;2 use forge_core::store::RepoSort;
5 use forge_core::store::migrate::{MIGRATIONS, migrate};3 use forge_core::store::migrate::{MIGRATIONS, migrate};
@@ -22,19 +20,16 @@ async fn star_and_unstar_round_trip_with_count() {
22 20
23 assert_eq!(store.star_count(&repo.id).await.unwrap(), 0);21 assert_eq!(store.star_count(&repo.id).await.unwrap(), 0);
24 store.star(&bob.id, &repo.id).await.unwrap();22 store.star(&bob.id, &repo.id).await.unwrap();
25- store.star(&bob.id, &repo.id).await.unwrap(); // second star is a no-op23+ store.star(&bob.id, &repo.id).await.unwrap();
26 store.star(&tahinli.id, &repo.id).await.unwrap();24 store.star(&tahinli.id, &repo.id).await.unwrap();
27 assert_eq!(store.star_count(&repo.id).await.unwrap(), 2);25 assert_eq!(store.star_count(&repo.id).await.unwrap(), 2);
28 assert!(store.is_starred(&bob.id, &repo.id).await.unwrap());26 assert!(store.is_starred(&bob.id, &repo.id).await.unwrap());
29 27
30 store.unstar(&bob.id, &repo.id).await.unwrap();28 store.unstar(&bob.id, &repo.id).await.unwrap();
31- store.unstar(&bob.id, &repo.id).await.unwrap(); // removing twice is fine29+ store.unstar(&bob.id, &repo.id).await.unwrap();
32 assert!(!store.is_starred(&bob.id, &repo.id).await.unwrap());30 assert!(!store.is_starred(&bob.id, &repo.id).await.unwrap());
31+ assert!(store.is_starred(&tahinli.id, &repo.id).await.unwrap());
33 assert_eq!(store.star_count(&repo.id).await.unwrap(), 1);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 #[tokio::test]35 #[tokio::test]
@@ -53,7 +48,7 @@ async fn delete_repo_removes_its_stars() {
53 48
54 store.delete_repo(&repo.id).await.unwrap();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 assert_eq!(store.star_count(&repo.id).await.unwrap(), 0);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 let names: Vec<&str> = all.iter().map(|(r, _, _)| r.name.as_str()).collect();91 let names: Vec<&str> = all.iter().map(|(r, _, _)| r.name.as_str()).collect();
97 assert_eq!(names, vec!["100%_done", "other", "tools"]);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 let (hits, total) = store94 let (hits, total) = store
101 .list_public_repos(Some("%"), RepoSort::Name, 1, 30)95 .list_public_repos(Some("%"), RepoSort::Name, 1, 30)
102 .await96 .await
@@ -108,14 +102,12 @@ async fn public_listing_hides_private_repos_and_matches_literally() {
108 .await102 .await
109 .unwrap();103 .unwrap();
110 assert_eq!(hits.len(), 1);104 assert_eq!(hits.len(), 1);
111- // A backslash matches a literal backslash in the description.
112 let (hits, _) = store105 let (hits, _) = store
113 .list_public_repos(Some("\\"), RepoSort::Name, 1, 30)106 .list_public_repos(Some("\\"), RepoSort::Name, 1, 30)
114 .await107 .await
115 .unwrap();108 .unwrap();
116 assert_eq!(hits.len(), 1);109 assert_eq!(hits.len(), 1);
117 assert_eq!(hits[0].0.name, "other");110 assert_eq!(hits[0].0.name, "other");
118- // Private repos never match, even by exact name.
119 let (hits, _) = store111 let (hits, _) = store
120 .list_public_repos(Some("secret"), RepoSort::Name, 1, 30)112 .list_public_repos(Some("secret"), RepoSort::Name, 1, 30)
121 .await113 .await
@@ -179,7 +171,6 @@ async fn recently_updated_uses_latest_push_over_creation() {
179 .create_repo(&tahinli.id, "newer", "", Visibility::Public, "main")171 .create_repo(&tahinli.id, "newer", "", Visibility::Public, "main")
180 .await172 .await
181 .unwrap();173 .unwrap();
182- // Only "older" gets a push, so it is the most recently updated.
183 store174 store
184 .record_push_event(&older.id, &tahinli.id, "refs/heads/main", "0", "1", "https")175 .record_push_event(&older.id, &tahinli.id, "refs/heads/main", "0", "1", "https")
185 .await176 .await
@@ -240,7 +231,6 @@ async fn database_at_0004_gains_stars_table() {
240 )231 )
241 .await232 .await
242 .unwrap();233 .unwrap();
243- // Store::open turns foreign keys on; this raw connection must do it too.
244 conn.execute_batch("PRAGMA foreign_keys = ON")234 conn.execute_batch("PRAGMA foreign_keys = ON")
245 .await235 .await
246 .unwrap();236 .unwrap();
crates/forge-core/tests/integration/store_basic.rsmodified+4 -20
@@ -1,6 +1,6 @@
1 //! Store round-trip tests against a real turso database file in a temp directory.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 use forge_core::{Error, Role, Visibility};4 use forge_core::{Error, Role, Visibility};
5 use std::time::Duration;5 use std::time::Duration;
6 6
@@ -117,14 +117,12 @@ async fn sessions_respect_expiry() {
117 &user.id,117 &user.id,
118 "hash-dead",118 "hash-dead",
119 "csrf-dead",119 "csrf-dead",
120- &stamp_after(Duration::from_secs(0)),120+ &stamp_ago(Duration::from_secs(1)),
121 None,121 None,
122 None,122 None,
123 )123 )
124 .await124 .await
125 .unwrap();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 let found = store127 let found = store
130 .session_by_token_hash("hash-live")128 .session_by_token_hash("hash-live")
@@ -186,10 +184,7 @@ async fn ssh_key_exact_blob_lookup() {
186 .await184 .await
187 .unwrap();185 .unwrap();
188 186
189- let blob: Vec<u8> = vec![187+ let blob = b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20\x01\x02\x03".to_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- ];
193 let key = store188 let key = store
194 .add_ssh_key(&user.id, "laptop", "ssh-ed25519", &blob, "SHA256:abc")189 .add_ssh_key(&user.id, "laptop", "ssh-ed25519", &blob, "SHA256:abc")
195 .await190 .await
@@ -257,11 +252,10 @@ async fn access_token_create_lookup_and_expiry() {
257 "old",252 "old",
258 "tok-old",253 "tok-old",
259 &[],254 &[],
260- Some(&stamp_after(Duration::from_secs(0))),255+ Some(&stamp_ago(Duration::from_secs(1))),
261 )256 )
262 .await257 .await
263 .unwrap();258 .unwrap();
264- tokio::time::sleep(Duration::from_millis(5)).await;
265 259
266 let found = store260 let found = store
267 .token_by_hash("tok-live")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 #[tokio::test]484 #[tokio::test]
501 async fn create_first_admin_only_inserts_into_empty_table() {485 async fn create_first_admin_only_inserts_into_empty_table() {
502 let dir = tempfile::tempdir().unwrap();486 let dir = tempfile::tempdir().unwrap();
crates/forge-git/src/backup.rsmodified+8 -14
@@ -8,7 +8,7 @@ use sha2::{Digest, Sha256};
8 use crate::command::{GitCommand, GitEnv};8 use crate::command::{GitCommand, GitEnv};
9 use crate::error::{Error, Result};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 fn path_str(p: &Path) -> Result<&str> {13 fn path_str(p: &Path) -> Result<&str> {
14 p.to_str()14 p.to_str()
@@ -48,11 +48,11 @@ pub fn refs_checksum_of_listing(listing: &[u8]) -> String {
48 hex::encode(hasher.finalize())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 /// without writing anything when the repo has no refs, because git refuses to create an empty52 /// 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 /// The written file is set to mode 0600.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 if std::fs::symlink_metadata(out).is_ok() {56 if std::fs::symlink_metadata(out).is_ok() {
57 return Err(Error::InvalidInput(format!(57 return Err(Error::InvalidInput(format!(
58 "bundle target already exists: {}",58 "bundle target already exists: {}",
@@ -64,7 +64,7 @@ pub async fn bundle_create(env: &GitEnv, repo: &Path, out: &Path) -> Result<Opti
64 .iter()64 .iter()
65 .all(|b| b.is_ascii_whitespace())65 .all(|b| b.is_ascii_whitespace())
66 {66 {
67- return Ok(None);67+ return Ok(false);
68 }68 }
69 GitCommand::new(env, "bundle")69 GitCommand::new(env, "bundle")
70 .git_dir(repo)70 .git_dir(repo)
@@ -74,7 +74,7 @@ pub async fn bundle_create(env: &GitEnv, repo: &Path, out: &Path) -> Result<Opti
74 .status()74 .status()
75 .await?;75 .await?;
76 set_private_mode(out)?;76 set_private_mode(out)?;
77- Ok(Some(()))77+ Ok(true)
78 }78 }
79 79
80 fn set_private_mode(path: &Path) -> Result<()> {80 fn set_private_mode(path: &Path) -> Result<()> {
@@ -163,10 +163,7 @@ mod tests {
163 .await163 .await
164 .expect("init");164 .expect("init");
165 let out = dir.path().join("empty.bundle");165 let out = dir.path().join("empty.bundle");
166- assert_eq!(166+ assert!(!bundle_create(&env, &bare, &out).await.expect("create"));
167- bundle_create(&env, &bare, &out).await.expect("create"),
168- None
169- );
170 assert!(!out.exists(), "nothing is written for an empty repo");167 assert!(!out.exists(), "nothing is written for an empty repo");
171 assert_eq!(168 assert_eq!(
172 refs_checksum(&env, &bare).await.expect("checksum"),169 refs_checksum(&env, &bare).await.expect("checksum"),
@@ -180,10 +177,7 @@ mod tests {
180 let env = env(dir.path());177 let env = env(dir.path());
181 let git_dir = repo_with_refs(dir.path());178 let git_dir = repo_with_refs(dir.path());
182 let out = dir.path().join("r.bundle");179 let out = dir.path().join("r.bundle");
183- assert_eq!(180+ assert!(bundle_create(&env, &git_dir, &out).await.expect("create"));
184- bundle_create(&env, &git_dir, &out).await.expect("create"),
185- Some(())
186- );
187 let scratch = dir.path().join("scratch.git");181 let scratch = dir.path().join("scratch.git");
188 crate::repo::init_bare(&env, &scratch, "main")182 crate::repo::init_bare(&env, &scratch, "main")
189 .await183 .await
crates/forge-git/src/blame.rsmodified+1 -3
@@ -41,9 +41,7 @@ pub struct Blame {
41 fn is_header(line: &str) -> Option<(&str, u32)> {41 fn is_header(line: &str) -> Option<(&str, u32)> {
42 let mut parts = line.split(' ');42 let mut parts = line.split(' ');
43 let oid = parts.next()?;43 let oid = parts.next()?;
44- if !(oid.len() == 40 || oid.len() == 64) || !oid.bytes().all(|b| b.is_ascii_hexdigit()) {44+ validate_oid(oid).ok()?;
45- return None;
46- }
47 let _orig = parts.next()?.parse::<u32>().ok()?;45 let _orig = parts.next()?.parse::<u32>().ok()?;
48 let fin = parts.next()?.parse::<u32>().ok()?;46 let fin = parts.next()?.parse::<u32>().ok()?;
49 Some((oid, fin))47 Some((oid, fin))
crates/forge-git/src/branches.rsmodified+1 -5
@@ -4,7 +4,7 @@ use std::path::Path;
4 4
5 use crate::command::GitEnv;5 use crate::command::GitEnv;
6 use crate::error::{Error, Result};6 use crate::error::{Error, Result};
7-use crate::history::{git, validate_oid};7+use crate::history::{git, validate_oid, zero_oid};
8 use crate::pulls::{delete_ref_cas, update_ref_cas};8 use crate::pulls::{delete_ref_cas, update_ref_cas};
9 9
10 /// `(ahead, behind)` of `tip` relative to `base`: commits only in `tip`, and commits only in `base`.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 /// Creates `refs/heads/<name>` at `oid`. Fails when the branch exists already.34 /// Creates `refs/heads/<name>` at `oid`. Fails when the branch exists already.
39 pub async fn create_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> {35 pub async fn create_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> {
40 validate_oid(oid)?;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 /// Tree object for `commit` at `path` ("" is the root). Ok(None) if the commit is missing or the363 /// Tree object for `commit` at `path` ("" is the root). Ok(None) if the commit is missing or the
354 /// path does not exist. A path that is a blob also yields None.364 /// path does not exist. A path that is a blob also yields None.
355 fn tree_at<'r>(365 fn tree_at<'r>(
@@ -357,15 +367,12 @@ fn tree_at<'r>(
357 commit: &str,367 commit: &str,
358 path: &str,368 path: &str,
359 ) -> Result<Option<gix::Tree<'r>>> {369 ) -> Result<Option<gix::Tree<'r>>> {
360- let id = parse_oid(commit)?;370+ let Some(mut root) = commit_root(repo, commit)? else {
361- if !is_commit(repo, id)? {
362 return Ok(None);371 return Ok(None);
363- }372+ };
364- let root = repo.find_commit(id).map_err(gerr)?.tree().map_err(gerr)?;
365 if path.is_empty() {373 if path.is_empty() {
366 return Ok(Some(root));374 return Ok(Some(root));
367 }375 }
368- let mut root = root;
369 let Some(entry) = root.peel_to_entry_by_path(path).map_err(gerr)? else {376 let Some(entry) = root.peel_to_entry_by_path(path).map_err(gerr)? else {
370 return Ok(None);377 return Ok(None);
371 };378 };
@@ -439,11 +446,9 @@ fn blob_at(
439 return Ok(None);446 return Ok(None);
440 }447 }
441 let repo = open(repo)?;448 let repo = open(repo)?;
442- let id = parse_oid(commit)?;449+ let Some(mut root) = commit_root(&repo, commit)? else {
443- if !is_commit(&repo, id)? {
444 return Ok(None);450 return Ok(None);
445- }451+ };
446- let mut root = repo.find_commit(id).map_err(gerr)?.tree().map_err(gerr)?;
447 let Some(entry) = root.peel_to_entry_by_path(path).map_err(gerr)? else {452 let Some(entry) = root.peel_to_entry_by_path(path).map_err(gerr)? else {
448 return Ok(None);453 return Ok(None);
449 };454 };
@@ -496,7 +501,7 @@ pub fn read_text_blob(
496 let Some(blob) = blob_at(repo, commit, path, max_bytes, true)? else {501 let Some(blob) = blob_at(repo, commit, path, max_bytes, true)? else {
497 return Ok(None);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 return Ok(None);505 return Ok(None);
501 }506 }
502 Ok(String::from_utf8(blob.data).ok())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 fn check_status(subcommand: &str, out: &Output) -> Result<()> {267 fn check_status(subcommand: &str, out: &Output) -> Result<()> {
260 if out.status.success() {268 if out.status.success() {
261 return Ok(());269 return Ok(());
262 }270 }
263- let stderr = String::from_utf8_lossy(&out.stderr);271+ Err(failed(subcommand, out))
264- Err(Error::Failed(format!(
265- "git {subcommand} exited with {}: {}",
266- out.status,
267- stderr.trim()
268- )))
269 }272 }
270 273
271 #[cfg(test)]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 use std::collections::{HashMap, HashSet};1 use std::collections::{HashMap, HashSet};
5 use std::path::Path;2 use std::path::Path;
6 use std::process::Stdio;3 use std::process::Stdio;
@@ -11,16 +8,13 @@ use crate::browse::{self, CommitInfo};
11 use crate::command::{GitCommand, GitEnv, ObjectSource};8 use crate::command::{GitCommand, GitEnv, ObjectSource};
12 use crate::error::{Error, Result};9 use crate::error::{Error, Result};
13 10
14-/// Byte cap on any single git output stream read by this module.
15 const OUTPUT_CAP: usize = 20 * 1024 * 1024;11 const OUTPUT_CAP: usize = 20 * 1024 * 1024;
16 const EMPTY_TREE_SHA1: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";12 const EMPTY_TREE_SHA1: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
17 const EMPTY_TREE_SHA256: &str = "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321";13 const EMPTY_TREE_SHA256: &str = "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321";
18 14
19-/// Record start (`%x1e`), field separator (`%x1f`), end of fields (`%x1d`).
20 const REC: u8 = 0x1e;15 const REC: u8 = 0x1e;
21 const FIELD: u8 = 0x1f;16 const FIELD: u8 = 0x1f;
22 const END: u8 = 0x1d;17 const END: u8 = 0x1d;
23-/// Commit fields: oid, parents, author name/email/time, committer name/email/time, summary, message.
24 const COMMIT_FORMAT: &str =18 const COMMIT_FORMAT: &str =
25 "--format=%x1e%H%x1f%P%x1f%an%x1f%ae%x1f%at%x1f%cn%x1f%ce%x1f%ct%x1f%s%x1f%B%x1d";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 pub truncated_files: bool,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 pub(crate) fn git(env: &GitEnv, subcommand: &'static str) -> GitCommand {84 pub(crate) fn git(env: &GitEnv, subcommand: &'static str) -> GitCommand {
93 GitCommand::new(env, subcommand)85 GitCommand::new(env, subcommand)
94 .env("GIT_CONFIG_COUNT", "1")86 .env("GIT_CONFIG_COUNT", "1")
@@ -96,7 +88,6 @@ pub(crate) fn git(env: &GitEnv, subcommand: &'static str) -> GitCommand {
96 .env("GIT_CONFIG_VALUE_0", "false")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 pub(crate) fn validate_oid(oid: &str) -> Result<()> {91 pub(crate) fn validate_oid(oid: &str) -> Result<()> {
101 let len_ok = oid.len() == 40 || oid.len() == 64;92 let len_ok = oid.len() == 40 || oid.len() == 64;
102 if len_ok && oid.bytes().all(|b| b.is_ascii_hexdigit()) {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 fn literal_spec(path: &str) -> String {106 fn literal_spec(path: &str) -> String {
113 format!(":(literal){path}")107 format!(":(literal){path}")
114 }108 }
115 109
116-/// Accepts `[A-Za-z0-9._-]+`, excluding `.` and `..` and a leading `-`.
117 fn validate_prefix(prefix: &str) -> Result<()> {110 fn validate_prefix(prefix: &str) -> Result<()> {
118 let charset_ok = !prefix.is_empty()111 let charset_ok = !prefix.is_empty()
119 && prefix112 && prefix
@@ -127,11 +120,8 @@ fn validate_prefix(prefix: &str) -> Result<()> {
127 Ok(())120 Ok(())
128 }121 }
129 122
130-/// Longest kept head of a child's output pipe, in bytes.
131 const PIPE_HEAD_CAP: u64 = 64 * 1024;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 pub(crate) async fn read_pipe_head(mut pipe: impl AsyncRead + Unpin) -> Vec<u8> {125 pub(crate) async fn read_pipe_head(mut pipe: impl AsyncRead + Unpin) -> Vec<u8> {
136 let mut kept = Vec::new();126 let mut kept = Vec::new();
137 let _ = (&mut pipe).take(PIPE_HEAD_CAP).read_to_end(&mut kept).await;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 kept129 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 async fn for_each_chunk(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Result<bool> {132 async fn for_each_chunk(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Result<bool> {
146 let mut command = cmd.into_tokio();133 let mut command = cmd.into_tokio();
147 command.stdout(Stdio::piped()).stderr(Stdio::piped());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 Ok(eof)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 pub(crate) async fn read_capped(cmd: GitCommand) -> Result<(Vec<u8>, bool)> {176 pub(crate) async fn read_capped(cmd: GitCommand) -> Result<(Vec<u8>, bool)> {
191 let mut buf = Vec::new();177 let mut buf = Vec::new();
192 let complete = for_each_chunk(cmd, |c| {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 Ok((buf, complete))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 async fn for_each_nul_record(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Result<bool> {186 async fn for_each_nul_record(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Result<bool> {
204 let mut carry = Vec::new();187 let mut carry = Vec::new();
205 for_each_chunk(cmd, |chunk| {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 .await202 .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 fn parse_record(rec: &[u8]) -> Option<(CommitInfo, &[u8])> {205 fn parse_record(rec: &[u8]) -> Option<(CommitInfo, &[u8])> {
225 let end = rec.iter().position(|&b| b == END)?;206 let end = rec.iter().position(|&b| b == END)?;
226 let fields = &rec[..end];207 let fields = &rec[..end];
@@ -260,7 +241,6 @@ fn parse_record(rec: &[u8]) -> Option<(CommitInfo, &[u8])> {
260 Some((info, rest))241 Some((info, rest))
261 }242 }
262 243
263-/// Commit history for `commit`, optionally limited to `path`, newest first.
264 pub async fn log(244 pub async fn log(
265 env: &GitEnv,245 env: &GitEnv,
266 repo: &Path,246 repo: &Path,
@@ -291,8 +271,6 @@ pub async fn log(
291 .collect())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 pub async fn count(env: &GitEnv, repo: &Path, commit: &str, path: Option<&str>) -> Result<u64> {274 pub async fn count(env: &GitEnv, repo: &Path, commit: &str, path: Option<&str>) -> Result<u64> {
297 validate_oid(commit)?;275 validate_oid(commit)?;
298 let mut cmd = git(env, "rev-list")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 .map_err(|_| Error::Failed(format!("unexpected rev-list count: {:?}", text.trim())))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 pub async fn new_commits(292 pub async fn new_commits(
318 env: &GitEnv,293 env: &GitEnv,
319 repo: &Path,294 repo: &Path,
@@ -324,7 +299,6 @@ pub async fn new_commits(
324 new_commits_with(env, repo, ObjectSource::default(), old, new, max).await299 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 pub async fn new_commits_with(302 pub async fn new_commits_with(
329 env: &GitEnv,303 env: &GitEnv,
330 repo: &Path,304 repo: &Path,
@@ -363,11 +337,11 @@ pub async fn new_commits_with(
363 Ok(commits)337 Ok(commits)
364 }338 }
365 339
366-/// Which `diff-tree` output a command produces.
367 #[derive(Clone, Copy)]340 #[derive(Clone, Copy)]
368 enum DiffMode {341 enum DiffMode {
369 NameStatus,342 NameStatus,
370 Patch,343 Patch,
344+ Raw,
371 }345 }
372 346
373 fn diff_tree_cmd(347 fn diff_tree_cmd(
@@ -387,12 +361,11 @@ fn diff_tree_cmd(
387 .arg("--no-color")361 .arg("--no-color")
388 .arg("--no-ext-diff")362 .arg("--no-ext-diff")
389 .arg("--no-textconv");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 let cmd = if ignore_ws { cmd.arg("-w") } else { cmd };364 let cmd = if ignore_ws { cmd.arg("-w") } else { cmd };
393 let cmd = match mode {365 let cmd = match mode {
394 DiffMode::NameStatus => cmd.arg("-z").arg("--name-status"),366 DiffMode::NameStatus => cmd.arg("-z").arg("--name-status"),
395 DiffMode::Patch => cmd.arg("-p").arg("--full-index"),367 DiffMode::Patch => cmd.arg("-p").arg("--full-index"),
368+ DiffMode::Raw => cmd.arg("-p").arg("--binary"),
396 };369 };
397 cmd.objects(src)?.user_revs(&[base, oid])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 async fn first_parent(env: &GitEnv, repo: &Path, oid: &str) -> Result<Option<String>> {381 async fn first_parent(env: &GitEnv, repo: &Path, oid: &str) -> Result<Option<String>> {
410 let out = git(env, "rev-list")382 let out = git(env, "rev-list")
411 .git_dir(repo)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 struct NameEntry {401 struct NameEntry {
431 status: DiffStatus,402 status: DiffStatus,
432 old_path: Option<String>,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 fn parse_name_status(buf: &[u8]) -> Vec<NameEntry> {418 fn parse_name_status(buf: &[u8]) -> Vec<NameEntry> {
449 let text = |p: &[u8]| String::from_utf8_lossy(p).into_owned();419 let text = |p: &[u8]| String::from_utf8_lossy(p).into_owned();
450 let mut out = Vec::new();420 let mut out = Vec::new();
@@ -478,7 +448,6 @@ fn parse_name_status(buf: &[u8]) -> Vec<NameEntry> {
478 out448 out
479 }449 }
480 450
481-/// Byte offsets where `diff --git` headers start at the beginning of a line.
482 fn block_starts(text: &str) -> Vec<usize> {451 fn block_starts(text: &str) -> Vec<usize> {
483 text.match_indices("diff --git ")452 text.match_indices("diff --git ")
484 .map(|(i, _)| i)453 .map(|(i, _)| i)
@@ -486,7 +455,6 @@ fn block_starts(text: &str) -> Vec<usize> {
486 .collect()455 .collect()
487 }456 }
488 457
489-/// `@@ -a[,b] +c[,d] @@` to the old and new start line numbers.
490 fn parse_hunk_start(line: &str) -> (u32, u32) {458 fn parse_hunk_start(line: &str) -> (u32, u32) {
491 let mut parts = line.split_whitespace().skip(1);459 let mut parts = line.split_whitespace().skip(1);
492 let start = |p: Option<&str>, sign: char| {460 let start = |p: Option<&str>, sign: char| {
@@ -500,7 +468,6 @@ fn parse_hunk_start(line: &str) -> (u32, u32) {
500 (old, new)468 (old, new)
501 }469 }
502 470
503-/// Totals and hunks of one file's section of the patch.
504 #[derive(Default)]471 #[derive(Default)]
505 struct BlockOut {472 struct BlockOut {
506 is_binary: bool,473 is_binary: bool,
@@ -510,8 +477,6 @@ struct BlockOut {
510 truncated: bool,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 fn parse_block(block: &str, limits: &DiffLimits, total_left: &mut usize) -> BlockOut {480 fn parse_block(block: &str, limits: &DiffLimits, total_left: &mut usize) -> BlockOut {
516 let mut out = BlockOut::default();481 let mut out = BlockOut::default();
517 let mut file_lines = 0usize;482 let mut file_lines = 0usize;
@@ -589,9 +554,6 @@ fn parse_block(block: &str, limits: &DiffLimits, total_left: &mut usize) -> Bloc
589 out554 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 pub async fn commit_diff(557 pub async fn commit_diff(
596 env: &GitEnv,558 env: &GitEnv,
597 repo: &Path,559 repo: &Path,
@@ -601,7 +563,6 @@ pub async fn commit_diff(
601 commit_diff_ws(env, repo, oid, limits, false).await563 commit_diff_ws(env, repo, oid, limits, false).await
602 }564 }
603 565
604-/// [`commit_diff`], optionally ignoring whitespace changes (`git diff -w`).
605 pub async fn commit_diff_ws(566 pub async fn commit_diff_ws(
606 env: &GitEnv,567 env: &GitEnv,
607 repo: &Path,568 repo: &Path,
@@ -626,8 +587,6 @@ pub async fn commit_diff_ws(
626 .await587 .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 pub(crate) async fn diff_between(590 pub(crate) async fn diff_between(
632 env: &GitEnv,591 env: &GitEnv,
633 repo: &Path,592 repo: &Path,
@@ -672,16 +631,12 @@ pub(crate) async fn diff_between(
672 .await?;631 .await?;
673 let patch = String::from_utf8_lossy(&patch_buf);632 let patch = String::from_utf8_lossy(&patch_buf);
674 let starts = block_starts(&patch);633 let starts = block_starts(&patch);
675- // A capped patch may end inside its last section, so that section is dropped.
676 let usable = if patch_complete {634 let usable = if patch_complete {
677 starts.len()635 starts.len()
678 } else {636 } else {
679 starts.len().saturating_sub(1)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 let mut slots: Vec<usize> = (0..entries.len()).collect();640 let mut slots: Vec<usize> = (0..entries.len()).collect();
686 if ignore_ws && patch_complete && starts.len() != entries.len() {641 if ignore_ws && patch_complete && starts.len() != entries.len() {
687 let mut j = 0usize;642 let mut j = 0usize;
@@ -731,7 +686,6 @@ pub(crate) async fn diff_between(
731 });686 });
732 }687 }
733 if ignore_ws {688 if ignore_ws {
734- // Whatever git listed, a text file with no changed lines left is whitespace only.
735 files.retain(|f| {689 files.retain(|f| {
736 f.status != DiffStatus::Modified690 f.status != DiffStatus::Modified
737 || f.is_binary691 || 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 pub struct PatchOut {702 pub struct PatchOut {
750 pub data: Vec<u8>,703 pub data: Vec<u8>,
751 pub complete: bool,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 pub async fn commit_patch(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchOut> {707 pub async fn commit_patch(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchOut> {
757 validate_oid(oid)?;708 validate_oid(oid)?;
758 let cmd = git(env, "format-patch")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 Ok(PatchOut { data, complete })719 Ok(PatchOut { data, complete })
769 }720 }
770 721
771-/// Plain unified diff of one commit against its first parent (`/commit/{oid}.diff`).
772 pub async fn commit_raw_diff(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchOut> {722 pub async fn commit_raw_diff(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchOut> {
773 validate_oid(oid)?;723 validate_oid(oid)?;
774 let base = match first_parent(env, repo, oid).await? {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 raw_diff(env, repo, ObjectSource::default(), &base, oid).await728 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 pub async fn raw_diff(731 pub async fn raw_diff(
783 env: &GitEnv,732 env: &GitEnv,
784 repo: &Path,733 repo: &Path,
@@ -788,23 +737,11 @@ pub async fn raw_diff(
788 ) -> Result<PatchOut> {737 ) -> Result<PatchOut> {
789 validate_oid(base)?;738 validate_oid(base)?;
790 validate_oid(oid)?;739 validate_oid(oid)?;
791- let cmd = git(env, "diff-tree")740+ let cmd = diff_tree_cmd(env, repo, src, base, oid, DiffMode::Raw, false)?;
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])?;
803 let (data, complete) = read_capped(cmd).await?;741 let (data, complete) = read_capped(cmd).await?;
804 Ok(PatchOut { data, complete })742 Ok(PatchOut { data, complete })
805 }743 }
806 744
807-/// Mbox of the commits reachable from `head` but not from `base`, oldest first.
808 pub async fn range_patch(745 pub async fn range_patch(
809 env: &GitEnv,746 env: &GitEnv,
810 repo: &Path,747 repo: &Path,
@@ -827,8 +764,6 @@ pub async fn range_patch(
827 Ok(PatchOut { data, complete })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 pub async fn list_files(767 pub async fn list_files(
833 env: &GitEnv,768 env: &GitEnv,
834 repo: &Path,769 repo: &Path,
@@ -857,8 +792,6 @@ pub async fn list_files(
857 Ok((paths, cut || !complete))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 pub async fn list_file_sizes(795 pub async fn list_file_sizes(
863 env: &GitEnv,796 env: &GitEnv,
864 repo: &Path,797 repo: &Path,
@@ -876,7 +809,6 @@ pub async fn list_file_sizes(
876 let mut out = Vec::new();809 let mut out = Vec::new();
877 let mut cut = false;810 let mut cut = false;
878 let complete = for_each_nul_record(cmd, |rec| {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 let Some(tab) = rec.iter().position(|&b| b == b'\t') else {812 let Some(tab) = rec.iter().position(|&b| b == b'\t') else {
881 return true;813 return true;
882 };814 };
@@ -904,9 +836,6 @@ pub async fn list_file_sizes(
904 Ok((out, cut || !complete))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 pub async fn last_commits(839 pub async fn last_commits(
911 env: &GitEnv,840 env: &GitEnv,
912 repo: &Path,841 repo: &Path,
@@ -948,7 +877,6 @@ pub async fn last_commits(
948 let Some((info, files)) = parse_record(rec) else {877 let Some((info, files)) = parse_record(rec) else {
949 return true;878 return true;
950 };879 };
951- // `-z --name-only` puts a NUL and/or newline between the format and the names.
952 let start = files880 let start = files
953 .iter()881 .iter()
954 .position(|&b| b != 0 && b != b'\n')882 .position(|&b| b != 0 && b != b'\n')
@@ -997,7 +925,6 @@ pub async fn last_commits(
997 Ok(found)925 Ok(found)
998 }926 }
999 927
1000-/// `git archive` for `commit`, with every entry under `<prefix>/`. The caller streams stdout.
1001 pub fn archive_command(928 pub fn archive_command(
1002 env: &GitEnv,929 env: &GitEnv,
1003 repo: &Path,930 repo: &Path,
crates/forge-git/src/mirror.rsmodified+3 -1
@@ -223,7 +223,9 @@ async fn fetch(
223 let head = base_command(env, Some(repo), "ls-remote", auth, allow_http, pin, local)?223 let head = base_command(env, Some(repo), "ls-remote", auth, allow_http, pin, local)?
224 .arg("--symref")224 .arg("--symref")
225 .user_revs(&[url, "HEAD"])?;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 let listing = String::from_utf8_lossy(&listing);229 let listing = String::from_utf8_lossy(&listing);
228 let Some(default_ref) = remote_default_branch(&listing) else {230 let Some(default_ref) = remote_default_branch(&listing) else {
229 return Ok(());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 use std::path::Path;1 use std::path::Path;
6 use std::process::{Output, Stdio};2 use std::process::{Output, Stdio};
7 3
8 use tokio::io::AsyncWriteExt;4 use tokio::io::AsyncWriteExt;
9 5
10 use crate::browse::{CommitInfo, validate_repo_path};6 use crate::browse::{CommitInfo, validate_repo_path};
11-use crate::command::{GitCommand, GitEnv, ObjectSource};7+use crate::command::{GitCommand, GitEnv, ObjectSource, failed};
12 use crate::error::{Error, Result};8 use crate::error::{Error, Result};
13 use crate::history::{9 use crate::history::{
14 CommitDiff, DiffLimits, diff_between, empty_tree_for, git, new_commits_with, validate_oid,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 #[derive(Debug, Clone, PartialEq, Eq)]23 #[derive(Debug, Clone, PartialEq, Eq)]
19 pub enum MergeCheck {24 pub enum MergeCheck {
20- /// The merge would be clean; `tree` is the id of the resulting tree.
21 Clean { tree: String },25 Clean { tree: String },
22- /// The merge would conflict; `files` are the conflicted paths, deduplicated.
23 Conflict { files: Vec<String> },26 Conflict { files: Vec<String> },
24- /// The head is already contained in the base.
25 UpToDate,27 UpToDate,
26 }28 }
27 29
28-/// Author or committer identity for [`commit_tree`]. `time_unix` is written as `<unix> +0000`.
29 #[derive(Debug, Clone, PartialEq, Eq)]30 #[derive(Debug, Clone, PartialEq, Eq)]
30 pub struct Signature {31 pub struct Signature {
31 pub name: String,32 pub name: String,
@@ -33,7 +34,6 @@ pub struct Signature {
33 pub time_unix: i64,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 async fn run_raw(cmd: GitCommand, stdin: Option<&[u8]>) -> Result<Output> {37 async fn run_raw(cmd: GitCommand, stdin: Option<&[u8]>) -> Result<Output> {
38 let mut command = cmd.into_tokio();38 let mut command = cmd.into_tokio();
39 command.stdout(Stdio::piped()).stderr(Stdio::piped());39 command.stdout(Stdio::piped()).stderr(Stdio::piped());
@@ -43,24 +43,14 @@ async fn run_raw(cmd: GitCommand, stdin: Option<&[u8]>) -> Result<Output> {
43 let mut child = command.spawn()?;43 let mut child = command.spawn()?;
44 if let (Some(data), Some(mut pipe)) = (stdin, child.stdin.take()) {44 if let (Some(data), Some(mut pipe)) = (stdin, child.stdin.take()) {
45 pipe.write_all(data).await?;45 pipe.write_all(data).await?;
46- // `pipe` is dropped here, which closes git's stdin.
47 }46 }
48 Ok(child.wait_with_output().await?)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 fn stdout_trimmed(out: &Output) -> String {50 fn stdout_trimmed(out: &Output) -> String {
60 String::from_utf8_lossy(&out.stdout).trim().to_owned()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 fn validate_ref(refname: &str) -> Result<()> {54 fn validate_ref(refname: &str) -> Result<()> {
65 let heads_ok = refname55 let heads_ok = refname
66 .strip_prefix("refs/heads/")56 .strip_prefix("refs/heads/")
@@ -93,7 +83,6 @@ fn valid_branch_rest(rest: &str) -> bool {
93 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'-' | b'+'))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 fn validate_signature(sig: &Signature) -> Result<()> {86 fn validate_signature(sig: &Signature) -> Result<()> {
98 let bad = |s: &str| s.is_empty() || s.contains(['<', '>', '\n', '\0']);87 let bad = |s: &str| s.is_empty() || s.contains(['<', '>', '\n', '\0']);
99 if bad(&sig.name) || bad(&sig.email) {88 if bad(&sig.name) || bad(&sig.email) {
@@ -102,7 +91,6 @@ fn validate_signature(sig: &Signature) -> Result<()> {
102 Ok(())91 Ok(())
103 }92 }
104 93
105-/// True when both paths name the same repository (equal, or equal after canonicalization).
106 fn same_repo(a: &Path, b: &Path) -> bool {94 fn same_repo(a: &Path, b: &Path) -> bool {
107 if a == b {95 if a == b {
108 return true;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 async fn fetch_object(env: &GitEnv, base_repo: &Path, head_repo: &Path, oid: &str) -> Result<()> {104 async fn fetch_object(env: &GitEnv, base_repo: &Path, head_repo: &Path, oid: &str) -> Result<()> {
120 let head_path = head_repo105 let head_path = head_repo
121 .to_str()106 .to_str()
122 .ok_or_else(|| Error::InvalidInput("repo path is not valid UTF-8".into()))?;107 .ok_or_else(|| Error::InvalidInput("repo path is not valid UTF-8".into()))?;
123 let build = |allow_any: bool| -> Result<GitCommand> {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 let cmd = git(env, "fetch")109 let cmd = git(env, "fetch")
126 .allow_local_transport()110 .allow_local_transport()
127 .git_dir(base_repo)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 pub async fn fetch_into_pull_ref(130 pub async fn fetch_into_pull_ref(
149 env: &GitEnv,131 env: &GitEnv,
150 base_repo: &Path,132 base_repo: &Path,
@@ -171,13 +153,10 @@ pub async fn fetch_into_pull_ref(
171 .await153 .await
172 }154 }
173 155
174-/// Best common ancestor of `a` and `b`, or `None` when they share no history.
175 pub async fn merge_base(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<Option<String>> {156 pub async fn merge_base(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<Option<String>> {
176 merge_base_with(env, repo, ObjectSource::default(), a, b).await157 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 pub async fn merge_base_with(160 pub async fn merge_base_with(
182 env: &GitEnv,161 env: &GitEnv,
183 repo: &Path,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 pub async fn blob_at(185 pub async fn blob_at(
209 env: &GitEnv,186 env: &GitEnv,
210 repo: &Path,187 repo: &Path,
211 commit: &str,188 commit: &str,
212 path: &str,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 ) -> Result<Option<String>> {190 ) -> Result<Option<String>> {
226 validate_oid(commit)?;191 validate_oid(commit)?;
227 validate_blob_path(path)?;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 let spec = format!(":(literal){path}");193 let spec = format!(":(literal){path}");
232 let out = git(env, "ls-tree")194 let out = git(env, "ls-tree")
233 .git_dir(repo)195 .git_dir(repo)
234- .objects(src)?
235 .arg("-z")196 .arg("-z")
236 .arg("--full-tree")197 .arg("--full-tree")
237 .user_arg(commit)?198 .user_arg(commit)?
238 .paths(&[spec.as_str()])199 .paths(&[spec.as_str()])
239 .output()200 .output()
240 .await?;201 .await?;
241- // Pathspecs can match more than one entry, so keep only the exact path.
242 let entry = out.split(|&b| b == 0).find_map(|rec| {202 let entry = out.split(|&b| b == 0).find_map(|rec| {
243 let text = std::str::from_utf8(rec).ok()?;203 let text = std::str::from_utf8(rec).ok()?;
244 let (meta, name) = text.split_once('\t')?;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 fn validate_blob_path(path: &str) -> Result<()> {223 fn validate_blob_path(path: &str) -> Result<()> {
266 if path.is_empty() {224 if path.is_empty() {
267 return Err(Error::InvalidInput("empty path".into()));225 return Err(Error::InvalidInput("empty path".into()));
@@ -275,7 +233,6 @@ fn validate_blob_path(path: &str) -> Result<()> {
275 validate_repo_path(path)233 validate_repo_path(path)
276 }234 }
277 235
278-/// True when `a` is an ancestor of `b` (or equal to it).
279 pub async fn is_ancestor(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<bool> {236 pub async fn is_ancestor(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<bool> {
280 validate_oid(a)?;237 validate_oid(a)?;
281 validate_oid(b)?;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 pub async fn check_merge(251 pub async fn check_merge(
296 env: &GitEnv,252 env: &GitEnv,
297 repo: &Path,253 repo: &Path,
@@ -321,20 +277,14 @@ pub async fn check_merge(
321 let mut lines = text.lines();277 let mut lines = text.lines();
322 let tree = lines.next().unwrap_or_default().trim().to_owned();278 let tree = lines.next().unwrap_or_default().trim().to_owned();
323 validate_oid(&tree)?;279 validate_oid(&tree)?;
324- let mut files: Vec<String> = Vec::new();280+ Ok(MergeCheck::Conflict {
325- for line in lines.map(str::trim).filter(|l| !l.is_empty()) {281+ files: conflict_files(lines),
326- if !files.iter().any(|f| f == line) {282+ })
327- files.push(line.to_owned());
328- }
329- }
330- Ok(MergeCheck::Conflict { files })
331 }283 }
332 _ => Err(failed("merge-tree", &out)),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 pub async fn commit_tree(288 pub async fn commit_tree(
339 env: &GitEnv,289 env: &GitEnv,
340 repo: &Path,290 repo: &Path,
@@ -377,8 +327,6 @@ pub async fn commit_tree(
377 Ok(oid)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 pub async fn update_ref_cas(330 pub async fn update_ref_cas(
383 env: &GitEnv,331 env: &GitEnv,
384 repo: &Path,332 repo: &Path,
@@ -406,10 +354,7 @@ pub async fn update_ref_cas(
406 Err(failed("update-ref", &out))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 pub async fn set_ref(env: &GitEnv, repo: &Path, refname: &str, new: &str) -> Result<()> {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 let queue_ok = refname358 let queue_ok = refname
414 .strip_prefix("refs/forge/merge-queue/")359 .strip_prefix("refs/forge/merge-queue/")
415 .is_some_and(valid_branch_rest);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 Err(failed("update-ref", &out))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 pub async fn delete_ref_cas(env: &GitEnv, repo: &Path, refname: &str, old: &str) -> Result<()> {378 pub async fn delete_ref_cas(env: &GitEnv, repo: &Path, refname: &str, old: &str) -> Result<()> {
438 validate_ref(refname)?;379 validate_ref(refname)?;
439 validate_oid(old)?;380 validate_oid(old)?;
@@ -453,8 +394,6 @@ pub async fn delete_ref_cas(env: &GitEnv, repo: &Path, refname: &str, old: &str)
453 Err(failed("update-ref", &out))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 pub async fn range_diff_files(397 pub async fn range_diff_files(
459 env: &GitEnv,398 env: &GitEnv,
460 repo: &Path,399 repo: &Path,
@@ -462,30 +401,18 @@ pub async fn range_diff_files(
462 head_oid: &str,401 head_oid: &str,
463 limits: DiffLimits,402 limits: DiffLimits,
464 ) -> Result<CommitDiff> {403 ) -> Result<CommitDiff> {
465- range_diff_files_with(404+ range_diff_files_ws(
466 env,405 env,
467 repo,406 repo,
468 ObjectSource::default(),407 ObjectSource::default(),
469 base_oid,408 base_oid,
470 head_oid,409 head_oid,
471 limits,410 limits,
411+ false,
472 )412 )
473 .await413 .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 pub async fn range_diff_files_ws(416 pub async fn range_diff_files_ws(
490 env: &GitEnv,417 env: &GitEnv,
491 repo: &Path,418 repo: &Path,
@@ -504,8 +431,6 @@ pub async fn range_diff_files_ws(
504 diff_between(env, repo, src, &from, head_oid, limits, ignore_ws).await431 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 pub async fn range_log(434 pub async fn range_log(
510 env: &GitEnv,435 env: &GitEnv,
511 repo: &Path,436 repo: &Path,
@@ -516,7 +441,6 @@ pub async fn range_log(
516 range_log_with(env, repo, ObjectSource::default(), base_oid, head_oid, max).await441 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 pub async fn range_log_with(444 pub async fn range_log_with(
521 env: &GitEnv,445 env: &GitEnv,
522 repo: &Path,446 repo: &Path,
@@ -530,20 +454,12 @@ pub async fn range_log_with(
530 new_commits_with(env, repo, src, Some(base_oid), head_oid, max).await454 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 #[derive(Debug, Clone, PartialEq, Eq)]457 #[derive(Debug, Clone, PartialEq, Eq)]
535 pub enum RebaseResult {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 Clean { tip: String, count: usize },459 Clean { tip: String, count: usize },
539- /// A commit does not apply; `commit` is its id and `files` the conflicted paths.
540 Conflict { commit: String, files: Vec<String> },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 pub async fn rebase_commits(463 pub async fn rebase_commits(
548 env: &GitEnv,464 env: &GitEnv,
549 repo: &Path,465 repo: &Path,
@@ -609,18 +525,10 @@ pub async fn rebase_commits(
609 let tree = match out.status.code() {525 let tree = match out.status.code() {
610 Some(0) => text.lines().next().unwrap_or_default().trim().to_owned(),526 Some(0) => text.lines().next().unwrap_or_default().trim().to_owned(),
611 Some(1) => {527 Some(1) => {
612- let mut files: Vec<String> = Vec::new();528+ return Ok(RebaseResult::Conflict {
613- for line in text529+ commit,
614- .lines()530+ files: conflict_files(text.lines().skip(1)),
615- .skip(1)531+ });
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 });
624 }532 }
625 _ => return Err(failed("merge-tree", &out)),533 _ => return Err(failed("merge-tree", &out)),
626 };534 };
@@ -657,21 +565,14 @@ pub async fn rebase_commits(
657 Ok(RebaseResult::Clean { tip, count })565 Ok(RebaseResult::Clean { tip, count })
658 }566 }
659 567
660-/// One file of a commit made by [`commit_file_edit`].
661 #[derive(Debug, Clone, Copy)]568 #[derive(Debug, Clone, Copy)]
662 pub struct FileEdit<'a> {569 pub struct FileEdit<'a> {
663- /// Repo path of the file. It must be a regular file in the base commit.
664 pub path: &'a str,570 pub path: &'a str,
665- /// The new content of the file.
666 pub content: &'a [u8],571 pub content: &'a [u8],
667 }572 }
668 573
669 static EDIT_INDEX_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);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 #[allow(clippy::too_many_arguments)]576 #[allow(clippy::too_many_arguments)]
676 pub async fn commit_file_edit(577 pub async fn commit_file_edit(
677 env: &GitEnv,578 env: &GitEnv,
@@ -692,7 +593,6 @@ pub async fn commit_file_edit(
692 env, repo, &index, refname, base, edit, message, author, committer,593 env, repo, &index, refname, base, edit, message, author, committer,
693 )594 )
694 .await;595 .await;
695- // The index is scratch space. A leftover file is harmless, but do not keep it.
696 let _ = tokio::fs::remove_file(&index).await;596 let _ = tokio::fs::remove_file(&index).await;
697 result597 result
698 }598 }
@@ -725,15 +625,13 @@ async fn edit_and_commit(
725 .status()625 .status()
726 .await?;626 .await?;
727 627
728- // `ls-files -s` gives `<mode> <oid> <stage>\t<path>`. The path must be the file itself, and a628+ let spec = format!(":(literal){}", edit.path);
729- // regular file: a symlink or a submodule is not something a suggestion can rewrite.
730 let listing = GitCommand::new(env, "ls-files")629 let listing = GitCommand::new(env, "ls-files")
731 .git_dir(repo)630 .git_dir(repo)
732 .env("GIT_INDEX_FILE", index)631 .env("GIT_INDEX_FILE", index)
733 .arg("-s")632 .arg("-s")
734 .arg("-z")633 .arg("-z")
735- .arg("--")634+ .paths(&[spec.as_str()])
736- .user_arg(edit.path)?
737 .output()635 .output()
738 .await?;636 .await?;
739 let entry =637 let entry =
@@ -786,7 +684,6 @@ mod tests {
786 max_total_lines: 10_000,684 max_total_lines: 10_000,
787 };685 };
788 686
789- /// Runs git in `dir` with a cleared environment and fixed identities.
790 fn git_in(dir: &Path, home: &Path, args: &[&str]) -> String {687 fn git_in(dir: &Path, home: &Path, args: &[&str]) -> String {
791 let out = Command::new("/usr/bin/git")688 let out = Command::new("/usr/bin/git")
792 .arg("-C")689 .arg("-C")
@@ -818,8 +715,6 @@ mod tests {
818 }715 }
819 716
820 impl Sandbox {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 fn new() -> Self {718 fn new() -> Self {
824 let dir = tempfile::tempdir().expect("tempdir");719 let dir = tempfile::tempdir().expect("tempdir");
825 let home = dir.path().join("home");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 fn repo(&self, name: &str) -> Work {733 fn repo(&self, name: &str) -> Work {
840 let work = self._dir.path().join(name);734 let work = self._dir.path().join(name);
841 std::fs::create_dir(&work).expect("work dir");735 std::fs::create_dir(&work).expect("work dir");
@@ -865,7 +759,6 @@ mod tests {
865 std::fs::write(self.work.join(name), content).expect("write file");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 fn commit(&self, msg: &str) -> String {762 fn commit(&self, msg: &str) -> String {
870 self.git(&["add", "-A"]);763 self.git(&["add", "-A"]);
871 self.git(&["commit", "-q", "--allow-empty", "-m", msg]);764 self.git(&["commit", "-q", "--allow-empty", "-m", msg]);
@@ -1001,7 +894,6 @@ mod tests {
1001 let c2 = w.commit("c2");894 let c2 = w.commit("c2");
1002 let gd = w.git_dir();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 let stale = update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c0).await;897 let stale = update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c0).await;
1006 assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}");898 assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}");
1007 assert_eq!(w.git(&["rev-parse", "main"]), c2);899 assert_eq!(w.git(&["rev-parse", "main"]), c2);
@@ -1024,7 +916,6 @@ mod tests {
1024 let c1 = w.commit("c1");916 let c1 = w.commit("c1");
1025 let gd = w.git_dir();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 let stale = delete_ref_cas(&env, &gd, "refs/heads/topic", &c1).await;919 let stale = delete_ref_cas(&env, &gd, "refs/heads/topic", &c1).await;
1029 assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}");920 assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}");
1030 assert_eq!(w.git(&["rev-parse", "topic"]), c0);921 assert_eq!(w.git(&["rev-parse", "topic"]), c0);
@@ -1035,7 +926,6 @@ mod tests {
1035 let gone = w.git(&["for-each-ref", "refs/heads/topic"]);926 let gone = w.git(&["for-each-ref", "refs/heads/topic"]);
1036 assert!(gone.is_empty(), "{gone:?}");927 assert!(gone.is_empty(), "{gone:?}");
1037 928
1038- // Deleting a ref that is already gone is a refusal, not a silent success.
1039 let missing = delete_ref_cas(&env, &gd, "refs/heads/topic", &c0).await;929 let missing = delete_ref_cas(&env, &gd, "refs/heads/topic", &c0).await;
1040 assert!(matches!(missing, Err(Error::RefMoved(_))), "{missing:?}");930 assert!(matches!(missing, Err(Error::RefMoved(_))), "{missing:?}");
1041 }931 }
@@ -1089,7 +979,6 @@ mod tests {
1089 assert_eq!(diff.files[0].status, DiffStatus::Added);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 fn has_object(git_dir: &Path, oid: &str) -> bool {982 fn has_object(git_dir: &Path, oid: &str) -> bool {
1094 Command::new("/usr/bin/git")983 Command::new("/usr/bin/git")
1095 .arg("--git-dir")984 .arg("--git-dir")
@@ -1111,7 +1000,6 @@ mod tests {
1111 let base = sb.repo("base");1000 let base = sb.repo("base");
1112 base.write("a.txt", "1\n");1001 base.write("a.txt", "1\n");
1113 let base_tip = base.commit("base");1002 let base_tip = base.commit("base");
1114- // The fork is a clone, so both histories share `base_tip`.
1115 let fork_dir = sb._dir.path().join("fork");1003 let fork_dir = sb._dir.path().join("fork");
1116 git_in(1004 git_in(
1117 sb._dir.path(),1005 sb._dir.path(),
@@ -1128,7 +1016,6 @@ mod tests {
1128 let fork_objects = fork.git_dir().join("objects");1016 let fork_objects = fork.git_dir().join("objects");
1129 assert!(!has_object(&base_git, &fork_head));1017 assert!(!has_object(&base_git, &fork_head));
1130 1018
1131- // Without the alternate the base cannot see the fork's commit.
1132 assert!(1019 assert!(
1133 range_log(&env, &base_git, &base_tip, &fork_head, 10)1020 range_log(&env, &base_git, &base_tip, &fork_head, 10)
1134 .await1021 .await
@@ -1149,7 +1036,7 @@ mod tests {
1149 .expect("merge base through alternate");1036 .expect("merge base through alternate");
1150 assert_eq!(merge.as_deref(), Some(base_tip.as_str()));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 .await1040 .await
1154 .expect("range diff through alternate");1041 .expect("range diff through alternate");
1155 let paths: Vec<String> = diff1042 let paths: Vec<String> = diff
@@ -1159,7 +1046,6 @@ mod tests {
1159 .collect();1046 .collect();
1160 assert_eq!(paths, vec!["b.txt".to_owned()]);1047 assert_eq!(paths, vec!["b.txt".to_owned()]);
1161 1048
1162- // Reading through the alternate wrote nothing into the base repo.
1163 assert!(!has_object(&base_git, &fork_head));1049 assert!(!has_object(&base_git, &fork_head));
1164 }1050 }
1165 1051
@@ -1238,7 +1124,6 @@ mod tests {
1238 let a1 = blob_at(&env, &gd, &c1, "a.txt").await.expect("ok");1124 let a1 = blob_at(&env, &gd, &c1, "a.txt").await.expect("ok");
1239 assert_eq!(a1, Some(w.git(&["hash-object", "a.txt"])));1125 assert_eq!(a1, Some(w.git(&["hash-object", "a.txt"])));
1240 assert_ne!(a1, Some(a0));1126 assert_ne!(a1, Some(a0));
1241- // The older commit still maps to the older blob.
1242 let old_spec = format!("{c0}:a.txt");1127 let old_spec = format!("{c0}:a.txt");
1243 assert_eq!(1128 assert_eq!(
1244 blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"),1129 blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"),
@@ -1273,7 +1158,6 @@ mod tests {
1273 blob_at(&env, &gd, &c0, ":colon").await.expect("ok"),1158 blob_at(&env, &gd, &c0, ":colon").await.expect("ok"),
1274 Some(w.git(&["hash-object", ":colon"]))1159 Some(w.git(&["hash-object", ":colon"]))
1275 );1160 );
1276- // A glob must not match other entries.
1277 assert_eq!(blob_at(&env, &gd, &c0, "st*").await.expect("ok"), None);1161 assert_eq!(blob_at(&env, &gd, &c0, "st*").await.expect("ok"), None);
1278 assert_eq!(blob_at(&env, &gd, &c0, "*").await.expect("ok"), None);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 use crate::command::{GitCommand, GitEnv};7 use crate::command::{GitCommand, GitEnv};
8 use crate::error::Result;8 use crate::error::Result;
9+use crate::history::zero_oid;
9 use crate::repo::check_branch;10 use crate::repo::check_branch;
10 use crate::wiki::temp_index;11 use crate::wiki::temp_index;
11 12
@@ -97,7 +98,7 @@ async fn write_commit(
97 .arg("forge initial commit")98 .arg("forge initial commit")
98 .user_arg(&format!("refs/heads/{branch}"))?99 .user_arg(&format!("refs/heads/{branch}"))?
99 .user_arg(&oid)?100 .user_arg(&oid)?
100- .user_arg(&"0".repeat(oid.len()))?101+ .user_arg(&zero_oid(&oid))?
101 .status()102 .status()
102 .await?;103 .await?;
103 Ok(oid)104 Ok(oid)
crates/forge-git/src/tags.rsmodified+5 -5
@@ -5,10 +5,10 @@ use std::path::Path;
5 5
6 use crate::command::GitEnv;6 use crate::command::GitEnv;
7 use crate::error::{Error, Result};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 /// Longest tag name, in bytes.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 /// True for a tag name git accepts and forge allows: ASCII letters, digits and `._-+`, with no13 /// True for a tag name git accepts and forge allows: ASCII letters, digits and `._-+`, with no
14 /// slash, no `..`, no leading `.` or `-`, and no trailing `.` or `.lock`.14 /// slash, no `..`, no leading `.` or `-`, and no trailing `.` or `.lock`.
@@ -16,7 +16,7 @@ pub fn valid_tag_name(name: &str) -> bool {
16 !name.is_empty()16 !name.is_empty()
17 && name.len() <= MAX_TAG_NAME_LEN17 && name.len() <= MAX_TAG_NAME_LEN
18 && !name.starts_with(['.', '-'])18 && !name.starts_with(['.', '-'])
19- && !name.ends_with(['.', '/'])19+ && !name.ends_with('.')
20 && !name.ends_with(".lock")20 && !name.ends_with(".lock")
21 && !name.contains("..")21 && !name.contains("..")
22 && name22 && name
@@ -37,7 +37,7 @@ pub async fn create_lightweight_tag(
37 }37 }
38 validate_oid(target)?;38 validate_oid(target)?;
39 let refname = format!("refs/tags/{name}");39 let refname = format!("refs/tags/{name}");
40- let zero = "0".repeat(target.len());40+ let zero = zero_oid(target);
41 git(env, "update-ref")41 git(env, "update-ref")
42 .git_dir(repo)42 .git_dir(repo)
43 .user_arg(&refname)?43 .user_arg(&refname)?
@@ -89,7 +89,7 @@ pub async fn previous_tag(
89 env: &GitEnv,89 env: &GitEnv,
90 repo: &Path,90 repo: &Path,
91 oid: &str,91 oid: &str,
92-) -> crate::error::Result<Option<(String, String)>> {92+) -> Result<Option<(String, String)>> {
93 validate_oid(oid)?;93 validate_oid(oid)?;
94 let parent = format!("{oid}^");94 let parent = format!("{oid}^");
95 let described = git(env, "describe")95 let described = git(env, "describe")
crates/forge-git/src/trailers.rsmodified+9 -19
@@ -16,7 +16,7 @@ pub struct CoAuthor {
16 pub fn co_authors(message: &str) -> Vec<CoAuthor> {16 pub fn co_authors(message: &str) -> Vec<CoAuthor> {
17 let lines = lines(message);17 let lines = lines(message);
18 let mut seen = HashSet::new();18 let mut seen = HashSet::new();
19- trailer_lines(&lines)19+ lines[last_paragraph_start(&lines)..]
20 .iter()20 .iter()
21 .filter_map(|line| parse(line))21 .filter_map(|line| parse(line))
22 .filter(|author| seen.insert(author.email.to_lowercase()))22 .filter(|author| seen.insert(author.email.to_lowercase()))
@@ -26,15 +26,14 @@ pub fn co_authors(message: &str) -> Vec<CoAuthor> {
26 /// The message with every `Co-authored-by:` line removed and trailing blank lines trimmed.26 /// The message with every `Co-authored-by:` line removed and trailing blank lines trimmed.
27 pub fn strip_co_authors(message: &str) -> String {27 pub fn strip_co_authors(message: &str) -> String {
28 let lines = lines(message);28 let lines = lines(message);
29- let start = last_paragraph_start(&lines);29+ let (head, tail) = lines.split_at(last_paragraph_start(&lines));
30- let kept: Vec<&str> = lines[..start]30+ let kept: Vec<&str> = head
31 .iter()31 .iter()
32 .copied()32 .copied()
33 .chain(33 .chain(
34- lines[start..]34+ tail.iter()
35- .iter()
36 .copied()35 .copied()
37- .filter(|line| !is_trailer(line)),36+ .filter(|line| trailer_value(line).is_none()),
38 )37 )
39 .collect();38 .collect();
40 kept.join("\n").trim_end().to_owned()39 kept.join("\n").trim_end().to_owned()
@@ -53,23 +52,14 @@ fn last_paragraph_start(lines: &[&str]) -> usize {
53 .map_or(0, |i| i + 1)52 .map_or(0, |i| i + 1)
54 }53 }
55 54
56-fn trailer_lines<'a>(lines: &[&'a str]) -> Vec<&'a str> {55+fn trailer_value(line: &str) -> Option<&str> {
57- lines[last_paragraph_start(lines)..].to_vec()56+ let (key, value) = line.split_once(':')?;
58-}57+ key.trim().eq_ignore_ascii_case(KEY).then_some(value)
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))
64 }58 }
65 59
66 /// Parses `Co-authored-by: Name <email>`. Lines without a non-empty `<email>` give `None`.60 /// Parses `Co-authored-by: Name <email>`. Lines without a non-empty `<email>` give `None`.
67 fn parse(line: &str) -> Option<CoAuthor> {61 fn parse(line: &str) -> Option<CoAuthor> {
68- let (key, value) = line.trim().split_once(':')?;62+ let value = trailer_value(line.trim())?.trim();
69- if !key.trim().eq_ignore_ascii_case(KEY) {
70- return None;
71- }
72- let value = value.trim();
73 let open = value.find('<')?;63 let open = value.find('<')?;
74 let close = open + value[open..].find('>')?;64 let close = open + value[open..].find('>')?;
75 let email = value[open + 1..close].trim();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 use crate::command::{GitCommand, GitEnv};12 use crate::command::{GitCommand, GitEnv};
13 use crate::error::{Error, Result};13 use crate::error::{Error, Result};
14+use crate::history::validate_oid;
14 15
15 /// What git said about one commit's signature.16 /// What git said about one commit's signature.
16 #[derive(Debug, Clone, PartialEq, Eq)]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 /// The raw commit object (`git cat-file commit <oid>`).51 /// The raw commit object (`git cat-file commit <oid>`).
61 async fn commit_object(env: &GitEnv, repo: &Path, oid: &str) -> Result<Vec<u8>> {52 async fn commit_object(env: &GitEnv, repo: &Path, oid: &str) -> Result<Vec<u8>> {
62- check_oid(oid)?;53+ validate_oid(oid)?;
63 GitCommand::new(env, "cat-file")54 GitCommand::new(env, "cat-file")
64 .git_dir(repo)55 .git_dir(repo)
65 .arg("commit")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 use crate::command::{GitCommand, GitEnv};3 use crate::command::{GitCommand, GitEnv};
4 use crate::error::{Error, Result};4 use crate::error::{Error, Result};
@@ -21,7 +21,7 @@ fn leading_number(s: &str) -> Option<u32> {
21 digits.parse().ok()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 format!("{major}.{minor}.{patch}")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 use crate::browse::{EntryKind, default_branch_commit, read_text_blob, read_tree};9 use crate::browse::{EntryKind, default_branch_commit, read_text_blob, read_tree};
10 use crate::command::{GitCommand, GitEnv};10 use crate::command::{GitCommand, GitEnv};
11 use crate::error::{Error, Result};11 use crate::error::{Error, Result};
12+use crate::history::zero_oid;
12 use crate::repo::init_bare;13 use crate::repo::init_bare;
13 14
14 /// The branch that holds the pages.15 /// The branch that holds the pages.
15 pub const WIKI_BRANCH: &str = "main";16 pub const WIKI_BRANCH: &str = "main";
16 /// Extension of a page file.17 /// Extension of a page file.
17-pub const PAGE_EXT: &str = ".md";18+const PAGE_EXT: &str = ".md";
18 /// Largest page the editor accepts, and the largest one read back.19 /// Largest page the editor accepts, and the largest one read back.
19 pub const MAX_PAGE_BYTES: usize = 256 * 1024;20 pub const MAX_PAGE_BYTES: usize = 256 * 1024;
20 /// Longest page name, in characters.21 /// Longest page name, in characters.
21-pub const MAX_PAGE_NAME: usize = 100;22+const MAX_PAGE_NAME: usize = 100;
22 23
23 /// One page edit. `name` is the page name without the extension.24 /// One page edit. `name` is the page name without the extension.
24 #[derive(Debug, Clone, Copy)]25 #[derive(Debug, Clone, Copy)]
@@ -115,7 +116,7 @@ pub async fn page_history(env: &GitEnv, wiki: &Path, name: &str) -> Result<Vec<P
115 let out = GitCommand::new(env, "log")116 let out = GitCommand::new(env, "log")
116 .git_dir(wiki)117 .git_dir(wiki)
117 .arg("--format=%H%x1f%an%x1f%at%x1f%s")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 .user_arg(&format!("refs/heads/{WIKI_BRANCH}"))?120 .user_arg(&format!("refs/heads/{WIKI_BRANCH}"))?
120 .paths(&[file.as_str()])121 .paths(&[file.as_str()])
121 .output()122 .output()
@@ -238,10 +239,9 @@ async fn write_commit(
238 // Compare-and-swap: the ref must still hold `base`, or be absent when there was no base.239 // Compare-and-swap: the ref must still hold `base`, or be absent when there was no base.
239 let old = match base {240 let old = match base {
240 Some(base) => base.to_owned(),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+ let swapped = GitCommand::new(env, "update-ref")
244- GitCommand::new(env, "update-ref")
245 .git_dir(wiki)245 .git_dir(wiki)
246 .arg("-m")246 .arg("-m")
247 .arg("forge wiki edit")247 .arg("forge wiki edit")
@@ -249,9 +249,16 @@ async fn write_commit(
249 .user_arg(&oid)?249 .user_arg(&oid)?
250 .user_arg(&old)?250 .user_arg(&old)?
251 .status()251 .status()
252- .await252+ .await;
253- .map_err(|_| Error::RefMoved(format!("wiki {WIKI_BRANCH} moved during the edit")))?;253+ match swapped {
254- Ok(oid)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 #[cfg(test)]264 #[cfg(test)]
crates/forge-git/tests/integration/browse.rsmodified+0 -2
@@ -35,7 +35,6 @@ fn git(dir: &Path, args: &[&str]) -> String {
35 String::from_utf8_lossy(&out.stdout).trim().to_string()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 fn fixture() -> Fixture {38 fn fixture() -> Fixture {
40 let dir = tempfile::tempdir().unwrap();39 let dir = tempfile::tempdir().unwrap();
41 let work = dir.path().join("work");40 let work = dir.path().join("work");
@@ -172,7 +171,6 @@ fn resolve_commit_rejects_revision_syntax_and_unknown() {
172 ] {171 ] {
173 assert_eq!(resolve_commit(&f.bare, rev).unwrap(), None, "rev {rev:?}");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 assert_eq!(resolve_commit(&f.bare, &f.head[..3]).unwrap(), None);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 //! Tests for the code-browsing helpers: whitespace-free diffs, patches, the recursive file list,1 //! Tests for the code-browsing helpers: whitespace-free diffs, patches, the recursive file list,
2 //! blame and branch operations.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 use forge_git::blame::blame;4 use forge_git::blame::blame;
9 use forge_git::branches::{ahead_behind, create_branch, delete_branch};5 use forge_git::branches::{ahead_behind, create_branch, delete_branch};
10 use forge_git::command::ObjectSource;6 use forge_git::command::ObjectSource;
11 use forge_git::history::{commit_diff_ws, commit_patch, commit_raw_diff, list_files, range_patch};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};9+use crate::common::{BIG, WorkRepo};
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-}
82 10
83 #[tokio::test]11 #[tokio::test]
84 async fn ignore_whitespace_drops_whitespace_only_files() {12 async fn ignore_whitespace_drops_whitespace_only_files() {
85- let f = fixture();13+ let f = WorkRepo::new();
86 f.write("x.txt", "a\nb\n");14 f.write("x.txt", "a\nb\n");
87 f.write("y.txt", "c\n");15 f.write("y.txt", "c\n");
88 f.commit("one");16 f.commit("one");
@@ -104,7 +32,7 @@ async fn ignore_whitespace_drops_whitespace_only_files() {
104 32
105 #[tokio::test]33 #[tokio::test]
106 async fn patch_and_diff_outputs() {34 async fn patch_and_diff_outputs() {
107- let f = fixture();35+ let f = WorkRepo::new();
108 f.write("x.txt", "a\n");36 f.write("x.txt", "a\n");
109 let root = f.commit("root commit");37 let root = f.commit("root commit");
110 f.write("x.txt", "a\nb\n");38 f.write("x.txt", "a\nb\n");
@@ -139,7 +67,7 @@ async fn patch_and_diff_outputs() {
139 67
140 #[tokio::test]68 #[tokio::test]
141 async fn list_files_is_recursive_and_capped() {69 async fn list_files_is_recursive_and_capped() {
142- let f = fixture();70+ let f = WorkRepo::new();
143 f.write("a.txt", "1");71 f.write("a.txt", "1");
144 f.write("dir/b.txt", "2");72 f.write("dir/b.txt", "2");
145 f.write("dir/sub/c.txt", "3");73 f.write("dir/sub/c.txt", "3");
@@ -155,7 +83,7 @@ async fn list_files_is_recursive_and_capped() {
155 83
156 #[tokio::test]84 #[tokio::test]
157 async fn blame_groups_by_commit() {85 async fn blame_groups_by_commit() {
158- let f = fixture();86+ let f = WorkRepo::new();
159 f.write("f.txt", "one\ntwo\nthree\n");87 f.write("f.txt", "one\ntwo\nthree\n");
160 let first = f.commit("first");88 let first = f.commit("first");
161 f.write("f.txt", "one\nTWO\nthree\nfour\n");89 f.write("f.txt", "one\nTWO\nthree\nfour\n");
@@ -189,14 +117,14 @@ async fn blame_groups_by_commit() {
189 117
190 #[tokio::test]118 #[tokio::test]
191 async fn branch_counts_create_and_delete() {119 async fn branch_counts_create_and_delete() {
192- let f = fixture();120+ let f = WorkRepo::new();
193 f.write("a.txt", "1");121 f.write("a.txt", "1");
194 let base = f.commit("base");122 let base = f.commit("base");
195- f.sh(&["checkout", "-q", "-b", "feature"]);123+ f.git(&["checkout", "-q", "-b", "feature"]);
196 f.write("b.txt", "2");124 f.write("b.txt", "2");
197 f.commit("feature 1");125 f.commit("feature 1");
198 let tip = f.commit("feature 2");126 let tip = f.commit("feature 2");
199- f.sh(&["checkout", "-q", "main"]);127+ f.git(&["checkout", "-q", "main"]);
200 f.write("c.txt", "3");128 f.write("c.txt", "3");
201 let main_tip = f.commit("main moved");129 let main_tip = f.commit("main moved");
202 130
@@ -209,7 +137,7 @@ async fn branch_counts_create_and_delete() {
209 .await137 .await
210 .unwrap();138 .unwrap();
211 assert_eq!(139 assert_eq!(
212- f.sh(&["rev-parse", "refs/heads/topic/x"]).trim(),140+ f.git(&["rev-parse", "refs/heads/topic/x"]).trim(),
213 base.as_str()141 base.as_str()
214 );142 );
215 assert!(143 assert!(
crates/forge-git/tests/integration/common.rsmodified+66 -0
@@ -2,6 +2,7 @@
2 2
3 use std::path::Path;3 use std::path::Path;
4 use std::path::PathBuf;4 use std::path::PathBuf;
5+use std::process::Command;
5 6
6 use forge_git::GitEnv;7 use forge_git::GitEnv;
7 use forge_git::history::DiffLimits;8 use forge_git::history::DiffLimits;
@@ -18,3 +19,68 @@ pub fn git_env(data_dir: &Path) -> GitEnv {
18 data_dir: data_dir.to_path_buf(),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 use std::process::Command;2 use std::process::Command;
3 3
4 use forge_git::command::GitCommand;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 use forge_git::repo::{init_bare, list_branches, repo_path};6 use forge_git::repo::{init_bare, list_branches, repo_path};
7 use forge_git::service::{GitService, service_command};7 use forge_git::service::{GitService, service_command};
8 use forge_git::setup::{write_hook_shims, write_managed_gitconfig};8 use forge_git::setup::{write_hook_shims, write_managed_gitconfig};
@@ -14,24 +14,22 @@ const ULID: &str = "01arz3ndektsv4rrffq69g5fav";
14 14
15 #[test]15 #[test]
16 fn version_parse() {16 fn version_parse() {
17- assert_eq!(parse_git_version("git version 2.56.0\n"), Some((2, 56, 0)));17+ let cases = [
18- assert_eq!(18+ ("git version 2.56.0\n", Some((2, 56, 0))),
19- parse_git_version("git version 2.39.2.windows.1"),19+ ("git version 2.39.2.windows.1", Some((2, 39, 2))),
20- Some((2, 39, 2))20+ ("git version 2.46", Some((2, 46, 0))),
21- );21+ ("git version 2.46.0-rc1", Some((2, 46, 0))),
22- assert_eq!(parse_git_version("git version 2.46"), Some((2, 46, 0)));22+ ("garbage", None),
23- assert_eq!(23+ ];
24- parse_git_version("git version 2.46.0-rc1"),24+ for (input, expected) in cases {
25- Some((2, 46, 0))25+ assert_eq!(parse_git_version(input), expected, "{input:?}");
26- );26+ }
27- assert_eq!(parse_git_version("garbage"), None);
28 }27 }
29 28
30 #[test]29 #[test]
31 fn pkt_line_encoding() {30 fn pkt_line_encoding() {
32 assert_eq!(pkt_line("a\n"), b"0006a\n".to_vec());31 assert_eq!(pkt_line("a\n"), b"0006a\n".to_vec());
33 assert_eq!(pkt_line(""), b"0004".to_vec());32 assert_eq!(pkt_line(""), b"0004".to_vec());
34- assert_eq!(FLUSH_PKT, b"0000");
35 let header = service_advertisement_header(GitService::UploadPack);33 let header = service_advertisement_header(GitService::UploadPack);
36 assert_eq!(header, b"001e# service=git-upload-pack\n0000".to_vec());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 use std::io::Write;1 use std::io::Write;
2-use std::path::{Path, PathBuf};
3 use std::process::{Command, Stdio};2 use std::process::{Command, Stdio};
4 3
4+use forge_git::Error;
5 use forge_git::history::{5 use forge_git::history::{
6 ArchiveFormat, CommitDiff, DiffLimits, DiffStatus, FileDiff, LineKind, archive_command,6 ArchiveFormat, CommitDiff, DiffLimits, DiffStatus, FileDiff, LineKind, archive_command,
7 commit_diff, count, last_commits, log,7 commit_diff, count, last_commits, log,
8 };8 };
9-use forge_git::{Error, GitEnv};
10 9
11-use crate::common::{BIG, git_env};10+use crate::common::{BIG, WorkRepo};
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-}
83 11
84 fn find<'a>(diff: &'a CommitDiff, path: &str) -> &'a FileDiff {12 fn find<'a>(diff: &'a CommitDiff, path: &str) -> &'a FileDiff {
85 diff.files13 diff.files
@@ -94,7 +22,7 @@ fn summaries(commits: &[forge_git::browse::CommitInfo]) -> Vec<&str> {
94 22
95 #[tokio::test]23 #[tokio::test]
96 async fn log_path_filter_and_pagination() {24 async fn log_path_filter_and_pagination() {
97- let f = fixture();25+ let f = WorkRepo::new();
98 f.write("a.txt", "1\n");26 f.write("a.txt", "1\n");
99 f.commit("add a");27 f.commit("add a");
100 f.write("b.txt", "1\n");28 f.write("b.txt", "1\n");
@@ -126,7 +54,7 @@ async fn log_path_filter_and_pagination() {
126 54
127 #[tokio::test]55 #[tokio::test]
128 async fn commit_diff_modify_add_delete_rename_binary() {56 async fn commit_diff_modify_add_delete_rename_binary() {
129- let f = fixture();57+ let f = WorkRepo::new();
130 f.write("a.txt", "one\ntwo\n");58 f.write("a.txt", "one\ntwo\n");
131 f.write("gone.txt", "bye\n");59 f.write("gone.txt", "bye\n");
132 f.write("old.txt", "alpha\nbeta\ngamma\ndelta\nepsilon\n");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 #[tokio::test]103 #[tokio::test]
176 async fn commit_diff_line_numbers_on_known_hunk() {104 async fn commit_diff_line_numbers_on_known_hunk() {
177- let f = fixture();105+ let f = WorkRepo::new();
178 f.write("n.txt", "l1\nl2\nl3\nl4\nl5\n");106 f.write("n.txt", "l1\nl2\nl3\nl4\nl5\n");
179 f.commit("base");107 f.commit("base");
180 f.write("n.txt", "l1\nl2\nX3\nl4\nl5\nl6\n");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 #[tokio::test]136 #[tokio::test]
209 async fn commit_diff_root_commit_uses_empty_tree() {137 async fn commit_diff_root_commit_uses_empty_tree() {
210- let f = fixture();138+ let f = WorkRepo::new();
211 f.write("a.txt", "x\ny\n");139 f.write("a.txt", "x\ny\n");
212 f.write("d/b.txt", "z\n");140 f.write("d/b.txt", "z\n");
213 let oid = f.commit("root");141 let oid = f.commit("root");
@@ -225,7 +153,7 @@ async fn commit_diff_root_commit_uses_empty_tree() {
225 153
226 #[tokio::test]154 #[tokio::test]
227 async fn commit_diff_limits_truncate() {155 async fn commit_diff_limits_truncate() {
228- let f = fixture();156+ let f = WorkRepo::new();
229 let old: String = (0..10).map(|i| format!("old{i}\n")).collect();157 let old: String = (0..10).map(|i| format!("old{i}\n")).collect();
230 f.write("big.txt", &old);158 f.write("big.txt", &old);
231 f.commit("base");159 f.commit("base");
@@ -272,7 +200,7 @@ async fn commit_diff_limits_truncate() {
272 200
273 #[tokio::test]201 #[tokio::test]
274 async fn last_commits_finds_newest_touch_per_child() {202 async fn last_commits_finds_newest_touch_per_child() {
275- let f = fixture();203+ let f = WorkRepo::new();
276 f.write("d/x.txt", "1\n");204 f.write("d/x.txt", "1\n");
277 f.commit("c1 add x");205 f.commit("c1 add x");
278 f.write("d/y.txt", "1\n");206 f.write("d/y.txt", "1\n");
@@ -317,7 +245,7 @@ async fn last_commits_finds_newest_touch_per_child() {
317 245
318 #[tokio::test]246 #[tokio::test]
319 async fn count_counts_all_commits_or_those_touching_a_path() {247 async fn count_counts_all_commits_or_those_touching_a_path() {
320- let f = fixture();248+ let f = WorkRepo::new();
321 f.write("d/x.txt", "1\n");249 f.write("d/x.txt", "1\n");
322 f.commit("c1 add x");250 f.commit("c1 add x");
323 f.write("d/y.txt", "1\n");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 #[tokio::test]283 #[tokio::test]
356 async fn archive_command_produces_listable_tar_gz() {284 async fn archive_command_produces_listable_tar_gz() {
357- let f = fixture();285+ let f = WorkRepo::new();
358 f.write("a.txt", "hello\n");286 f.write("a.txt", "hello\n");
359 f.write("d/b.txt", "world\n");287 f.write("d/b.txt", "world\n");
360 let oid = f.commit("archive me");288 let oid = f.commit("archive me");
@@ -381,7 +309,7 @@ async fn archive_command_produces_listable_tar_gz() {
381 309
382 #[tokio::test]310 #[tokio::test]
383 async fn non_hex_commit_arguments_are_rejected() {311 async fn non_hex_commit_arguments_are_rejected() {
384- let f = fixture();312+ let f = WorkRepo::new();
385 f.write("a.txt", "1\n");313 f.write("a.txt", "1\n");
386 let oid = f.commit("one");314 let oid = f.commit("one");
387 315
crates/forge-git/tests/integration/main.rsmodified+0 -1
@@ -1,6 +1,5 @@
1 //! forge-git integration tests. All modules compile into this single test binary.1 //! forge-git integration tests. All modules compile into this single test binary.
2 2
3-#[allow(dead_code)]
4 mod common;3 mod common;
5 4
6 mod browse;5 mod browse;
crates/forge-ssh/src/backend.rsmodified+4 -5
@@ -4,7 +4,7 @@ use std::future::Future;
4 4
5 use forge_git::GitService;5 use forge_git::GitService;
6 6
7-use crate::parse::LfsOperation;7+use crate::parse::{LfsOperation, RepoPath};
8 8
9 /// Implemented by forge-web. The SSH server holds it in an `Arc`.9 /// Implemented by forge-web. The SSH server holds it in an `Arc`.
10 pub trait GitBackend: Send + Sync + 'static {10 pub trait GitBackend: Send + Sync + 'static {
@@ -21,17 +21,16 @@ pub trait GitBackend: Send + Sync + 'static {
21 &self,21 &self,
22 user_id: &str,22 user_id: &str,
23 service: GitService,23 service: GitService,
24- repo_path: &str,24+ repo_path: &RepoPath,
25 git_protocol: Option<&str>,25 git_protocol: Option<&str>,
26 ) -> impl Future<Output = Result<tokio::process::Command, String>> + Send;26 ) -> impl Future<Output = Result<tokio::process::Command, String>> + Send;
27 27
28 /// Authorizes a `git-lfs-authenticate` request and returns the JSON reply for stdout.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 stderr29+ /// `Err` sends the message on stderr and exits 1.
30- /// and exits 1.
31 fn lfs_authenticate(30 fn lfs_authenticate(
32 &self,31 &self,
33 user_id: &str,32 user_id: &str,
34- repo_path: &str,33+ repo_path: &RepoPath,
35 operation: LfsOperation,34 operation: LfsOperation,
36 ) -> impl Future<Output = Result<String, String>> + Send;35 ) -> impl Future<Output = Result<String, String>> + Send;
37 }36 }
crates/forge-ssh/src/lib.rsmodified+5 -5
@@ -1,11 +1,11 @@
1 //! git-over-SSH server for forge, built on russh.1 //! git-over-SSH server for forge, built on russh.
2 2
3-pub mod backend;3+mod backend;
4-pub mod error;4+mod error;
5-pub mod parse;5+mod parse;
6-pub mod server;6+mod server;
7 7
8 pub use backend::GitBackend;8 pub use backend::GitBackend;
9 pub use error::{Error, Result};9 pub use error::{Error, Result};
10-pub use parse::{LfsOperation, ParseError, parse_exec, parse_lfs_authenticate};10+pub use parse::{LfsOperation, RepoPath};
11 pub use server::{SshConfig, run};11 pub use server::{SshConfig, run};
crates/forge-ssh/src/parse.rsmodified+20 -17
@@ -23,9 +23,15 @@ const PREFIXES: &[(&str, GitService)] = &[
23 ("git receive-pack ", GitService::ReceivePack),23 ("git receive-pack ", GitService::ReceivePack),
24 ];24 ];
25 25
26-/// Returns the service and the repository path with `.git` stripped and the26+/// Owner and repository name with `.git` stripped and the leading `/` or `~/` removed.
27-/// leading `/` or `~/` removed. Anything else is an error.27+#[derive(Debug, Clone, PartialEq, Eq)]
28-pub fn parse_exec(cmd: &str) -> Result<(GitService, String), ParseError> {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 let (service, rest) = split_service(cmd)?;35 let (service, rest) = split_service(cmd)?;
30 let raw = unquote_argument(rest)?;36 let raw = unquote_argument(rest)?;
31 let path = normalize_path(raw)?;37 let path = normalize_path(raw)?;
@@ -44,18 +50,12 @@ pub enum LfsOperation {
44 50
45 /// Parses `git-lfs-authenticate '<owner>/<repo>[.git]' download|upload`. The path follows the51 /// Parses `git-lfs-authenticate '<owner>/<repo>[.git]' download|upload`. The path follows the
46 /// same rules as `parse_exec`, and the operation must be exactly `download` or `upload`.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 let rest = cmd54 let rest = cmd
49 .strip_prefix(LFS_AUTHENTICATE_PREFIX)55 .strip_prefix(LFS_AUTHENTICATE_PREFIX)
50 .ok_or(ParseError::UnsupportedCommand)?;56 .ok_or(ParseError::UnsupportedCommand)?;
51- // The path argument ends at its closing quote, or at the first space when it is bare.57+ let (arg, op) = rest.rsplit_once(' ').ok_or(ParseError::MalformedPath)?;
52- let end = if let Some(quoted) = rest.strip_prefix('\'') {58+ let operation = match op {
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,59 "download" => LfsOperation::Download,
60 "upload" => LfsOperation::Upload,60 "upload" => LfsOperation::Upload,
61 _ => return Err(ParseError::MalformedPath),61 _ => return Err(ParseError::MalformedPath),
@@ -96,8 +96,8 @@ fn unquote_argument(rest: &str) -> Result<&str, ParseError> {
96 }96 }
97 97
98 /// Strips one leading `/` or `~/`, then requires exactly `owner/repo` or98 /// Strips one leading `/` or `~/`, then requires exactly `owner/repo` or
99-/// `owner/repo.git`, returning `owner/repo`.99+/// `owner/repo.git`.
100-fn normalize_path(raw: &str) -> Result<String, ParseError> {100+fn normalize_path(raw: &str) -> Result<RepoPath, ParseError> {
101 let path = raw.strip_prefix('/').unwrap_or(raw);101 let path = raw.strip_prefix('/').unwrap_or(raw);
102 let path = path.strip_prefix("~/").unwrap_or(path);102 let path = path.strip_prefix("~/").unwrap_or(path);
103 103
@@ -122,7 +122,10 @@ fn normalize_path(raw: &str) -> Result<String, ParseError> {
122 if repo.is_empty() {122 if repo.is_empty() {
123 return Err(ParseError::MalformedPath);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 #[cfg(test)]131 #[cfg(test)]
@@ -131,7 +134,7 @@ mod tests {
131 134
132 fn ok(cmd: &str) -> (GitService, String) {135 fn ok(cmd: &str) -> (GitService, String) {
133 match parse_exec(cmd) {136 match parse_exec(cmd) {
134- Ok(v) => v,137+ Ok((service, path)) => (service, format!("{}/{}", path.owner, path.name)),
135 Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"),138 Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"),
136 }139 }
137 }140 }
@@ -293,7 +296,7 @@ mod tests {
293 296
294 fn lfs_ok(cmd: &str) -> (String, LfsOperation) {297 fn lfs_ok(cmd: &str) -> (String, LfsOperation) {
295 match parse_lfs_authenticate(cmd) {298 match parse_lfs_authenticate(cmd) {
296- Ok(v) => v,299+ Ok((path, operation)) => (format!("{}/{}", path.owner, path.name), operation),
297 Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"),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 use std::borrow::Cow;1 use std::borrow::Cow;
4 use std::collections::HashMap;2 use std::collections::HashMap;
5 use std::fs::OpenOptions;3 use std::fs::OpenOptions;
@@ -30,28 +28,20 @@ use crate::backend::GitBackend;
30 use crate::error::{Error, Result};28 use crate::error::{Error, Result};
31 use crate::parse::{LFS_AUTHENTICATE_PREFIX, parse_exec, parse_lfs_authenticate};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 const PUMP_CHUNK: usize = 32 * 1024;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 const STDIN_QUEUE: usize = 8;32 const STDIN_QUEUE: usize = 8;
38-/// Failed publickey attempts before the connection is dropped.
39 const MAX_AUTH_ATTEMPTS: usize = 6;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 const MAX_CONNECTIONS: usize = 256;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 #[derive(Debug, Clone)]38 #[derive(Debug, Clone)]
45 pub struct SshConfig {39 pub struct SshConfig {
46 pub listen: SocketAddr,40 pub listen: SocketAddr,
47 pub host_key_path: PathBuf,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 pub auth_rejection_time: Duration,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 pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()> {45 pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()> {
56 let host_key = load_or_create_host_key(&config.host_key_path)?;46 let host_key = load_or_create_host_key(&config.host_key_path)?;
57 let russh_config = Arc::new(Config {47 let russh_config = Arc::new(Config {
@@ -59,7 +49,7 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()
59 methods: publickey_only(),49 methods: publickey_only(),
60 auth_rejection_time: config.auth_rejection_time,50 auth_rejection_time: config.auth_rejection_time,
61 max_auth_attempts: MAX_AUTH_ATTEMPTS,51 max_auth_attempts: MAX_AUTH_ATTEMPTS,
62- inactivity_timeout: Some(config.inactivity_timeout),52+ inactivity_timeout: Some(INACTIVITY_TIMEOUT),
63 preferred: preferred_algorithms(),53 preferred: preferred_algorithms(),
64 ..Config::default()54 ..Config::default()
65 });55 });
@@ -72,13 +62,11 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()
72 let (stream, peer) = match listener.accept().await {62 let (stream, peer) = match listener.accept().await {
73 Ok(v) => v,63 Ok(v) => v,
74 Err(e) => {64 Err(e) => {
75- // Typically EMFILE. Back off briefly instead of tearing the server down.
76 tracing::warn!(error = %e, "ssh accept failed");65 tracing::warn!(error = %e, "ssh accept failed");
77 tokio::time::sleep(Duration::from_millis(100)).await;66 tokio::time::sleep(Duration::from_millis(100)).await;
78 continue;67 continue;
79 }68 }
80 };69 };
81- // At the limit the socket is dropped at once rather than queued.
82 let Ok(permit) = connection_slots.clone().try_acquire_owned() else {70 let Ok(permit) = connection_slots.clone().try_acquire_owned() else {
83 tracing::warn!(%peer, "ssh connection limit reached, dropping connection");71 tracing::warn!(%peer, "ssh connection limit reached, dropping connection");
84 continue;72 continue;
@@ -86,28 +74,34 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()
86 let authed = Arc::new(AtomicBool::new(false));74 let authed = Arc::new(AtomicBool::new(false));
87 let client = Client {75 let client = Client {
88 backend: Arc::clone(&backend),76 backend: Arc::clone(&backend),
89- peer: Some(peer),77+ peer,
90 authed: Arc::clone(&authed),78 authed: Arc::clone(&authed),
91 user_id: None,79 user_id: None,
92 git_protocol: None,80 git_protocol: None,
93 channels: HashMap::new(),81 channels: HashMap::new(),
94 };82 };
95 let russh_config = Arc::clone(&russh_config);83 let russh_config = Arc::clone(&russh_config);
96- let auth_timeout = config.auth_timeout;
97 tokio::spawn(async move {84 tokio::spawn(async move {
98- // Held until the connection ends, then the slot is free for the next client.
99 let _permit = permit;85 let _permit = permit;
100- let running = match run_stream(russh_config, stream, client).await {86+ let running = match tokio::time::timeout(
101- Ok(running) => running,87+ AUTH_TIMEOUT,
102- Err(e) => {88+ run_stream(russh_config, stream, client),
89+ )
90+ .await
91+ {
92+ Ok(Ok(running)) => running,
93+ Ok(Err(e)) => {
103 tracing::debug!(%peer, error = %e, "ssh handshake failed");94 tracing::debug!(%peer, error = %e, "ssh handshake failed");
104 return;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 let handle = running.handle();102 let handle = running.handle();
109 tokio::spawn(async move {103 tokio::spawn(async move {
110- tokio::time::sleep(auth_timeout).await;104+ tokio::time::sleep(AUTH_TIMEOUT).await;
111 if !authed.load(Ordering::Acquire) {105 if !authed.load(Ordering::Acquire) {
112 let _ = handle106 let _ = handle
113 .disconnect(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 fn publickey_only() -> MethodSet {122 fn publickey_only() -> MethodSet {
130 let mut methods = MethodSet::empty();123 let mut methods = MethodSet::empty();
131 methods.push(MethodKind::PublicKey);124 methods.push(MethodKind::PublicKey);
132 methods125 methods
133 }126 }
134 127
135-/// Host and user key algorithms this server negotiates. RSA is not listed: russh is built without it.
136 fn preferred_algorithms() -> Preferred {128 fn preferred_algorithms() -> Preferred {
137 Preferred {129 Preferred {
138 key: Cow::Owned(vec![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 fn key_type_allowed(algorithm: &Algorithm) -> bool {148 fn key_type_allowed(algorithm: &Algorithm) -> bool {
158 matches!(149 matches!(
159 algorithm,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 fn valid_git_protocol(value: &str) -> bool {158 fn valid_git_protocol(value: &str) -> bool {
169 let bytes = value.as_bytes();159 let bytes = value.as_bytes();
170 bytes.len() == 9 && value.starts_with("version=") && bytes[8].is_ascii_digit()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 if let Some(parent) = path.parent() {181 if let Some(parent) = path.parent() {
192 std::fs::create_dir_all(parent)?;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 let mut file = OpenOptions::new()184 let mut file = OpenOptions::new()
196 .write(true)185 .write(true)
197 .create_new(true)186 .create_new(true)
@@ -204,15 +193,12 @@ fn load_or_create_host_key(path: &Path) -> Result<PrivateKey> {
204 Ok(key)193 Ok(key)
205 }194 }
206 195
207-/// Per-connection SSH handler.
208 struct Client<B> {196 struct Client<B> {
209 backend: Arc<B>,197 backend: Arc<B>,
210- peer: Option<SocketAddr>,198+ peer: SocketAddr,
211 authed: Arc<AtomicBool>,199 authed: Arc<AtomicBool>,
212 user_id: Option<String>,200 user_id: Option<String>,
213 git_protocol: Option<String>,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 channels: HashMap<ChannelId, mpsc::Sender<Bytes>>,202 channels: HashMap<ChannelId, mpsc::Sender<Bytes>>,
217 }203 }
218 204
@@ -227,8 +213,6 @@ impl<B: GitBackend> Client<B> {
227 .await213 .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 async fn exec_lfs_authenticate(216 async fn exec_lfs_authenticate(
233 &self,217 &self,
234 session: &mut Session,218 session: &mut Session,
@@ -265,7 +249,6 @@ impl<B: GitBackend> Handler for Client<B> {
265 _user: &str,249 _user: &str,
266 offer: PublicKeyOffer<'_>,250 offer: PublicKeyOffer<'_>,
267 ) -> std::result::Result<Auth, Self::Error> {251 ) -> std::result::Result<Auth, Self::Error> {
268- // Probe before the client signs. Reject early so unknown keys never get a signature.
269 if self.lookup(offer.public_key).await.is_some() {252 if self.lookup(offer.public_key).await.is_some() {
270 Ok(Auth::Accept)253 Ok(Auth::Accept)
271 } else {254 } else {
@@ -280,7 +263,7 @@ impl<B: GitBackend> Handler for Client<B> {
280 ) -> std::result::Result<Auth, Self::Error> {263 ) -> std::result::Result<Auth, Self::Error> {
281 match self.lookup(verified.public_key).await {264 match self.lookup(verified.public_key).await {
282 Some(user_id) => {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 self.user_id = Some(user_id);267 self.user_id = Some(user_id);
285 self.authed.store(true, Ordering::Release);268 self.authed.store(true, Ordering::Release);
286 Ok(Auth::Accept)269 Ok(Auth::Accept)
@@ -312,7 +295,6 @@ impl<B: GitBackend> Handler for Client<B> {
312 variable_value: &str,295 variable_value: &str,
313 _session: &mut Session,296 _session: &mut Session,
314 ) -> std::result::Result<(), Self::Error> {297 ) -> std::result::Result<(), Self::Error> {
315- // Only GIT_PROTOCOL is kept. Everything else is ignored, never forwarded.
316 if variable_name == "GIT_PROTOCOL" && valid_git_protocol(variable_value) {298 if variable_name == "GIT_PROTOCOL" && valid_git_protocol(variable_value) {
317 self.git_protocol = Some(variable_value.to_owned());299 self.git_protocol = Some(variable_value.to_owned());
318 }300 }
@@ -382,7 +364,6 @@ impl<B: GitBackend> Handler for Client<B> {
382 _session: &mut Session,364 _session: &mut Session,
383 ) -> std::result::Result<(), Self::Error> {365 ) -> std::result::Result<(), Self::Error> {
384 if let Some(tx) = self.channels.get(&channel) {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 let _ = tx.send(Bytes::copy_from_slice(data)).await;367 let _ = tx.send(Bytes::copy_from_slice(data)).await;
387 }368 }
388 Ok(())369 Ok(())
@@ -452,27 +433,8 @@ impl<B: GitBackend> Handler for Client<B> {
452 session.channel_failure(channel)?;433 session.channel_failure(channel)?;
453 Ok(())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 fn reject_exec(438 fn reject_exec(
477 session: &mut Session,439 session: &mut Session,
478 channel: ChannelId,440 channel: ChannelId,
@@ -486,27 +448,29 @@ fn reject_exec(
486 Ok(())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 async fn run_child(451 async fn run_child(
492 handle: Handle,452 handle: Handle,
493 channel: ChannelId,453 channel: ChannelId,
494 mut child: Child,454 mut child: Child,
495 stdin_rx: mpsc::Receiver<Bytes>,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 let abort = Arc::new(Notify::new());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 let stdout_task = tokio::spawn(pump(465 let stdout_task = tokio::spawn(pump(
502- child.stdout.take(),466+ stdout,
503 handle.clone(),467 handle.clone(),
504 channel,468 channel,
505 None,469 None,
506 Arc::clone(&abort),470 Arc::clone(&abort),
507 ));471 ));
508 let stderr_task = tokio::spawn(pump(472 let stderr_task = tokio::spawn(pump(
509- child.stderr.take(),473+ stderr,
510 handle.clone(),474 handle.clone(),
511 channel,475 channel,
512 Some(1),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 let _ = stdout_task.await;488 let _ = stdout_task.await;
526 let _ = stderr_task.await;489 let _ = stderr_task.await;
527 feeder.abort();490 feeder.abort();
@@ -531,23 +494,17 @@ async fn run_child(
531 let _ = handle.close(channel).await;494 let _ = handle.close(channel).await;
532 }495 }
533 496
534-async fn feed_stdin(stdin: Option<ChildStdin>, mut rx: mpsc::Receiver<Bytes>) {497+async fn feed_stdin(mut stdin: ChildStdin, mut rx: mpsc::Receiver<Bytes>) {
535- let Some(mut stdin) = stdin else {
536- return;
537- };
538 while let Some(chunk) = rx.recv().await {498 while let Some(chunk) = rx.recv().await {
539 if stdin.write_all(&chunk).await.is_err() {499 if stdin.write_all(&chunk).await.is_err() {
540 break;500 break;
541 }501 }
542 }502 }
543- // Dropping stdin here closes the child's input.
544 let _ = stdin.shutdown().await;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 async fn pump<R>(506 async fn pump<R>(
550- reader: Option<R>,507+ mut reader: R,
551 handle: Handle,508 handle: Handle,
552 channel: ChannelId,509 channel: ChannelId,
553 ext: Option<u32>,510 ext: Option<u32>,
@@ -555,17 +512,13 @@ async fn pump<R>(
555 ) where512 ) where
556 R: AsyncRead + Unpin + Send + 'static,513 R: AsyncRead + Unpin + Send + 'static,
557 {514 {
558- let Some(mut reader) = reader else {
559- return;
560- };
561 let mut buf = vec![0u8; PUMP_CHUNK];515 let mut buf = vec![0u8; PUMP_CHUNK];
562 loop {516 loop {
563 let n = match reader.read(&mut buf).await {517 let n = match reader.read(&mut buf).await {
564 Ok(0) | Err(_) => break,518 Ok(0) | Err(_) => break,
565 Ok(n) => n,519 Ok(n) => n,
566 };520 };
567- // A right-sized copy: a chunk queued for the client holds only the bytes read.521+ let chunk = Bytes::copy_from_slice(&buf[..n]);
568- let chunk = Bytes::copy_from_slice(buf.get(..n).unwrap_or_default());
569 let sent = match ext {522 let sent = match ext {
570 None => handle.data(channel, chunk).await.is_ok(),523 None => handle.data(channel, chunk).await.is_ok(),
571 Some(kind) => handle.extended_data(channel, kind, chunk).await.is_ok(),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 use std::time::Duration;8 use std::time::Duration;
9 9
10 use forge_git::GitService;10 use forge_git::GitService;
11-use forge_ssh::{GitBackend, LfsOperation, SshConfig};11+use forge_ssh::{GitBackend, LfsOperation, RepoPath, SshConfig};
12 use russh::keys::PublicKey;12 use russh::keys::PublicKey;
13 use tokio::process::Command;13 use tokio::process::Command;
14 14
@@ -30,7 +30,7 @@ impl GitBackend for TestBackend {
30 &self,30 &self,
31 user_id: &str,31 user_id: &str,
32 service: GitService,32 service: GitService,
33- repo_path: &str,33+ repo_path: &RepoPath,
34 _git_protocol: Option<&str>,34 _git_protocol: Option<&str>,
35 ) -> Result<Command, String> {35 ) -> Result<Command, String> {
36 if user_id != self.user_id {36 if user_id != self.user_id {
@@ -38,7 +38,7 @@ impl GitBackend for TestBackend {
38 }38 }
39 let repo = self39 let repo = self
40 .repos40 .repos
41- .get(repo_path)41+ .get(&format!("{}/{}", repo_path.owner, repo_path.name))
42 .ok_or_else(|| "repository not found".to_owned())?;42 .ok_or_else(|| "repository not found".to_owned())?;
43 let mut cmd = Command::new("git");43 let mut cmd = Command::new("git");
44 cmd.arg(service.name().trim_start_matches("git-")).arg(repo);44 cmd.arg(service.name().trim_start_matches("git-")).arg(repo);
@@ -48,10 +48,11 @@ impl GitBackend for TestBackend {
48 async fn lfs_authenticate(48 async fn lfs_authenticate(
49 &self,49 &self,
50 user_id: &str,50 user_id: &str,
51- repo_path: &str,51+ repo_path: &RepoPath,
52 operation: LfsOperation,52 operation: LfsOperation,
53 ) -> Result<String, String> {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 return Err("repository not found".to_owned());56 return Err("repository not found".to_owned());
56 }57 }
57 let op = match operation {58 let op = match operation {
@@ -59,7 +60,7 @@ impl GitBackend for TestBackend {
59 LfsOperation::Upload => "upload",60 LfsOperation::Upload => "upload",
60 };61 };
61 Ok(format!(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 let config = SshConfig {192 let config = SshConfig {
192 listen: ([127, 0, 0, 1], port).into(),193 listen: ([127, 0, 0, 1], port).into(),
193 host_key_path: host_key.clone(),194 host_key_path: host_key.clone(),
194- auth_timeout: Duration::from_secs(10),
195- inactivity_timeout: Duration::from_secs(60),
196 // Production rejects a failed auth after 1s. OpenSSH's `none` probe fails on every195 // Production rejects a failed auth after 1s. OpenSSH's `none` probe fails on every
197 // connection, so the test would wait that second for each of its ~20 connections.196 // connection, so the test would wait that second for each of its ~20 connections.
198 auth_rejection_time: Duration::ZERO,197 auth_rejection_time: Duration::ZERO,
crates/forge-web-account/src/pages/banner.rsmodified+7 -9
@@ -4,8 +4,6 @@
4 //! in the `forge_banner` cookie for a signed-out visitor, and as the `banner_dismissed` account4 //! in the `forge_banner` cookie for a signed-out visitor, and as the `banner_dismissed` account
5 //! preference for a signed-in user.5 //! preference for a signed-in user.
6 6
7-use std::time::Duration;
8-
9 use serde::Deserialize;7 use serde::Deserialize;
10 use topcoat::Result;8 use topcoat::Result;
11 use topcoat::context::{Cx, context};9 use topcoat::context::{Cx, context};
@@ -19,8 +17,6 @@ use crate::pages::theme_cookie::safe_back;
19 use crate::state::AppState;17 use crate::state::AppState;
20 use crate::views::{BANNER_COOKIE, BANNER_PREF};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 #[derive(Deserialize)]20 #[derive(Deserialize)]
25 struct DismissForm {21 struct DismissForm {
26 #[serde(default)]22 #[serde(default)]
@@ -32,21 +28,22 @@ struct DismissForm {
32 #[route(POST "/-/banner/dismiss")]28 #[route(POST "/-/banner/dismiss")]
33 async fn dismiss(cx: &Cx, Form(form): Form<DismissForm>) -> Result<SeeOther> {29 async fn dismiss(cx: &Cx, Form(form): Form<DismissForm>) -> Result<SeeOther> {
34 let hash_ok = form.hash.len() == 16 && form.hash.bytes().all(|b| b.is_ascii_hexdigit());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 context::<AppState>(cx)35 context::<AppState>(cx)
37 .store36 .store
38 .set_user_pref(&user.id, BANNER_PREF, &form.hash)37 .set_user_pref(&user.id, BANNER_PREF, &form.hash)
39 .await?;38 .await?;
40- } else if hash_ok {39+ } else {
41- let max_age =
42- time::Duration::seconds(i64::try_from(BANNER_COOKIE_TTL.as_secs()).unwrap_or(i64::MAX));
43 cookies(cx).add(40 cookies(cx).add(
44 Cookie::build((BANNER_COOKIE, form.hash))41 Cookie::build((BANNER_COOKIE, form.hash))
45 .path("/")42 .path("/")
46 .secure(true)43 .secure(true)
47 .http_only(true)44 .http_only(true)
48 .same_site(SameSite::Lax)45 .same_site(SameSite::Lax)
49- .max_age(max_age)46+ .max_age(time::Duration::days(365))
50 .build(),47 .build(),
51 );48 );
52 }49 }
@@ -91,5 +88,6 @@ mod tests {
91 Some(86_400 + 60)88 Some(86_400 + 60)
92 );89 );
93 assert!(forge_core::config::parse_banner_expiry("tomorrow").is_none());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 use base64::Engine;13 use base64::Engine;
14 use base64::engine::general_purpose::URL_SAFE_NO_PAD;14 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
15-use forge_core::session::new_csrf_token;
16 use forge_core::store::passkeys::{MAX_PASSKEYS, PasskeyRow, clean_name};15 use forge_core::store::passkeys::{MAX_PASSKEYS, PasskeyRow, clean_name};
17 use forge_core::{AuditAction, User};16 use forge_core::{AuditAction, User};
18 use http::header::{HeaderValue, RETRY_AFTER};17 use http::header::{HeaderValue, RETRY_AFTER};
@@ -125,7 +124,7 @@ fn stash(ceremony: Ceremony) -> Option<String> {
125 if map.len() >= CEREMONY_CAP {124 if map.len() >= CEREMONY_CAP {
126 return None;125 return None;
127 }126 }
128- let id = new_csrf_token();127+ let id = forge_core::token::random_b64url();
129 map.insert(id.clone(), (now, ceremony));128 map.insert(id.clone(), (now, ceremony));
130 Some(id)129 Some(id)
131 }130 }
crates/forge-web-app/src/auth.rsmodified+4 -5
@@ -7,9 +7,8 @@ use std::sync::{Arc, OnceLock};
7 use std::time::Duration;7 use std::time::Duration;
8 8
9 use forge_core::password::{hash_password, verify_password};9 use forge_core::password::{hash_password, verify_password};
10-use forge_core::session::{new_csrf_token, new_session_token};
11 use forge_core::time::stamp_after;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 use forge_core::{Session, Store, User, secret, totp};12 use forge_core::{Session, Store, User, secret, totp};
14 use tokio::sync::Semaphore;13 use tokio::sync::Semaphore;
15 use topcoat::Result;14 use topcoat::Result;
@@ -77,13 +76,13 @@ pub async fn current_user(cx: &Cx) -> forge_core::Result<Option<(User, Session)>
77 /// Creates a session for `user` and sets the session cookie on the response.76 /// Creates a session for `user` and sets the session cookie on the response.
78 pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {77 pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {
79 let store = &context::<AppState>(cx).store;78 let store = &context::<AppState>(cx).store;
80- let token = new_session_token();79+ let token = random_b64url();
81 let addr = client_addr(cx).to_string();80 let addr = client_addr(cx).to_string();
82 let session = store81 let session = store
83 .create_session(82 .create_session(
84 &user.id,83 &user.id,
85 &hash_token(&token),84 &hash_token(&token),
86- &new_csrf_token(),85+ &random_b64url(),
87 &stamp_after(SESSION_TTL),86 &stamp_after(SESSION_TTL),
88 user_agent(cx).as_deref(),87 user_agent(cx).as_deref(),
89 Some(&addr),88 Some(&addr),
@@ -134,7 +133,7 @@ pub fn pre_csrf_token(cx: &Cx) -> String {
134 return value.to_owned();133 return value.to_owned();
135 }134 }
136 }135 }
137- let token = new_csrf_token();136+ let token = random_b64url();
138 session_jar(cx).add(pre_csrf_cookie(token.clone()));137 session_jar(cx).add(pre_csrf_cookie(token.clone()));
139 token138 token
140 }139 }
crates/forge-web-app/src/backup/create.rsmodified+7 -10
@@ -265,16 +265,7 @@ async fn bundle_git_repo(
265 ) -> Result<(String, Option<String>)> {265 ) -> Result<(String, Option<String>)> {
266 let refs_sha256 = forge_git::backup::refs_checksum(git, repo_dir).await?;266 let refs_sha256 = forge_git::backup::refs_checksum(git, repo_dir).await?;
267 let out = staging.join(rel);267 let out = staging.join(rel);
268- let bundle = match forge_git::backup::bundle_create(git, repo_dir, &out).await? {268+ let bundle = if 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
276- }
277- Some(()) => {
278 let scratch = scratch_root.join(scratch_name);269 let scratch = scratch_root.join(scratch_name);
279 forge_git::repo::init_bare(git, &scratch, "main").await?;270 forge_git::repo::init_bare(git, &scratch, "main").await?;
280 let imported = forge_git::backup::bundle_verify(git, &scratch, &out).await?;271 let imported = forge_git::backup::bundle_verify(git, &scratch, &out).await?;
@@ -285,7 +276,13 @@ async fn bundle_git_repo(
285 )));276 )));
286 }277 }
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 Ok((refs_sha256, bundle))287 Ok((refs_sha256, bundle))
291 }288 }
crates/forge-web-app/src/ci/api.rsmodified+7 -8
@@ -7,16 +7,16 @@
7 //! Every response is JSON except the empty 204 of an empty claim and the body of a log append.7 //! Every response is JSON except the empty 204 of an empty claim and the body of a log append.
8 8
9 use forge_ci::config::JobSpec;9 use forge_ci::config::JobSpec;
10-use forge_ci::mask::Masker;10+use forge_ci::mask::{MaskStream, Masker};
11 use forge_ci::proto::{11 use forge_ci::proto::{
12 BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse,12 BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse,
13 JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER,13 JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER,
14- RegisterRequest, RegisterResponse, RequeueRequest, RestartMode as WireRestart,14+ RegisterRequest, RegisterResponse, RequeueRequest, RunnerConfigOverrides, RunnerConfigReport,
15- RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch,15+ RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch,
16 };16 };
17 use forge_core::Error as CoreError;17 use forge_core::Error as CoreError;
18 use forge_core::ci::{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 use futures_util::StreamExt;21 use futures_util::StreamExt;
22 use http::header::HeaderValue;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 /// The restart an admin asked for, in the wire type. `None` when nothing is pending.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> {311+async fn pending_restart(state: &AppState, runner_id: &str) -> Option<RestartMode> {
312- let mode = state.store.runner_restart(runner_id).await.ok().flatten()?;312+ state.store.runner_restart(runner_id).await.ok().flatten()
313- WireRestart::parse(mode.as_str())
314 }313 }
315 314
316 /// Adds the pending restart request to a claim answer. Sent on every answer until the runner315 /// 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 .await975 .await
977 .map_err(api::internal)?;976 .map_err(api::internal)?;
978 let masker = Masker::new(values.into_values());977 let masker = Masker::new(values.into_values());
979- let mut stream = masker.stream();978+ let mut stream = MaskStream::new(masker);
980 let mut out = stream.push(chunk);979 let mut out = stream.push(chunk);
981 out.extend(stream.finish());980 out.extend(stream.finish());
982 Ok(out)981 Ok(out)
crates/forge-web-app/src/ci/api_tests.rsmodified+50 -102
@@ -3,7 +3,7 @@
3 3
4 use std::path::PathBuf;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 use forge_core::{Repo, Store, Visibility};7 use forge_core::{Repo, Store, Visibility};
8 use http::header::{AUTHORIZATION, CONTENT_TYPE};8 use http::header::{AUTHORIZATION, CONTENT_TYPE};
9 use serde_json::{Value, json};9 use serde_json::{Value, json};
@@ -72,12 +72,12 @@ struct Bare {
72 _dir: tempfile::TempDir,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 let dir = tempfile::tempdir().expect("tempdir");76 let dir = tempfile::tempdir().expect("tempdir");
77 let data_dir = dir.path().to_path_buf();77 let data_dir = dir.path().to_path_buf();
78 let mut state = test_state(&data_dir).await;78 let mut state = test_state(&data_dir).await;
79 let mut config = (*state.config).clone();79 let mut config = (*state.config).clone();
80- tune(&mut config.ci);80+ tune(&mut config);
81 state.set_config(config);81 state.set_config(config);
82 let store = state.store.clone();82 let store = state.store.clone();
83 let router = app_router(state);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 /// A runner registered through the store, with its secret.107 /// A runner registered through the store, with its secret.
103 async fn runner(env: &Bare, labels: &[&str]) -> (CiRunner, String) {108 async fn runner(env: &Bare, labels: &[&str]) -> (CiRunner, String) {
104 let token = env109 let token = env
@@ -147,15 +152,17 @@ async fn make_run(
147 .collect();152 .collect();
148 env.store153 env.store
149 .create_run(154 .create_run(
150- &env.repo.id,155+ &NewRun {
156+ repo_id: &env.repo.id,
151 trigger,157 trigger,
152- "refs/heads/main",158+ git_ref: "refs/heads/main",
153- commit,159+ commit_oid: commit,
154- pull,160+ pull_number: pull,
155- &env.owner_id,161+ actor_id: &env.owner_id,
156- false,162+ needs_approval: false,
163+ config_error: None,
164+ },
157 &new,165 &new,
158- None,
159 )166 )
160 .await167 .await
161 .unwrap()168 .unwrap()
@@ -792,9 +799,9 @@ async fn put_artifact(
792 799
793 #[tokio::test]800 #[tokio::test]
794 async fn artifact_upload_stores_and_checks_name_count_and_size() {801 async fn artifact_upload_stores_and_checks_name_count_and_size() {
795- let env = bare(|ci| {802+ let env = bare(|c| {
796- ci.max_artifacts_per_job = 3;803+ c.ci.max_artifacts_per_job = 3;
797- ci.max_artifact_mb = 1;804+ c.ci.max_artifact_mb = 1;
798 })805 })
799 .await;806 .await;
800 let (_, secret) = runner(&env, &[]).await;807 let (_, secret) = runner(&env, &[]).await;
@@ -851,18 +858,22 @@ fn finish_body(outcome: &str) -> Vec<u8> {
851 json_body(&json!({ "outcome": outcome, "exit_code": 0, "message": null }))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 async fn finish_with(env: &Bare, secret: &str, body: Value) -> (String, Value) {872 async fn finish_with(env: &Bare, secret: &str, body: Value) -> (String, Value) {
855 let assignment = claim_job(&env.router, secret).await;873 let assignment = claim_job(&env.router, secret).await;
856 let id = assignment["job_id"].as_str().unwrap().to_owned();874 let id = assignment["job_id"].as_str().unwrap().to_owned();
857 let token = assignment["job_token"].as_str().unwrap();875 let token = assignment["job_token"].as_str().unwrap();
858- let sent = send(876+ let sent = finish_as(&env.router, &id, token, json_body(&body)).await;
859- &env.router,
860- "POST",
861- &format!("/api/v1/ci/jobs/{id}/finish"),
862- &[bearer(token)],
863- json_body(&body),
864- )
865- .await;
866 assert_eq!(sent.status, 200, "{}", sent.json());877 assert_eq!(sent.status, 200, "{}", sent.json());
867 (id, sent.json())878 (id, sent.json())
868 }879 }
@@ -957,14 +968,7 @@ async fn finish_queues_dependants_on_success_and_skips_them_on_failure() {
957 let job_id = assignment["job_id"].as_str().unwrap();968 let job_id = assignment["job_id"].as_str().unwrap();
958 let token = assignment["job_token"].as_str().unwrap();969 let token = assignment["job_token"].as_str().unwrap();
959 970
960- let sent = send(971+ let sent = finish_as(&env.router, job_id, token, finish_body("success")).await;
961- &env.router,
962- "POST",
963- &format!("/api/v1/ci/jobs/{job_id}/finish"),
964- &[bearer(token)],
965- finish_body("success"),
966- )
967- .await;
968 assert_eq!(sent.status, 200, "{}", sent.json());972 assert_eq!(sent.status, 200, "{}", sent.json());
969 973
970 let jobs = env.store.jobs_for_run(&run.id).await.unwrap();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 assert_eq!(next["job_name"], "b");980 assert_eq!(next["job_name"], "b");
977 let b_id = next["job_id"].as_str().unwrap();981 let b_id = next["job_id"].as_str().unwrap();
978 let b_token = next["job_token"].as_str().unwrap();982 let b_token = next["job_token"].as_str().unwrap();
979- let sent = send(983+ let sent = finish_as(&env.router, b_id, b_token, finish_body("success")).await;
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;
987 assert_eq!(sent.status, 200, "{}", sent.json());984 assert_eq!(sent.status, 200, "{}", sent.json());
988 985
989 // Scenario 2: a failed `a` skips `b`, and the run ends in failure.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 let job_id = assignment["job_id"].as_str().unwrap();989 let job_id = assignment["job_id"].as_str().unwrap();
993 let token = assignment["job_token"].as_str().unwrap();990 let token = assignment["job_token"].as_str().unwrap();
994 991
995- let sent = send(992+ let sent = finish_as(&env.router, job_id, token, finish_body("failure")).await;
996- &env.router,
997- "POST",
998- &format!("/api/v1/ci/jobs/{job_id}/finish"),
999- &[bearer(token)],
1000- finish_body("failure"),
1001- )
1002- .await;
1003 assert_eq!(sent.status, 200, "{}", sent.json());993 assert_eq!(sent.status, 200, "{}", sent.json());
1004 assert_eq!(sent.json()["state"], "failure");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 assert_eq!(run_now.state.as_str(), "failure");1000 assert_eq!(run_now.state.as_str(), "failure");
1011 1001
1012 // A finished job's token is refused.1002 // A finished job's token is refused.
1013- let again = send(1003+ let again = finish_as(&env.router, job_id, token, finish_body("success")).await;
1014- &env.router,
1015- "POST",
1016- &format!("/api/v1/ci/jobs/{job_id}/finish"),
1017- &[bearer(token)],
1018- finish_body("success"),
1019- )
1020- .await;
1021 assert_eq!(again.status, 401);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 /// fails. Neither finish leaves the run in a state that self-update deploys.1008 /// fails. Neither finish leaves the run in a state that self-update deploys.
1026 #[tokio::test]1009 #[tokio::test]
1027 async fn build_green_before_test_fails_never_qualifies_for_self_update() {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 let (_, secret) = runner(&env, &[]).await;1012 let (_, secret) = runner(&env, &[]).await;
1030 let run = make_run(1013 let run = make_run(
1031 &env,1014 &env,
@@ -1059,16 +1042,7 @@ async fn build_green_before_test_fails_never_qualifies_for_self_update() {
1059 let job_id = assignment["job_id"].as_str().unwrap().to_owned();1042 let job_id = assignment["job_id"].as_str().unwrap().to_owned();
1060 let token = assignment["job_token"].as_str().unwrap().to_owned();1043 let token = assignment["job_token"].as_str().unwrap().to_owned();
1061 let router = env.router.clone();1044 let router = env.router.clone();
1062- async move {1045+ async move { finish_as(&router, &job_id, &token, finish_body(outcome)).await }
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- }
1072 };1046 };
1073 1047
1074 let sent = finish(&build, "success").await;1048 let sent = finish(&build, "success").await;
@@ -1131,19 +1105,21 @@ async fn job_token_reads_over_smart_http_but_never_pushes() {
1131 let owner_id = fx.store.user_by_username(OWNER).await.unwrap().unwrap().id;1105 let owner_id = fx.store.user_by_username(OWNER).await.unwrap().unwrap().id;
1132 fx.store1106 fx.store
1133 .create_run(1107 .create_run(
1134- &repo.id,1108+ &NewRun {
1135- "push",1109+ repo_id: &repo.id,
1136- "refs/heads/main",1110+ trigger: "push",
1137- &fx.root,1111+ git_ref: "refs/heads/main",
1138- None,1112+ commit_oid: &fx.root,
1139- &owner_id,1113+ pull_number: None,
1140- false,1114+ actor_id: &owner_id,
1115+ needs_approval: false,
1116+ config_error: None,
1117+ },
1141 &[NewJob {1118 &[NewJob {
1142 name: "a",1119 name: "a",
1143 spec_json: &spec(&[], &[]),1120 spec_json: &spec(&[], &[]),
1144 needs: &[],1121 needs: &[],
1145 }],1122 }],
1146- None,
1147 )1123 )
1148 .await1124 .await
1149 .unwrap();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 #[tokio::test]1211 #[tokio::test]
1264 async fn runner_binary_needs_runner_auth_and_self_update() {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 async fn runner_binary_streams_the_running_binary_with_its_sha() {1225 async fn runner_binary_streams_the_running_binary_with_its_sha() {
1278 use sha2::{Digest, Sha256};1226 use sha2::{Digest, Sha256};
1279 1227
1280- let env = bare_with_self_update().await;1228+ let env = bare(self_update_on).await;
1281 let (_, secret) = runner(&env, &[]).await;1229 let (_, secret) = runner(&env, &[]).await;
1282 let uri = "/api/v1/ci/runners/binary";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 #[tokio::test]1264 #[tokio::test]
1317 async fn claim_advertises_the_binary_only_to_a_matching_target() {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 let (_, secret) = runner(&env, &["linux"]).await;1267 let (_, secret) = runner(&env, &["linux"]).await;
1320 let target = crate::self_update::target();1268 let target = crate::self_update::target();
1321 let claim_with = |target: Option<String>| {1269 let claim_with = |target: Option<String>| {
crates/forge-web-app/src/ci/schedule.rsmodified+11 -9
@@ -6,7 +6,7 @@
6 6
7 use forge_ci::config::{CiConfig, Event, parse_config};7 use forge_ci::config::{CiConfig, Event, parse_config};
8 use forge_core::authz::{Action, authorize};8 use forge_core::authz::{Action, authorize};
9-use forge_core::ci::{CiRun, NewJob};9+use forge_core::ci::{CiRun, NewJob, NewRun};
10 use forge_core::store::commit_status::StatusState;10 use forge_core::store::commit_status::StatusState;
11 use forge_core::{PullRequest, Repo};11 use forge_core::{PullRequest, Repo};
12 use forge_git::browse::{peel_to_commit, read_blob, resolve_commit};12 use forge_git::browse::{peel_to_commit, read_blob, resolve_commit};
@@ -358,15 +358,17 @@ async fn create(
358 let run = state358 let run = state
359 .store359 .store
360 .create_run(360 .create_run(
361- &req.repo.id,361+ &NewRun {
362- req.trigger,362+ repo_id: &req.repo.id,
363- req.git_ref,363+ trigger: req.trigger,
364- req.commit,364+ git_ref: req.git_ref,
365- req.pull_number,365+ commit_oid: req.commit,
366- req.actor_id,366+ pull_number: req.pull_number,
367- req.needs_approval,367+ actor_id: req.actor_id,
368- &new_jobs,368+ needs_approval: req.needs_approval,
369 config_error,369 config_error,
370+ },
371+ &new_jobs,
370 )372 )
371 .await?;373 .await?;
372 state.ci_live.bump_repo(&run.repo_id);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 forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?;249 forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?;
250 let bundled = bundle_create(&state.git, &git_dir, &dir.join("repo.bundle"))250 let bundled = bundle_create(&state.git, &git_dir, &dir.join("repo.bundle"))
251 .await251 .await
252- .map_err(|e| format!("bundling {}: {e}", repo.name))?252+ .map_err(|e| format!("bundling {}: {e}", repo.name))?;
253- .is_some();
254 253
255 let labels = state254 let labels = state
256 .store255 .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 mod tests {131 mod tests {
132 use std::sync::Arc;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 use forge_core::time::{now_stamp, stamp_after};135 use forge_core::time::{now_stamp, stamp_after};
136 136
137 use super::*;137 use super::*;
@@ -207,7 +207,7 @@ mod tests {
207 "the released row goes out without waiting"207 "the released row goes out without waiting"
208 );208 );
209 let row = state.store.recent_mail(10).await.expect("rows").remove(0);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 #[tokio::test]213 #[tokio::test]
@@ -249,7 +249,7 @@ mod tests {
249 assert_eq!(sent[0].to, "a@example.com");249 assert_eq!(sent[0].to, "a@example.com");
250 let row = state.store.recent_mail(10).await.expect("rows");250 let row = state.store.recent_mail(10).await.expect("rows");
251 assert_eq!(row.len(), 1);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 #[tokio::test]255 #[tokio::test]
@@ -284,7 +284,7 @@ mod tests {
284 assert_eq!(tick(&state).await.expect("pass"), BACKSTOP);284 assert_eq!(tick(&state).await.expect("pass"), BACKSTOP);
285 assert!(fake.sent().is_empty());285 assert!(fake.sent().is_empty());
286 let row = state.store.recent_mail(10).await.expect("rows");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 assert_eq!(row[0].attempts, 0, "waiting costs no attempts");288 assert_eq!(row[0].attempts, 0, "waiting costs no attempts");
289 }289 }
290 290
@@ -322,7 +322,7 @@ mod tests {
322 let by_key = |to: &str| rows.iter().find(|r| r.to_addr == to).expect("row").clone();322 let by_key = |to: &str| rows.iter().find(|r| r.to_addr == to).expect("row").clone();
323 323
324 let retried = by_key("a@example.com");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 assert_eq!(retried.attempts, 1);326 assert_eq!(retried.attempts, 1);
327 assert_eq!(retried.last_error.as_deref(), Some("timeout"));327 assert_eq!(retried.last_error.as_deref(), Some("timeout"));
328 let due = retried.next_attempt_at.expect("scheduled");328 let due = retried.next_attempt_at.expect("scheduled");
@@ -330,7 +330,7 @@ mod tests {
330 assert!(due <= stamp_after(Duration::from_secs(120)));330 assert!(due <= stamp_after(Duration::from_secs(120)));
331 331
332 let bounced = by_key("b@example.com");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 assert_eq!(bounced.attempts, 1);334 assert_eq!(bounced.attempts, 1);
335 assert_eq!(bounced.last_error.as_deref(), Some("550 no such user"));335 assert_eq!(bounced.last_error.as_deref(), Some("550 no such user"));
336 assert_eq!(fake.sent().len(), 0, "nothing reached the transport");336 assert_eq!(fake.sent().len(), 0, "nothing reached the transport");
@@ -362,13 +362,13 @@ mod tests {
362 };362 };
363 deliver(&state, &last).await;363 deliver(&state, &last).await;
364 let after = state.store.recent_mail(10).await.expect("rows").remove(0);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 assert_eq!(after.last_error.as_deref(), Some("timeout"));366 assert_eq!(after.last_error.as_deref(), Some("timeout"));
367 367
368 // The same failure on an early try is rescheduled instead.368 // The same failure on an early try is rescheduled instead.
369 let early = OutboxEntry { attempts: 1, ..row };369 let early = OutboxEntry { attempts: 1, ..row };
370 deliver(&state, &early).await;370 deliver(&state, &early).await;
371 let after = state.store.recent_mail(10).await.expect("rows").remove(0);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 //! Merging a pull request: the merge gate, the merge itself and what follows it, shared by the1 //! Merging a pull request: the merge gate, the merge itself and what follows it, shared by the
2 //! merge page, auto-merge and the merge queue.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 use forge_core::store::commit_status::StatusState;5 use forge_core::store::commit_status::StatusState;
6 use forge_core::{MergeStyle, PullRequest, ReviewState, Role, User};6 use forge_core::{MergeStyle, PullRequest, ReviewState, Role, User};
7 use forge_git::browse::{CommitInfo, default_branch_commit};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 /// The base branch's merge rule for a pull request, with the facts that rule checks.99 /// The base branch's merge rule for a pull request, with the facts that rule checks.
100 #[derive(Debug, Clone, PartialEq, Eq)]100 #[derive(Debug, Clone, PartialEq, Eq)]
101 pub struct MergeGate {101 pub struct MergeGate {
102- pub rule: Protection,102+ pub rule: RuleFlags,
103 /// Distinct counting reviewers whose latest submitted review is an approval.103 /// Distinct counting reviewers whose latest submitted review is an approval.
104 pub approvals: u32,104 pub approvals: u32,
105 /// Some counting reviewer's latest submitted review requests changes.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 use forge_core::webhooks::WebhookEvent;18 use forge_core::webhooks::WebhookEvent;
19 use forge_core::{Repo, User};19 use forge_core::{Repo, User};
20 use forge_git::browse::{self, RefInfo, RefKind};20 use forge_git::browse::{self, RefInfo, RefKind};
21+use forge_git::history::zero_oid;
21 use forge_git::repo::repo_path;22 use forge_git::repo::repo_path;
22 use forge_git::tags::{create_lightweight_tag, move_lightweight_tag, valid_tag_name};23 use forge_git::tags::{create_lightweight_tag, move_lightweight_tag, valid_tag_name};
23 use futures_util::{Stream, StreamExt};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 /// Tells the ref hooks, webhooks, CI and mirrors that a tag moved from `old` to `new`.171 /// Tells the ref hooks, webhooks, CI and mirrors that a tag moved from `old` to `new`.
176 async fn fire_tag_hook(172 async fn fire_tag_hook(
177 state: &AppState,173 state: &AppState,
@@ -202,6 +198,24 @@ fn check_fields(title: &str, body: &str) -> Result<(), ReleaseError> {
202 Ok(())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 /// `NotFound` when the release belongs to another repo.219 /// `NotFound` when the release belongs to another repo.
206 fn ensure_same_repo(repo: &Repo, release: &Release) -> Result<(), ReleaseError> {220 fn ensure_same_repo(repo: &Repo, release: &Release) -> Result<(), ReleaseError> {
207 if release.repo_id == repo.id {221 if release.repo_id == repo.id {
@@ -244,22 +258,9 @@ pub async fn create(
244 actor: &User,258 actor: &User,
245 input: CreateRelease,259 input: CreateRelease,
246 ) -> Result<Release, ReleaseError> {260 ) -> Result<Release, ReleaseError> {
247- if !valid_tag_name(&input.tag) {261+ check_tag_name(&input.tag)?;
248- return Err(ReleaseError::Invalid(
249- "the tag name may only use letters, digits and . _ - +".to_owned(),
250- ));
251- }
252 check_fields(&input.title, &input.body)?;262 check_fields(&input.title, &input.body)?;
253- if state263+ ensure_tag_unused(state, repo, &input.tag).await?;
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 let path = path_of(state, repo)?;264 let path = path_of(state, repo)?;
264 let refs = refs_of(path.clone()).await?;265 let refs = refs_of(path.clone()).await?;
265 let target_oid = match tag_oid(&refs, &input.tag) {266 let target_oid = match tag_oid(&refs, &input.tag) {
@@ -272,7 +273,7 @@ pub async fn create(
272 .unwrap_or(&repo.default_branch);273 .unwrap_or(&repo.default_branch);
273 let oid = resolve_target(&path, &refs, target).await?;274 let oid = resolve_target(&path, &refs, target).await?;
274 create_lightweight_tag(&state.git, &path, &input.tag, &oid).await?;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 oid277 oid
277 }278 }
278 };279 };
@@ -310,27 +311,14 @@ pub async fn update(
310 check_fields(&edit.title, &edit.body)?;311 check_fields(&edit.title, &edit.body)?;
311 let new_tag = edit.tag.clone().unwrap_or_else(|| release.tag.clone());312 let new_tag = edit.tag.clone().unwrap_or_else(|| release.tag.clone());
312 let retag = new_tag != release.tag;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 let wanted = edit.target.as_deref().filter(|t| !t.is_empty());314 let wanted = edit.target.as_deref().filter(|t| !t.is_empty());
319 let path = path_of(state, repo)?;315 let path = path_of(state, repo)?;
320 let refs = refs_of(path.clone()).await?;316 let refs = refs_of(path.clone()).await?;
321 let mut target_oid = release.target_oid.clone();317 let mut target_oid = release.target_oid.clone();
322 318
323 if retag {319 if retag {
324- if state320+ check_tag_name(&new_tag)?;
325- .store321+ ensure_tag_unused(state, repo, &new_tag).await?;
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- }
334 match tag_oid(&refs, &new_tag) {322 match tag_oid(&refs, &new_tag) {
335 Some(existing) => {323 Some(existing) => {
336 if let Some(target) = wanted324 if let Some(target) = wanted
@@ -348,7 +336,7 @@ pub async fn update(
348 None => release.target_oid.clone(),336 None => release.target_oid.clone(),
349 };337 };
350 create_lightweight_tag(&state.git, &path, &new_tag, &oid).await?;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 target_oid = oid;340 target_oid = oid;
353 }341 }
354 }342 }
@@ -367,7 +355,7 @@ pub async fn update(
367 }355 }
368 None => {356 None => {
369 create_lightweight_tag(&state.git, &path, &release.tag, &oid).await?;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 target_oid = oid;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 pub mod worker;1 pub mod worker;
11 2
12 use std::collections::HashMap;3 use std::collections::HashMap;
@@ -17,31 +8,22 @@ use std::sync::{Mutex, PoisonError};
17 use std::time::{Duration, Instant};8 use std::time::{Duration, Instant};
18 9
19 use forge_git::GitEnv;10 use forge_git::GitEnv;
11+use forge_git::backup::REFS_FORMAT;
20 use forge_git::command::GitCommand;12 use forge_git::command::GitCommand;
21 use tokio::process::Command;13 use tokio::process::Command;
22 use tokio::sync::Notify;14 use tokio::sync::Notify;
23 15
24 use crate::state::AppState;16 use crate::state::AppState;
25 17
26-/// How long a repo waits after its last ref update before it is pushed.
27 pub const PUSH_DEBOUNCE: Duration = Duration::from_secs(5);18 pub const PUSH_DEBOUNCE: Duration = Duration::from_secs(5);
28-/// Newest database snapshots kept on the standby.
29 pub const KEEP_SNAPSHOTS: usize = 24;19 pub const KEEP_SNAPSHOTS: usize = 24;
30-/// Name of the snapshot directory on the standby, under the base.
31 const DB_DIR: &str = "db";20 const DB_DIR: &str = "db";
32-/// Name of the repo directory on the standby, under the base.
33 const REPOS_DIR: &str = "repos";21 const REPOS_DIR: &str = "repos";
34-/// Suffix of the replication status subject that names a repo's wiki.
35 const WIKI_SUBJECT_SUFFIX: &str = ".wiki";22 const WIKI_SUBJECT_SUFFIX: &str = ".wiki";
36-/// Prefix and suffix of a snapshot file name: `forge-<UTC stamp>.db`.
37 const SNAPSHOT_PREFIX: &str = "forge-";23 const SNAPSHOT_PREFIX: &str = "forge-";
38 const SNAPSHOT_SUFFIX: &str = ".db";24 const SNAPSHOT_SUFFIX: &str = ".db";
39-/// Stamp layout in snapshot names: `YYYYMMDDTHHMMSSZ`.
40 const STAMP_LEN: usize = 16;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 pub fn validate_remote_path(path: &str) -> Result<(), String> {27 pub fn validate_remote_path(path: &str) -> Result<(), String> {
46 let well_formed = path.starts_with('/')28 let well_formed = path.starts_with('/')
47 && path.len() > 129 && 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 pub fn wiki_subject(repo_id: &str) -> String {45 pub fn wiki_subject(repo_id: &str) -> String {
65 format!("{repo_id}{WIKI_SUBJECT_SUFFIX}")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 pub fn wiki_subject_repo(subject: &str) -> Option<&str> {49 pub fn wiki_subject_repo(subject: &str) -> Option<&str> {
70 subject.strip_suffix(WIKI_SUBJECT_SUFFIX)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 pub fn validate_repo_id(id: &str) -> Result<(), String> {53 pub fn validate_repo_id(id: &str) -> Result<(), String> {
75 if id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) {54 if id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) {
76 Ok(())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 pub fn sh_quote(arg: &str) -> String {61 pub fn sh_quote(arg: &str) -> String {
85 format!("'{}'", arg.replace('\'', "'\\''"))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 #[derive(Debug, Clone, PartialEq, Eq)]65 #[derive(Debug, Clone, PartialEq, Eq)]
90 pub struct Target {66 pub struct Target {
91 pub user: Option<String>,67 pub user: Option<String>,
92 pub host: String,68 pub host: String,
93 pub port: u16,69 pub port: u16,
94- /// Validated absolute base directory on the standby.
95 pub base: String,70 pub base: String,
96 }71 }
97 72
98 impl Target {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 pub fn parse(spec: &str, port: u16) -> Result<Target, String> {74 pub fn parse(spec: &str, port: u16) -> Result<Target, String> {
102 let (dest, base) = spec75 let (dest, base) = spec
103 .split_once(':')76 .split_once(':')
@@ -133,7 +106,6 @@ impl Target {
133 })106 })
134 }107 }
135 108
136- /// `user@host`, or `host` without a user.
137 pub fn destination(&self) -> String {109 pub fn destination(&self) -> String {
138 match &self.user {110 match &self.user {
139 Some(user) => format!("{user}@{}", self.host),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 pub fn repo_url(&self, remote_repo_dir: &str) -> String {116 pub fn repo_url(&self, remote_repo_dir: &str) -> String {
146 format!(117 format!(
147 "ssh://{}:{}{remote_repo_dir}",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 #[derive(Debug, Clone, PartialEq, Eq)]125 #[derive(Debug, Clone, PartialEq, Eq)]
157 pub struct Layout {126 pub struct Layout {
158 pub base: String,127 pub base: String,
@@ -174,19 +143,16 @@ impl Layout {
174 format!("{}/{DB_DIR}", self.base)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 pub fn repo_dir(&self, repo_id: &str) -> Result<String, String> {146 pub fn repo_dir(&self, repo_id: &str) -> Result<String, String> {
179 validate_repo_id(repo_id)?;147 validate_repo_id(repo_id)?;
180 Ok(format!("{}/{repo_id}.git", self.repos_dir()))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 pub fn wiki_dir(&self, repo_id: &str) -> Result<String, String> {151 pub fn wiki_dir(&self, repo_id: &str) -> Result<String, String> {
185 validate_repo_id(repo_id)?;152 validate_repo_id(repo_id)?;
186 Ok(format!("{}/{repo_id}.wiki.git", self.repos_dir()))153 Ok(format!("{}/{repo_id}.wiki.git", self.repos_dir()))
187 }154 }
188 155
189- /// `<base>/db/forge-<stamp>.db`.
190 pub fn snapshot_file(&self, stamp: &str) -> String {156 pub fn snapshot_file(&self, stamp: &str) -> String {
191 format!(157 format!(
192 "{}/{SNAPSHOT_PREFIX}{stamp}{SNAPSHOT_SUFFIX}",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 pub fn is_snapshot_name(name: &str) -> bool {168 pub fn is_snapshot_name(name: &str) -> bool {
204 let Some(stamp) = name169 let Some(stamp) = name
205 .strip_prefix(SNAPSHOT_PREFIX)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 pub fn snapshot_stamp() -> String {183 pub fn snapshot_stamp() -> String {
220 const FORMAT: &[time::format_description::FormatItem<'static>] =184 const FORMAT: &[time::format_description::FormatItem<'static>] =
221 time::macros::format_description!("[year][month][day]T[hour][minute][second]Z");185 time::macros::format_description!("[year][month][day]T[hour][minute][second]Z");
@@ -224,23 +188,15 @@ pub fn snapshot_stamp() -> String {
224 .unwrap_or_else(|_| "00000000T000000Z".to_owned())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 pub trait StandbyTransport: Send + Sync {191 pub trait StandbyTransport: Send + Sync {
230- /// Runs one shell command (already quoted) on the standby and returns its stdout.
231 fn run(&self, remote_cmd: &str) -> impl Future<Output = Result<Vec<u8>, String>> + Send;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 fn repo_url(&self, remote_repo_dir: &str) -> String;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 fn local_git(&self) -> bool;196 fn local_git(&self) -> bool;
238 197
239- /// The `GIT_SSH_COMMAND` git must use to reach the standby, if any.
240 fn push_ssh_command(&self) -> Option<String>;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 fn upload(200 fn upload(
245 &self,201 &self,
246 local: &Path,202 local: &Path,
@@ -248,7 +204,6 @@ pub trait StandbyTransport: Send + Sync {
248 ) -> impl Future<Output = Result<(), String>> + Send;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 fn upload_command(remote_path: &str) -> String {207 fn upload_command(remote_path: &str) -> String {
253 let (dir, name) = remote_path.rsplit_once('/').unwrap_or(("", remote_path));208 let (dir, name) = remote_path.rsplit_once('/').unwrap_or(("", remote_path));
254 let tmp = format!("{dir}/.tmp-{name}");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 async fn pipe_file(mut command: Command, file: &Path) -> Result<(), String> {218 async fn pipe_file(mut command: Command, file: &Path) -> Result<(), String> {
265 use std::process::Stdio;219 use std::process::Stdio;
266 use tokio::io::AsyncWriteExt;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 async fn capture(mut command: Command) -> Result<Vec<u8>, String> {259 async fn capture(mut command: Command) -> Result<Vec<u8>, String> {
307 use std::process::Stdio;260 use std::process::Stdio;
308 command.stdin(Stdio::null()).kill_on_drop(true);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 async fn push_mirror(277 async fn push_mirror(
326 git: &GitEnv,278 git: &GitEnv,
327 repo_dir: &Path,279 repo_dir: &Path,
@@ -348,8 +300,6 @@ async fn push_mirror(
348 .map_err(|e| e.to_string())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 #[derive(Debug, Clone)]303 #[derive(Debug, Clone)]
354 pub struct SshTransport {304 pub struct SshTransport {
355 target: Target,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 pub fn ssh_options(&self) -> Vec<String> {319 pub fn ssh_options(&self) -> Vec<String> {
371 vec![320 vec![
372 "-i".to_owned(),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 pub fn ssh_argv(&self, remote_cmd: &str) -> Vec<String> {341 pub fn ssh_argv(&self, remote_cmd: &str) -> Vec<String> {
394 let mut argv = self.ssh_options();342 let mut argv = self.ssh_options();
395 argv.push(self.target.destination());343 argv.push(self.target.destination());
@@ -397,7 +345,6 @@ impl SshTransport {
397 argv345 argv
398 }346 }
399 347
400- /// The value for `GIT_SSH_COMMAND`: the same ssh invocation, each word quoted for the shell.
401 pub fn git_ssh_command(&self) -> String {348 pub fn git_ssh_command(&self) -> String {
402 std::iter::once("ssh".to_owned())349 std::iter::once("ssh".to_owned())
403 .chain(self.ssh_options())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 #[cfg(any(test, feature = "test-support"))]392 #[cfg(any(test, feature = "test-support"))]
448 #[derive(Debug, Clone, Copy, Default)]393 #[derive(Debug, Clone, Copy, Default)]
449 pub struct LocalTransport;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 pub async fn push_repo<T: StandbyTransport>(428 pub async fn push_repo<T: StandbyTransport>(
486 transport: &T,429 transport: &T,
487 git: &GitEnv,430 git: &GitEnv,
@@ -498,7 +441,6 @@ pub async fn push_repo<T: StandbyTransport>(
498 .await441 .await
499 }442 }
500 443
501-/// The refs checksum of the bare repo at `remote_repo_dir`, read through the transport.
502 pub async fn remote_refs_checksum<T: StandbyTransport>(444 pub async fn remote_refs_checksum<T: StandbyTransport>(
503 transport: &T,445 transport: &T,
504 remote_repo_dir: &str,446 remote_repo_dir: &str,
@@ -512,8 +454,6 @@ pub async fn remote_refs_checksum<T: StandbyTransport>(
512 Ok(forge_git::backup::refs_checksum_of_listing(&out))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 #[derive(Default)]457 #[derive(Default)]
518 pub struct ReplicationQueue {458 pub struct ReplicationQueue {
519 notify: Notify,459 notify: Notify,
@@ -522,7 +462,6 @@ pub struct ReplicationQueue {
522 }462 }
523 463
524 impl ReplicationQueue {464 impl ReplicationQueue {
525- /// Queues `repo_id` for a push once [`PUSH_DEBOUNCE`] has passed without another update.
526 pub fn enqueue(&self, repo_id: &str) {465 pub fn enqueue(&self, repo_id: &str) {
527 let due = Instant::now() + PUSH_DEBOUNCE;466 let due = Instant::now() + PUSH_DEBOUNCE;
528 self.pending467 self.pending
@@ -532,7 +471,6 @@ impl ReplicationQueue {
532 self.notify.notify_one();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 pub fn take_due(&self, now: Instant) -> Vec<String> {474 pub fn take_due(&self, now: Instant) -> Vec<String> {
537 let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);475 let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
538 let mut due: Vec<String> = pending476 let mut due: Vec<String> = pending
@@ -547,7 +485,6 @@ impl ReplicationQueue {
547 due485 due
548 }486 }
549 487
550- /// The earliest debounce due time among the queued repos, or `None` when nothing is queued.
551 pub fn next_due(&self) -> Option<Instant> {488 pub fn next_due(&self) -> Option<Instant> {
552 self.pending489 self.pending
553 .lock()490 .lock()
@@ -557,24 +494,20 @@ impl ReplicationQueue {
557 .copied()494 .copied()
558 }495 }
559 496
560- /// Asks the worker for a full reconcile pass as soon as it can.
561 pub fn request_reconcile(&self) {497 pub fn request_reconcile(&self) {
562 self.reconcile.store(true, Ordering::SeqCst);498 self.reconcile.store(true, Ordering::SeqCst);
563 self.notify.notify_one();499 self.notify.notify_one();
564 }500 }
565 501
566- /// Returns true once per request.
567 pub fn take_reconcile_request(&self) -> bool {502 pub fn take_reconcile_request(&self) -> bool {
568 self.reconcile.swap(false, Ordering::SeqCst)503 self.reconcile.swap(false, Ordering::SeqCst)
569 }504 }
570 505
571- /// Resolves when something is queued or a reconcile is requested.
572 pub async fn wait(&self) {506 pub async fn wait(&self) {
573 self.notify.notified().await;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 pub fn enqueue_repo(state: &AppState, repo_id: &str) {511 pub fn enqueue_repo(state: &AppState, repo_id: &str) {
579 if state.config.replication.enabled() {512 if state.config.replication.enabled() {
580 state.replication.enqueue(repo_id);513 state.replication.enqueue(repo_id);
@@ -628,7 +561,6 @@ mod tests {
628 assert_eq!(sh_quote("it's"), "'it'\\''s'");561 assert_eq!(sh_quote("it's"), "'it'\\''s'");
629 assert_eq!(sh_quote("$(rm -rf /)`x`;|&"), "'$(rm -rf /)`x`;|&'");562 assert_eq!(sh_quote("$(rm -rf /)`x`;|&"), "'$(rm -rf /)`x`;|&'");
630 assert_eq!(sh_quote("'"), "''\\'''");563 assert_eq!(sh_quote("'"), "''\\'''");
631- // Round trip through a real shell: each quoted word comes back unchanged.
632 let words = ["plain", "it's", "a b", "$HOME", "x'y'z", "back\\slash"];564 let words = ["plain", "it's", "a b", "$HOME", "x'y'z", "back\\slash"];
633 let line = words565 let line = words
634 .iter()566 .iter()
crates/forge-web-app/src/ssh_backend.rsmodified+13 -19
@@ -6,7 +6,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
6 use forge_core::lfs_token::{self, LfsOp};6 use forge_core::lfs_token::{self, LfsOp};
7 use forge_core::{Repo, User};7 use forge_core::{Repo, User};
8 use forge_git::GitService;8 use forge_git::GitService;
9-use forge_ssh::{GitBackend, LfsOperation};9+use forge_ssh::{GitBackend, LfsOperation, RepoPath};
10 10
11 use crate::access::{self, AccessError, Transport};11 use crate::access::{self, AccessError, Transport};
12 use crate::state::AppState;12 use crate::state::AppState;
@@ -97,15 +97,12 @@ impl GitBackend for SshBackend {
97 &self,97 &self,
98 user_id: &str,98 user_id: &str,
99 service: GitService,99 service: GitService,
100- repo_path: &str,100+ repo_path: &RepoPath,
101 git_protocol: Option<&str>,101 git_protocol: Option<&str>,
102 ) -> Result<tokio::process::Command, String> {102 ) -> Result<tokio::process::Command, String> {
103- // parse_exec has already stripped the leading '/' and the trailing ".git".103+ let (user, repo, path) = self
104- let (owner, name) = repo_path104+ .authorize(user_id, &repo_path.owner, &repo_path.name, service)
105- .split_once('/')105+ .await?;
106- .ok_or_else(|| MSG_NOT_FOUND.to_string())?;
107-
108- let (user, repo, path) = self.authorize(user_id, owner, name, service).await?;
109 106
110 Ok(access::git_process(107 Ok(access::git_process(
111 &self.state,108 &self.state,
@@ -123,20 +120,17 @@ impl GitBackend for SshBackend {
123 async fn lfs_authenticate(120 async fn lfs_authenticate(
124 &self,121 &self,
125 user_id: &str,122 user_id: &str,
126- repo_path: &str,123+ repo_path: &RepoPath,
127 operation: LfsOperation,124 operation: LfsOperation,
128 ) -> Result<String, String> {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 // Download is a read and upload is a write, checked exactly as git does.126 // Download is a read and upload is a write, checked exactly as git does.
135- let service = match operation {127+ let (service, op) = match operation {
136- LfsOperation::Download => GitService::UploadPack,128+ LfsOperation::Download => (GitService::UploadPack, LfsOp::Download),
137- LfsOperation::Upload => GitService::ReceivePack,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 if operation == LfsOperation::Upload {135 if operation == LfsOperation::Upload {
142 // Archived repos are refused by the Write check. Pull mirrors are read-only.136 // Archived repos are refused by the Write check. Pull mirrors are read-only.
@@ -153,7 +147,7 @@ impl GitBackend for SshBackend {
153 let token = lfs_token::issue(147 let token = lfs_token::issue(
154 &self.state.key,148 &self.state.key,
155 &repo.id,149 &repo.id,
156- LfsOp::Any,150+ op,
157 now_unix() + LFS_TOKEN_TTL_SECS,151 now_unix() + LFS_TOKEN_TTL_SECS,
158 );152 );
159 let base = self.state.config.base_url.trim_end_matches('/');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 let mut seen = HashSet::new();280 let mut seen = HashSet::new();
281 for id in ids {281 for id in ids {
282 assert!(282 assert!(
283- forge_core::store::ui_prefs::valid_accent(id),283+ forge_core::store::ui_prefs::valid_slug(id),
284 "{kind} {id} is not a slug"284 "{kind} {id} is not a slug"
285 );285 );
286 assert!(seen.insert(id), "{kind} {id} is listed twice");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 releases_ci::{self as g, K},12 releases_ci::{self as g, K},
13 };13 };
14 use crate::pages::ci_job::log_tail;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 use crate::state::AppState;16 use crate::state::AppState;
17+use forge_ci::steps::strip_ansi;
17 18
18 /// How far after the first error line its reason and place are looked for.19 /// How far after the first error line its reason and place are looked for.
19 const WINDOW: usize = 30;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 use std::time::Duration;12 use std::time::Duration;
13 13
14 use bytes::Bytes;14 use bytes::Bytes;
15+use forge_ci::steps::strip_ansi;
15 use forge_core::ci::{CiArtifact, CiJob, CiRun, JobState};16 use forge_core::ci::{CiArtifact, CiJob, CiRun, JobState};
16 use forge_core::{Store, User};17 use forge_core::{Store, User};
17 use futures_util::{Stream, TryStreamExt};18 use futures_util::{Stream, TryStreamExt};
@@ -37,7 +38,7 @@ use crate::i18n::{
37 use crate::live::{changed_event, events_response};38 use crate::live::{changed_event, events_response};
38 use crate::pages::ci_runs::{39 use crate::pages::ci_runs::{
39 age_text, can_write, commit_reachable_for, dock_bars, duration_text, job_href, run_href,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 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};43 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};
43 use crate::state::AppState;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 use std::future::Future;12 use std::future::Future;
13 use std::path::Path;13 use std::path::Path;
14 14
15+use forge_ci::steps::strip_ansi;
15 use forge_core::ci::{CiJob, CiRun, JobSample, JobState, JobStep, RunState, StepSample, StepState};16 use forge_core::ci::{CiJob, CiRun, JobSample, JobState, JobStep, RunState, StepSample, StepState};
16 use forge_core::{Action, Denied, Store, User, authorize};17 use forge_core::{Action, Denied, Store, User, authorize};
17 use forge_git::browse::{RefInfo, RefKind, commit_reachable, reachable_commits, read_commit};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 /// The last non-empty line of a tail: what a job row previews.1475 /// The last non-empty line of a tail: what a job row previews.
1507 fn last_line(tail: &[String]) -> Option<&str> {1476 fn last_line(tail: &[String]) -> Option<&str> {
1508 tail.iter()1477 tail.iter()
crates/forge-web-pages/src/pages/edit_history.rsmodified+15 -25
@@ -7,7 +7,7 @@
7 use std::collections::HashMap;7 use std::collections::HashMap;
8 use std::sync::Arc;8 use std::sync::Arc;
9 9
10-use forge_core::{EditVersion, Issue, Thread};10+use forge_core::{EditTarget, EditVersion, Issue, Thread};
11 use similar::{ChangeTag, TextDiff};11 use similar::{ChangeTag, TextDiff};
12 use topcoat::Result;12 use topcoat::Result;
13 use topcoat::context::{Cx, context};13 use topcoat::context::{Cx, context};
@@ -36,35 +36,23 @@ path_param!(target_id);
36 /// Unchanged lines shown around each change.36 /// Unchanged lines shown around each change.
37 const CONTEXT_LINES: usize = 3;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 /// The history URL of one target of an item: `/{o}/{r}/{issues|pulls}/{n}/history/{kind}/{id}`.39 /// The history URL of one target of an item: `/{o}/{r}/{issues|pulls}/{n}/history/{kind}/{id}`.
43 pub fn history_href(40 pub fn history_href(
44 owner: &str,41 owner: &str,
45 repo_name: &str,42 repo_name: &str,
46 kind: ItemKind,43 kind: ItemKind,
47 number: i64,44 number: i64,
48- target_kind: &str,45+ target_kind: EditTarget,
49 target: &str,46 target: &str,
50 ) -> String {47 ) -> String {
51 repo_href(48 repo_href(
52 owner,49 owner,
53 repo_name,50 repo_name,
54 kind.segment(),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 /// Edit counts for the root comments and replies of `threads`, shared by every thread of a page.56 /// Edit counts for the root comments and replies of `threads`, shared by every thread of a page.
69 pub async fn thread_edit_counts(57 pub async fn thread_edit_counts(
70 state: &AppState,58 state: &AppState,
@@ -75,7 +63,7 @@ pub async fn thread_edit_counts(
75 .flat_map(|thread| std::iter::once(&thread.root).chain(thread.replies.iter()))63 .flat_map(|thread| std::iter::once(&thread.root).chain(thread.replies.iter()))
76 .map(|comment| comment.id.as_str())64 .map(|comment| comment.id.as_str())
77 .collect();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 /// One line of a diff: its CSS class from the `diff-*` set and its text with its sign.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 ctx: RepoCtx,158 ctx: RepoCtx,
171 kind_item: ItemKind,159 kind_item: ItemKind,
172 item: Issue,160 item: Issue,
173- target_kind: &'static str,161+ target_kind: EditTarget,
174 target: String,162 target: String,
175 ) -> Result<impl View> {163 ) -> Result<impl View> {
176 let target = target.as_str();164 let target = target.as_str();
@@ -187,14 +175,14 @@ async fn history_page(
187 }175 }
188 176
189 let (current_title, current_body): (Option<String>, String) = match target_kind {177 let (current_title, current_body): (Option<String>, String) = match target_kind {
190- "issue" => (Some(item.title.clone()), item.body.clone()),178+ EditTarget::Issue => (Some(item.title.clone()), item.body.clone()),
191- "comment" => {179+ EditTarget::Comment => {
192 let Some(comment) = state.store.comment_by_id(&item.id, target).await? else {180 let Some(comment) = state.store.comment_by_id(&item.id, target).await? else {
193 return Err(not_found().into());181 return Err(not_found().into());
194 };182 };
195 (None, comment.body)183 (None, comment.body)
196 }184 }
197- _ => {185+ EditTarget::ReviewComment => {
198 let Some(comment) = state.store.review_comment(target).await? else {186 let Some(comment) = state.store.review_comment(target).await? else {
199 return Err(not_found().into());187 return Err(not_found().into());
200 };188 };
@@ -214,7 +202,7 @@ async fn history_page(
214 now,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 let back = repo_href(&owner, &name, kind_item.segment(), &number.to_string());206 let back = repo_href(&owner, &name, kind_item.segment(), &number.to_string());
219 let page_title = g::history_title(lang, what, &format!("{owner}/{name} #{number}"));207 let page_title = g::history_title(lang, what, &format!("{owner}/{name} #{number}"));
220 let header = ctx208 let header = ctx
@@ -305,10 +293,12 @@ async fn history_entry(cx: &Cx, lang: Lang, entry: HistoryEntry) -> Result<impl
305 }293 }
306 294
307 /// Parses the `{kind}` segment, or 404 for anything without edit history.295 /// Parses the `{kind}` segment, or 404 for anything without edit history.
308-fn parse_kind(raw: &str) -> Result<&'static str> {296+fn parse_kind(raw: &str) -> Result<EditTarget> {
309- match KINDS.into_iter().find(|known| *known == raw) {297+ match raw {
310- Some(known) => Ok(known),298+ "issue" => Ok(EditTarget::Issue),
311- None => Err(not_found().into()),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 use std::collections::HashSet;6 use std::collections::HashSet;
7 use topcoat::context::Cx;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 use forge_core::{Reaction, ReactionSummary, ReactionTarget};12 use forge_core::{Reaction, ReactionSummary, ReactionTarget};
11 use forge_core::{ReviewState, Thread, authorize, validate_body};13 use forge_core::{ReviewState, Thread, authorize, validate_body};
12 use serde::Deserialize;14 use serde::Deserialize;
@@ -19,7 +21,7 @@ use crate::auth::check_csrf;
19 use crate::i18n::Lang;21 use crate::i18n::Lang;
20 use crate::i18n::issues::{self as g, K};22 use crate::i18n::issues::{self as g, K};
21 use crate::notify::{self, Activity};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 use crate::pages::notifications::{NotifyBox, notify_pill};25 use crate::pages::notifications::{NotifyBox, notify_pill};
24 use crate::pages::pull_reviews::suggest_states;26 use crate::pages::pull_reviews::suggest_states;
25 use crate::pages::repo_ctx::RepoCtx;27 use crate::pages::repo_ctx::RepoCtx;
@@ -52,7 +54,6 @@ impl ItemKind {
52 }54 }
53 }55 }
54 56
55-// Permissions
56 57
57 pub fn viewer(ctx: &RepoCtx) -> Option<&User> {58 pub fn viewer(ctx: &RepoCtx) -> Option<&User> {
58 ctx.viewer.as_ref().map(|(user, _)| user)59 ctx.viewer.as_ref().map(|(user, _)| user)
@@ -116,7 +117,6 @@ pub fn csrf_of(ctx: &RepoCtx) -> String {
116 .unwrap_or_default()117 .unwrap_or_default()
117 }118 }
118 119
119-// Lookups
120 120
121 /// Parses an issue number: digits only, greater than zero. Anything else is 404.121 /// Parses an issue number: digits only, greater than zero. Anything else is 404.
122 pub fn parse_number(raw: &str) -> Result<i64> {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 .unwrap_or_default()181 .unwrap_or_default()
182 }182 }
183 183
184-// Timeline
185 184
186 /// One comment, or the item body (which uses the same item shape without a delete action).185 /// One comment, or the item body (which uses the same item shape without a delete action).
187 pub struct CommentView {186 pub struct CommentView {
@@ -343,7 +342,6 @@ fn event_line(
343 "base_changed" => g::event_base_changed(lang, &text("from"), &text("to")),342 "base_changed" => g::event_base_changed(lang, &text("from"), &text("to")),
344 other => other.to_owned(),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 let (link_href, link_label) = if is_hex_oid(&commit) {345 let (link_href, link_label) = if is_hex_oid(&commit) {
348 let href = reachable346 let href = reachable
349 .contains(&commit)347 .contains(&commit)
@@ -702,7 +700,6 @@ pub async fn load_discussion(
702 let comments = store.list_comments(&item.id).await?;700 let comments = store.list_comments(&item.id).await?;
703 let events = store.list_events(&item.id).await?;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 let event_commits: Vec<String> = events703 let event_commits: Vec<String> = events
707 .iter()704 .iter()
708 .filter_map(|e| e.data.get("commit").and_then(Json::as_str))705 .filter_map(|e| e.data.get("commit").and_then(Json::as_str))
@@ -711,7 +708,6 @@ pub async fn load_discussion(
711 .collect();708 .collect();
712 let reachable = reachable_among(&ctx.path, event_commits).await;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 let mut ids: Vec<String> = std::iter::once(item.author_id.clone())711 let mut ids: Vec<String> = std::iter::once(item.author_id.clone())
716 .chain(comments.iter().map(|c| c.author_id.clone()))712 .chain(comments.iter().map(|c| c.author_id.clone()))
717 .chain(events.iter().filter_map(|e| e.actor_id.clone()))713 .chain(events.iter().filter_map(|e| e.actor_id.clone()))
@@ -731,8 +727,6 @@ pub async fn load_discussion(
731 let link = link_context(state, &ctx.repo, &ctx.repo.default_branch, "");727 let link = link_context(state, &ctx.repo, &ctx.repo.default_branch, "");
732 let csrf = csrf_of(ctx);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 let viewer_id = viewer(ctx).map(|user| user.id.clone());730 let viewer_id = viewer(ctx).map(|user| user.id.clone());
737 let can_react = viewer_id.is_some() && !ctx.repo.archived && may_converse(ctx, item);731 let can_react = viewer_id.is_some() && !ctx.repo.archived && may_converse(ctx, item);
738 let reaction_action = repo_href(&owner, &name, segment, &format!("{number}/reactions"));732 let reaction_action = repo_href(&owner, &name, segment, &format!("{number}/reactions"));
@@ -752,7 +746,6 @@ pub async fn load_discussion(
752 )746 )
753 .await?;747 .await?;
754 748
755- // Body: first entry of the timeline.
756 let (author, author_hash) = who(&item.author_id);749 let (author, author_hash) = who(&item.author_id);
757 let body_source = if item.body.trim().is_empty() {750 let body_source = if item.body.trim().is_empty() {
758 g::t(lang, K::NoDescription)751 g::t(lang, K::NoDescription)
@@ -764,11 +757,11 @@ pub async fn load_discussion(
764 ItemKind::Pull => format!("pull-{number}"),757 ItemKind::Pull => format!("pull-{number}"),
765 };758 };
766 let opened = When::new(lang, &item.created_at, &tz, now);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 let body_history = body_edits761 let body_history = body_edits
769 .get(&item.id)762 .get(&item.id)
770 .is_some_and(|count| *count > 0)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 let body = CommentView {765 let body = CommentView {
773 anchor: body_anchor,766 anchor: body_anchor,
774 author: display_name(lang, &author),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 let comment_ids: Vec<&str> = comments.iter().map(|c| c.id.as_str()).collect();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 let mut keyed: Vec<(String, Entry)> = Vec::new();795 let mut keyed: Vec<(String, Entry)> = Vec::new();
804 for comment in comments {796 for comment in comments {
805 let (who_name, hash) = who(&comment.author_id);797 let (who_name, hash) = who(&comment.author_id);
@@ -816,7 +808,9 @@ pub async fn load_discussion(
816 when: When::new(lang, &comment.created_at, &tz, now),808 when: When::new(lang, &comment.created_at, &tz, now),
817 html: render_markdown(&comment.body, Some(&link)),809 html: render_markdown(&comment.body, Some(&link)),
818 history_href: edited810 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 edit_href: mine814 edit_href: mine
821 .then(|| repo_href(&owner, &name, segment, &format!("{comment_path}/edit"))),815 .then(|| repo_href(&owner, &name, segment, &format!("{comment_path}/edit"))),
822 delete_href: mine816 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 /// A reaction's name in the viewer's language, for its picker button.989 /// A reaction's name in the viewer's language, for its picker button.
997 fn reaction_label(lang: Lang, reaction: Reaction) -> &'static str {990 fn reaction_label(lang: Lang, reaction: Reaction) -> &'static str {
998 use crate::i18n::s;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 fn reaction_title(lang: Lang, users: &[String], count: usize) -> String {1005 fn reaction_title(lang: Lang, users: &[String], count: usize) -> String {
1012 let names = users.join(", ");1006 let names = users.join(", ");
1013 match count.saturating_sub(users.len()) {1007 match count.saturating_sub(users.len()) {
@@ -1108,7 +1102,6 @@ async fn review_entries(
1108 Ok(keyed)1102 Ok(keyed)
1109 }1103 }
1110 1104
1111-// Sidebar
1112 1105
1113 pub struct LabelRow {1106 pub struct LabelRow {
1114 id: String,1107 id: String,
@@ -1422,7 +1415,6 @@ pub async fn item_sidebar(
1422 locked,1415 locked,
1423 lock_reason,1416 lock_reason,
1424 } = sidebar;1417 } = sidebar;
1425- // "Assign to me" posts the whole list with the viewer added, since the route replaces it.
1426 let assign_next = match viewer {1418 let assign_next = match viewer {
1427 Some(me) if write && !assignees.iter().any(|a| *a == me) => {1419 Some(me) if write && !assignees.iter().any(|a| *a == me) => {
1428 let mut next = assignees.clone();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 /// The id of the comment form. The head's Close and Reopen buttons post it with `form=`, so a1443 /// The id of the comment form. The head's Close and Reopen buttons post it with `form=`, so a
1453 /// close can carry the draft text as its comment, as it always did.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 /// The form fields of a comment or state POST.1509 /// The form fields of a comment or state POST.
1520 #[derive(Deserialize)]1510 #[derive(Deserialize)]
@@ -1582,7 +1572,6 @@ pub async fn post_comment(
1582 if !pull {1572 if !pull {
1583 state.live.bump_issue(&ctx.repo.id, &item.id);1573 state.live.bump_issue(&ctx.repo.id, &item.id);
1584 }1574 }
1585- // The author's contribution calendar counts the comment.
1586 state.live.bump(&crate::live::Topic::User(user.id.clone()));1575 state.live.bump(&crate::live::Topic::User(user.id.clone()));
1587 emit_comment(state, &ctx.repo, &sender, "created", pull, item, &comment).await;1576 emit_comment(state, &ctx.repo, &sender, "created", pull, item, &comment).await;
1588 notify::dispatch(1577 notify::dispatch(
@@ -1611,11 +1600,11 @@ pub async fn post_comment(
1611 ("reopened", Activity::Reopened)1600 ("reopened", Activity::Reopened)
1612 };1601 };
1613 emit_item_action(state, &ctx.repo, &sender, pull, item.number, action).await;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 crate::merge_queue::drop_pull(state, &ctx.repo, &item.id, "closed").await;1604 crate::merge_queue::drop_pull(state, &ctx.repo, &item.id, "closed").await;
1616 }1605 }
1617 if pull1606 if pull
1618- && action == "reopened"1607+ && next == IssueState::Open
1619 && let Some(pr) = state1608 && let Some(pr) = state
1620 .store1609 .store
1621 .pull_by_number(&ctx.repo.id, item.number)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 use forge_core::store::admin_alerts::AdminNotice;11 use forge_core::store::admin_alerts::AdminNotice;
12 use forge_core::store::advisories::AdvisoryNotice;12 use forge_core::store::advisories::AdvisoryNotice;
13 use forge_core::store::transfers::PendingTransfer;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 use futures_util::{Stream, StreamExt, future, stream};15 use futures_util::{Stream, StreamExt, future, stream};
16 use serde::Deserialize;16 use serde::Deserialize;
17 use topcoat::Result;17 use topcoat::Result;
@@ -160,11 +160,11 @@ impl Entry {
160 160
161 /// The row for an issue or pull inbox entry.161 /// The row for an issue or pull inbox entry.
162 fn issue_row(lang: Lang, note: &Notification, tz: &str, now: i64) -> RowView {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()) {163+ let (kind_label, icon_class) = match (note.is_pull, note.issue_state) {
164- (false, "open") => (g::t(lang, K::KindOpenIssue), "notif-icon issue-open"),164+ (false, IssueState::Open) => (g::t(lang, K::KindOpenIssue), "notif-icon issue-open"),
165- (false, _) => (g::t(lang, K::KindClosedIssue), "notif-icon issue-closed"),165+ (false, IssueState::Closed) => (g::t(lang, K::KindClosedIssue), "notif-icon issue-closed"),
166- (true, "open") => (g::t(lang, K::KindOpenPull), "notif-icon pull-open"),166+ (true, IssueState::Open) => (g::t(lang, K::KindOpenPull), "notif-icon pull-open"),
167- (true, _) => (g::t(lang, K::KindClosedPull), "notif-icon pull-closed"),167+ (true, IssueState::Closed) => (g::t(lang, K::KindClosedPull), "notif-icon pull-closed"),
168 };168 };
169 let actor = note169 let actor = note
170 .last_actor_name170 .last_actor_name
@@ -498,7 +498,11 @@ async fn inbox_fingerprint(state: &AppState, user: &User, all: bool) -> Result<S
498 {498 {
499 lines.push(format!(499 lines.push(format!(
500 "issue {} {} {} {} {}",500 "issue {} {} {} {} {}",
501- note.id, note.unread, note.updated_at, note.title, note.issue_state501+ note.id,
502+ note.unread,
503+ note.updated_at,
504+ note.title,
505+ note.issue_state.as_str()
502 ));506 ));
503 }507 }
504 for note in state508 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 use std::collections::{HashMap, HashSet};1 use std::collections::{HashMap, HashSet};
5 use std::path::PathBuf;2 use std::path::PathBuf;
6 use std::time::Duration;3 use std::time::Duration;
7 4
8 use forge_core::Repo as RepoRecord;5 use forge_core::Repo as RepoRecord;
9 use forge_core::WatchLevel;6 use forge_core::WatchLevel;
10-use forge_core::time::stamp_before;7+use forge_core::time::stamp_ago;
11 use forge_git::browse;8 use forge_git::browse;
12 use forge_git::repo::repo_path;9 use forge_git::repo::repo_path;
13 use topcoat::Result;10 use topcoat::Result;
@@ -39,11 +36,6 @@ use crate::views::{
39 path_param!(owner);36 path_param!(owner);
40 path_param!(repo);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 #[component]39 #[component]
48 pub async fn repo_head(40 pub async fn repo_head(
49 cx: &Cx,41 cx: &Cx,
@@ -85,12 +77,10 @@ pub async fn repo_head(
85 let vis = i18n::visibility_label(lang, visibility);77 let vis = i18n::visibility_label(lang, visibility);
86 let shown_title = title.unwrap_or_else(|| tab_title(lang, active, &name));78 let shown_title = title.unwrap_or_else(|| tab_title(lang, active, &name));
87 let active = active.to_owned();79 let active = active.to_owned();
88- // The fork button posts with the same session CSRF token as the star form.
89 let fork_control = match (can_fork, star.as_ref()) {80 let fork_control = match (can_fork, star.as_ref()) {
90 (true, Some(star)) => Some((repo_href(&owner, &name, "fork", ""), star.csrf.clone())),81 (true, Some(star)) => Some((repo_href(&owner, &name, "fork", ""), star.csrf.clone())),
91 _ => None,82 _ => None,
92 };83 };
93- // Signed-in viewers get a button that stars or unstars; anonymous viewers see the count only.
94 let star_control = match star {84 let star_control = match star {
95 Some(star) => {85 Some(star) => {
96 let (path, label) = if star.starred {86 let (path, label) = if star.starred {
@@ -103,7 +93,6 @@ pub async fn repo_head(
103 None => None,93 None => None,
104 };94 };
105 let anon_count = format!("\u{2605} {stars}");95 let anon_count = format!("\u{2605} {stars}");
106- // Signed-in viewers get the watch level select; everyone gets the watcher count.
107 let watch_control = watch.map(|watch| {96 let watch_control = watch.map(|watch| {
108 let level = match watch.level {97 let level = match watch.level {
109 WatchLevel::Participating => "participating",98 WatchLevel::Participating => "participating",
@@ -114,13 +103,11 @@ pub async fn repo_head(
114 });103 });
115 let watch_count = g::watching_count(lang, watchers);104 let watch_count = g::watching_count(lang, watchers);
116 let fork_count = g::forks_count(lang, forks);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 let mut parts: Vec<SubPart> = Vec::new();106 let mut parts: Vec<SubPart> = Vec::new();
119 if is_code {107 if is_code {
120 if !description.is_empty() {108 if !description.is_empty() {
121 parts.push(SubPart::text(description.as_str()));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 if private {111 if private {
125 parts.push(SubPart::text(vis));112 parts.push(SubPart::text(vis));
126 }113 }
@@ -183,12 +170,9 @@ pub async fn repo_head(
183 <p class="state" role="status">(g::t(lang, K::ArchivedNotice))</p>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 .boxed())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 #[component]176 #[component]
193 async fn clone_popover(177 async fn clone_popover(
194 cx: &Cx,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 #[component]205 #[component]
224 async fn branches_card(206 async fn branches_card(
225 cx: &Cx,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 const MAX_PUSH_BANNERS: usize = 3;243 const MAX_PUSH_BANNERS: usize = 3;
263-/// How far back a push still counts as recent.
264 const RECENT_PUSH_WINDOW: Duration = Duration::from_secs(60 * 60);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 struct PushBanner {246 struct PushBanner {
268 branch: String,247 branch: String,
269 at_unix: i64,248 at_unix: i64,
270- /// The push's stamp, for the `<time>` that shows its age.
271 at: String,249 at: String,
272 href: String,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 async fn recent_push_banners(253 async fn recent_push_banners(
281 state: &AppState,254 state: &AppState,
282 ctx: &RepoCtx,255 ctx: &RepoCtx,
@@ -295,7 +268,6 @@ async fn recent_push_banners(
295 None => repo.clone(),268 None => repo.clone(),
296 };269 };
297 270
298- // Forks the viewer owns, or that an organization they hold a role in owns.
299 let mut forks: Vec<RepoRecord> = Vec::new();271 let mut forks: Vec<RepoRecord> = Vec::new();
300 for fork in state.store.list_forks(&repo.id).await? {272 for fork in state.store.list_forks(&repo.id).await? {
301 let mine = fork.owner_id == user.id273 let mine = fork.owner_id == user.id
@@ -311,7 +283,7 @@ async fn recent_push_banners(
311 let mut candidates: Vec<&RepoRecord> = vec![repo];283 let mut candidates: Vec<&RepoRecord> = vec![repo];
312 candidates.extend(forks.iter());284 candidates.extend(forks.iter());
313 let ids: Vec<&str> = candidates.iter().map(|r| r.id.as_str()).collect();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 let pushes = state287 let pushes = state
316 .store288 .store
317 .recent_branch_pushes(&ids, &user.id, &since)289 .recent_branch_pushes(&ids, &user.id, &since)
@@ -371,7 +343,6 @@ async fn recent_push_banners(
371 Ok(banners)343 Ok(banners)
372 }344 }
373 345
374-/// The "had recent pushes" banners above the code tab.
375 #[component]346 #[component]
376 async fn recent_pushes(347 async fn recent_pushes(
377 cx: &Cx,348 cx: &Cx,
@@ -415,7 +386,6 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
415 let push_ssh = format!("git remote add origin {ssh}\ngit push -u origin {branch}");386 let push_ssh = format!("git remote add origin {ssh}\ngit push -u origin {branch}");
416 let title = format!("{}/{}", repo.owner_name, repo.name);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 let mut tree = None;389 let mut tree = None;
420 let mut readme = None;390 let mut readme = None;
421 let mut bar = None;391 let mut bar = None;
@@ -443,7 +413,6 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
443 ));413 ));
444 }414 }
445 let follows = follows_branch(&refs, &branch);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 let live = home_live_url(&repo.owner_name, &repo.name, &branch);416 let live = home_live_url(&repo.owner_name, &repo.name, &branch);
448 let owner_name = repo.owner_name.clone();417 let owner_name = repo.owner_name.clone();
449 let repo_name = repo.name.clone();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 #[route(* "/{owner}/{repo}")]470 #[route(* "/{owner}/{repo}")]
503 async fn repo_other_methods(cx: &Cx) -> Result<&'static str> {471 async fn repo_other_methods(cx: &Cx) -> Result<&'static str> {
504 Err(not_found().into())472 Err(not_found().into())
crates/forge-web-repo/src/pages/authoring_tests.rsmodified+2 -2
@@ -1,6 +1,6 @@
1 //! Router-level tests for attachments, suggestions, task toggles and review requests.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 use topcoat::router::request::Request;4 use topcoat::router::request::Request;
5 use topcoat::router::{Body, to_bytes};5 use topcoat::router::{Body, to_bytes};
6 6
@@ -206,7 +206,7 @@ async fn scenario_task_toggles(fx: &Fixture) {
206 .unwrap()206 .unwrap()
207 .unwrap();207 .unwrap();
208 assert_eq!(now.body, "- [ ] one\n- [x] two\n");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 assert_eq!(history.len(), 1);210 assert_eq!(history.len(), 1);
211 assert_eq!(history[0].old_body, "- [ ] one\n- [ ] two\n");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 use forge_core::protection::effective;7 use forge_core::protection::effective;
8 use forge_git::branches;8 use forge_git::branches;
9 use forge_git::browse::{self, RefKind};9 use forge_git::browse::{self, RefKind};
10+use forge_git::history::zero_oid;
10 use serde::Deserialize;11 use serde::Deserialize;
11 use topcoat::Result;12 use topcoat::Result;
12 use topcoat::context::{Cx, context};13 use topcoat::context::{Cx, context};
@@ -372,7 +373,7 @@ async fn branch_create(cx: &Cx, Form(form): Form<CreateForm>) -> Result<SeeOther
372 branch = %branch,373 branch = %branch,
373 "branch created from the branches page"374 "branch created from the branches page"
374 );375 );
375- let zero = "0".repeat(oid.len());376+ let zero = zero_oid(&oid);
376 let refname = format!("refs/heads/{branch}");377 let refname = format!("refs/heads/{branch}");
377 if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &zero, &oid).await {378 if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &zero, &oid).await {
378 tracing::error!(error = %e, "post-update work after branch create failed");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 branch = %branch,431 branch = %branch,
431 "branch deleted from the branches page"432 "branch deleted from the branches page"
432 );433 );
433- let zero = "0".repeat(tip.len());434+ let zero = zero_oid(&tip);
434 let refname = format!("refs/heads/{branch}");435 let refname = format!("refs/heads/{branch}");
435 if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &tip, &zero).await {436 if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &tip, &zero).await {
436 tracing::error!(error = %e, "post-update work after branch delete failed");437 tracing::error!(error = %e, "post-update work after branch delete failed");
crates/forge-web-repo/src/pages/ci_tests.rsmodified+47 -76
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
6 use std::sync::Arc;6 use std::sync::Arc;
7 use std::time::Duration;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 use forge_core::{Role, Store, Visibility};10 use forge_core::{Role, Store, Visibility};
11 use forge_git::repo::{init_bare, repo_path};11 use forge_git::repo::{init_bare, repo_path};
12 use topcoat::router::request::Request;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 async fn get(app: &Router, uri: &str, cookie: Option<&str>) -> Reply {144 async fn get(app: &Router, uri: &str, cookie: Option<&str>) -> Reply {
137 let mut builder = Request::builder().method("GET").uri(uri);145 let mut builder = Request::builder().method("GET").uri(uri);
138 if let Some(cookie) = cookie {146 if let Some(cookie) = cookie {
@@ -183,15 +191,17 @@ async fn run_with(fx: &Fixture, jobs: &[&str], needs_approval: bool) -> CiRun {
183 .collect();191 .collect();
184 fx.store192 fx.store
185 .create_run(193 .create_run(
186- &fx.repo.id,194+ &NewRun {
187- "push",195+ repo_id: &fx.repo.id,
188- "refs/heads/main",196+ trigger: "push",
189- &fx.head,197+ git_ref: "refs/heads/main",
190- None,198+ commit_oid: &fx.head,
191- &fx.tahinli,199+ pull_number: None,
200+ actor_id: &fx.tahinli,
192 needs_approval,201 needs_approval,
202+ config_error: None,
203+ },
193 &specs,204 &specs,
194- None,
195 )205 )
196 .await206 .await
197 .expect("run")207 .expect("run")
@@ -1058,12 +1068,7 @@ async fn approve_only_works_while_waiting_for_approval() {
1058 &[],1068 &[],
1059 )1069 )
1060 .await;1070 .await;
1061- assert!(1071+ assert_notice(&approved, "approved");
1062- approved
1063- .location()
1064- .unwrap_or_default()
1065- .ends_with("?notice=approved")
1066- );
1067 let now = fx1072 let now = fx
1068 .store1073 .store
1069 .run_by_id(&run.id)1074 .run_by_id(&run.id)
@@ -1084,12 +1089,7 @@ async fn approve_only_works_while_waiting_for_approval() {
1084 &[],1089 &[],
1085 )1090 )
1086 .await;1091 .await;
1087- assert!(1092+ assert_notice(&again, "not-waiting");
1088- again
1089- .location()
1090- .unwrap_or_default()
1091- .ends_with("?notice=not-waiting")
1092- );
1093 let still = fx1093 let still = fx
1094 .store1094 .store
1095 .run_by_id(&run.id)1095 .run_by_id(&run.id)
@@ -1112,12 +1112,7 @@ async fn cancel_and_rerun_post_and_redirect() {
1112 &[],1112 &[],
1113 )1113 )
1114 .await;1114 .await;
1115- assert!(1115+ assert_notice(&cancelled, "cancelled");
1116- cancelled
1117- .location()
1118- .unwrap_or_default()
1119- .ends_with("?notice=cancelled")
1120- );
1121 let now = fx1116 let now = fx
1122 .store1117 .store
1123 .run_by_id(&run.id)1118 .run_by_id(&run.id)
@@ -1132,12 +1127,7 @@ async fn cancel_and_rerun_post_and_redirect() {
1132 &[],1127 &[],
1133 )1128 )
1134 .await;1129 .await;
1135- assert!(1130+ assert_notice(&finished, "finished");
1136- finished
1137- .location()
1138- .unwrap_or_default()
1139- .ends_with("?notice=finished")
1140- );
1141 1131
1142 let rerun = post(1132 let rerun = post(
1143 &fx.app,1133 &fx.app,
@@ -1170,11 +1160,7 @@ async fn manual_run_refuses_an_unknown_branch() {
1170 &[("branch", "no-such-branch")],1160 &[("branch", "no-such-branch")],
1171 )1161 )
1172 .await;1162 .await;
1173- assert!(1163+ assert_notice(&res, "no-branch");
1174- res.location()
1175- .unwrap_or_default()
1176- .ends_with("?notice=no-branch")
1177- );
1178 let reader = post(1164 let reader = post(
1179 &fx.app,1165 &fx.app,
1180 RUN_BASE,1166 RUN_BASE,
@@ -1249,15 +1235,17 @@ async fn badge_follows_read_access_and_has_no_run_before_one_exists() {
1249 }];1235 }];
1250 fx.store1236 fx.store
1251 .create_run(1237 .create_run(
1252- &open.id,1238+ &NewRun {
1253- "push",1239+ repo_id: &open.id,
1254- "refs/heads/main",1240+ trigger: "push",
1255- SHA,1241+ git_ref: "refs/heads/main",
1256- None,1242+ commit_oid: SHA,
1257- &fx.tahinli,1243+ pull_number: None,
1258- false,1244+ actor_id: &fx.tahinli,
1245+ needs_approval: false,
1246+ config_error: None,
1247+ },
1259 &specs,1248 &specs,
1260- None,
1261 )1249 )
1262 .await1250 .await
1263 .expect("run");1251 .expect("run");
@@ -1327,15 +1315,17 @@ async fn run_at(fx: &Fixture, commit: &str) {
1327 }];1315 }];
1328 fx.store1316 fx.store
1329 .create_run(1317 .create_run(
1330- &fx.repo.id,1318+ &NewRun {
1331- "push",1319+ repo_id: &fx.repo.id,
1332- "refs/heads/main",1320+ trigger: "push",
1333- commit,1321+ git_ref: "refs/heads/main",
1334- None,1322+ commit_oid: commit,
1335- &fx.tahinli,1323+ pull_number: None,
1336- false,1324+ actor_id: &fx.tahinli,
1325+ needs_approval: false,
1326+ config_error: None,
1327+ },
1337 &specs,1328 &specs,
1338- None,
1339 )1329 )
1340 .await1330 .await
1341 .expect("run");1331 .expect("run");
@@ -1584,12 +1574,7 @@ async fn rerun_failed_and_rerun_job_start_partial_runs() {
1584 let page = get(&fx.app, &run_url, Some(&writer)).await.text();1574 let page = get(&fx.app, &run_url, Some(&writer)).await.text();
1585 assert!(!page.contains("Re-run failed jobs"));1575 assert!(!page.contains("Re-run failed jobs"));
1586 let early = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await;1576 let early = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await;
1587- assert!(1577+ assert_notice(&early, "not-done");
1588- early
1589- .location()
1590- .unwrap_or_default()
1591- .ends_with("?notice=not-done")
1592- );
1593 1578
1594 let cancelled = post(&fx.app, &format!("{run_url}/cancel"), &writer, &[]).await;1579 let cancelled = post(&fx.app, &format!("{run_url}/cancel"), &writer, &[]).await;
1595 assert_eq!(cancelled.status, 303);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 .await;1634 .await;
1650- assert!(1635+ assert_notice(&early, "not-done");
1651- early
1652- .location()
1653- .unwrap_or_default()
1654- .ends_with("?notice=not-done")
1655- );
1656 let refused = post(1636 let refused = post(
1657 &fx.app,1637 &fx.app,
1658 &format!("/tahinli/proj/ci/jobs/{}/rerun", job.id),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 assert!(!page.contains(">Re-run<"));1663 assert!(!page.contains(">Re-run<"));
1684 assert!(!page.contains(&format!("/commit/{SHA}")));1664 assert!(!page.contains(&format!("/commit/{SHA}")));
1685 let refused = post(&fx.app, &format!("{run_url}/rerun"), &writer, &[]).await;1665 let refused = post(&fx.app, &format!("{run_url}/rerun"), &writer, &[]).await;
1686- assert!(1666+ assert_notice(&refused, "overwritten");
1687- refused
1688- .location()
1689- .unwrap_or_default()
1690- .ends_with("?notice=overwritten")
1691- );
1692 }1667 }
1693 1668
1694 #[tokio::test]1669 #[tokio::test]
@@ -1702,11 +1677,7 @@ async fn a_run_with_no_failed_jobs_has_nothing_to_rerun() {
1702 let page = get(&fx.app, &run_url, Some(&writer)).await.text();1677 let page = get(&fx.app, &run_url, Some(&writer)).await.text();
1703 assert!(!page.contains("Re-run failed jobs"));1678 assert!(!page.contains("Re-run failed jobs"));
1704 let none = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await;1679 let none = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await;
1705- assert!(1680+ assert_notice(&none, "no-failed");
1706- none.location()
1707- .unwrap_or_default()
1708- .ends_with("?notice=no-failed")
1709- );
1710 }1681 }
1711 1682
1712 #[tokio::test]1683 #[tokio::test]
crates/forge-web-repo/src/pages/pulls_merge.rsmodified+3 -3
@@ -166,7 +166,7 @@ mod tests {
166 use std::path::{Path, PathBuf};166 use std::path::{Path, PathBuf};
167 use std::time::Duration;167 use std::time::Duration;
168 168
169- use forge_core::protection::Protection;169+ use forge_core::protection::RuleFlags;
170 use forge_core::store::commit_status::StatusState;170 use forge_core::store::commit_status::StatusState;
171 use forge_core::{IssueState, PullRequest, Repo, Role, Store, User, Visibility};171 use forge_core::{IssueState, PullRequest, Repo, Role, Store, User, Visibility};
172 use forge_git::repo::{init_bare, repo_path};172 use forge_git::repo::{init_bare, repo_path};
@@ -1037,9 +1037,9 @@ mod tests {
1037 checks: &[Option<StatusState>],1037 checks: &[Option<StatusState>],
1038 ) -> MergeGate {1038 ) -> MergeGate {
1039 MergeGate {1039 MergeGate {
1040- rule: Protection {1040+ rule: RuleFlags {
1041 required_approvals: need,1041 required_approvals: need,
1042- ..Protection::default()1042+ ..RuleFlags::default()
1043 },1043 },
1044 approvals,1044 approvals,
1045 changes_requested: false,1045 changes_requested: false,
crates/forge-web/src/boot.rsmodified+2 -8
@@ -28,7 +28,7 @@ use crate::ssh_backend::SshBackend;
28 use crate::state::AppState;28 use crate::state::AppState;
29 29
30 /// Minimum git version forge relies on (receive-pack and stateless-rpc behaviour).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 /// Boots every component and serves until shutdown.33 /// Boots every component and serves until shutdown.
34 pub async fn serve(34 pub async fn serve(
@@ -196,7 +196,7 @@ pub async fn serve(
196 user_content = %user_content_listen,196 user_content = %user_content_listen,
197 ssh = %ssh_listen,197 ssh = %ssh_listen,
198 data_dir = %data_dir.display(),198 data_dir = %data_dir.display(),
199- git = %format_version(version),199+ git = %forge_git::version::fmt_version(version),
200 "forge starting"200 "forge starting"
201 );201 );
202 202
@@ -213,8 +213,6 @@ pub async fn serve(
213 let ssh_config = SshConfig {213 let ssh_config = SshConfig {
214 listen: ssh_listen,214 listen: ssh_listen,
215 host_key_path: data_dir.join("ssh_host_ed25519_key"),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 auth_rejection_time: ssh_auth_rejection_time,216 auth_rejection_time: ssh_auth_rejection_time,
219 };217 };
220 let ssh_backend = Arc::new(SshBackend {218 let ssh_backend = Arc::new(SshBackend {
@@ -337,7 +335,3 @@ fn random_hex() -> String {
337 rand::fill(&mut buf);335 rand::fill(&mut buf);
338 hex::encode(buf)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 use std::time::Duration;3 use std::time::Duration;
4 4
5 use forge_core::Visibility;5 use forge_core::Visibility;
6-use forge_core::time::stamp_before;6+use forge_core::time::stamp_ago;
7 7
8 use forge_git::repo::{init_bare, repo_path};8 use forge_git::repo::{init_bare, repo_path};
9 9
@@ -13,11 +13,6 @@ use topcoat::router::{Body, Router, to_bytes};
13 use crate::auth::SESSION_COOKIE;13 use crate::auth::SESSION_COOKIE;
14 use crate::state::AppState;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 fn git(dir: &Path, args: &[&str]) {16 fn git(dir: &Path, args: &[&str]) {
22 let status = Command::new("git")17 let status = Command::new("git")
23 .current_dir(dir)18 .current_dir(dir)
@@ -38,7 +33,8 @@ fn git(dir: &Path, args: &[&str]) {
38 33
39 /// `tahinli/demo` (public, default branch `main` with content) and `tahinli/secret` (private, empty).34 /// `tahinli/demo` (public, default branch `main` with content) and `tahinli/secret` (private, empty).
40 async fn fixture(dir: &Path) -> (Router, AppState) {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 let tahinli = state38 let tahinli = state
43 .store39 .store
44 .create_user("tahinli", None, "x", false)40 .create_user("tahinli", None, "x", false)
@@ -91,18 +87,6 @@ async fn fixture(dir: &Path) -> (Router, AppState) {
91 (router, state)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 // The read-only tests below share one fixture: they only read the demo repo, so each scenario90 // The read-only tests below share one fixture: they only read the demo repo, so each scenario
107 // sees the same pristine contents.91 // sees the same pristine contents.
108 92
@@ -112,7 +96,7 @@ async fn demo_pages_render_from_the_repo_contents() {
112 let (router, _) = fixture(dir.path()).await;96 let (router, _) = fixture(dir.path()).await;
113 97
114 // Home renders the README, the tree, the clone popover and the archive links.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 assert_eq!(status, 200);100 assert_eq!(status, 200);
117 assert!(body.contains("Hello from the README"), "README rendered");101 assert!(body.contains("Hello from the README"), "README rendered");
118 assert!(102 assert!(
@@ -134,16 +118,16 @@ async fn demo_pages_render_from_the_repo_contents() {
134 assert!(body.contains("data-ref-filter"), "branch switcher rendered");118 assert!(body.contains("data-ref-filter"), "branch switcher rendered");
135 119
136 // Trees list their entries and link to subtrees and blobs.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 assert_eq!(status, 200);122 assert_eq!(status, 200);
139 assert!(body.contains("main.rs"));123 assert!(body.contains("main.rs"));
140 assert!(body.contains("/tahinli/demo/blob/main/src/main.rs"));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 assert_eq!(status, 200);126 assert_eq!(status, 200);
143 assert!(body.contains("/tahinli/demo/tree/main/docs"));127 assert!(body.contains("/tahinli/demo/tree/main/docs"));
144 128
145 // Rust source is highlighted with line anchors.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 assert_eq!(status, 200);131 assert_eq!(status, 200);
148 assert!(body.contains("id=\"L1\""));132 assert!(body.contains("id=\"L1\""));
149 assert!(body.contains("href=\"#L2\""));133 assert!(body.contains("href=\"#L2\""));
@@ -151,33 +135,33 @@ async fn demo_pages_render_from_the_repo_contents() {
151 assert!(body.contains("/assets/highlight.css?v="));135 assert!(body.contains("/assets/highlight.css?v="));
152 136
153 // Markdown renders unless the viewer asks for the plain source.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 assert_eq!(status, 200);139 assert_eq!(status, 200);
156 assert!(140 assert!(
157 body.contains("markdown-body") && body.contains("<table>"),141 body.contains("markdown-body") && body.contains("<table>"),
158 "GFM table rendered"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 assert_eq!(status, 200);145 assert_eq!(status, 200);
162 assert!(body.contains("file-table"), "source shown as lines");146 assert!(body.contains("file-table"), "source shown as lines");
163 assert!(!body.contains("markdown-body"), "not rendered");147 assert!(!body.contains("markdown-body"), "not rendered");
164 148
165 // Binary blobs show their size instead of content.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 assert_eq!(status, 200);151 assert_eq!(status, 200);
168 assert!(body.contains("Binary file, 3 bytes"));152 assert!(body.contains("Binary file, 3 bytes"));
169 153
170 // Fixed segment routes win over the repo catch-all.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 assert_eq!(status, 200);156 assert_eq!(status, 200);
173 assert!(body.contains("default"), "default branch marked");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 assert_eq!(status, 200);159 assert_eq!(status, 200);
176 assert!(body.contains("Nothing here yet."));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 assert_eq!(status, 200);162 assert_eq!(status, 200);
179 assert!(body.contains("README.md"));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 assert_eq!(status, 200);165 assert_eq!(status, 200);
182 assert!(body.contains("Hello from the README"));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 "/tahinli/demo/blob/main/src",177 "/tahinli/demo/blob/main/src",
194 "/tahinli/demo/blob/main",178 "/tahinli/demo/blob/main",
195 ] {179 ] {
196- let (status, _) = get(&router, uri).await;180+ let (status, _) = get_as(&router, uri, None).await;
197 assert_eq!(status, 404, "{uri}");181 assert_eq!(status, 404, "{uri}");
198 }182 }
199 for uri in [183 for uri in [
@@ -203,7 +187,7 @@ async fn missing_paths_and_private_repos_are_404_for_anonymous() {
203 "/tahinli/secret/branches",187 "/tahinli/secret/branches",
204 "/tahinli/secret/tags",188 "/tahinli/secret/tags",
205 ] {189 ] {
206- let (status, _) = get(&router, uri).await;190+ let (status, _) = get_as(&router, uri, None).await;
207 assert_eq!(status, 404, "{uri}");191 assert_eq!(status, 404, "{uri}");
208 }192 }
209 }193 }
@@ -237,7 +221,7 @@ fn make_branch(bare: &Path, branch: &str) {
237 221
238 /// Records a push of `branch` to `repo_id` by `actor_id`, `age` ago.222 /// Records a push of `branch` to `repo_id` by `actor_id`, `age` ago.
239 async fn record_push(state: &AppState, repo_id: &str, actor_id: &str, branch: &str, age: Duration) {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 let full = format!("refs/heads/{branch}");225 let full = format!("refs/heads/{branch}");
242 state226 state
243 .store227 .store