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 +1752 -4049

crates/forge-ci/src/config.rsmodified+16 -21
@@ -20,28 +20,28 @@ use serde::{Deserialize, Serialize};
2020 use crate::error::ConfigError;
2121
2222 /// Largest accepted `ci.toml`, in bytes.
23-pub const MAX_CONFIG_BYTES: usize = 64 * 1024;
23+const MAX_CONFIG_BYTES: usize = 64 * 1024;
2424 /// Largest number of jobs in one workflow.
25-pub const MAX_JOBS: usize = 20;
25+const MAX_JOBS: usize = 20;
2626 /// Default job timeout.
27-pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60;
27+const DEFAULT_TIMEOUT_MINUTES: u32 = 60;
2828 /// 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;
3030 /// Longest workflow `name`, in characters, after trimming.
31-pub const MAX_WORKFLOW_NAME_CHARS: usize = 40;
31+const MAX_WORKFLOW_NAME_CHARS: usize = 40;
3232 /// Largest number of `cache` entries in one job.
33-pub const MAX_CACHE_ENTRIES: usize = 8;
33+const MAX_CACHE_ENTRIES: usize = 8;
3434 /// Longest `cache` entry, in characters.
35-pub const MAX_CACHE_PATH_CHARS: usize = 200;
35+const MAX_CACHE_PATH_CHARS: usize = 200;
3636 /// Largest number of `[release] assets` entries.
37-pub const MAX_RELEASE_ASSETS: usize = 32;
37+const MAX_RELEASE_ASSETS: usize = 32;
3838 /// 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;
4040
4141 /// Most `[on] schedule` entries.
42-pub const MAX_SCHEDULES: usize = 8;
42+const MAX_SCHEDULES: usize = 8;
4343 /// Longest matrix axis value, in characters.
44-pub const MAX_MATRIX_VALUE_CHARS: usize = 64;
44+const MAX_MATRIX_VALUE_CHARS: usize = 64;
4545
4646 /// A parsed and validated workflow.
4747 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -257,7 +257,7 @@ pub struct MatrixSpec {
257257 }
258258
259259 /// 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);
261261
262262 /// Reads `memory` as a size string (`"4g"`) or as a byte count (what the stored spec holds).
263263 fn deserialize_memory<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
@@ -449,9 +449,9 @@ impl CiConfig {
449449 validate_trigger_glob("tag", pattern)?;
450450 }
451451 if self.on.schedule.len() > MAX_SCHEDULES {
452- return Err(ConfigError::InvalidSchedule {
453- expr: String::new(),
454- reason: format!("at most {MAX_SCHEDULES} schedules are allowed"),
452+ return Err(ConfigError::TooManySchedules {
453+ count: self.on.schedule.len(),
454+ max: MAX_SCHEDULES,
455455 });
456456 }
457457 for expr in &self.on.schedule {
@@ -746,11 +746,6 @@ fn validate_release_title(title: &str) -> Result<(), ConfigError> {
746746 Ok(())
747747 }
748748
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-
754749 /// Whether `selected` (a job name from the config) names `job`: the job itself, or any
755750 /// combination of the matrix job `selected`.
756751 fn names_job(selected: &str, job: &str) -> bool {
@@ -1753,7 +1748,7 @@ artifacts = ["target/release/forge"]
17531748 }
17541749 let many = ["\"0 3 * * *\""; MAX_SCHEDULES + 1].join(", ");
17551750 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 { .. }));
17571752 }
17581753
17591754 #[test]
crates/forge-ci/src/error.rsmodified+3 -0
@@ -32,6 +32,9 @@ pub enum ConfigError {
3232 #[error("invalid schedule {expr:?}: {reason}")]
3333 InvalidSchedule { expr: String, reason: String },
3434
35+ #[error("{count} schedules are defined, the limit is {max}")]
36+ TooManySchedules { count: usize, max: usize },
37+
3538 #[error("invalid job name {0:?}: must match ^[a-z0-9][a-z0-9_-]{{0,39}}$")]
3639 InvalidJobName(String),
3740
crates/forge-ci/src/mask.rsmodified+18 -31
@@ -44,17 +44,6 @@ impl Masker {
4444 patterns.sort_by_key(|p| std::cmp::Reverse(p.len()));
4545 Self { patterns }
4646 }
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- }
5847 }
5948
6049 /// 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>) {
9887 let mut i = 0;
9988 while i < input.len() {
10089 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- }
10690 if !last
10791 && patterns
10892 .iter()
@@ -110,19 +94,17 @@ fn scan(patterns: &[Vec<u8>], input: &[u8], last: bool) -> (Vec<u8>, Vec<u8>) {
11094 {
11195 return (out, tail.to_vec());
11296 }
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+ }
113102 out.push(input[i]);
114103 i += 1;
115104 }
116105 (out, Vec::new())
117106 }
118107
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-
126108 #[cfg(test)]
127109 mod tests {
128110 use super::*;
@@ -132,7 +114,7 @@ mod tests {
132114 }
133115
134116 fn stream_all(m: &Masker, chunks: &[&[u8]]) -> String {
135- let mut s = m.stream();
117+ let mut s = MaskStream::new(m.clone());
136118 let mut out = Vec::new();
137119 for c in chunks {
138120 out.extend(s.push(c));
@@ -146,31 +128,36 @@ mod tests {
146128 let secret = "hunter2-secret";
147129 let encoded = STANDARD.encode(secret.as_bytes());
148130 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: ***");
150132 let other = masker(&["abcdefgh"]);
151133 let enc = STANDARD.encode("abcdefgh");
152- assert_eq!(other.mask(&enc), "***");
134+ assert_eq!(stream_all(&other, &[enc.as_bytes()]), "***");
153135 }
154136
155137 #[test]
156138 fn short_values_are_ignored() {
157139 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");
159141 // 4 chars is the minimum that is masked.
160142 let m = masker(&["abcd"]);
161- assert_eq!(m.mask("xabcdx"), "x***x");
143+ assert_eq!(stream_all(&m, &[b"xabcdx"]), "x***x");
162144 }
163145
164146 #[test]
165147 fn longest_match_wins() {
166148 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"]), "***");
168156 }
169157
170158 #[test]
171159 fn empty_secret_set_is_a_no_op() {
172160 let m = Masker::new(std::iter::empty());
173- assert_eq!(m.mask("anything"), "anything");
174161 assert_eq!(stream_all(&m, &[b"anything"]), "anything");
175162 }
176163
@@ -218,7 +205,7 @@ mod tests {
218205 #[test]
219206 fn held_bytes_are_bounded() {
220207 let m = masker(&["0123456789"]);
221- let mut s = m.stream();
208+ let mut s = MaskStream::new(m);
222209 let out = s.push(b"0123456");
223210 assert!(out.is_empty());
224211 assert!(s.held.len() <= 9);
crates/forge-ci/src/steps.rsmodified+25 -8
@@ -59,19 +59,36 @@ pub fn scan(bytes: &[u8], base_offset: u64, depth: &mut u32) -> Scan {
5959 }
6060 }
6161
62-/// Removes ANSI CSI sequences: `ESC [`, any parameter bytes, then one final byte.
63-fn strip_ansi(line: &str) -> String {
62+/// Drops the ANSI escape sequences and the other control characters (a tab stays) of a log line.
63+pub fn strip_ansi(line: &str) -> String {
6464 let mut out = String::with_capacity(line.len());
6565 let mut chars = line.chars().peekable();
6666 while let Some(c) = chars.next() {
67- if c == '\u{1b}' && chars.peek() == Some(&'[') {
68- chars.next();
69- for f in chars.by_ref() {
70- if ('\u{40}'..='\u{7e}').contains(&f) {
71- break;
67+ if c == '\u{1b}' {
68+ match chars.peek() {
69+ Some('[') => {
70+ chars.next();
71+ for n in chars.by_ref() {
72+ if ('@'..='~').contains(&n) {
73+ break;
74+ }
75+ }
7276 }
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+ _ => {}
7390 }
74- } else {
91+ } else if c == '\t' || !c.is_control() {
7592 out.push(c);
7693 }
7794 }
crates/forge-core/src/advisories.rsmodified+0 -2
@@ -256,7 +256,6 @@ pub fn affects(advisory: &Advisory, version: &str) -> bool {
256256 /// `fixed` (exclusive) or `last_affected` (inclusive). `introduced` of `0` starts at the beginning.
257257 /// An interval still open at the end runs forever.
258258 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`.
260259 let mut open: Option<Option<semver::Version>> = None;
261260 for event in &range.events {
262261 match event {
@@ -264,7 +263,6 @@ fn range_affects(range: &Range, version: &semver::Version) -> bool {
264263 open = Some(if raw == "0" {
265264 None
266265 } else {
267- // An unreadable start is treated as "from the beginning": more alerts, never fewer.
268266 parse_version(raw)
269267 });
270268 }
crates/forge-core/src/alerts.rsmodified+0 -26
@@ -18,32 +18,6 @@ pub enum AlertKind {
1818 Replication,
1919 }
2020
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-
4721 /// Whether a job's result looks like the process was killed: SIGKILL (`signal: 9`, `SIGKILL`,
4822 /// `Killed`), the shell's `128 + 9` exit code, or an out-of-memory message.
4923 pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool {
crates/forge-core/src/audit.rsmodified+126 -331
@@ -6,339 +6,135 @@ use ulid::Ulid;
66
77 use crate::time::now_stamp;
88
9-/// Every security-relevant action that is recorded. The `as_str` names are stored and shown.
10-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11-pub enum AuditAction {
12- LoginSuccess,
13- LoginFailed,
14- Login2faFailed,
15- Logout,
16- PasswordChanged,
17- EmailChanged,
18- PasswordResetByAdmin,
19- TotpEnabled,
20- TotpDisabled,
21- RecoveryCodesRegenerated,
22- SshKeyAdded,
23- SshKeyRemoved,
24- GpgKeyAdded,
25- GpgKeyDeleted,
26- TokenCreated,
27- TokenRevoked,
28- SessionRevoked,
29- UserCreated,
30- UsernameChanged,
31- UserDeleted,
32- RepoCreated,
33- RepoDeleted,
34- RepoRenamed,
35- RepoTransferred,
36- RepoTransferInitiated,
37- RepoTransferAccepted,
38- RepoTransferDeclined,
39- RepoTransferCancelled,
40- RepoVisibilityChanged,
41- CollaboratorAdded,
42- CollaboratorRemoved,
43- CollaboratorRoleChanged,
44- BranchRuleCreated,
45- BranchRuleUpdated,
46- BranchRuleDeleted,
47- RepoArchived,
48- RepoUnarchived,
49- WebhookCreated,
50- WebhookUpdated,
51- WebhookDeleted,
52- MirrorCreated,
53- MirrorUpdated,
54- MirrorDeleted,
55- MirrorSyncFailed,
56- BackupStarted,
57- FsckStarted,
58- ReplicationReconcileStarted,
59- CiSecretSet,
60- CiSecretDeleted,
61- CiRunnerRegistered,
62- CiRunnerDeleted,
63- CiRunnerRestartRequested,
64- CiRunnerConfigChanged,
65- CiRegistrationTokenCreated,
66- AdvisoryAlertDismissed,
67- AdvisoryAlertReopened,
68- UiPrefsChanged,
69- DiscussionsEnabled,
70- DiscussionsDisabled,
71- DiscussionCreated,
72- DiscussionEdited,
73- DiscussionDeleted,
74- DiscussionLocked,
75- DiscussionUnlocked,
76- DiscussionAnswered,
77- DiscussionCommentCreated,
78- DiscussionCommentEdited,
79- DiscussionCommentDeleted,
80- MailSettingsUpdated,
81- MailTestQueued,
82- ServerSettingsUpdated,
83- ServerRestarted,
84- SnippetCreated,
85- SnippetUpdated,
86- SnippetDeleted,
87- WikiPageSaved,
88- WikiEnabled,
89- WikiDisabled,
90- WikiPushed,
91- OrgCreated,
92- OrgDeleted,
93- OrgSettingsUpdated,
94- OrgMemberAdded,
95- OrgMemberRemoved,
96- OrgMemberRoleChanged,
97- TeamCreated,
98- TeamUpdated,
99- TeamDeleted,
100- TeamMemberAdded,
101- TeamMemberRemoved,
102- TeamRepoAdded,
103- TeamRepoRemoved,
104- PasswordResetCompleted,
105- EmailVerified,
106- InviteSent,
107- InviteAccepted,
108- UserSuspended,
109- UserUnsuspended,
110- AdminGranted,
111- AdminRevoked,
112- TotpDisabledByAdmin,
113- PasskeyAdded,
114- PasskeyRenamed,
115- PasskeyDeleted,
116- PasskeysRemovedByAdmin,
117- PasskeyLogin,
118-}
9+macro_rules! audit_actions {
10+ ($($variant:ident => $name:literal,)*) => {
11+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
12+ pub enum AuditAction {
13+ $($variant,)*
14+ }
11915
120-impl AuditAction {
121- /// Every action, in declaration order. Used to parse filter values.
122- pub const ALL: &'static [AuditAction] = &[
123- AuditAction::LoginSuccess,
124- AuditAction::LoginFailed,
125- AuditAction::Login2faFailed,
126- AuditAction::Logout,
127- AuditAction::PasswordChanged,
128- AuditAction::EmailChanged,
129- AuditAction::PasswordResetByAdmin,
130- AuditAction::TotpEnabled,
131- AuditAction::TotpDisabled,
132- AuditAction::RecoveryCodesRegenerated,
133- AuditAction::SshKeyAdded,
134- AuditAction::SshKeyRemoved,
135- AuditAction::GpgKeyAdded,
136- AuditAction::GpgKeyDeleted,
137- AuditAction::TokenCreated,
138- AuditAction::TokenRevoked,
139- AuditAction::SessionRevoked,
140- AuditAction::UserCreated,
141- AuditAction::UsernameChanged,
142- AuditAction::UserDeleted,
143- AuditAction::RepoCreated,
144- AuditAction::RepoDeleted,
145- AuditAction::RepoRenamed,
146- AuditAction::RepoTransferred,
147- AuditAction::RepoTransferInitiated,
148- AuditAction::RepoTransferAccepted,
149- AuditAction::RepoTransferDeclined,
150- AuditAction::RepoTransferCancelled,
151- AuditAction::RepoVisibilityChanged,
152- AuditAction::CollaboratorAdded,
153- AuditAction::CollaboratorRemoved,
154- AuditAction::CollaboratorRoleChanged,
155- AuditAction::BranchRuleCreated,
156- AuditAction::BranchRuleUpdated,
157- AuditAction::BranchRuleDeleted,
158- AuditAction::RepoArchived,
159- AuditAction::RepoUnarchived,
160- AuditAction::WebhookCreated,
161- AuditAction::WebhookUpdated,
162- AuditAction::WebhookDeleted,
163- AuditAction::MirrorCreated,
164- AuditAction::MirrorUpdated,
165- AuditAction::MirrorDeleted,
166- AuditAction::MirrorSyncFailed,
167- AuditAction::BackupStarted,
168- AuditAction::FsckStarted,
169- AuditAction::ReplicationReconcileStarted,
170- AuditAction::CiSecretSet,
171- AuditAction::CiSecretDeleted,
172- AuditAction::CiRunnerRegistered,
173- AuditAction::CiRunnerDeleted,
174- AuditAction::CiRunnerRestartRequested,
175- AuditAction::CiRunnerConfigChanged,
176- AuditAction::CiRegistrationTokenCreated,
177- AuditAction::AdvisoryAlertDismissed,
178- AuditAction::AdvisoryAlertReopened,
179- AuditAction::UiPrefsChanged,
180- AuditAction::DiscussionsEnabled,
181- AuditAction::DiscussionsDisabled,
182- AuditAction::DiscussionCreated,
183- AuditAction::DiscussionEdited,
184- AuditAction::DiscussionDeleted,
185- AuditAction::DiscussionLocked,
186- AuditAction::DiscussionUnlocked,
187- AuditAction::DiscussionAnswered,
188- AuditAction::DiscussionCommentCreated,
189- AuditAction::DiscussionCommentEdited,
190- AuditAction::DiscussionCommentDeleted,
191- AuditAction::MailSettingsUpdated,
192- AuditAction::MailTestQueued,
193- AuditAction::ServerSettingsUpdated,
194- AuditAction::ServerRestarted,
195- AuditAction::SnippetCreated,
196- AuditAction::SnippetUpdated,
197- AuditAction::SnippetDeleted,
198- AuditAction::WikiPageSaved,
199- AuditAction::WikiEnabled,
200- AuditAction::WikiDisabled,
201- AuditAction::WikiPushed,
202- AuditAction::OrgCreated,
203- AuditAction::OrgDeleted,
204- AuditAction::OrgSettingsUpdated,
205- AuditAction::OrgMemberAdded,
206- AuditAction::OrgMemberRemoved,
207- AuditAction::OrgMemberRoleChanged,
208- AuditAction::TeamCreated,
209- AuditAction::TeamUpdated,
210- AuditAction::TeamDeleted,
211- AuditAction::TeamMemberAdded,
212- AuditAction::TeamMemberRemoved,
213- AuditAction::TeamRepoAdded,
214- AuditAction::TeamRepoRemoved,
215- AuditAction::PasswordResetCompleted,
216- AuditAction::EmailVerified,
217- AuditAction::InviteSent,
218- AuditAction::InviteAccepted,
219- AuditAction::UserSuspended,
220- AuditAction::UserUnsuspended,
221- AuditAction::AdminGranted,
222- AuditAction::AdminRevoked,
223- AuditAction::TotpDisabledByAdmin,
224- AuditAction::PasskeyAdded,
225- AuditAction::PasskeyRenamed,
226- AuditAction::PasskeyDeleted,
227- AuditAction::PasskeysRemovedByAdmin,
228- AuditAction::PasskeyLogin,
229- ];
16+ impl AuditAction {
17+ pub const ALL: &'static [AuditAction] = &[$(AuditAction::$variant,)*];
23018
231- pub fn as_str(self) -> &'static str {
232- match self {
233- AuditAction::LoginSuccess => "login_success",
234- AuditAction::LoginFailed => "login_failed",
235- AuditAction::Login2faFailed => "login_2fa_failed",
236- AuditAction::Logout => "logout",
237- AuditAction::PasswordChanged => "password_changed",
238- AuditAction::EmailChanged => "email_changed",
239- AuditAction::PasswordResetByAdmin => "password_reset_by_admin",
240- AuditAction::TotpEnabled => "totp_enabled",
241- AuditAction::TotpDisabled => "totp_disabled",
242- AuditAction::RecoveryCodesRegenerated => "recovery_codes_regenerated",
243- AuditAction::SshKeyAdded => "ssh_key_added",
244- AuditAction::SshKeyRemoved => "ssh_key_removed",
245- AuditAction::GpgKeyAdded => "gpg_key_added",
246- AuditAction::GpgKeyDeleted => "gpg_key_deleted",
247- AuditAction::TokenCreated => "token_created",
248- AuditAction::TokenRevoked => "token_revoked",
249- AuditAction::SessionRevoked => "session_revoked",
250- AuditAction::UserCreated => "user_created",
251- AuditAction::UsernameChanged => "username_changed",
252- AuditAction::UserDeleted => "user_deleted",
253- AuditAction::RepoCreated => "repo_created",
254- AuditAction::RepoDeleted => "repo_deleted",
255- AuditAction::RepoRenamed => "repo_renamed",
256- AuditAction::RepoTransferred => "repo_transferred",
257- AuditAction::RepoTransferInitiated => "repo_transfer_initiated",
258- AuditAction::RepoTransferAccepted => "repo_transfer_accepted",
259- AuditAction::RepoTransferDeclined => "repo_transfer_declined",
260- AuditAction::RepoTransferCancelled => "repo_transfer_cancelled",
261- AuditAction::RepoVisibilityChanged => "repo_visibility_changed",
262- AuditAction::CollaboratorAdded => "collaborator_added",
263- AuditAction::CollaboratorRemoved => "collaborator_removed",
264- AuditAction::CollaboratorRoleChanged => "collaborator_role_changed",
265- AuditAction::BranchRuleCreated => "branch_rule_created",
266- AuditAction::BranchRuleUpdated => "branch_rule_updated",
267- AuditAction::BranchRuleDeleted => "branch_rule_deleted",
268- AuditAction::RepoArchived => "repo_archived",
269- AuditAction::RepoUnarchived => "repo_unarchived",
270- AuditAction::WebhookCreated => "webhook_created",
271- AuditAction::WebhookUpdated => "webhook_updated",
272- AuditAction::WebhookDeleted => "webhook_deleted",
273- AuditAction::MirrorCreated => "mirror_created",
274- AuditAction::MirrorUpdated => "mirror_updated",
275- AuditAction::MirrorDeleted => "mirror_deleted",
276- AuditAction::MirrorSyncFailed => "mirror_sync_failed",
277- AuditAction::BackupStarted => "backup_started",
278- AuditAction::FsckStarted => "fsck_started",
279- AuditAction::ReplicationReconcileStarted => "replication_reconcile_started",
280- AuditAction::CiSecretSet => "ci_secret_set",
281- AuditAction::CiSecretDeleted => "ci_secret_deleted",
282- AuditAction::CiRunnerRegistered => "ci_runner_registered",
283- AuditAction::CiRunnerDeleted => "ci_runner_deleted",
284- AuditAction::CiRunnerRestartRequested => "ci_runner_restart_requested",
285- AuditAction::CiRunnerConfigChanged => "ci_runner_config_changed",
286- AuditAction::CiRegistrationTokenCreated => "ci_registration_token_created",
287- AuditAction::AdvisoryAlertDismissed => "advisory_alert_dismissed",
288- AuditAction::AdvisoryAlertReopened => "advisory_alert_reopened",
289- AuditAction::UiPrefsChanged => "ui_prefs_changed",
290- AuditAction::DiscussionsEnabled => "discussions_enabled",
291- AuditAction::DiscussionsDisabled => "discussions_disabled",
292- AuditAction::DiscussionCreated => "discussion_created",
293- AuditAction::DiscussionEdited => "discussion_edited",
294- AuditAction::DiscussionDeleted => "discussion_deleted",
295- AuditAction::DiscussionLocked => "discussion_locked",
296- AuditAction::DiscussionUnlocked => "discussion_unlocked",
297- AuditAction::DiscussionAnswered => "discussion_answered",
298- AuditAction::DiscussionCommentCreated => "discussion_comment_created",
299- AuditAction::DiscussionCommentEdited => "discussion_comment_edited",
300- AuditAction::DiscussionCommentDeleted => "discussion_comment_deleted",
301- AuditAction::MailSettingsUpdated => "mail_settings_updated",
302- AuditAction::MailTestQueued => "mail_test_queued",
303- AuditAction::ServerSettingsUpdated => "server_settings_updated",
304- AuditAction::ServerRestarted => "server_restarted",
305- AuditAction::SnippetCreated => "snippet_created",
306- AuditAction::SnippetUpdated => "snippet_updated",
307- AuditAction::SnippetDeleted => "snippet_deleted",
308- AuditAction::WikiPageSaved => "wiki_page_saved",
309- AuditAction::WikiEnabled => "wiki_enabled",
310- AuditAction::WikiDisabled => "wiki_disabled",
311- AuditAction::WikiPushed => "wiki_pushed",
312- AuditAction::OrgCreated => "org_created",
313- AuditAction::OrgDeleted => "org_deleted",
314- AuditAction::OrgSettingsUpdated => "org_settings_updated",
315- AuditAction::OrgMemberAdded => "org_member_added",
316- AuditAction::OrgMemberRemoved => "org_member_removed",
317- AuditAction::OrgMemberRoleChanged => "org_member_role_changed",
318- AuditAction::TeamCreated => "team_created",
319- AuditAction::TeamUpdated => "team_updated",
320- AuditAction::TeamDeleted => "team_deleted",
321- AuditAction::TeamMemberAdded => "team_member_added",
322- AuditAction::TeamMemberRemoved => "team_member_removed",
323- AuditAction::TeamRepoAdded => "team_repo_added",
324- AuditAction::TeamRepoRemoved => "team_repo_removed",
325- AuditAction::PasswordResetCompleted => "password_reset_completed",
326- AuditAction::EmailVerified => "email_verified",
327- AuditAction::InviteSent => "invite_sent",
328- AuditAction::InviteAccepted => "invite_accepted",
329- AuditAction::UserSuspended => "user_suspended",
330- AuditAction::UserUnsuspended => "user_unsuspended",
331- AuditAction::AdminGranted => "admin_granted",
332- AuditAction::AdminRevoked => "admin_revoked",
333- AuditAction::TotpDisabledByAdmin => "totp_disabled_by_admin",
334- AuditAction::PasskeyAdded => "passkey_added",
335- AuditAction::PasskeyRenamed => "passkey_renamed",
336- AuditAction::PasskeyDeleted => "passkey_deleted",
337- AuditAction::PasskeysRemovedByAdmin => "passkeys_removed_by_admin",
338- AuditAction::PasskeyLogin => "passkey_login",
19+ pub fn as_str(self) -> &'static str {
20+ match self {
21+ $(AuditAction::$variant => $name,)*
22+ }
23+ }
33924 }
340- }
25+ };
26+}
27+
28+audit_actions! {
29+ LoginSuccess => "login_success",
30+ LoginFailed => "login_failed",
31+ Login2faFailed => "login_2fa_failed",
32+ Logout => "logout",
33+ PasswordChanged => "password_changed",
34+ EmailChanged => "email_changed",
35+ PasswordResetByAdmin => "password_reset_by_admin",
36+ TotpEnabled => "totp_enabled",
37+ TotpDisabled => "totp_disabled",
38+ RecoveryCodesRegenerated => "recovery_codes_regenerated",
39+ SshKeyAdded => "ssh_key_added",
40+ SshKeyRemoved => "ssh_key_removed",
41+ GpgKeyAdded => "gpg_key_added",
42+ GpgKeyDeleted => "gpg_key_deleted",
43+ TokenCreated => "token_created",
44+ TokenRevoked => "token_revoked",
45+ SessionRevoked => "session_revoked",
46+ UserCreated => "user_created",
47+ UsernameChanged => "username_changed",
48+ UserDeleted => "user_deleted",
49+ RepoCreated => "repo_created",
50+ RepoDeleted => "repo_deleted",
51+ RepoRenamed => "repo_renamed",
52+ RepoTransferred => "repo_transferred",
53+ RepoTransferInitiated => "repo_transfer_initiated",
54+ RepoTransferAccepted => "repo_transfer_accepted",
55+ RepoTransferDeclined => "repo_transfer_declined",
56+ RepoTransferCancelled => "repo_transfer_cancelled",
57+ RepoVisibilityChanged => "repo_visibility_changed",
58+ CollaboratorAdded => "collaborator_added",
59+ CollaboratorRemoved => "collaborator_removed",
60+ CollaboratorRoleChanged => "collaborator_role_changed",
61+ BranchRuleCreated => "branch_rule_created",
62+ BranchRuleUpdated => "branch_rule_updated",
63+ BranchRuleDeleted => "branch_rule_deleted",
64+ RepoArchived => "repo_archived",
65+ RepoUnarchived => "repo_unarchived",
66+ WebhookCreated => "webhook_created",
67+ WebhookUpdated => "webhook_updated",
68+ WebhookDeleted => "webhook_deleted",
69+ MirrorCreated => "mirror_created",
70+ MirrorUpdated => "mirror_updated",
71+ MirrorDeleted => "mirror_deleted",
72+ MirrorSyncFailed => "mirror_sync_failed",
73+ BackupStarted => "backup_started",
74+ FsckStarted => "fsck_started",
75+ ReplicationReconcileStarted => "replication_reconcile_started",
76+ CiSecretSet => "ci_secret_set",
77+ CiSecretDeleted => "ci_secret_deleted",
78+ CiRunnerRegistered => "ci_runner_registered",
79+ CiRunnerDeleted => "ci_runner_deleted",
80+ CiRunnerRestartRequested => "ci_runner_restart_requested",
81+ CiRunnerConfigChanged => "ci_runner_config_changed",
82+ CiRegistrationTokenCreated => "ci_registration_token_created",
83+ AdvisoryAlertDismissed => "advisory_alert_dismissed",
84+ AdvisoryAlertReopened => "advisory_alert_reopened",
85+ UiPrefsChanged => "ui_prefs_changed",
86+ DiscussionsEnabled => "discussions_enabled",
87+ DiscussionsDisabled => "discussions_disabled",
88+ DiscussionCreated => "discussion_created",
89+ DiscussionEdited => "discussion_edited",
90+ DiscussionDeleted => "discussion_deleted",
91+ DiscussionLocked => "discussion_locked",
92+ DiscussionUnlocked => "discussion_unlocked",
93+ DiscussionAnswered => "discussion_answered",
94+ DiscussionCommentCreated => "discussion_comment_created",
95+ DiscussionCommentEdited => "discussion_comment_edited",
96+ DiscussionCommentDeleted => "discussion_comment_deleted",
97+ MailSettingsUpdated => "mail_settings_updated",
98+ MailTestQueued => "mail_test_queued",
99+ ServerSettingsUpdated => "server_settings_updated",
100+ ServerRestarted => "server_restarted",
101+ SnippetCreated => "snippet_created",
102+ SnippetUpdated => "snippet_updated",
103+ SnippetDeleted => "snippet_deleted",
104+ WikiPageSaved => "wiki_page_saved",
105+ WikiEnabled => "wiki_enabled",
106+ WikiDisabled => "wiki_disabled",
107+ WikiPushed => "wiki_pushed",
108+ OrgCreated => "org_created",
109+ OrgDeleted => "org_deleted",
110+ OrgSettingsUpdated => "org_settings_updated",
111+ OrgMemberAdded => "org_member_added",
112+ OrgMemberRemoved => "org_member_removed",
113+ OrgMemberRoleChanged => "org_member_role_changed",
114+ TeamCreated => "team_created",
115+ TeamUpdated => "team_updated",
116+ TeamDeleted => "team_deleted",
117+ TeamMemberAdded => "team_member_added",
118+ TeamMemberRemoved => "team_member_removed",
119+ TeamRepoAdded => "team_repo_added",
120+ TeamRepoRemoved => "team_repo_removed",
121+ PasswordResetCompleted => "password_reset_completed",
122+ EmailVerified => "email_verified",
123+ InviteSent => "invite_sent",
124+ InviteAccepted => "invite_accepted",
125+ UserSuspended => "user_suspended",
126+ UserUnsuspended => "user_unsuspended",
127+ AdminGranted => "admin_granted",
128+ AdminRevoked => "admin_revoked",
129+ TotpDisabledByAdmin => "totp_disabled_by_admin",
130+ PasskeyAdded => "passkey_added",
131+ PasskeyRenamed => "passkey_renamed",
132+ PasskeyDeleted => "passkey_deleted",
133+ PasskeysRemovedByAdmin => "passkeys_removed_by_admin",
134+ PasskeyLogin => "passkey_login",
135+}
341136
137+impl AuditAction {
342138 /// The action with this stored name, if any.
343139 pub fn parse(name: &str) -> Option<AuditAction> {
344140 AuditAction::ALL
@@ -436,13 +232,12 @@ mod tests {
436232 #[test]
437233 fn names_are_unique_and_round_trip() {
438234 let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect();
439- assert_eq!(names.len(), 106);
440235 for action in AuditAction::ALL {
441236 assert_eq!(AuditAction::parse(action.as_str()), Some(*action));
442237 }
443238 names.sort();
444239 names.dedup();
445- assert_eq!(names.len(), 106);
240+ assert_eq!(names.len(), AuditAction::ALL.len());
446241 assert_eq!(AuditAction::parse("nope"), None);
447242 }
448243
crates/forge-core/src/authz.rsmodified+1 -14
@@ -23,20 +23,7 @@ pub enum Denied {
2323
2424 /// The higher of two optional roles. `Read < Triage < Write < Maintain < Admin`.
2525 pub fn max_role(a: Option<Role>, b: Option<Role>) -> Option<Role> {
26- fn rank(role: Role) -> u8 {
27- match role {
28- Role::Read => 1,
29- Role::Triage => 2,
30- Role::Write => 3,
31- Role::Maintain => 4,
32- Role::Admin => 5,
33- }
34- }
35- match (a, b) {
36- (Some(x), Some(y)) => Some(if rank(y) > rank(x) { y } else { x }),
37- (x, None) => x,
38- (None, y) => y,
39- }
26+ a.max(b)
4027 }
4128
4229 /// 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> {
193193 let entry = entry.ok()?;
194194 let path = entry.path().ok()?.into_owned();
195195 let mut parts = path.components();
196- parts.next()?;
197- let file = parts.next()?;
196+ let (Some(_), Some(file)) = (parts.next(), parts.next()) else {
197+ continue;
198+ };
198199 let is_top = parts.next().is_none();
199200 let file_name = file.as_os_str().to_string_lossy().to_ascii_lowercase();
200201 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 @@
22 //! migrations/0024_ci.sql; the store functions live in store/ci.rs.
33 //!
44 //! 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.
66
77 use std::collections::BTreeMap;
88 use std::str::FromStr;
99
10+use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY};
11+
12+pub use forge_ci::proto::RestartMode;
13+
1014 use crate::error::{Error, Result};
1115
1216 /// State of a run. Stored as the `as_str` name.
@@ -142,35 +146,6 @@ pub struct CiRunner {
142146 pub config_overrides: BTreeMap<String, serde_json::Value>,
143147 }
144148
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-
174149 /// A pending runner restart: asked for, not yet seen to happen.
175150 #[derive(Debug, Clone, PartialEq, Eq)]
176151 pub struct RunnerRestart {
@@ -319,8 +294,8 @@ pub fn validate_runner_field(
319294 match key {
320295 "concurrency" => int_in(
321296 raw,
322- i64::from(MIN_RUNNER_CONCURRENCY),
323- i64::from(MAX_RUNNER_CONCURRENCY),
297+ i64::from(MIN_CONCURRENCY),
298+ i64::from(MAX_CONCURRENCY),
324299 "concurrency",
325300 ),
326301 "labels" => {
@@ -529,10 +504,6 @@ impl CiRunner {
529504 }
530505 }
531506
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-
536507 /// One run of the workflow for a commit.
537508 #[derive(Debug, Clone, PartialEq, Eq)]
538509 pub struct CiRun {
@@ -673,6 +644,17 @@ pub struct NewJob<'a> {
673644 pub needs: &'a [String],
674645 }
675646
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+
676658 #[cfg(test)]
677659 mod memory_tests {
678660 use super::*;
crates/forge-core/src/config.rsmodified+20 -22
@@ -233,30 +233,12 @@ impl BannerConfig {
233233
234234 /// Parses `YYYY-MM-DD HH:MM` (UTC) into unix seconds.
235235 pub fn parse_banner_expiry(raw: &str) -> Option<i64> {
236- let raw = raw.trim();
237- let (date, time) = raw.split_once(' ')?;
238- let mut d = date.split('-');
239- let (y, m, day): (i64, i64, i64) = (
240- d.next()?.parse().ok()?,
241- d.next()?.parse().ok()?,
242- d.next()?.parse().ok()?,
243- );
244- if d.next().is_some() || !(1..=12).contains(&m) || !(1..=31).contains(&day) {
236+ let dt = jiff::civil::DateTime::strptime("%Y-%m-%d %H:%M", raw.trim()).ok()?;
237+ if dt.year() < 1970 {
245238 return None;
246239 }
247- let (hh, mm) = time.split_once(':')?;
248- let (hh, mm): (i64, i64) = (hh.parse().ok()?, mm.parse().ok()?);
249- if !(0..24).contains(&hh) || !(0..60).contains(&mm) || y < 1970 {
250- return None;
251- }
252- // Days from civil (Howard Hinnant).
253- let y2 = if m <= 2 { y - 1 } else { y };
254- let era = y2 / 400;
255- let yoe = y2 - era * 400;
256- let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day - 1;
257- let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
258- let days = era * 146_097 + doe - 719_468;
259- Some(days * 86_400 + hh * 3_600 + mm * 60)
240+ let zoned = dt.to_zoned_datetime(jiff::tz::TimeZone::UTC).ok()?;
241+ Some(zoned.timestamp().as_second())
260242 }
261243
262244 /// Self-update, from the `[self_update]` section. When enabled, a successful push run of `repo`
@@ -423,6 +405,21 @@ impl Default for AdvisoriesConfig {
423405 }
424406 }
425407
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+
426423 /// Git LFS limits, from the `[lfs]` section.
427424 #[derive(Debug, Clone, Deserialize)]
428425 #[serde(deny_unknown_fields, default)]
@@ -804,6 +801,7 @@ impl Config {
804801 self.backup.validate()?;
805802 self.replication.validate()?;
806803 self.self_update.validate()?;
804+ self.advisories.validate()?;
807805 self.storage.validate()?;
808806 Ok(())
809807 }
crates/forge-core/src/issue_refs.rsmodified+14 -19
@@ -11,25 +11,13 @@ const CLOSING_KEYWORDS: [&str; 9] = [
1111 /// Maximum number of digits in an issue number.
1212 const MAX_DIGITS: usize = 9;
1313
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-
2014 /// Every `#N` reference in `text`, deduplicated, in order of first appearance.
2115 ///
2216 /// A reference is `#` followed by 1 to 9 digits. It is not recognised when the `#` is preceded by
2317 /// an alphanumeric char, `&` or `/`, or when the digits are followed by an alphanumeric char.
2418 /// `#0` is not an issue number and is ignored.
2519 pub fn find_issue_refs(text: &str) -> Vec<i64> {
26- let mut out: Vec<i64> = Vec::new();
27- for (_, n) in scan_refs(text) {
28- if !out.contains(&n) {
29- out.push(n);
30- }
31- }
32- out
20+ dedup(issue_ref_spans(text).into_iter().map(|(_, n)| n))
3321 }
3422
3523 /// Issue numbers closed by closing keywords in `text`, deduplicated, in order.
@@ -38,11 +26,17 @@ pub fn find_issue_refs(text: &str) -> Vec<i64> {
3826 /// separated by a `:`, with at least one whitespace char between the keyword (or colon) and `#`.
3927 /// Example: `"Fixes: #3, closes #4"` gives `[3, 4]`; `"unfixes #2"` gives nothing.
4028 pub fn find_closing_refs(text: &str) -> Vec<i64> {
29+ dedup(
30+ issue_ref_spans(text)
31+ .into_iter()
32+ .filter(|(range, _)| preceded_by_closing_keyword(&text[..range.start]))
33+ .map(|(_, n)| n),
34+ )
35+}
36+
37+fn dedup(values: impl Iterator<Item = i64>) -> Vec<i64> {
4138 let mut out: Vec<i64> = Vec::new();
42- for (range, n) in scan_refs(text) {
43- if !preceded_by_closing_keyword(&text[..range.start]) {
44- continue;
45- }
39+ for n in values {
4640 if !out.contains(&n) {
4741 out.push(n);
4842 }
@@ -50,8 +44,9 @@ pub fn find_closing_refs(text: &str) -> Vec<i64> {
5044 out
5145 }
5246
53-/// Byte range of each valid `#N` reference and its value, in order of appearance.
54-fn scan_refs(text: &str) -> Vec<(Range<usize>, i64)> {
47+/// Byte range (including the `#`) and value of every valid `#N` reference in `text`, in order.
48+/// Duplicates are kept. Used to link references in rendered markdown with the same rules.
49+pub fn issue_ref_spans(text: &str) -> Vec<(Range<usize>, i64)> {
5550 let bytes = text.as_bytes();
5651 let mut refs = Vec::new();
5752 let mut i = 0;
crates/forge-core/src/lib.rsmodified+1 -2
@@ -30,7 +30,6 @@ pub mod releases;
3030 pub mod reviews;
3131 pub mod secret;
3232 pub mod server_settings;
33-pub mod session;
3433 pub mod store;
3534 pub mod suggestions;
3635 pub mod time;
@@ -50,4 +49,4 @@ pub use pulls::*;
5049 pub use reactions::{Reaction, ReactionMap, ReactionSummary, ReactionTarget};
5150 pub use reviews::*;
5251 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 {
271271 pub last_error: Option<String>,
272272 }
273273
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-
292274 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-
303275 /// The state of the row at `now` (an RFC 3339-style stamp, compared as text).
304276 pub fn state_at(&self, now: &str) -> MailState {
305277 if self.sent_at.is_some() {
@@ -527,31 +499,4 @@ mod tests {
527499 entry.sent_at = Some(now.into());
528500 assert_eq!(entry.state_at(now), MailState::Sent);
529501 }
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- }
557502 }
crates/forge-core/src/merge_queue.rsmodified+0 -8
@@ -25,14 +25,6 @@ impl QueueState {
2525 QueueState::Removed => "removed",
2626 }
2727 }
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- }
3628 }
3729
3830 impl std::str::FromStr for QueueState {
crates/forge-core/src/model.rsmodified+1 -1
@@ -9,7 +9,7 @@ pub enum Visibility {
99 Private,
1010 }
1111
12-#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
12+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
1313 #[serde(rename_all = "lowercase")]
1414 pub enum Role {
1515 Read,
crates/forge-core/src/names.rsmodified+0 -4
@@ -43,10 +43,6 @@ pub const RESERVED: &[&str] = &[
4343 "favicon.ico",
4444 "robots.txt",
4545 "security.txt",
46- ".well-known",
47- "-",
48- ".",
49- "..",
5046 ];
5147
5248 /// NFKC normalization plus case fold.
crates/forge-core/src/notifications.rsmodified+2 -2
@@ -1,5 +1,6 @@
11 //! Notification models: repo watch levels, issue subscriptions and inbox entries.
22
3+use crate::issues::IssueState;
34 use crate::model::Id;
45
56 /// How much activity a user hears about in a repo. A user with no row is `Participating`.
@@ -126,8 +127,7 @@ pub struct Notification {
126127 /// True for pull requests (`issues.kind = 'pull'`).
127128 pub is_pull: bool,
128129 pub title: String,
129- /// `open` or `closed`.
130- pub issue_state: String,
130+ pub issue_state: IssueState,
131131 pub reason: Reason,
132132 pub last_activity: String,
133133 /// `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 {
3232 pub created_at: String,
3333 }
3434
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.
3651 #[derive(Debug, Clone, Default, PartialEq, Eq)]
3752 pub struct RuleFlags {
3853 pub allow_force_push: bool,
@@ -56,19 +71,6 @@ impl RuleFlags {
5671 }
5772 }
5873
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-
7274 /// Rejects `required_approvals` above `MAX_REQUIRED_APPROVALS`.
7375 pub fn validate_required_approvals(n: u32) -> Result<()> {
7476 if n > MAX_REQUIRED_APPROVALS {
@@ -219,7 +221,7 @@ fn is_literal(pattern: &str) -> bool {
219221 /// longest pattern wins, and ties go to the earliest created_at.
220222 /// 2. Otherwise, if `branch == default_branch`: built-in protection {force_push: false, deletion: false}.
221223 /// 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 {
223225 let best = rules
224226 .iter()
225227 .filter(|r| pattern_matches(&r.pattern, branch))
@@ -233,29 +235,12 @@ pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> Pr
233235 .then_with(|| a.pattern.cmp(&b.pattern))
234236 });
235237 if let Some(rule) = best {
236- return Protection {
237- allow_force_push: rule.allow_force_push,
238- allow_deletion: rule.allow_deletion,
239- required_approvals: rule.required_approvals,
240- block_on_changes_requested: rule.block_on_changes_requested,
241- require_up_to_date: rule.require_up_to_date,
242- restrict_push: rule.restrict_push,
243- require_merge_queue: rule.require_merge_queue,
244- required_checks: rule.required_checks.clone(),
245- };
238+ return rule.flags();
246239 }
247240 if branch == default_branch {
248- Protection {
249- allow_force_push: false,
250- allow_deletion: false,
251- ..Protection::default()
252- }
241+ RuleFlags::basic(false, false)
253242 } else {
254- Protection {
255- allow_force_push: true,
256- allow_deletion: true,
257- ..Protection::default()
258- }
243+ RuleFlags::basic(true, true)
259244 }
260245 }
261246
@@ -280,14 +265,6 @@ mod tests {
280265 }
281266 }
282267
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-
291268 #[test]
292269 fn pattern_matches_cases() {
293270 assert!(pattern_matches("main", "main"));
@@ -335,27 +312,27 @@ mod tests {
335312 #[test]
336313 fn effective_without_rules_protects_only_default() {
337314 let none: &[BranchRule] = &[];
338- assert_eq!(effective(none, "main", "main"), flags(false, false));
339- assert_eq!(effective(none, "main", "feature"), flags(true, true));
315+ assert_eq!(effective(none, "main", "main"), RuleFlags::basic(false, false));
316+ assert_eq!(effective(none, "main", "feature"), RuleFlags::basic(true, true));
340317 }
341318
342319 #[test]
343320 fn effective_literal_allows_force_push_on_main() {
344321 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));
346323 }
347324
348325 #[test]
349326 fn effective_literal_beats_glob() {
350327 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));
352329 }
353330
354331 #[test]
355332 fn effective_longer_glob_wins() {
356333 // Both `*` and `rel*` match `release`; the longer `rel*` wins even though `*` is older.
357334 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));
359336 // `release/**` is longer than `release/*`, so it wins for nested names.
360337 let rules = [
361338 rule("release/*", true, true, "1"),
@@ -363,7 +340,7 @@ mod tests {
363340 ];
364341 assert_eq!(
365342 effective(&rules, "main", "release/a/b"),
366- flags(false, false)
343+ RuleFlags::basic(false, false)
367344 );
368345 }
369346
@@ -377,7 +354,7 @@ mod tests {
377354 let rules = [gated];
378355 assert_eq!(
379356 effective(&rules, "main", "main"),
380- Protection {
357+ RuleFlags {
381358 allow_force_push: false,
382359 allow_deletion: false,
383360 required_approvals: 2,
crates/forge-core/src/reactions.rsmodified+0 -9
@@ -1,7 +1,6 @@
11 //! Emoji reactions: the fixed set a user can put on an issue, a pull request or a comment, and
22 //! the summaries the pages show. Stored as the short name (`+1`, `heart`, ...).
33
4-use crate::error::{Error, Result};
54 use crate::model::Id;
65
76 /// The fixed reaction set, in the order the pages list them.
@@ -64,14 +63,6 @@ impl Reaction {
6463 }
6564 }
6665
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-
7566 /// What a reaction is attached to. Pull requests are issue rows, so they use `Issue`.
7667 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
7768 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]> {
2424 }
2525
2626 fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {
27- use std::io::Write;
28-
2927 use rand::TryRng;
3028
3129 let mut key = [0u8; 32];
@@ -33,6 +31,16 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {
3331 .try_fill_bytes(&mut key)
3432 .map_err(std::io::Error::other)?;
3533
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+
3644 let mut options = std::fs::OpenOptions::new();
3745 options.write(true).create_new(true);
3846 #[cfg(unix)]
@@ -41,14 +49,8 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {
4149 options.mode(0o600);
4250 }
4351 let mut file = options.open(path)?;
44- let written = file.write_all(&key).and_then(|()| file.sync_all());
45- if let Err(e) = written {
46- // Do not leave a truncated key behind; the next start would reject it.
47- drop(file);
48- let _ = std::fs::remove_file(path);
49- return Err(e);
50- }
51- Ok(key)
52+ file.write_all(key)?;
53+ file.sync_all()
5254 }
5355
5456 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-
171 use std::collections::{BTreeMap, BTreeSet};
182 use std::net::IpAddr;
193 use std::sync::{Arc, RwLock};
204
215 use ipnet::IpNet;
226
7+use crate::advisories::KNOWN_ECOSYSTEMS;
238 use crate::config::{Config, MailTransport, OrgCreation, Registration, StorageBackend};
249 use crate::error::{Error, Result};
2510
26-/// How a field reaches the running process.
2711 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2812 pub enum Kind {
2913 Live,
@@ -31,7 +15,6 @@ pub enum Kind {
3115 ReadOnly,
3216 }
3317
34-/// The page tab a field belongs to.
3518 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
3619 pub enum Group {
3720 General,
@@ -68,21 +51,15 @@ impl Group {
6851 }
6952 }
7053
71-/// The value type of a field, which decides the input and the server-side check.
7254 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
7355 pub enum Ty {
7456 Bool,
75- /// Whole number in `min..=max`.
7657 Uint(u64, u64),
7758 Text,
78- /// A filesystem path. Empty is allowed and usually means "off".
7959 Path,
8060 Choice(&'static [&'static str]),
81- /// Comma separated entries.
8261 List,
83- /// Write-only text.
8462 Secret,
85- /// Socket address (read-only fields only).
8663 Addr,
8764 }
8865
@@ -132,7 +109,6 @@ const JURISDICTION: &[&str] = &["", "eu", "fedramp"];
132109 const MB: Ty = Ty::Uint(1, 1_048_576);
133110 const PORT: Ty = Ty::Uint(1, 65_535);
134111
135-/// Every setting, in display order.
136112 pub static FIELDS: &[Field] = &[
137113 f(
138114 "registration",
@@ -723,7 +699,6 @@ pub static FIELDS: &[Field] = &[
723699 ),
724700 ];
725701
726-/// The field for a dotted key.
727702 pub fn field(key: &str) -> Option<&'static Field> {
728703 FIELDS.iter().find(|f| f.key == key)
729704 }
@@ -740,7 +715,6 @@ fn split_list(raw: &str) -> Vec<String> {
740715 .collect()
741716 }
742717
743-/// Checks `raw` against the field's type and returns its canonical string.
744718 pub fn normalize(field: &Field, raw: &str) -> Result<String> {
745719 let raw = raw.trim();
746720 match field.ty {
@@ -807,7 +781,7 @@ pub fn normalize(field: &Field, raw: &str) -> Result<String> {
807781 }
808782 if field.key == "advisories.ecosystems" {
809783 for item in &items {
810- if !matches!(item.as_str(), "crates.io" | "npm" | "Go") {
784+ if !KNOWN_ECOSYSTEMS.contains(&item.as_str()) {
811785 return Err(invalid(field, &format!("unknown ecosystem `{item}`")));
812786 }
813787 }
@@ -840,8 +814,6 @@ fn backend_name(b: StorageBackend) -> &'static str {
840814 }
841815 }
842816
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.
845817 pub fn get(cfg: &Config, key: &str) -> String {
846818 let path = |p: &std::path::Path| p.to_string_lossy().into_owned();
847819 let list = |v: &[String]| v.join(", ");
@@ -944,7 +916,6 @@ pub fn get(cfg: &Config, key: &str) -> String {
944916 }
945917 }
946918
947-/// Checks `raw` and stores it into `cfg`. A read-only or unknown key is refused.
948919 pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> {
949920 let field = field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?;
950921 if field.kind == Kind::ReadOnly {
@@ -1072,8 +1043,6 @@ pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> {
10721043 Ok(())
10731044 }
10741045
1075-/// `file` with every override applied. Read-only keys in `overrides` are ignored. Does not
1076-/// validate the result; see [`Config::validate`].
10771046 pub fn apply(file: &Config, overrides: &BTreeMap<String, String>) -> Result<Config> {
10781047 let mut cfg = file.clone();
10791048 for (key, value) in overrides {
@@ -1084,9 +1053,6 @@ pub fn apply(file: &Config, overrides: &BTreeMap<String, String>) -> Result<Conf
10841053 Ok(cfg)
10851054 }
10861055
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.
10901056 pub fn boot_config(file: &Config, overrides: &BTreeMap<String, String>) -> (Config, Option<Error>) {
10911057 match apply(file, overrides).and_then(|c| c.validate().map(|()| c)) {
10921058 Ok(config) => (config, None),
@@ -1094,17 +1060,14 @@ pub fn boot_config(file: &Config, overrides: &BTreeMap<String, String>) -> (Conf
10941060 }
10951061 }
10961062
1097-/// `boot` with the `Live` fields taken from `pending`: what the running process uses.
10981063 pub fn live_view(boot: &Config, pending: &Config) -> Config {
10991064 let mut cfg = boot.clone();
11001065 for f in FIELDS.iter().filter(|f| f.kind == Kind::Live) {
1101- // Values from `get` always pass `normalize`, so this cannot fail.
11021066 let _ = set(&mut cfg, f.key, &get(pending, f.key));
11031067 }
11041068 cfg
11051069 }
11061070
1107-/// Where a field's effective value comes from.
11081071 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
11091072 pub enum Source {
11101073 Default,
@@ -1112,23 +1075,16 @@ pub enum Source {
11121075 Ui,
11131076 }
11141077
1115-/// One field as the page shows it.
11161078 #[derive(Debug, Clone)]
11171079 pub struct FieldView {
11181080 pub field: &'static Field,
1119- /// Effective value. Empty for a secret.
11201081 pub value: String,
1121- /// The value the file (or default) gives. Empty for a secret.
11221082 pub file_value: String,
11231083 pub source: Source,
1124- /// For a secret: whether a value is set.
11251084 pub secret_set: bool,
1126- /// Saved but not yet running: a restart field whose value differs from the running one.
11271085 pub restart_pending: bool,
11281086 }
11291087
1130-/// The process-wide settings handle: the file config, the config boot ran with, and the live view
1131-/// consumers read.
11321088 pub struct Live {
11331089 file: Arc<Config>,
11341090 file_keys: BTreeSet<String>,
@@ -1146,7 +1102,6 @@ impl Live {
11461102 }
11471103 }
11481104
1149- /// The config the running process uses right now.
11501105 pub fn current(&self) -> Arc<Config> {
11511106 self.current
11521107 .read()
@@ -1154,15 +1109,6 @@ impl Live {
11541109 .clone()
11551110 }
11561111
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.
11661112 pub fn publish(&self, overrides: &BTreeMap<String, String>) -> Result<()> {
11671113 let pending = apply(&self.file, overrides)?;
11681114 pending.validate()?;
@@ -1174,7 +1120,6 @@ impl Live {
11741120 Ok(())
11751121 }
11761122
1177- /// Every field with its effective value and source.
11781123 pub fn views(&self, overrides: &BTreeMap<String, String>) -> Vec<FieldView> {
11791124 let pending = apply(&self.file, overrides).unwrap_or_else(|_| (*self.file).clone());
11801125 FIELDS
@@ -1210,9 +1155,6 @@ impl Live {
12101155 .collect()
12111156 }
12121157
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.
12161158 pub fn plan_save(
12171159 &self,
12181160 existing: &BTreeMap<String, String>,
@@ -1262,7 +1204,6 @@ impl Live {
12621204 })
12631205 }
12641206
1265- /// The overrides after dropping `key`, validated.
12661207 pub fn plan_reset(
12671208 &self,
12681209 existing: &BTreeMap<String, String>,
@@ -1276,12 +1217,10 @@ impl Live {
12761217 }
12771218 }
12781219
1279-/// The outcome of [`Live::plan_save`].
12801220 #[derive(Debug)]
12811221 pub struct SavePlan {
12821222 pub sets: Vec<(String, String)>,
12831223 pub clears: Vec<String>,
1284- /// All overrides once the plan is applied.
12851224 pub overrides: BTreeMap<String, String>,
12861225 }
12871226
@@ -1379,7 +1318,7 @@ max_log_mb = 20
13791318 let v = live.views(&over);
13801319 let v = v.iter().find(|v| v.field.key == "base_url").unwrap();
13811320 assert!(v.restart_pending);
1382- let (boot, err) = boot_config(live.file(), &over);
1321+ let (boot, err) = boot_config(&base(), &over);
13831322 assert!(err.is_none());
13841323 assert_eq!(boot.base_url, "https://new.example");
13851324 let after = Live::new(Arc::new(base()), Default::default(), Arc::new(boot));
@@ -1402,7 +1341,6 @@ max_log_mb = 20
14021341 let mut cfg = base();
14031342 assert!(set(&mut cfg, key, value).is_err(), "{key}={value}");
14041343 }
1405- // Cross-field loader rules apply to a whole save.
14061344 let group_form = form(&[("storage.backend", "r2")]);
14071345 assert!(
14081346 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 @@
55
66 use std::time::Duration;
77
8-use super::issues::finish;
8+use super::finish;
99 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,
1112 };
1213 use crate::error::{Error, Result};
1314 use crate::model::{AccountKind, User};
@@ -98,10 +99,10 @@ impl Store {
9899 let conn = self.read_conn().await;
99100 fetch_opt(
100101 &conn,
101- "SELECT id, username, email, password_hash, is_admin, created_at, about, timezone, \
102- (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \
103- theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark, sidebar_side FROM users WHERE LOWER(email) = LOWER(?1) \
104- AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1",
102+ &format!(
103+ "SELECT {USER_COLS} FROM users WHERE LOWER(email) = LOWER(?1) \
104+ AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1"
105+ ),
105106 (email.to_owned(),),
106107 map_user,
107108 )
crates/forge-core/src/store/admin_alerts.rsmodified+2 -6
@@ -6,8 +6,8 @@
66
77 use turso::{Row, Value};
88
9-use super::issues::finish;
10-use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id};
9+use super::finish;
10+use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id, text};
1111 use crate::error::Result;
1212 use crate::time::now_stamp;
1313
@@ -59,10 +59,6 @@ fn map_notice(row: &Row) -> Result<AdminNotice> {
5959 })
6060 }
6161
62-fn text(s: &str) -> Value {
63- Value::Text(s.to_owned())
64-}
65-
6662 impl Store {
6763 /// Marks the condition `key` active. Returns true when it was not active before, which is
6864 /// 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 {
302302 outcome.opened += 1;
303303 }
304304 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?;
306306 outcome.opened += 1;
307307 }
308308 Some(AlertState::Open | AlertState::Dismissed) => {}
@@ -310,7 +310,7 @@ impl Store {
310310 }
311311 for (key, state) in &existing {
312312 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?;
314314 outcome.fixed += 1;
315315 }
316316 }
@@ -333,21 +333,7 @@ impl Store {
333333 let rid = repo_id.to_string();
334334 let now = now_stamp();
335335 let outcome: Result<bool> = async {
336- let mut params = key_params(&rid, key);
337- params.extend([
338- Value::Text(to.as_str().to_string()),
339- Value::Text(now.clone()),
340- Value::Text(from.as_str().to_string()),
341- ]);
342- let changed = tx
343- .execute(
344- "UPDATE repo_alerts SET state = ?6, updated_at = ?7 WHERE repo_id = ?1 AND \
345- advisory_id = ?2 AND ecosystem = ?3 AND package = ?4 AND version = ?5 AND \
346- state = ?8",
347- params,
348- )
349- .await
350- .map_err(db_err)?;
336+ let changed = set_state(&tx, &rid, key, from, to, &now).await?;
351337 Ok(changed > 0)
352338 }
353339 .await;
@@ -531,22 +517,23 @@ async fn set_state(
531517 tx: &turso::transaction::Transaction<'_>,
532518 repo_id: &str,
533519 key: &AlertKey,
534- state: AlertState,
520+ from: AlertState,
521+ to: AlertState,
535522 now: &str,
536-) -> Result<()> {
523+) -> Result<u64> {
537524 let mut params = key_params(repo_id, key);
538525 params.extend([
539- Value::Text(state.as_str().to_string()),
526+ Value::Text(to.as_str().to_string()),
540527 Value::Text(now.to_string()),
528+ Value::Text(from.as_str().to_string()),
541529 ]);
542530 tx.execute(
543531 "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",
545533 params,
546534 )
547535 .await
548- .map_err(db_err)?;
549- Ok(())
536+ .map_err(db_err)
550537 }
551538
552539 #[cfg(test)]
crates/forge-core/src/store/audit.rsmodified+1 -10
@@ -2,7 +2,7 @@
22
33 use turso::{Row, Value};
44
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};
66 use crate::audit::{AuditAction, AuditCursor, AuditEntry, AuditFilter};
77 use crate::error::{Error, Result};
88
@@ -142,15 +142,6 @@ impl Store {
142142 fetch_all(&conn, &sql, params, map_audit).await
143143 }
144144
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-
154145 /// Retention: deletes entries stamped before `cutoff` (an RFC 3339 UTC stamp). Returns the
155146 /// number of entries removed. This is the only delete on the audit log.
156147 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 @@
33
44 use turso::{Row, Value};
55
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};
77 use crate::error::{Error, Result};
88 use crate::time::now_stamp;
99
@@ -76,29 +76,12 @@ pub struct BackupRun {
7676 pub error: Option<String>,
7777 }
7878
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-
9579 fn map_run(row: &Row) -> Result<BackupRun> {
9680 let kind = col_text(row, 1)?;
9781 let trigger = col_text(row, 8)?;
98- let bytes = match opt_int(row, 6)? {
99- Some(n) => Some(u64::try_from(n).map_err(|_| Error::Database("negative run size".into()))?),
100- None => None,
101- };
82+ let bytes = col_opt_int(row, 6)?
83+ .map(|n| u64::try_from(n).map_err(|_| Error::Database("negative run size".into())))
84+ .transpose()?;
10285 Ok(BackupRun {
10386 id: col_text(row, 0)?,
10487 kind: RunKind::parse(&kind)
@@ -106,11 +89,11 @@ fn map_run(row: &Row) -> Result<BackupRun> {
10689 trigger: RunTrigger::parse(&trigger)
10790 .ok_or_else(|| Error::Database(format!("unknown run trigger {trigger:?}")))?,
10891 started_at: col_text(row, 2)?,
109- finished_at: opt_text(row, 3)?,
110- ok: opt_int(row, 4)?.map(|n| n != 0),
111- path: opt_text(row, 5)?,
92+ finished_at: col_opt_text(row, 3)?,
93+ ok: col_opt_int(row, 4)?.map(|n| n != 0),
94+ path: col_opt_text(row, 5)?,
11295 bytes,
113- error: opt_text(row, 7)?,
96+ error: col_opt_text(row, 7)?,
11497 })
11598 }
11699
crates/forge-core/src/store/ci.rsmodified+151 -238
@@ -10,19 +10,19 @@ use std::time::Duration;
1010 use turso::{Connection, Row, Value};
1111
1212 use super::{
13- Store, col_blob, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt,
14- finish, insert_err, missing_row, new_id,
13+ Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all,
14+ fetch_opt, finish, insert_err, missing_row, new_id, opt_int_value, opt_text, text,
1515 };
1616 use crate::ci::{
1717 CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, JobStep,
18- MAX_RUNNER_CONCURRENCY, MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode,
19- RunState, RunnerJob, RunnerReport, RunnerRestart, STARVE_AFTER_SECS, StepSample,
20- pick_by_memory, validate_runner_field,
18+ MemoryOffer, NewJob, NewRun, QueueSkips, RestartMode, RunState, RunnerJob, RunnerReport,
19+ RunnerRestart, STARVE_AFTER_SECS, StepSample, pick_by_memory, validate_runner_field,
2120 };
2221 use crate::error::{Error, Result};
2322 use crate::secret;
2423 use crate::time::{now_stamp, stamp_after, stamp_to_unix};
2524 use crate::token::{generate_token, hash_token};
25+use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY};
2626 use forge_ci::steps::{MAX_STEPS, StepMark};
2727
2828 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;
5050 /// Longest page `list_runs` returns.
5151 const MAX_PER_PAGE: u32 = 100;
5252
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-
7453 fn map_runner(row: &Row) -> Result<CiRunner> {
7554 let labels = serde_json::from_str::<Vec<String>>(&col_text(row, 2)?)
7655 .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> {
8665 concurrency: opt_u32(row, 7)?,
8766 version: col_opt_text(row, 8)?,
8867 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()),
9069 build: col_opt_text(row, 14)?,
9170 boot_id: col_opt_text(row, 15)?,
9271 capabilities: col_opt_text(row, 18)?
@@ -97,15 +76,14 @@ fn map_runner(row: &Row) -> Result<CiRunner> {
9776 .collect()
9877 })
9978 .unwrap_or_default(),
100- memory_budget: opt_int(row, 19)?.and_then(|n| u64::try_from(n).ok()),
101- memory_free: opt_int(row, 20)?.and_then(|n| u64::try_from(n).ok()),
102- memory_reserve: opt_int(row, 21)?.and_then(|n| u64::try_from(n).ok()),
79+ memory_budget: col_opt_int(row, 19)?.and_then(|n| u64::try_from(n).ok()),
80+ memory_free: col_opt_int(row, 20)?.and_then(|n| u64::try_from(n).ok()),
81+ memory_reserve: col_opt_int(row, 21)?.and_then(|n| u64::try_from(n).ok()),
10382 },
10483 restart: match (col_opt_text(row, 16)?, col_opt_text(row, 17)?) {
105- (Some(mode), Some(requested_at)) => mode
106- .parse::<RestartMode>()
107- .ok()
108- .map(|mode| RunnerRestart { mode, requested_at }),
84+ (Some(mode), Some(requested_at)) => {
85+ RestartMode::parse(&mode).map(|mode| RunnerRestart { mode, requested_at })
86+ }
10987 _ => None,
11088 },
11189 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>>
123101
124102 /// A NULL-able integer column that holds a count.
125103 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()))
127105 }
128106
129107 fn map_run(row: &Row) -> Result<CiRun> {
@@ -134,7 +112,7 @@ fn map_run(row: &Row) -> Result<CiRun> {
134112 trigger: col_text(row, 3)?,
135113 git_ref: col_text(row, 4)?,
136114 commit_oid: col_text(row, 5)?,
137- pull_number: opt_int(row, 6)?,
115+ pull_number: col_opt_int(row, 6)?,
138116 actor_id: col_text(row, 7)?,
139117 state: col_text(row, 8)?.parse::<RunState>()?,
140118 config_error: col_opt_text(row, 9)?,
@@ -151,7 +129,7 @@ fn map_job(row: &Row) -> Result<CiJob> {
151129 spec_json: col_text(row, 3)?,
152130 state: col_text(row, 4)?.parse::<JobState>()?,
153131 runner_id: col_opt_text(row, 5)?,
154- exit_code: opt_int(row, 6)?,
132+ exit_code: col_opt_int(row, 6)?,
155133 message: col_opt_text(row, 7)?,
156134 queued_at: col_opt_text(row, 8)?,
157135 started_at: col_opt_text(row, 9)?,
@@ -411,14 +389,54 @@ async fn recompute_run(conn: &Connection, run_id: &str, now: &str) -> Result<()>
411389 Ok(())
412390 }
413391
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+
414437 impl Store {
415438 fn seal_ci_secret(&self, plain: &[u8]) -> Result<Vec<u8>> {
416- let key = self
417- .inner
418- .secret_key
419- .get()
420- .ok_or_else(|| Error::Crypto("instance secret key is not set".into()))?;
421- Ok(secret::seal(key, plain)?.into_bytes())
439+ Ok(secret::seal(self.secret_key()?, plain)?.into_bytes())
422440 }
423441
424442 /// Creates a single-use registration token valid for `ttl_hours`. Returns the plaintext,
@@ -457,8 +475,9 @@ impl Store {
457475 let conn = self.inner.conn.lock().await;
458476 let mut rows = conn
459477 .query(
460- "SELECT 1 FROM ci_registration_tokens WHERE token_hash = ?1 AND used_at IS NULL",
461- vec![text(token_hash)],
478+ "SELECT 1 FROM ci_registration_tokens \
479+ WHERE token_hash = ?1 AND used_at IS NULL AND expires_at > ?2",
480+ vec![text(token_hash), text(&now_stamp())],
462481 )
463482 .await
464483 .map_err(db_err)?;
@@ -655,10 +674,10 @@ impl Store {
655674 /// must be 1 to 64, else `Invalid`. `NotFound` if the runner does not exist.
656675 pub async fn set_runner_concurrency(&self, id: &str, value: Option<u32>) -> Result<()> {
657676 if let Some(n) = value
658- && !(MIN_RUNNER_CONCURRENCY..=MAX_RUNNER_CONCURRENCY).contains(&n)
677+ && !(MIN_CONCURRENCY..=MAX_CONCURRENCY).contains(&n)
659678 {
660679 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}"
662681 )));
663682 }
664683 let conn = self.inner.conn.lock().await;
@@ -695,14 +714,7 @@ impl Store {
695714 .await;
696715 }
697716 let conn = self.inner.conn.lock().await;
698- let mut runner = fetch_opt(
699- &conn,
700- &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"),
701- (id.to_string(),),
702- map_runner,
703- )
704- .await?
705- .ok_or(Error::NotFound)?;
717+ let mut runner = load_runner(&conn, id).await?.ok_or(Error::NotFound)?;
706718 match parsed {
707719 Some(v) => {
708720 runner.config_overrides.insert(key.to_owned(), v);
@@ -719,7 +731,6 @@ impl Store {
719731 .map_err(|e| Error::Database(e.to_string()))?,
720732 )
721733 };
722- // The forge claims with the labels it stores, so a labels override is live at once.
723734 let labels = if key == "labels" {
724735 let chosen = runner
725736 .config_overrides
@@ -762,14 +773,7 @@ impl Store {
762773 config: &BTreeMap<String, serde_json::Value>,
763774 ) -> Result<bool> {
764775 let conn = self.inner.conn.lock().await;
765- let current = fetch_opt(
766- &conn,
767- &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"),
768- (id.to_string(),),
769- map_runner,
770- )
771- .await?;
772- let Some(current) = current else {
776+ let Some(current) = load_runner(&conn, id).await? else {
773777 return Ok(false);
774778 };
775779 if &current.reported_config == config {
@@ -831,14 +835,7 @@ impl Store {
831835 /// value. Returns true when a stored value changed, so the caller can tell live pages.
832836 pub async fn record_runner_report(&self, id: &str, report: &RunnerReport) -> Result<bool> {
833837 let conn = self.inner.conn.lock().await;
834- let current = fetch_opt(
835- &conn,
836- &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"),
837- (id.to_string(),),
838- map_runner,
839- )
840- .await?;
841- let Some(current) = current else {
838+ let Some(current) = load_runner(&conn, id).await? else {
842839 return Ok(false);
843840 };
844841 let merged = RunnerReport {
@@ -860,7 +857,6 @@ impl Store {
860857 if merged == current.reported {
861858 return Ok(false);
862859 }
863- // A new boot id while a restart is pending means the runner came back.
864860 if merged.boot_id != current.reported.boot_id && current.restart.is_some() {
865861 conn.execute(
866862 "UPDATE ci_runners SET restart_mode = NULL, restart_requested_at = NULL \
@@ -924,7 +920,7 @@ impl Store {
924920 |row| col_opt_text(row, 0),
925921 )
926922 .await?;
927- Ok(found.flatten().and_then(|m| m.parse().ok()))
923+ Ok(found.flatten().and_then(|m| RestartMode::parse(&m)))
928924 }
929925
930926 /// Removes a runner. `NotFound` if it does not exist.
@@ -947,18 +943,17 @@ impl Store {
947943 /// `Blocked` until `approve_run`. Otherwise need-less jobs are `Queued` and the run is
948944 /// `Queued`. Jobs with needs are always `Blocked` at first.
949945 #[allow(clippy::too_many_arguments)]
950- pub async fn create_run(
951- &self,
952- repo_id: &str,
953- trigger: &str,
954- git_ref: &str,
955- commit_oid: &str,
956- pull_number: Option<i64>,
957- actor_id: &str,
958- needs_approval: bool,
959- jobs: &[NewJob<'_>],
960- config_error: Option<&str>,
961- ) -> Result<CiRun> {
946+ pub async fn create_run(&self, run: &NewRun<'_>, jobs: &[NewJob<'_>]) -> Result<CiRun> {
947+ let NewRun {
948+ repo_id,
949+ trigger,
950+ git_ref,
951+ commit_oid,
952+ pull_number,
953+ actor_id,
954+ needs_approval,
955+ config_error,
956+ } = *run;
962957 let id = new_id();
963958 let now = now_stamp();
964959 let conn = self.inner.conn.lock().await;
@@ -1099,11 +1094,10 @@ impl Store {
10991094 let candidates: Vec<(Option<u64>, u64)> = compatible
11001095 .iter()
11011096 .map(|(_, spec, queued_at)| {
1102- let waited = queued_at
1103- .as_deref()
1104- .and_then(stamp_to_unix)
1105- .map_or(0, |at| u64::try_from(now - at).unwrap_or(0));
1106- (declared_memory(spec), waited)
1097+ (
1098+ declared_memory(spec),
1099+ waited_secs(queued_at.as_deref(), now),
1100+ )
11071101 })
11081102 .collect();
11091103 compatible = pick_by_memory(&candidates, &offer, STARVE_AFTER_SECS)
@@ -1168,7 +1162,6 @@ impl Store {
11681162 ..QueueSkips::default()
11691163 };
11701164 let mut missing = BTreeSet::new();
1171- // The same walk as `pick_by_memory`, oldest first, counting instead of picking.
11721165 for (spec, queued_at) in &queued {
11731166 if !runs_on_covered(spec, &runner.labels) {
11741167 skips.lacking_labels += 1;
@@ -1191,11 +1184,7 @@ impl Store {
11911184 let need = offer.reservation(declared);
11921185 skips.too_big += 1;
11931186 skips.smallest_need = Some(skips.smallest_need.map_or(need, |n| n.min(need)));
1194- let waited = queued_at
1195- .as_deref()
1196- .and_then(stamp_to_unix)
1197- .map_or(0, |at| u64::try_from(now - at).unwrap_or(0));
1198- if waited >= STARVE_AFTER_SECS {
1187+ if waited_secs(queued_at.as_deref(), now) >= STARVE_AFTER_SECS {
11991188 skips.starved_need = Some(need);
12001189 }
12011190 }
@@ -1280,7 +1269,8 @@ impl Store {
12801269
12811270 /// Finishes a job with a terminal state. Dependants are then unblocked or skipped, and the
12821271 /// 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.
12841274 pub async fn finish_job(
12851275 &self,
12861276 job_id: &str,
@@ -1316,21 +1306,7 @@ impl Store {
13161306 .map_err(db_err)?;
13171307 propagate(&tx, &job.run_id, &now).await?;
13181308 if matches!(state, JobState::Failure | JobState::Error) {
1319- // Fail fast: the run cannot succeed any more, so stop the sibling jobs now.
1320- tx.execute(
1321- "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \
1322- WHERE run_id = ?1 AND state IN ('queued', 'blocked')",
1323- (job.run_id.clone(), now.clone()),
1324- )
1325- .await
1326- .map_err(db_err)?;
1327- tx.execute(
1328- "UPDATE ci_jobs SET cancel_requested = 1 \
1329- WHERE run_id = ?1 AND state = 'running'",
1330- (job.run_id.clone(),),
1331- )
1332- .await
1333- .map_err(db_err)?;
1309+ cancel_open_jobs(&tx, &job.run_id, &now).await?;
13341310 }
13351311 recompute_run(&tx, &job.run_id, &now).await?;
13361312 load_run(&tx, &job.run_id).await?.ok_or_else(missing_row)
@@ -1388,19 +1364,7 @@ impl Store {
13881364 if run.state.is_terminal() {
13891365 return Ok(());
13901366 }
1391- tx.execute(
1392- "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \
1393- WHERE run_id = ?1 AND state IN ('queued', 'blocked')",
1394- (run_id.to_string(), now.clone()),
1395- )
1396- .await
1397- .map_err(db_err)?;
1398- tx.execute(
1399- "UPDATE ci_jobs SET cancel_requested = 1 WHERE run_id = ?1 AND state = 'running'",
1400- (run_id.to_string(),),
1401- )
1402- .await
1403- .map_err(db_err)?;
1367+ cancel_open_jobs(&tx, run_id, &now).await?;
14041368 recompute_run(&tx, run_id, &now).await
14051369 }
14061370 .await;
@@ -1507,15 +1471,17 @@ impl Store {
15071471 .collect();
15081472 let created = self
15091473 .create_run(
1510- &run.repo_id,
1511- &run.trigger,
1512- &run.git_ref,
1513- &run.commit_oid,
1514- run.pull_number,
1515- actor_id,
1516- false,
1474+ &NewRun {
1475+ repo_id: &run.repo_id,
1476+ trigger: &run.trigger,
1477+ git_ref: &run.git_ref,
1478+ commit_oid: &run.commit_oid,
1479+ pull_number: run.pull_number,
1480+ actor_id,
1481+ needs_approval: false,
1482+ config_error: run.config_error.as_deref(),
1483+ },
15171484 &new_jobs,
1518- run.config_error.as_deref(),
15191485 )
15201486 .await?;
15211487 let warnings = self.run_warnings(&run.id).await?;
@@ -1527,7 +1493,11 @@ impl Store {
15271493
15281494 /// Stores the config warnings of a run, replacing any earlier ones.
15291495 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"));
15311501 let conn = self.inner.conn.lock().await;
15321502 conn.execute(
15331503 "UPDATE ci_runs SET config_warnings = ?2 WHERE id = ?1",
@@ -1599,6 +1569,7 @@ impl Store {
15991569 )
16001570 .await?;
16011571 let mut runs: Vec<String> = Vec::new();
1572+ let mut failed_runs: Vec<String> = Vec::new();
16021573 for job in &lost {
16031574 tx.execute(
16041575 "UPDATE ci_jobs SET \
@@ -1613,9 +1584,15 @@ impl Store {
16131584 if !runs.contains(&job.run_id) {
16141585 runs.push(job.run_id.clone());
16151586 }
1587+ if !job.cancel_requested && !failed_runs.contains(&job.run_id) {
1588+ failed_runs.push(job.run_id.clone());
1589+ }
16161590 }
16171591 for run_id in &runs {
16181592 propagate(&tx, run_id, &now).await?;
1593+ if failed_runs.contains(run_id) {
1594+ cancel_open_jobs(&tx, run_id, &now).await?;
1595+ }
16191596 recompute_run(&tx, run_id, &now).await?;
16201597 }
16211598 let mut out = Vec::with_capacity(lost.len());
@@ -1708,27 +1685,10 @@ impl Store {
17081685 repo_id: &str,
17091686 git_refs: &[String],
17101687 ) -> Result<Vec<JobSample>> {
1711- let mut params: Vec<Value> = Vec::with_capacity(git_refs.len() + 1);
1712- params.push(Value::Text(repo_id.to_string()));
1713- params.extend(git_refs.iter().map(|git_ref| Value::Text(git_ref.clone())));
1714- let scope = if git_refs.is_empty() {
1715- "done.repo_rank <= 5".to_owned()
1716- } else {
1717- let marks: Vec<String> = (2..=git_refs.len() + 1).map(|i| format!("?{i}")).collect();
1718- format!(
1719- "(done.branch_rank <= 5 AND done.git_ref IN ({})) OR done.repo_rank <= 5",
1720- marks.join(", ")
1721- )
1722- };
1688+ let (params, scope) = recent_done_scope(repo_id, git_refs);
17231689 let sql = format!(
1724- "WITH done AS ( \
1725- SELECT id, git_ref, \
1726- ROW_NUMBER() OVER (PARTITION BY git_ref ORDER BY number DESC) AS branch_rank, \
1727- ROW_NUMBER() OVER (ORDER BY number DESC) AS repo_rank \
1728- FROM ci_runs WHERE repo_id = ?1 AND state = 'success' \
1729- ) \
1730- SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, j.started_at, \
1731- j.finished_at \
1690+ "{DONE_RUNS} SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, \
1691+ j.started_at, j.finished_at \
17321692 FROM done JOIN ci_jobs j ON j.run_id = done.id \
17331693 WHERE ({scope}) \
17341694 AND j.state = 'success' AND j.started_at IS NOT NULL AND j.finished_at IS NOT NULL"
@@ -1868,26 +1828,9 @@ impl Store {
18681828 repo_id: &str,
18691829 git_refs: &[String],
18701830 ) -> Result<Vec<StepSample>> {
1871- let mut params: Vec<Value> = Vec::with_capacity(git_refs.len() + 1);
1872- params.push(Value::Text(repo_id.to_string()));
1873- params.extend(git_refs.iter().map(|git_ref| Value::Text(git_ref.clone())));
1874- let scope = if git_refs.is_empty() {
1875- "done.repo_rank <= 5".to_owned()
1876- } else {
1877- let marks: Vec<String> = (2..=git_refs.len() + 1).map(|i| format!("?{i}")).collect();
1878- format!(
1879- "(done.branch_rank <= 5 AND done.git_ref IN ({})) OR done.repo_rank <= 5",
1880- marks.join(", ")
1881- )
1882- };
1831+ let (params, scope) = recent_done_scope(repo_id, git_refs);
18831832 let sql = format!(
1884- "WITH done AS ( \
1885- SELECT id, git_ref, \
1886- ROW_NUMBER() OVER (PARTITION BY git_ref ORDER BY number DESC) AS branch_rank, \
1887- ROW_NUMBER() OVER (ORDER BY number DESC) AS repo_rank \
1888- FROM ci_runs WHERE repo_id = ?1 AND state = 'success' \
1889- ) \
1890- SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, s.name, \
1833+ "{DONE_RUNS} SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, s.name, \
18911834 s.started_at, s.finished_at \
18921835 FROM done JOIN ci_jobs j ON j.run_id = done.id \
18931836 JOIN ci_job_steps s ON s.job_id = j.id \
@@ -2031,7 +1974,6 @@ impl Store {
20311974 let conn = self.inner.conn.lock().await;
20321975 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
20331976 let outcome: Result<(Vec<String>, Vec<String>, Vec<String>)> = async {
2034- // Which run owns each artifact, read before the rows go.
20351977 let owners: BTreeMap<String, String> = fetch_all(
20361978 &tx,
20371979 "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 {
20732015 .await
20742016 .map_err(db_err)?;
20752017
2076- // Keep only the newest `keep_runs` runs (per repo) that still have artifacts.
20772018 if keep_runs > 0 {
20782019 let old = fetch_all(
20792020 &tx,
20802021 "SELECT a.id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id \
20812022 WHERE j.run_id NOT IN ( \
20822023 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) \
20842025 AS rn \
20852026 FROM ci_runs r \
20862027 WHERE EXISTS (SELECT 1 FROM ci_artifacts a2 JOIN ci_jobs j2 \
@@ -2099,10 +2040,8 @@ impl Store {
20992040 artifact_ids.extend(old);
21002041 }
21012042
2102- // Over the disk limit: drop the oldest runs' artifacts, one whole run at a time.
21032043 if max_total_bytes > 0 {
21042044 let limit = i64::try_from(max_total_bytes).unwrap_or(i64::MAX);
2105- // (artifact id, run id, size), oldest run first.
21062045 let rows = fetch_all(
21072046 &tx,
21082047 "SELECT a.id, j.run_id, a.size FROM ci_artifacts a \
@@ -2215,14 +2154,9 @@ impl Store {
22152154 if !names.contains(&name) {
22162155 continue;
22172156 }
2218- let key = self
2219- .inner
2220- .secret_key
2221- .get()
2222- .ok_or_else(|| Error::Crypto("instance secret key is not set".into()))?;
22232157 let sealed = String::from_utf8(sealed)
22242158 .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)?;
22262160 let value = String::from_utf8(plain)
22272161 .map_err(|_| Error::Crypto("CI secret is not UTF-8".into()))?;
22282162 out.insert(name, value);
@@ -2305,15 +2239,17 @@ mod tests {
23052239 .collect();
23062240 store
23072241 .create_run(
2308- repo_id,
2309- "push",
2310- "refs/heads/main",
2311- "abc123",
2312- None,
2313- actor,
2314- approval,
2242+ &NewRun {
2243+ repo_id,
2244+ trigger: "push",
2245+ git_ref: "refs/heads/main",
2246+ commit_oid: "abc123",
2247+ pull_number: None,
2248+ actor_id: actor,
2249+ needs_approval: approval,
2250+ config_error: None,
2251+ },
23152252 &new,
2316- None,
23172253 )
23182254 .await
23192255 .unwrap()
@@ -2363,7 +2299,6 @@ mod tests {
23632299 .create_registration_token(&fx.tahinli.id, 1)
23642300 .await
23652301 .unwrap();
2366- // Only the hash is stored.
23672302 {
23682303 let conn = fx.store.inner.conn.lock().await;
23692304 let n = fetch_opt(
@@ -2511,7 +2446,6 @@ mod tests {
25112446 assert_eq!(found.config_overrides["limits.memory"], "8g");
25122447 assert_eq!(found.reported_config["limits.memory"], "4g");
25132448
2514- // Labels are claimed with at once, and a reset restores what the runner reported.
25152449 fx.store
25162450 .set_runner_field(&runner.id, "labels", Some("linux, arm"))
25172451 .await
@@ -2530,7 +2464,6 @@ mod tests {
25302464 assert_eq!(after.labels, vec!["linux".to_string()]);
25312465 assert!(after.config_overrides.is_empty());
25322466
2533- // Concurrency goes through the same entry point.
25342467 fx.store
25352468 .set_runner_field(&runner.id, "concurrency", Some("6"))
25362469 .await
@@ -2566,7 +2499,6 @@ mod tests {
25662499 .await,
25672500 Err(Error::Invalid(_))
25682501 ));
2569- // A boot id alone is not enough, the version is the same for every build.
25702502 fx.store
25712503 .record_runner_report(&runner.id, &boot_report("b1", &[]))
25722504 .await
@@ -2606,13 +2538,11 @@ mod tests {
26062538 assert_eq!(listed.restart.as_ref().unwrap().mode, RestartMode::Drain);
26072539 assert!(listed.supports_restart());
26082540
2609- // The same process reporting again changes nothing.
26102541 fx.store
26112542 .record_runner_report(&runner.id, &boot_report("b1", &["restart"]))
26122543 .await
26132544 .unwrap();
26142545 assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some());
2615- // A heartbeat without a boot id changes nothing either.
26162546 let beat = RunnerReport {
26172547 concurrency: Some(2),
26182548 ..RunnerReport::default()
@@ -2623,7 +2553,6 @@ mod tests {
26232553 .unwrap();
26242554 assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some());
26252555
2626- // "Restart now" replaces the pending drain.
26272556 fx.store
26282557 .request_runner_restart(&runner.id, RestartMode::Now)
26292558 .await
@@ -2633,7 +2562,6 @@ mod tests {
26332562 Some(RestartMode::Now)
26342563 );
26352564
2636- // The runner comes back with a new boot id: the request is cleared, capability kept.
26372565 assert!(
26382566 fx.store
26392567 .record_runner_report(&runner.id, &boot_report("b2", &["restart"]))
@@ -2678,7 +2606,6 @@ mod tests {
26782606 .unwrap(),
26792607 "an identical report is not a change"
26802608 );
2681- // A heartbeat reports only the concurrency and keeps the host facts.
26822609 let beat = RunnerReport {
26832610 concurrency: Some(3),
26842611 ..RunnerReport::default()
@@ -2699,7 +2626,6 @@ mod tests {
26992626 );
27002627 assert_eq!(listed.running_jobs, 0);
27012628
2702- // The running count comes from the job table, and drops when the job finishes.
27032629 create(
27042630 &fx.store,
27052631 &fx.repo.id,
@@ -2801,15 +2727,17 @@ mod tests {
28012727 let broken = fx
28022728 .store
28032729 .create_run(
2804- &repo.id,
2805- "push",
2806- "refs/heads/main",
2807- "abc123",
2808- None,
2809- &fx.tahinli.id,
2810- false,
2730+ &NewRun {
2731+ repo_id: &repo.id,
2732+ trigger: "push",
2733+ git_ref: "refs/heads/main",
2734+ commit_oid: "abc123",
2735+ pull_number: None,
2736+ actor_id: &fx.tahinli.id,
2737+ needs_approval: false,
2738+ config_error: Some("line 3: unknown key"),
2739+ },
28112740 &[],
2812- Some("line 3: unknown key"),
28132741 )
28142742 .await
28152743 .unwrap();
@@ -2842,15 +2770,17 @@ mod tests {
28422770 let dev = fx
28432771 .store
28442772 .create_run(
2845- &repo.id,
2846- "push",
2847- "refs/heads/dev",
2848- "abc123",
2849- None,
2850- &fx.tahinli.id,
2851- false,
2773+ &NewRun {
2774+ repo_id: &repo.id,
2775+ trigger: "push",
2776+ git_ref: "refs/heads/dev",
2777+ commit_oid: "abc123",
2778+ pull_number: None,
2779+ actor_id: &fx.tahinli.id,
2780+ needs_approval: false,
2781+ config_error: Some("broken"),
2782+ },
28522783 &[],
2853- Some("broken"),
28542784 )
28552785 .await
28562786 .unwrap();
@@ -2922,7 +2852,7 @@ mod tests {
29222852 let run = create(store, repo_id, actor, jobs, approval).await;
29232853 let conn = store.inner.conn.lock().await;
29242854 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));
29262856 conn.execute(
29272857 "UPDATE ci_jobs SET queued_at = ?1 WHERE name = ?2",
29282858 (at, j.name.clone()),
@@ -2971,7 +2901,6 @@ mod tests {
29712901 )
29722902 .await;
29732903 let runner = bare_runner(&["linux"]);
2974- // 2 GiB free: the 4 GiB job is skipped (it is young), the 1 GiB one runs.
29752904 let first = fx
29762905 .store
29772906 .claim_job_fitting(&runner, offer(2))
@@ -2979,7 +2908,6 @@ mod tests {
29792908 .unwrap()
29802909 .unwrap();
29812910 assert_eq!(first.0.name, "small");
2982- // 1 GiB left: a job with no memory reserves the default 1 GiB and fits.
29832911 let second = fx
29842912 .store
29852913 .claim_job_fitting(&runner, offer(1))
@@ -2987,7 +2915,6 @@ mod tests {
29872915 .unwrap()
29882916 .unwrap();
29892917 assert_eq!(second.0.name, "plain");
2990- // Nothing fits in 0 GiB, and the big job is still queued.
29912918 assert!(
29922919 fx.store
29932920 .claim_job_fitting(&runner, offer(0))
@@ -2995,7 +2922,6 @@ mod tests {
29952922 .unwrap()
29962923 .is_none()
29972924 );
2998- // An idle runner takes it.
29992925 let big = fx
30002926 .store
30012927 .claim_job_fitting(&runner, offer(6))
@@ -3068,7 +2994,7 @@ mod tests {
30682994 false,
30692995 )
30702996 .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));
30722998 {
30732999 let conn = fx.store.inner.conn.lock().await;
30743000 conn.execute(
@@ -3087,7 +3013,6 @@ mod tests {
30873013 .is_none(),
30883014 "the old big job holds the line"
30893015 );
3090- // Once enough memory is free the big job goes first.
30913016 let claimed = fx
30923017 .store
30933018 .claim_job_fitting(&runner, offer(5))
@@ -3128,7 +3053,6 @@ mod tests {
31283053 assert_eq!(back.oom_kills, None);
31293054 let run = fx.store.run_by_id(&run.id).await.unwrap().unwrap();
31303055 assert_eq!(run.state, RunState::Running);
3131- // The old token no longer matches, and only a running job can be requeued.
31323056 assert!(!fx.store.requeue_job(&claimed.id).await.unwrap());
31333057 assert!(!fx.store.requeue_job("missing").await.unwrap());
31343058 let (again, _, token) = fx
@@ -3292,7 +3216,6 @@ mod tests {
32923216 second.0.id.clone()
32933217 };
32943218
3295- // Success unblocks b; c still waits on b.
32963219 let after_a = fx
32973220 .store
32983221 .finish_job(&a_id, JobState::Success, Some(0), None)
@@ -3308,7 +3231,6 @@ mod tests {
33083231 JobState::Blocked
33093232 );
33103233
3311- // Failure of b skips c transitively once b is done.
33123234 let b_claim = fx.store.claim_job(&runner).await.unwrap().unwrap();
33133235 assert_eq!(b_claim.0.name, "b");
33143236 fx.store
@@ -3467,7 +3389,6 @@ mod tests {
34673389 .unwrap();
34683390 assert_eq!(done.state, RunState::Cancelled);
34693391 assert!(done.finished_at.is_some());
3470- // A finished run does not change again.
34713392 fx.store.request_cancel(&run.id).await.unwrap();
34723393 assert_eq!(
34733394 fx.store.run_by_id(&run.id).await.unwrap().unwrap().state,
@@ -3528,7 +3449,6 @@ mod tests {
35283449 .finish_job(&b.id, JobState::Failure, Some(1), None)
35293450 .await
35303451 .unwrap();
3531- // Fail fast cancels the queued `d` and skips `c`.
35323452 let done = fx.store.run_by_id(&first.id).await.unwrap().unwrap();
35333453 assert_eq!(done.state, RunState::Failure);
35343454 assert_eq!(
@@ -3557,7 +3477,6 @@ mod tests {
35573477 assert_eq!(c2.state, JobState::Blocked);
35583478 assert_eq!(spec_needs(&c2.spec_json), ["b"]);
35593479
3560- // One finished job brings its dependants; a live one is refused.
35613480 let single = fx
35623481 .store
35633482 .rerun_job(&first.id, &a.id, &fx.tahinli.id)
@@ -3628,7 +3547,6 @@ mod tests {
36283547 .await
36293548 .unwrap()
36303549 .unwrap();
3631- // Nothing is older than the epoch.
36323550 assert!(fx.store.reap_lost_jobs(DAWN).await.unwrap().is_empty());
36333551 let future = stamp_after(Duration::from_secs(3600));
36343552 let reaped = fx.store.reap_lost_jobs(&future).await.unwrap();
@@ -3739,13 +3657,10 @@ mod tests {
37393657 .await
37403658 .unwrap();
37413659 artifacts.push(made.id);
3742- // ULIDs made in the same millisecond do not sort by creation order.
37433660 tokio::time::sleep(Duration::from_millis(2)).await;
37443661 }
3745- // Keep the newest two runs: the oldest run's artifact goes.
37463662 let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap();
37473663 assert_eq!(deleted, vec![artifacts[0].clone()]);
3748- // 20 + 30 bytes left against a 35 byte limit: the older run (20 bytes) goes.
37493664 let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();
37503665 assert_eq!(deleted, vec![artifacts[1].clone()]);
37513666 let (_, again, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap();
@@ -3795,7 +3710,6 @@ mod tests {
37953710 .await
37963711 .unwrap();
37973712
3798- // Raw storage is sealed, not plaintext.
37993713 {
38003714 let conn = fx.store.inner.conn.lock().await;
38013715 let raw = fetch_opt(
@@ -3827,7 +3741,6 @@ mod tests {
38273741 assert_eq!(values.len(), 1);
38283742 assert_eq!(values.get("DEPLOY_KEY").map(String::as_str), Some(plain));
38293743
3830- // Replacing keeps one row.
38313744 fx.store
38323745 .set_ci_secret(&repo.id, "DEPLOY_KEY", b"rotated")
38333746 .await
crates/forge-core/src/store/contributions.rsmodified+36 -54
@@ -13,6 +13,27 @@ use crate::tz::local_date;
1313 /// Most contributions `contributions_between` returns for one day.
1414 const DAY_LIMIT: u32 = 200;
1515
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+
1637 /// What a contribution was: a branch push, an issue, pull request or comment the user wrote, or
1738 /// a commit the user was credited with as a co-author.
1839 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -81,35 +102,21 @@ impl Store {
81102 since: &str,
82103 tz: &str,
83104 ) -> Result<Vec<(String, u32)>> {
84- // Parameters: ?1 user, ?2 since, ?3 and ?4 zero oids.
85- let sql = "SELECT minute, COUNT(*) FROM ( \
86- SELECT substr(created_at, 1, 16) AS minute FROM push_events \
87- WHERE actor_id = ?1 AND created_at >= ?2 AND new_oid NOT IN (?3, ?4) \
88- AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \
89- UNION ALL \
90- SELECT substr(created_at, 1, 16) FROM issues \
91- WHERE author_id = ?1 AND created_at >= ?2 AND kind IN ('issue', 'pull') \
92- AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \
93- UNION ALL \
94- SELECT substr(c.created_at, 1, 16) FROM comments c JOIN issues i ON i.id = c.issue_id \
95- WHERE c.author_id = ?1 AND c.created_at >= ?2 AND i.repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \
96- UNION ALL \
97- SELECT substr(created_at, 1, 16) FROM coauthored_commits \
98- WHERE user_id = ?1 AND created_at >= ?2 AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \
99- ) GROUP BY minute";
105+ let sql = format!(
106+ "SELECT substr(created_at, 1, 16) AS minute, COUNT(*) FROM ({}) \
107+ WHERE user_id = ?1 AND created_at >= ?2 GROUP BY minute",
108+ activity_sql()
109+ );
100110 let params = vec![
101111 Value::Text(user_id.to_string()),
102112 Value::Text(since.to_string()),
103- Value::Text(ZERO_OID_SHA1.to_string()),
104- Value::Text(ZERO_OID_SHA256.to_string()),
105113 ];
106114
107115 let conn = self.read_conn().await;
108- let rows = fetch_all(&conn, sql, params, |row| {
116+ let rows = fetch_all(&conn, &sql, params, |row| {
109117 Ok((col_text(row, 0)?, col_int(row, 1)?))
110118 })
111119 .await?;
112- // `minute` is `YYYY-MM-DDTHH:MM` in UTC; the stamp is completed with seconds to parse.
113120 let mut days: BTreeMap<String, u32> = BTreeMap::new();
114121 for (minute, count) in rows {
115122 let Ok(ts) = format!("{minute}:00Z").parse::<Timestamp>() else {
@@ -131,41 +138,23 @@ impl Store {
131138 from: &str,
132139 to: &str,
133140 ) -> Result<Vec<ContributionItem>> {
134- // Parameters: ?1 user, ?2 from, ?3 to, ?4 and ?5 zero oids.
135- let sql = "SELECT 'push' AS created_kind, o.username, r.name, p.created_at, p.ref_name, \
136- 0, '', '' FROM push_events p \
137- JOIN repos r ON r.id = p.repo_id JOIN users o ON o.id = r.owner_id \
138- WHERE p.actor_id = ?1 AND p.created_at >= ?2 AND p.created_at < ?3 \
139- AND p.new_oid NOT IN (?4, ?5) AND r.visibility = 'public' \
140- UNION ALL \
141- SELECT i.kind, o.username, r.name, i.created_at, '', i.number, i.title, '' FROM issues i \
142- JOIN repos r ON r.id = i.repo_id JOIN users o ON o.id = r.owner_id \
143- WHERE i.author_id = ?1 AND i.created_at >= ?2 AND i.created_at < ?3 \
144- AND i.kind IN ('issue', 'pull') AND r.visibility = 'public' \
145- UNION ALL \
146- SELECT 'comment', o.username, r.name, c.created_at, '', i.number, i.title, '' \
147- FROM comments c JOIN issues i ON i.id = c.issue_id \
148- JOIN repos r ON r.id = i.repo_id JOIN users o ON o.id = r.owner_id \
149- WHERE c.author_id = ?1 AND c.created_at >= ?2 AND c.created_at < ?3 \
150- AND r.visibility = 'public' \
151- UNION ALL \
152- SELECT 'coauthored', o.username, r.name, k.created_at, '', 0, k.summary, k.commit_oid \
153- FROM coauthored_commits k \
154- JOIN repos r ON r.id = k.repo_id JOIN users o ON o.id = r.owner_id \
155- WHERE k.user_id = ?1 AND k.created_at >= ?2 AND k.created_at < ?3 \
156- AND r.visibility = 'public' \
157- ORDER BY created_at DESC LIMIT ?6";
141+ let sql = format!(
142+ "SELECT a.kind, o.username, r.name, a.created_at, a.ref_name, a.number, a.title, \
143+ a.commit_oid FROM ({}) a \
144+ JOIN repos r ON r.id = a.repo_id JOIN users o ON o.id = r.owner_id \
145+ WHERE a.user_id = ?1 AND a.created_at >= ?2 AND a.created_at < ?3 \
146+ ORDER BY a.created_at DESC LIMIT ?4",
147+ activity_sql()
148+ );
158149 let params = vec![
159150 Value::Text(user_id.to_string()),
160151 Value::Text(from.to_string()),
161152 Value::Text(to.to_string()),
162- Value::Text(ZERO_OID_SHA1.to_string()),
163- Value::Text(ZERO_OID_SHA256.to_string()),
164153 Value::Integer(i64::from(DAY_LIMIT)),
165154 ];
166155
167156 let conn = self.read_conn().await;
168- fetch_all(&conn, sql, params, map_item).await
157+ fetch_all(&conn, &sql, params, map_item).await
169158 }
170159
171160 /// Credits `user_id` with a co-authored commit in `repo_id`. A commit is recorded once per
@@ -311,7 +300,6 @@ mod tests {
311300 .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at)
312301 .await
313302 .unwrap();
314- // A repeat of the same commit is ignored.
315303 store
316304 .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at)
317305 .await
@@ -349,7 +337,6 @@ mod tests {
349337 .await
350338 .unwrap();
351339
352- // Day one: a push and an issue.
353340 let day1 = "2026-03-01T10:00:00.000000000Z";
354341 let day2 = "2026-03-02T10:00:00.000000000Z";
355342 let before = "2026-02-28T10:00:00.000000000Z";
@@ -363,7 +350,6 @@ mod tests {
363350 .unwrap();
364351 set_created_at(&store, "issues", &issue.id, day1).await;
365352
366- // Day two: a branch update, a deletion (not counted), a pull request, a comment.
367353 store
368354 .record_push_event_at(&demo.id, &tahinli.id, "refs/heads/main", OID, OID, day2)
369355 .await
@@ -393,7 +379,6 @@ mod tests {
393379 .unwrap();
394380 set_created_at(&store, "comments", &comment.id, day2).await;
395381
396- // Before `since`, and someone else's activity: left out.
397382 store
398383 .record_push_event_at(&demo.id, &tahinli.id, "refs/heads/main", OID, OID, before)
399384 .await
@@ -413,8 +398,6 @@ mod tests {
413398 vec![("2026-03-01".to_string(), 2), ("2026-03-02".to_string(), 3)]
414399 );
415400
416- // `since` filters out the first day. In Kiritimati (+14) the 10:00 UTC events fall on
417- // the next local day.
418401 let later = store
419402 .contribution_counts(
420403 &tahinli.id,
@@ -425,7 +408,6 @@ mod tests {
425408 .unwrap();
426409 assert_eq!(later, vec![("2026-03-03".to_string(), 3)]);
427410
428- // A user with nothing in range gets an empty list.
429411 assert!(
430412 store
431413 .contribution_counts(&bob.id, "2026-03-03T00:00:00.000000000Z", "UTC")
crates/forge-core/src/store/discussions.rsmodified+56 -48
@@ -5,7 +5,7 @@
55 use turso::transaction::Transaction;
66 use turso::{Connection, Row, Value};
77
8-use super::issues::finish;
8+use super::finish;
99 use super::{
1010 Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id,
1111 };
@@ -452,23 +452,16 @@ impl Store {
452452 .await
453453 .map_err(db_err)?;
454454 if discussion.author_id != author_id {
455- tx.execute(
456- "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \
457- last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, 'reply', ?4, 1, ?5) \
458- ON CONFLICT (user_id, discussion_id) DO UPDATE SET \
459- reason = CASE WHEN discussion_notifications.reason = 'mention' THEN 'mention' \
460- ELSE 'reply' END, last_actor_id = excluded.last_actor_id, unread = 1, \
461- updated_at = excluded.updated_at",
462- (
463- discussion.author_id.clone(),
464- discussion_id.to_string(),
465- discussion.repo_id.clone(),
466- author_id.to_string(),
467- now,
468- ),
455+ upsert_discussion_notification(
456+ &tx,
457+ &discussion.author_id,
458+ &discussion.repo_id,
459+ discussion_id,
460+ "reply",
461+ author_id,
462+ &now,
469463 )
470- .await
471- .map_err(db_err)?;
464+ .await?;
472465 }
473466 Ok(comment)
474467 }
@@ -598,21 +591,16 @@ impl Store {
598591 let conn = self.inner.conn.lock().await;
599592 let now = now_stamp();
600593 for user_id in user_ids {
601- conn.execute(
602- "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \
603- last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, 'mention', ?4, 1, ?5) \
604- ON CONFLICT (user_id, discussion_id) DO UPDATE SET reason = 'mention', \
605- last_actor_id = excluded.last_actor_id, unread = 1, updated_at = excluded.updated_at",
606- (
607- user_id.clone(),
608- discussion_id.to_string(),
609- repo_id.to_string(),
610- actor_id.to_string(),
611- now.clone(),
612- ),
594+ upsert_discussion_notification(
595+ &conn,
596+ user_id,
597+ repo_id,
598+ discussion_id,
599+ "mention",
600+ actor_id,
601+ &now,
613602 )
614- .await
615- .map_err(db_err)?;
603+ .await?;
616604 }
617605 Ok(())
618606 }
@@ -696,27 +684,47 @@ impl Store {
696684 repo_id: Option<&str>,
697685 ) -> Result<()> {
698686 let conn = self.inner.conn.lock().await;
699- let result = match repo_id {
700- Some(repo) => {
701- conn.execute(
702- "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND repo_id = ?2 AND unread = 1",
703- (user_id.to_string(), repo.to_string()),
704- )
705- .await
706- }
707- None => {
708- conn.execute(
709- "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1",
710- (user_id.to_string(),),
711- )
712- .await
713- }
714- };
715- result.map_err(db_err)?;
687+ conn.execute(
688+ "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1 \
689+ AND (?2 IS NULL OR repo_id = ?2)",
690+ (user_id.to_string(), repo_id.map(str::to_string)),
691+ )
692+ .await
693+ .map_err(db_err)?;
716694 Ok(())
717695 }
718696 }
719697
698+async fn upsert_discussion_notification(
699+ conn: &Connection,
700+ user_id: &str,
701+ repo_id: &str,
702+ discussion_id: &str,
703+ reason: &str,
704+ actor_id: &str,
705+ now: &str,
706+) -> Result<()> {
707+ conn.execute(
708+ "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \
709+ last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, 1, ?6) \
710+ ON CONFLICT (user_id, discussion_id) DO UPDATE SET \
711+ reason = CASE WHEN excluded.reason = 'mention' OR discussion_notifications.reason = 'mention' \
712+ THEN 'mention' ELSE 'reply' END, last_actor_id = excluded.last_actor_id, unread = 1, \
713+ updated_at = excluded.updated_at",
714+ (
715+ user_id.to_string(),
716+ discussion_id.to_string(),
717+ repo_id.to_string(),
718+ reason.to_string(),
719+ actor_id.to_string(),
720+ now.to_string(),
721+ ),
722+ )
723+ .await
724+ .map_err(db_err)?;
725+ Ok(())
726+}
727+
720728 #[cfg(test)]
721729 mod tests {
722730 use super::*;
crates/forge-core/src/store/edit_history_read.rsmodified+29 -17
@@ -4,11 +4,26 @@
44
55 use std::collections::HashMap;
66
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};
88 use crate::error::Result;
99
10-/// Longest id list sent in one `IN (...)` query.
11-const CHUNK: usize = 500;
10+/// The kinds of target that have edit history. `as_str` is the stored text.
11+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12+pub enum EditTarget {
13+ Issue,
14+ Comment,
15+ ReviewComment,
16+}
17+
18+impl EditTarget {
19+ pub fn as_str(self) -> &'static str {
20+ match self {
21+ Self::Issue => "issue",
22+ Self::Comment => "comment",
23+ Self::ReviewComment => "review_comment",
24+ }
25+ }
26+}
1227
1328 /// One previous version of an issue, pull request, comment or review comment.
1429 #[derive(Debug, Clone, PartialEq)]
@@ -22,15 +37,11 @@ pub struct EditVersion {
2237 pub old_body: String,
2338 }
2439
25-fn placeholders(n: usize) -> String {
26- vec!["?"; n].join(",")
27-}
28-
2940 impl Store {
3041 /// The previous versions of one target, newest first.
3142 pub async fn edit_history(
3243 &self,
33- target_kind: &str,
44+ target_kind: EditTarget,
3445 target_id: &str,
3546 ) -> Result<Vec<EditVersion>> {
3647 let conn = self.read_conn().await;
@@ -40,7 +51,7 @@ impl Store {
4051 FROM edit_history h JOIN users u ON u.id = h.editor_id \
4152 WHERE h.target_kind = ?1 AND h.target_id = ?2 \
4253 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()),
4455 |row| {
4556 Ok(EditVersion {
4657 id: col_text(row, 0)?,
@@ -58,7 +69,7 @@ impl Store {
5869 /// absent from the map. One query per 500 ids.
5970 pub async fn edit_count(
6071 &self,
61- target_kind: &str,
72+ target_kind: EditTarget,
6273 target_ids: &[&str],
6374 ) -> Result<HashMap<String, u64>> {
6475 let mut out = HashMap::new();
@@ -66,14 +77,14 @@ impl Store {
6677 return Ok(out);
6778 }
6879 let conn = self.read_conn().await;
69- for chunk in target_ids.chunks(CHUNK) {
80+ for chunk in target_ids.chunks(IN_CHUNK) {
7081 let sql = format!(
7182 "SELECT target_id, COUNT(*) FROM edit_history \
7283 WHERE target_kind = ?1 AND target_id IN ({}) GROUP BY target_id",
7384 placeholders(chunk.len())
7485 );
7586 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()));
7788 params.extend(chunk.iter().map(|id| turso::Value::Text((*id).to_string())));
7889 let rows = fetch_all(&conn, &sql, params, |row| {
7990 let count = u64::try_from(col_int(row, 1)?).unwrap_or(0);
@@ -89,14 +100,15 @@ impl Store {
89100 /// target does not exist (a deleted comment has no history either).
90101 pub async fn edit_target_issue(
91102 &self,
92- target_kind: &str,
103+ target_kind: EditTarget,
93104 target_id: &str,
94105 ) -> Result<Option<String>> {
95106 let sql = match target_kind {
96- "issue" => "SELECT id FROM issues WHERE id = ?1 LIMIT 1",
97- "comment" => "SELECT issue_id FROM comments WHERE id = ?1 LIMIT 1",
98- "review_comment" => "SELECT issue_id FROM review_comments WHERE id = ?1 LIMIT 1",
99- _ => return Ok(None),
107+ EditTarget::Issue => "SELECT id FROM issues WHERE id = ?1 LIMIT 1",
108+ EditTarget::Comment => "SELECT issue_id FROM comments WHERE id = ?1 LIMIT 1",
109+ EditTarget::ReviewComment => {
110+ "SELECT issue_id FROM review_comments WHERE id = ?1 LIMIT 1"
111+ }
100112 };
101113 let conn = self.read_conn().await;
102114 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};
55 use crate::time::{stamp_ago, stamp_to_unix};
66
77 /// 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;
99
1010 /// Whether a runner counts as online at `now_unix`: enabled, and its last report within
1111 /// [`RUNNER_ONLINE_SECS`]. The runners page dot and the live signal of the runners page both use
1212 /// this one rule.
1313 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);
1514 !disabled
1615 && last_seen_at
1716 .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)
1918 }
2019
2120 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -31,7 +30,7 @@ impl Store {
3130 /// Counts of repos, users, queued CI jobs and runners. Five indexed `COUNT(*)` queries.
3231 pub async fn health_counts(&self) -> Result<HealthCounts> {
3332 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()));
3534 let plain = |sql: &'static str| {
3635 let conn = &conn;
3736 async move {
crates/forge-core/src/store/imports.rsmodified+7 -7
@@ -3,7 +3,7 @@
33
44 use turso::{Row, Value};
55
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};
77 use crate::error::{Error, Result};
88 use crate::time::now_stamp;
99
@@ -100,10 +100,6 @@ fn map_job(row: &Row) -> Result<ImportJob> {
100100 })
101101 }
102102
103-fn text(s: &str) -> Value {
104- Value::Text(s.to_owned())
105-}
106-
107103 impl Store {
108104 /// Creates a queued job. `source_ref` must not hold a credential.
109105 pub async fn create_import_job(
@@ -186,7 +182,11 @@ impl Store {
186182 error: Option<&str>,
187183 ) -> Result<()> {
188184 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+ };
190190 let conn = self.inner.conn.lock().await;
191191 conn.execute(
192192 "UPDATE import_jobs SET state = ?2, error = ?3, updated_at = ?4, finished_at = ?5 \
@@ -196,7 +196,7 @@ impl Store {
196196 text(state.as_str()),
197197 error.map_or(Value::Null, text),
198198 text(&now),
199- finished.as_deref().map_or(Value::Null, text),
199+ finished,
200200 ],
201201 )
202202 .await
crates/forge-core/src/store/issues.rsmodified+17 -125
@@ -1,6 +1,3 @@
1-//! Issues, comments, timeline events and milestones. Every multi-row write runs in one
2-//! transaction. Numbers come from `repos.next_issue_number` in the same transaction as the insert.
3-
41 use std::collections::HashMap;
52
63 use serde_json::{Map, Value as Json};
@@ -8,8 +5,8 @@ use turso::transaction::Transaction;
85 use turso::{Connection, Row, Value};
96
107 use super::{
11- Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, missing_row,
12- new_id,
8+ IN_CHUNK, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish,
9+ insert_err, missing_row, new_id, placeholders,
1310 };
1411 use crate::error::{Error, Result};
1512 use crate::issues::{
@@ -19,7 +16,6 @@ use crate::issues::{
1916 use crate::names::normalize_name;
2017 use crate::time::now_stamp;
2118
22-/// Event kinds the timeline knows. Anything else is rejected by `add_event`.
2319 const EVENT_KINDS: &[&str] = &[
2420 "closed",
2521 "reopened",
@@ -33,7 +29,6 @@ const EVENT_KINDS: &[&str] = &[
3329 "referenced",
3430 "locked",
3531 "unlocked",
36- // Pull requests (store/pulls.rs).
3732 "merged",
3833 "head_updated",
3934 "base_changed",
@@ -44,11 +39,9 @@ const EVENT_KINDS: &[&str] = &[
4439 "converted_to_draft",
4540 "auto_merge_enabled",
4641 "auto_merge_disabled",
47- // Pull request reviews (store/reviews.rs).
4842 "review_dismissed",
4943 "thread_resolved",
5044 "thread_unresolved",
51- // Pinned issues (store/pinned.rs).
5245 "pinned",
5346 "unpinned",
5447 ];
@@ -59,15 +52,11 @@ pub(super) const ISSUE_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body,
5952 const COMMENT_COLS: &str = "id, issue_id, author_id, body, created_at, updated_at, edited";
6053 const LABEL_COLS: &str = "l.id, l.repo_id, l.name, l.color, l.description";
6154
62-/// Caps the number of placeholders in one `IN (...)` list.
63-const IN_CHUNK: usize = 500;
64-
6555 pub(super) fn parse_db<T: std::str::FromStr<Err = Error>>(s: &str) -> Result<T> {
6656 s.parse::<T>()
6757 .map_err(|e| Error::Database(format!("stored value {s:?}: {e}")))
6858 }
6959
70-/// Reads `ISSUE_COLS` (columns 0 to 14).
7160 pub(super) fn map_issue(row: &Row) -> Result<Issue> {
7261 Ok(Issue {
7362 id: col_text(row, 0)?,
@@ -117,7 +106,6 @@ fn map_event(row: &Row) -> Result<IssueEvent> {
117106 })
118107 }
119108
120-/// A label read from `LABEL_COLS` (or any five columns) starting at `base`.
121109 fn map_label(row: &Row, base: usize) -> Result<Label> {
122110 Ok(Label {
123111 id: col_text(row, base)?,
@@ -128,10 +116,6 @@ fn map_label(row: &Row, base: usize) -> Result<Label> {
128116 })
129117 }
130118
131-fn placeholders(n: usize) -> String {
132- vec!["?"; n].join(",")
133-}
134-
135119 pub(crate) fn like_pattern(query: &str) -> String {
136120 let mut out = String::with_capacity(query.len() + 2);
137121 out.push('%');
@@ -145,32 +129,16 @@ pub(crate) fn like_pattern(query: &str) -> String {
145129 out
146130 }
147131
148-/// Validates a `YYYY-MM-DD` due date.
149-pub fn validate_due_on(due_on: &str) -> Result<()> {
150- let format = time::macros::format_description!("[year]-[month]-[day]");
151- match time::Date::parse(due_on, &format) {
152- Ok(_) => Ok(()),
153- Err(_) => Err(Error::Invalid(format!(
154- "due date {due_on:?} is not YYYY-MM-DD"
155- ))),
156- }
157-}
158-
159-/// Runs `outcome` inside `tx`: commits on success, rolls back on error.
160-pub(super) async fn finish<T>(tx: Transaction<'_>, outcome: Result<T>) -> Result<T> {
161- match outcome {
162- Ok(value) => {
163- tx.commit().await.map_err(db_err)?;
164- Ok(value)
165- }
166- Err(e) => {
167- let _ = tx.rollback().await;
168- Err(e)
169- }
132+fn event_data(data: Json) -> Result<Map<String, Json>> {
133+ match data {
134+ Json::Object(map) => Ok(map),
135+ Json::Null => Ok(Map::new()),
136+ _ => Err(Error::Invalid(
137+ "event data must be a JSON object".to_string(),
138+ )),
170139 }
171140 }
172141
173-/// Inserts a timeline event. `data` must be a JSON object or null (stored as `{}`).
174142 pub(super) async fn insert_event(
175143 conn: &Connection,
176144 issue_id: &str,
@@ -195,9 +163,6 @@ pub(super) async fn insert_event(
195163 Ok(())
196164 }
197165
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.
201166 pub(super) async fn load_issue(conn: &Connection, issue_id: &str) -> Result<Issue> {
202167 fetch_opt(
203168 conn,
@@ -209,7 +174,6 @@ pub(super) async fn load_issue(conn: &Connection, issue_id: &str) -> Result<Issu
209174 .ok_or(Error::NotFound)
210175 }
211176
212-/// Labels of an issue, read through `issue_labels`, keyed by issue id.
213177 async fn labels_for_issues(
214178 conn: &Connection,
215179 issue_ids: &[String],
@@ -233,7 +197,6 @@ async fn labels_for_issues(
233197 Ok(out)
234198 }
235199
236-/// Display usernames of assignees, keyed by issue id.
237200 async fn assignees_for_issues(
238201 conn: &Connection,
239202 issue_ids: &[String],
@@ -257,10 +220,7 @@ async fn assignees_for_issues(
257220 Ok(out)
258221 }
259222
260-// issues
261223 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.
264224 pub async fn create_issue(
265225 &self,
266226 repo_id: &str,
@@ -341,8 +301,6 @@ impl Store {
341301 .await
342302 }
343303
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.
346304 pub async fn list_issues(
347305 &self,
348306 repo_id: &str,
@@ -351,7 +309,6 @@ impl Store {
351309 self.list_of_kind(repo_id, f, "issue").await
352310 }
353311
354- /// `list_issues` for any `kind` ('issue' or 'pull'). Pull request listing shares it.
355312 pub(super) async fn list_of_kind(
356313 &self,
357314 repo_id: &str,
@@ -401,18 +358,15 @@ impl Store {
401358 params.push(Value::Text(normalize_name(reviewer)));
402359 }
403360 if let Some(query) = non_empty(f.query.as_deref()) {
404- // Escape the LIKE wildcards and the escape character itself.
405361 clauses.push("i.title LIKE ? ESCAPE '\\'");
406362 params.push(Value::Text(like_pattern(query)));
407363 }
408- if let (true, Some(draft)) = (kind == "pull", f.draft) {
409- {
410- clauses.push(if draft {
411- "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 1)"
412- } else {
413- "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 0)"
414- });
415- }
364+ if kind == "pull" && let Some(draft) = f.draft {
365+ clauses.push(if draft {
366+ "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 1)"
367+ } else {
368+ "EXISTS (SELECT 1 FROM pull_requests pr WHERE pr.issue_id = i.id AND pr.draft = 0)"
369+ });
416370 }
417371 let where_sql = clauses.join(" AND ");
418372 let order = match f.sort {
@@ -468,12 +422,10 @@ impl Store {
468422 Ok((items, total))
469423 }
470424
471- /// Open and closed issue counts of the repo (issues only, not pulls).
472425 pub async fn issue_counts(&self, repo_id: &str) -> Result<(u64, u64)> {
473426 self.counts_of_kind(repo_id, "issue").await
474427 }
475428
476- /// Open and closed counts for one `kind` ('issue' or 'pull').
477429 pub(super) async fn counts_of_kind(&self, repo_id: &str, kind: &str) -> Result<(u64, u64)> {
478430 let conn = self.read_conn().await;
479431 let row = fetch_opt(
@@ -492,8 +444,6 @@ impl Store {
492444 ))
493445 }
494446
495- /// Saves the previous title and body to the edit history. A title change also records a
496- /// `renamed` event with `{"from", "to"}`.
497447 pub async fn edit_issue(
498448 &self,
499449 issue_id: &str,
@@ -543,9 +493,6 @@ impl Store {
543493 finish(tx, outcome).await
544494 }
545495
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.
549496 pub async fn set_issue_state(
550497 &self,
551498 issue_id: &str,
@@ -554,15 +501,7 @@ impl Store {
554501 reason: Option<StateReason>,
555502 data: Json,
556503 ) -> Result<bool> {
557- let mut data = match data {
558- Json::Object(map) => map,
559- Json::Null => Map::new(),
560- _ => {
561- return Err(Error::Invalid(
562- "event data must be a JSON object".to_string(),
563- ));
564- }
565- };
504+ let mut data = event_data(data)?;
566505 let conn = self.inner.conn.lock().await;
567506 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
568507 let outcome: Result<bool> = async {
@@ -604,9 +543,6 @@ impl Store {
604543 finish(tx, outcome).await
605544 }
606545
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.
610546 pub async fn set_issue_locked(
611547 &self,
612548 issue_id: &str,
@@ -653,10 +589,6 @@ impl Store {
653589 finish(tx, outcome).await
654590 }
655591
656- // comments
657-
658- /// Adds a comment, bumps the issue's `comment_count` and `updated_at`. Blank bodies are
659- /// rejected.
660592 pub async fn add_comment(
661593 &self,
662594 issue_id: &str,
@@ -718,7 +650,6 @@ impl Store {
718650 .await
719651 }
720652
721- /// Saves the previous body to the edit history and marks the comment edited.
722653 pub async fn edit_comment(&self, comment_id: &str, editor_id: &str, body: &str) -> Result<()> {
723654 validate_body(body)?;
724655 if body.trim().is_empty() {
@@ -761,7 +692,6 @@ impl Store {
761692 finish(tx, outcome).await
762693 }
763694
764- /// Deletes the comment with its edit history and decrements the issue's `comment_count`.
765695 pub async fn delete_comment(&self, comment_id: &str) -> Result<()> {
766696 let conn = self.inner.conn.lock().await;
767697 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -817,8 +747,6 @@ impl Store {
817747 .await
818748 }
819749
820- // events
821-
822750 pub async fn list_events(&self, issue_id: &str) -> Result<Vec<IssueEvent>> {
823751 let conn = self.read_conn().await;
824752 fetch_all(
@@ -831,8 +759,6 @@ impl Store {
831759 .await
832760 }
833761
834- /// Records a timeline event. `kind` must be one of the known event kinds, and `data` a JSON
835- /// object or null.
836762 pub async fn add_event(
837763 &self,
838764 issue_id: &str,
@@ -843,23 +769,12 @@ impl Store {
843769 if !EVENT_KINDS.contains(&kind) {
844770 return Err(Error::Invalid(format!("event kind {kind:?}")));
845771 }
846- let data = match data {
847- Json::Object(_) => data,
848- Json::Null => Json::Object(Map::new()),
849- _ => {
850- return Err(Error::Invalid(
851- "event data must be a JSON object".to_string(),
852- ));
853- }
854- };
772+ let data = Json::Object(event_data(data)?);
855773 let conn = self.inner.conn.lock().await;
856774 load_issue(&conn, issue_id).await?;
857775 insert_event(&conn, issue_id, actor_id, kind, &data).await
858776 }
859777
860- // users
861-
862- /// Display name and avatar hash for each id that exists. Unknown ids are left out.
863778 pub async fn usernames_by_ids(
864779 &self,
865780 ids: &[String],
@@ -895,7 +810,6 @@ impl Store {
895810 }
896811 }
897812
898-/// Repo deletion for the M3 tables. Called from `Store::delete_repo` inside its transaction.
899813 pub(super) async fn delete_repo_issue_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {
900814 let id = repo_id.to_string();
901815 for sql in [
@@ -954,7 +868,6 @@ mod tests {
954868 }
955869 }
956870
957- /// A repo of its own, so issue numbers and repo-wide counts start clean per scenario.
958871 async fn fresh_repo(store: &Store, owner: &str, name: &str) -> String {
959872 store
960873 .create_repo(owner, name, "", Visibility::Public, "main")
@@ -975,13 +888,11 @@ mod tests {
975888 items.into_iter().map(|i| i.issue.title).collect()
976889 }
977890
978- // Creating, filtering, paging and counting issues. Each scenario has its own repo.
979891 #[tokio::test]
980892 async fn issue_create_and_list_rules_hold_in_each_scenario() {
981893 let fx = fixture().await;
982894 let s = &fx.store;
983895
984- // Scenario 1: numbers start at one and advance; lookup by number.
985896 let repo = fresh_repo(s, &fx.tahinli.id, "numbers").await;
986897 let a = s
987898 .create_issue(&repo, &fx.tahinli.id, " First ", "body")
@@ -1002,7 +913,6 @@ mod tests {
1002913 "numbers: no third issue"
1003914 );
1004915
1005- // Scenario 2: invalid input and missing repos are refused without taking a number.
1006916 let repo = fresh_repo(s, &fx.tahinli.id, "validate").await;
1007917 assert!(
1008918 matches!(
@@ -1032,7 +942,6 @@ mod tests {
1032942 .unwrap();
1033943 assert_eq!(ok.number, 1, "validate: failed creates kept no number");
1034944
1035- // Scenario 3: concurrent creates still get unique numbers one to twenty.
1036945 let repo = fresh_repo(s, &fx.tahinli.id, "concurrent").await;
1037946 let mut handles = Vec::new();
1038947 for i in 0..20 {
@@ -1061,7 +970,6 @@ mod tests {
1061970 "concurrent: all open"
1062971 );
1063972
1064- // Scenario 4: state, author and text filters.
1065973 let repo = fresh_repo(s, &fx.tahinli.id, "filters").await;
1066974 let a = s
1067975 .create_issue(&repo, &fx.tahinli.id, "Crash on start", "")
@@ -1080,7 +988,6 @@ mod tests {
1080988 .await
1081989 .unwrap();
1082990
1083- // Default filter (open only).
1084991 assert_eq!(
1085992 titles(s, &repo, &IssueFilter::default()).await,
1086993 vec!["Typo in docs"],
@@ -1116,7 +1023,6 @@ mod tests {
11161023 "filters: text is case-insensitive"
11171024 );
11181025
1119- // Scenario 5: wildcards in the text query are literal.
11201026 let repo = fresh_repo(s, &fx.tahinli.id, "wildcards").await;
11211027 for t in [
11221028 "100% done",
@@ -1158,7 +1064,6 @@ mod tests {
11581064 "wildcards: blank query matches everything"
11591065 );
11601066
1161- // Scenario 6: paging and clamping.
11621067 let repo = fresh_repo(s, &fx.tahinli.id, "pages").await;
11631068 for i in 0..30 {
11641069 s.create_issue(&repo, &fx.tahinli.id, &format!("issue {i}"), "")
@@ -1176,14 +1081,12 @@ mod tests {
11761081 let (second, _) = s.list_issues(&repo, &page(2, 25)).await.unwrap();
11771082 assert_eq!(second.len(), 5, "pages: second page size");
11781083 assert_eq!(second[4].issue.number, 1, "pages: oldest last");
1179- // per_page clamps to 1..=100, page to 1..=1000.
11801084 let (one, _) = s.list_issues(&repo, &page(0, 0)).await.unwrap();
11811085 assert_eq!(one.len(), 1, "pages: per_page and page clamp up");
11821086 assert_eq!(one[0].issue.number, 30, "pages: clamped to first page");
11831087 let (big, _) = s.list_issues(&repo, &page(5000, 1000)).await.unwrap();
11841088 assert!(big.is_empty(), "pages: far past the end");
11851089
1186- // Scenario 7: sorting by number and by last update.
11871090 let repo = fresh_repo(s, &fx.tahinli.id, "sorts").await;
11881091 let first = s
11891092 .create_issue(&repo, &fx.tahinli.id, "one", "")
@@ -1212,7 +1115,6 @@ mod tests {
12121115 "sorts: recently updated"
12131116 );
12141117
1215- // Scenario 8: labels and assignees are attached, and filterable by name.
12161118 let repo = fresh_repo(s, &fx.tahinli.id, "labels").await;
12171119 let issue = s
12181120 .create_issue(&repo, &fx.tahinli.id, "labelled", "")
@@ -1264,7 +1166,6 @@ mod tests {
12641166 "labels: filter by assignee"
12651167 );
12661168
1267- // Scenario 9: counts split open and closed.
12681169 let repo = fresh_repo(s, &fx.tahinli.id, "counts").await;
12691170 let a = s
12701171 .create_issue(&repo, &fx.tahinli.id, "a", "")
@@ -1283,13 +1184,11 @@ mod tests {
12831184 );
12841185 }
12851186
1286- // Editing, locking, state, comments, events and usernames. Each scenario has its own repo.
12871187 #[tokio::test]
12881188 async fn issue_edit_and_thread_rules_hold_in_each_scenario() {
12891189 let fx = fixture().await;
12901190 let s = &fx.store;
12911191
1292- // Scenario 1: an edit saves history and records a rename, body-only edits do not.
12931192 let repo = fresh_repo(s, &fx.tahinli.id, "edit").await;
12941193 let issue = s
12951194 .create_issue(&repo, &fx.tahinli.id, "old", "old body")
@@ -1339,7 +1238,6 @@ mod tests {
13391238 "edit: rename actor"
13401239 );
13411240
1342- // Body-only edit: history yes, no rename event.
13431241 s.edit_issue(&issue.id, &fx.bob.id, "new", "newer")
13441242 .await
13451243 .unwrap();
@@ -1356,7 +1254,6 @@ mod tests {
13561254 "edit: unknown issue"
13571255 );
13581256
1359- // Scenario 2: locking toggles the reason and records events.
13601257 let repo = fresh_repo(s, &fx.tahinli.id, "locks").await;
13611258 let issue = s
13621259 .create_issue(&repo, &fx.tahinli.id, "t", "")
@@ -1414,7 +1311,6 @@ mod tests {
14141311 .collect();
14151312 assert_eq!(kinds, vec!["locked", "unlocked"], "lock: events");
14161313
1417- // Scenario 3: closing and reopening record events and stamps.
14181314 let repo = fresh_repo(s, &fx.tahinli.id, "state").await;
14191315 let issue = s
14201316 .create_issue(&repo, &fx.tahinli.id, "t", "")
@@ -1504,7 +1400,6 @@ mod tests {
15041400 "state: payload must be an object"
15051401 );
15061402
1507- // Scenario 4: comments keep the count, timestamps and ordering in step.
15081403 let repo = fresh_repo(s, &fx.tahinli.id, "comments").await;
15091404 let issue = s
15101405 .create_issue(&repo, &fx.tahinli.id, "t", "")
@@ -1580,7 +1475,6 @@ mod tests {
15801475 "comments: delete twice"
15811476 );
15821477
1583- // Scenario 5: events validate their kind and their issue.
15841478 let repo = fresh_repo(s, &fx.tahinli.id, "events").await;
15851479 let issue = s
15861480 .create_issue(&repo, &fx.tahinli.id, "t", "")
@@ -1632,7 +1526,6 @@ mod tests {
16321526 "events: unknown issue"
16331527 );
16341528
1635- // Scenario 6: usernames are batched and unknown ids are skipped.
16361529 let ids = vec![
16371530 fx.tahinli.id.clone(),
16381531 fx.bob.id.clone(),
@@ -1648,7 +1541,6 @@ mod tests {
16481541 );
16491542 }
16501543
1651- // Kept on its own store: it counts rows in whole tables, so other repos must not exist.
16521544 #[tokio::test]
16531545 async fn delete_repo_leaves_no_m3_rows() {
16541546 let fx = fixture().await;
crates/forge-core/src/store/labels.rsmodified+19 -56
@@ -4,22 +4,23 @@
44 use std::collections::{BTreeMap, BTreeSet};
55
66 use jiff::civil::Date;
7-use serde_json::{Value, json};
8-use turso::transaction::Transaction;
7+use serde_json::json;
98 use turso::{Connection, Row};
109
10+use super::issues::insert_event;
1111 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,
1314 };
1415 use crate::authz::{Action, authorize};
1516 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+};
1720 use crate::model::User;
1821 use crate::names::normalize_name;
1922 use crate::time::now_stamp;
2023
21-/// Most assignees one issue can have.
22-pub const MAX_ASSIGNEES: usize = 10;
2324 /// Most labels one repo can have.
2425 pub const MAX_LABELS: i64 = 500;
2526
@@ -53,7 +54,8 @@ const LABEL_COLS: &str = "id, repo_id, name, color, description";
5354 const MILESTONE_SELECT: &str = "SELECT m.id, m.repo_id, m.title, m.description, m.due_on, m.state, \
5455 m.created_at, m.closed_at, \
5556 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'";
5759
5860 // labels
5961
@@ -206,7 +208,7 @@ impl Store {
206208 Ok(())
207209 }
208210 .await;
209- commit_or_rollback(tx, outcome).await
211+ finish(tx, outcome).await
210212 }
211213
212214 /// The labels on one issue, ordered by case-folded name.
@@ -309,7 +311,7 @@ impl Store {
309311 Ok(())
310312 }
311313 .await;
312- commit_or_rollback(tx, outcome).await
314+ finish(tx, outcome).await
313315 }
314316
315317 /// The issue's assignees as `(user id, display username)`, ordered by name.
@@ -426,7 +428,7 @@ impl Store {
426428 Ok(())
427429 }
428430 .await;
429- commit_or_rollback(tx, outcome).await
431+ finish(tx, outcome).await
430432 }
431433
432434 // milestones
@@ -528,8 +530,8 @@ impl Store {
528530 (
529531 id.to_string(),
530532 repo_id.to_string(),
533+ title.clone(),
531534 normalize_name(&title),
532- title,
533535 description.to_string(),
534536 due_on.map(str::to_owned),
535537 state.as_str().to_string(),
@@ -569,7 +571,7 @@ impl Store {
569571 Ok(())
570572 }
571573 .await;
572- commit_or_rollback(tx, outcome).await
574+ finish(tx, outcome).await
573575 }
574576
575577 /// Sets or clears the issue's milestone. The milestone must belong to the issue's repo
@@ -646,7 +648,7 @@ impl Store {
646648 Ok(())
647649 }
648650 .await;
649- commit_or_rollback(tx, outcome).await
651+ finish(tx, outcome).await
650652 }
651653 }
652654
@@ -710,49 +712,10 @@ async fn issue_repo_id(conn: &Connection, issue_id: &str) -> Result<String> {
710712 .ok_or(Error::NotFound)
711713 }
712714
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-
753715 #[cfg(test)]
754716 mod tests {
755717 use super::*;
718+ use serde_json::Value;
756719 use crate::issues::{IssueEvent, StateReason};
757720 use crate::model::{Role, Visibility};
758721
@@ -1259,17 +1222,17 @@ mod tests {
12591222 ),
12601223 "update: other repo refused"
12611224 );
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)
12631226 .await
12641227 .unwrap();
12651228 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");
12671230 assert_eq!(closed.description, "done", "update: description");
12681231 assert!(closed.due_on.is_none(), "update: due date cleared");
12691232 assert!(matches!(closed.state, IssueState::Closed), "update: closed");
12701233 assert!(closed.closed_at.is_some(), "update: closed stamp set");
12711234
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)
12731236 .await
12741237 .unwrap();
12751238 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 {
106106 validate_settings(update)?;
107107 let sealed = match update.password {
108108 Some(password) => {
109- let key = self
110- .inner
111- .secret_key
112- .get()
113- .ok_or_else(|| Error::Crypto("the instance key is not set".into()))?;
114- Some(secret::seal(key, password.as_bytes())?.into_bytes())
109+ Some(secret::seal(self.secret_key()?, password.as_bytes())?.into_bytes())
115110 }
116111 None => None,
117112 };
@@ -161,11 +156,7 @@ impl Store {
161156 let Some(bytes) = sealed else {
162157 return Ok(None);
163158 };
164- let key = self
165- .inner
166- .secret_key
167- .get()
168- .ok_or_else(|| Error::Crypto("the instance key is not set".into()))?;
159+ let key = self.secret_key()?;
169160 let text = String::from_utf8(bytes)
170161 .map_err(|_| Error::Crypto("sealed mail password is not text".into()))?;
171162 let plain = secret::open(key, &text)?;
@@ -317,20 +308,22 @@ impl Store {
317308 /// How many outbox rows stand in each state at `now`, in `MailState::ALL` order.
318309 pub async fn mail_state_counts(&self, now: &str) -> Result<Vec<(MailState, u32)>> {
319310 let conn = self.read_conn().await;
320- let mut counts = Vec::with_capacity(MailState::ALL.len());
321- for state in MailState::ALL {
322- let clause = state_clause(state);
323- let sql = format!("SELECT COUNT(*) FROM mail_outbox WHERE {clause}");
324- // A clause without `?1` must be bound with no parameters at all.
325- let n = if clause.contains("?1") {
326- fetch_opt(&conn, &sql, (now.to_owned(),), |row| col_int(row, 0)).await?
327- } else {
328- fetch_opt(&conn, &sql, (), |row| col_int(row, 0)).await?
329- }
330- .unwrap_or(0);
331- counts.push((state, u32::try_from(n).unwrap_or(u32::MAX)));
332- }
333- Ok(counts)
311+ let columns = MailState::ALL
312+ .map(|state| format!("COUNT(CASE WHEN {} THEN 1 END)", state_clause(state)))
313+ .join(", ");
314+ let sql = format!("SELECT {columns} FROM mail_outbox");
315+ let counts = fetch_opt(&conn, &sql, (now.to_owned(),), |row| {
316+ MailState::ALL
317+ .into_iter()
318+ .enumerate()
319+ .map(|(i, state)| {
320+ let n = col_int(row, i)?;
321+ Ok((state, u32::try_from(n).unwrap_or(u32::MAX)))
322+ })
323+ .collect::<Result<Vec<_>>>()
324+ })
325+ .await?;
326+ Ok(counts.unwrap_or_default())
334327 }
335328
336329 /// Gives a failed message a fresh set of tries, due at `now`. Returns `false` when the row is
@@ -426,7 +419,7 @@ mod tests {
426419 use std::time::Duration;
427420
428421 use super::*;
429- use crate::mail::OutboxStatus;
422+ use crate::mail::MailState;
430423 use crate::time::{now_stamp, stamp_after};
431424
432425 const KEY: [u8; 32] = [7u8; 32];
@@ -562,7 +555,7 @@ mod tests {
562555 .is_empty()
563556 );
564557 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);
566559 assert_eq!(rows[0].attempts, 1);
567560 }
568561
@@ -598,14 +591,14 @@ mod tests {
598591 let row = store.recent_mail(10).await.expect("rows").remove(0);
599592 assert_eq!(row.attempts, 1);
600593 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);
602595
603596 store
604597 .mark_mail_failed(&row.id, "gone", None)
605598 .await
606599 .expect("gave up");
607600 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);
609602 assert_eq!(store.next_mail_due().await.expect("none"), None);
610603 }
611604
crates/forge-core/src/store/merge_queue.rsmodified+1 -16
@@ -3,8 +3,7 @@
33
44 use turso::Value;
55
6-use super::issues::finish;
7-use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
6+use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
87 use crate::error::{Error, Result};
98 use crate::merge_queue::{QueueEntry, QueueState};
109 use crate::pulls::MergeStyle;
@@ -178,20 +177,6 @@ impl Store {
178177 .await
179178 }
180179
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-
195180 /// Moves a tested entry to `merging`. False when another event already took it.
196181 pub async fn queue_set_merging(&self, id: &str) -> Result<bool> {
197182 self.queue_update(
crates/forge-core/src/store/migrate.rsmodified+34 -137
@@ -192,9 +192,7 @@ async fn applied_versions(conn: &Connection) -> Result<Vec<i64>> {
192192 mod tests {
193193 use super::*;
194194
195- #[tokio::test]
196- async fn database_at_0001_gains_profile_columns_with_defaults() {
197- let dir = tempfile::tempdir().unwrap();
195+ async fn open_at(dir: &tempfile::TempDir, version: u32) -> (turso::Database, Connection) {
198196 let path = dir.path().join("old.db");
199197 let db = turso::Builder::new_local(path.to_str().unwrap())
200198 .build()
@@ -206,16 +204,32 @@ mod tests {
206204 )
207205 .await
208206 .unwrap();
209- conn.execute_batch(MIGRATIONS[0].1).await.unwrap();
207+ for &(v, sql) in MIGRATIONS.iter().filter(|(v, _)| *v <= version) {
208+ conn.execute_batch(sql).await.unwrap();
209+ conn.execute(
210+ "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, 'then')",
211+ (i64::from(v),),
212+ )
213+ .await
214+ .unwrap();
215+ }
216+ (db, conn)
217+ }
218+
219+ #[tokio::test]
220+ async fn database_at_0001_gains_all_later_schema() {
221+ let dir = tempfile::tempdir().unwrap();
222+ let (_db, conn) = open_at(&dir, 1).await;
210223 conn.execute(
211- "INSERT INTO schema_migrations (version, applied_at) VALUES (1, 'then')",
224+ "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \
225+ VALUES ('u1', 'Old', 'old', 'h', 0, 'then')",
212226 (),
213227 )
214228 .await
215229 .unwrap();
216230 conn.execute(
217- "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \
218- VALUES ('u1', 'Old', 'old', 'h', 0, 'then')",
231+ "INSERT INTO repos (id, owner_id, name, name_folded, description, visibility, default_branch, archived, created_at) \
232+ VALUES ('r1', 'u1', 'proj', 'proj', '', 'public', 'main', 0, 'then')",
219233 (),
220234 )
221235 .await
@@ -230,6 +244,7 @@ mod tests {
230244 let row = rows.next().await.unwrap().expect("user row");
231245 assert_eq!(row.get_value(0).unwrap(), turso::Value::Text(String::new()));
232246 assert_eq!(row.get_value(1).unwrap(), turso::Value::Text("UTC".into()));
247+ drop(rows);
233248 let mut rows = conn
234249 .query("SELECT version FROM schema_migrations ORDER BY version", ())
235250 .await
@@ -243,102 +258,7 @@ mod tests {
243258 .map(|(v, _)| turso::Value::Integer(i64::from(*v)))
244259 .collect();
245260 assert_eq!(versions, expected);
246- }
247-
248- #[tokio::test]
249- async fn database_at_0002_gains_branch_protections() {
250- let dir = tempfile::tempdir().unwrap();
251- let path = dir.path().join("v2.db");
252- let db = turso::Builder::new_local(path.to_str().unwrap())
253- .build()
254- .await
255- .unwrap();
256- let conn = db.connect().unwrap();
257- conn.execute_batch(
258- "CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)",
259- )
260- .await
261- .unwrap();
262- for (version, sql) in &MIGRATIONS[..2] {
263- conn.execute_batch(sql).await.unwrap();
264- conn.execute(
265- "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, 'then')",
266- (i64::from(*version),),
267- )
268- .await
269- .unwrap();
270- }
271- conn.execute(
272- "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \
273- VALUES ('u1', 'Old', 'old', 'h', 0, 'then')",
274- (),
275- )
276- .await
277- .unwrap();
278- conn.execute(
279- "INSERT INTO repos (id, owner_id, name, name_folded, description, visibility, default_branch, archived, created_at) \
280- VALUES ('r1', 'u1', 'proj', 'proj', '', 'public', 'main', 0, 'then')",
281- (),
282- )
283- .await
284- .unwrap();
285-
286- migrate(&conn).await.unwrap();
287-
288- conn.execute(
289- "INSERT INTO branch_protections (id, repo_id, pattern, allow_force_push, allow_deletion, created_at) \
290- VALUES ('b1', 'r1', 'main', 1, 0, 'then')",
291- (),
292- )
293- .await
294- .unwrap();
295- let mut rows = conn
296- .query("SELECT COUNT(*) FROM branch_protections", ())
297- .await
298- .unwrap();
299- let row = rows.next().await.unwrap().expect("count row");
300- assert_eq!(row.get_value(0).unwrap(), turso::Value::Integer(1));
301- }
302-
303- #[tokio::test]
304- async fn database_at_0003_gains_issue_tables_and_counter() {
305- let dir = tempfile::tempdir().unwrap();
306- let path = dir.path().join("v3.db");
307- let db = turso::Builder::new_local(path.to_str().unwrap())
308- .build()
309- .await
310- .unwrap();
311- let conn = db.connect().unwrap();
312- conn.execute_batch(
313- "CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)",
314- )
315- .await
316- .unwrap();
317- for (version, sql) in &MIGRATIONS[..3] {
318- conn.execute_batch(sql).await.unwrap();
319- conn.execute(
320- "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, 'then')",
321- (i64::from(*version),),
322- )
323- .await
324- .unwrap();
325- }
326- conn.execute(
327- "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \
328- VALUES ('u1', 'Old', 'old', 'h', 0, 'then')",
329- (),
330- )
331- .await
332- .unwrap();
333- conn.execute(
334- "INSERT INTO repos (id, owner_id, name, name_folded, description, visibility, default_branch, archived, created_at) \
335- VALUES ('r1', 'u1', 'proj', 'proj', '', 'public', 'main', 0, 'then')",
336- (),
337- )
338- .await
339- .unwrap();
340-
341- migrate(&conn).await.unwrap();
261+ drop(rows);
342262
343263 let mut rows = conn
344264 .query("SELECT next_issue_number FROM repos WHERE id = 'r1'", ())
@@ -361,44 +281,14 @@ mod tests {
361281 )
362282 .await
363283 .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- }
392284 conn.execute(
393- "INSERT INTO users (id, username, username_folded, password_hash, is_admin, created_at) \
394- VALUES ('u1', 'Old', 'old', 'h', 0, 'then')",
285+ "INSERT INTO branch_protections (id, repo_id, pattern, allow_force_push, allow_deletion, created_at) \
286+ VALUES ('b1', 'r1', 'main', 1, 0, 'then')",
395287 (),
396288 )
397289 .await
398290 .unwrap();
399291
400- migrate(&conn).await.unwrap();
401-
402292 let mut rows = conn
403293 .query(
404294 "SELECT totp_secret_sealed, totp_enabled, totp_last_step FROM users WHERE id = 'u1'",
@@ -413,7 +303,14 @@ mod tests {
413303 drop(rows);
414304
415305 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')",
417314 (),
418315 )
419316 .await
@@ -421,7 +318,7 @@ mod tests {
421318 conn.execute_batch("PRAGMA foreign_keys = ON")
422319 .await
423320 .unwrap();
424- conn.execute("DELETE FROM users WHERE id = 'u1'", ())
321+ conn.execute("DELETE FROM users WHERE id = 'u2'", ())
425322 .await
426323 .unwrap();
427324 let mut rows = conn
crates/forge-core/src/store/mirrors.rsmodified+13 -69
@@ -7,8 +7,8 @@
77 use turso::{Row, Value};
88
99 use super::{
10- Store, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish,
11- insert_err, missing_row, new_id,
10+ Store, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt,
11+ finish, insert_err, missing_row, new_id, opt_text,
1212 };
1313 use crate::error::{Error, Result};
1414 use crate::mirrors::{
@@ -38,29 +38,12 @@ fn map_mirror(row: &Row) -> Result<Mirror> {
3838 enabled: col_bool(row, 7)?,
3939 next_sync_at: col_text(row, 8)?,
4040 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),
4242 last_error: col_opt_text(row, 11)?,
4343 created_at: col_text(row, 12)?,
4444 })
4545 }
4646
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-
6447 /// Rejects an interval that is neither `0` (manual only) nor at least the minimum.
6548 fn validate_interval(minutes: u32) -> Result<()> {
6649 if minutes != 0 && minutes < MIN_INTERVAL_MINUTES {
@@ -74,12 +57,7 @@ fn validate_interval(minutes: u32) -> Result<()> {
7457 impl Store {
7558 /// Seals a plaintext mirror secret with the instance key.
7659 fn seal_mirror_secret(&self, plain: &[u8]) -> Result<Vec<u8>> {
77- let key = self
78- .inner
79- .secret_key
80- .get()
81- .ok_or_else(|| Error::Crypto("mirror secret key is not set".into()))?;
82- Ok(secret::seal(key, plain)?.into_bytes())
60+ Ok(secret::seal(self.secret_key()?, plain)?.into_bytes())
8361 }
8462
8563 /// Creates a mirror. The repo has at most one pull mirror (`Conflict` for a second) and at
@@ -263,12 +241,7 @@ impl Store {
263241 };
264242 let sealed = String::from_utf8(sealed)
265243 .map_err(|_| Error::Crypto("sealed mirror secret is not UTF-8".into()))?;
266- let key = self
267- .inner
268- .secret_key
269- .get()
270- .ok_or_else(|| Error::Crypto("mirror secret key is not set".into()))?;
271- Ok(Some(secret::open(key, &sealed)?))
244+ Ok(Some(secret::open(self.secret_key()?, &sealed)?))
272245 }
273246
274247 /// Enabled mirrors due at or before `now`, earliest first, at most `limit` (capped at 200).
@@ -328,7 +301,7 @@ impl Store {
328301 let params = vec![
329302 Value::Text(id.to_string()),
330303 Value::Text(now_stamp()),
331- opt_int_value(Some(ok)),
304+ Value::Integer(i64::from(ok)),
332305 opt_text(error),
333306 Value::Text(next_sync_at.to_string()),
334307 ];
@@ -389,41 +362,6 @@ mod tests {
389362 }
390363 }
391364
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-
427365 async fn add_repo(store: &Store, owner: &User, name: &str) -> Repo {
428366 store
429367 .create_repo(&owner.id, name, "", Visibility::Public, "main")
@@ -653,6 +591,7 @@ mod tests {
653591 #[tokio::test]
654592 async fn due_mirrors_are_earliest_first_and_skip_disabled() {
655593 let (store, _tahinli, repo, _dir) = setup().await;
594+ assert_eq!(store.next_mirror_due().await.unwrap(), None);
656595 let late = store
657596 .create_mirror(&push(&repo, "https://late.example/r.git"))
658597 .await
@@ -678,7 +617,7 @@ mod tests {
678617 .await
679618 .unwrap();
680619 store
681- .schedule_mirror(&off.id, "2020-01-01T00:00:00.000000000Z")
620+ .schedule_mirror(&off.id, "2019-12-31T00:00:00.000000000Z")
682621 .await
683622 .unwrap();
684623 store
@@ -696,6 +635,11 @@ mod tests {
696635 )
697636 .await
698637 .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+ );
699643
700644 let now = now_stamp();
701645 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};
7171 use crate::time::now_stamp;
7272
7373 const BUSY_TIMEOUT: Duration = Duration::from_millis(5000);
74+
75+const IN_CHUNK: usize = 500;
7476 /// Longest accepted `about` text, in characters.
7577 pub const MAX_ABOUT_CHARS: usize = 2000;
7678 /// Longest accepted display name, in characters.
@@ -152,13 +154,12 @@ impl Store {
152154 let conn = db.connect().map_err(db_err)?;
153155 apply_pragmas(&conn).await;
154156 migrate::migrate(&conn).await?;
155- // Readers are opened after migrations so their schema view is current.
156157 let mut readers = Vec::with_capacity(READER_COUNT);
157158 for _ in 0..READER_COUNT {
158159 let reader = db.connect().map_err(db_err)?;
159160 apply_pragmas(&reader).await;
160- apply_query_only(&reader).await?;
161- apply_reader_cache_size(&reader).await?;
161+ run_pragma(&reader, "PRAGMA query_only = 1").await.map_err(db_err)?;
162+ run_pragma(&reader, "PRAGMA cache_size = -2048").await.map_err(db_err)?;
162163 readers.push(Mutex::new(reader));
163164 }
164165 Ok(Store {
@@ -193,7 +194,13 @@ impl Store {
193194 let _ = self.inner.secret_key.set(key);
194195 }
195196
196- // users
197+ fn secret_key(&self) -> Result<&[u8; 32]> {
198+ self.inner
199+ .secret_key
200+ .get()
201+ .ok_or_else(|| Error::Crypto("the instance key is not set".into()))
202+ }
203+
197204 pub async fn user_count(&self) -> Result<u64> {
198205 let conn = self.read_conn().await;
199206 let mut rows = conn
@@ -212,27 +219,7 @@ impl Store {
212219 password_hash: &str,
213220 is_admin: bool,
214221 ) -> Result<User> {
215- let user = User {
216- id: new_id(),
217- username: username.to_string(),
218- email: email.map(str::to_owned),
219- password_hash: password_hash.to_string(),
220- is_admin,
221- created_at: now_stamp(),
222- about: String::new(),
223- display_name: None,
224- timezone: "UTC".to_string(),
225- avatar_hash: None,
226- theme: "light".into(),
227- language: "auto".into(),
228- accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
229- accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
230- base_light: crate::store::ui_prefs::DEFAULT_BASE.into(),
231- base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(),
232- sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(),
233- kind: AccountKind::User,
234- email_notifications: true,
235- };
222+ let user = new_user(username, email, password_hash, is_admin);
236223 let conn = self.inner.conn.lock().await;
237224 conn.execute(
238225 "INSERT INTO users (id, username, username_folded, email, password_hash, is_admin, created_at, theme) \
@@ -260,27 +247,7 @@ impl Store {
260247 email: Option<&str>,
261248 password_hash: &str,
262249 ) -> Result<Option<User>> {
263- let user = User {
264- id: new_id(),
265- username: username.to_string(),
266- email: email.map(str::to_owned),
267- password_hash: password_hash.to_string(),
268- is_admin: true,
269- created_at: now_stamp(),
270- about: String::new(),
271- display_name: None,
272- timezone: "UTC".to_string(),
273- avatar_hash: None,
274- theme: "light".into(),
275- language: "auto".into(),
276- accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
277- accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
278- base_light: crate::store::ui_prefs::DEFAULT_BASE.into(),
279- base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(),
280- sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(),
281- kind: AccountKind::User,
282- email_notifications: true,
283- };
250+ let user = new_user(username, email, password_hash, true);
284251 let conn = self.inner.conn.lock().await;
285252 let inserted = conn
286253 .execute(
@@ -334,7 +301,6 @@ impl Store {
334301 .await
335302 }
336303
337- // sessions
338304 /// Changes only the display casing of a username. `display` must validate and fold to the
339305 /// user's current `username_folded`; anything else is rejected and nothing is written.
340306 pub async fn set_username_display(&self, user_id: &str, display: &str) -> Result<()> {
@@ -454,7 +420,6 @@ impl Store {
454420 .await
455421 }
456422
457- // ssh keys
458423 pub async fn add_ssh_key(
459424 &self,
460425 user_id: &str,
@@ -479,7 +444,7 @@ impl Store {
479444 "SELECT COUNT(*) FROM ssh_keys WHERE user_id = ?1",
480445 user_id,
481446 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"),
483448 )
484449 .await?;
485450 conn.execute(
@@ -549,7 +514,6 @@ impl Store {
549514 Ok(())
550515 }
551516
552- // tokens
553517 pub async fn create_token(
554518 &self,
555519 user_id: &str,
@@ -575,7 +539,7 @@ impl Store {
575539 "SELECT COUNT(*) FROM access_tokens WHERE user_id = ?1",
576540 user_id,
577541 MAX_TOKENS,
578- "an account can have at most 100 access tokens",
542+ &format!("an account can have at most {MAX_TOKENS} access tokens"),
579543 )
580544 .await?;
581545 conn.execute(
@@ -648,7 +612,6 @@ impl Store {
648612 Ok(())
649613 }
650614
651- // repos
652615 pub async fn create_repo(
653616 &self,
654617 owner_id: &str,
@@ -683,7 +646,6 @@ impl Store {
683646 let conn = self.inner.conn.lock().await;
684647 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
685648 let outcome: Result<Option<Repo>> = async {
686- // A new repo takes over an old name, so any redirect for it is dropped.
687649 tx.execute(
688650 "DELETE FROM repo_redirects WHERE owner_folded = (SELECT username_folded FROM users WHERE id = ?1) AND name_folded = ?2",
689651 (owner_id.to_string(), normalize_name(name)),
@@ -716,20 +678,7 @@ impl Store {
716678 .await
717679 }
718680 .await;
719- match outcome {
720- Ok(Some(repo)) => {
721- tx.commit().await.map_err(db_err)?;
722- Ok(repo)
723- }
724- Ok(None) => {
725- let _ = tx.rollback().await;
726- Err(missing_row())
727- }
728- Err(e) => {
729- let _ = tx.rollback().await;
730- Err(e)
731- }
732- }
681+ finish(tx, outcome.and_then(|repo| repo.ok_or_else(missing_row))).await
733682 }
734683
735684 /// Normalized. The caller strips a trailing ".git" from `name`.
@@ -778,10 +727,7 @@ impl Store {
778727 )
779728 .await
780729 .map_err(db_err)?;
781- if n == 0 {
782- return Err(Error::NotFound);
783- }
784- Ok(())
730+ affected(n)
785731 }
786732
787733 pub async fn collaborator_role(&self, repo_id: &str, user_id: &str) -> Result<Option<Role>> {
@@ -811,7 +757,6 @@ impl Store {
811757 Ok(())
812758 }
813759
814- // events
815760 pub async fn record_push_event(
816761 &self,
817762 repo_id: &str,
@@ -840,7 +785,7 @@ impl Store {
840785 .map_err(db_err)?;
841786 Ok(())
842787 }
843- // profile
788+
844789 /// Sets the about text and timezone. `about` is at most 2000 characters and `timezone`
845790 /// must be a known IANA name; anything else is rejected and nothing is written.
846791 pub async fn set_profile(&self, user_id: &str, about: &str, timezone: &str) -> Result<()> {
@@ -858,10 +803,7 @@ impl Store {
858803 )
859804 .await
860805 .map_err(db_err)?;
861- if n == 0 {
862- return Err(Error::NotFound);
863- }
864- Ok(())
806+ affected(n)
865807 }
866808
867809 /// Sets the display name. `name` goes through `validate_display_name`; an empty name clears
@@ -879,10 +821,7 @@ impl Store {
879821 )
880822 .await
881823 .map_err(db_err)?;
882- if n == 0 {
883- return Err(Error::NotFound);
884- }
885- Ok(())
824+ affected(n)
886825 }
887826
888827 /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest.
@@ -940,16 +879,57 @@ impl Store {
940879 }
941880 }
942881
943-// ---- helpers ----
944-
945882 fn new_id() -> String {
946883 Ulid::generate().to_string()
947884 }
948885
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+
949922 fn db_err(e: turso::Error) -> Error {
950923 Error::Database(e.to_string())
951924 }
952925
926+fn affected(n: u64) -> Result<()> {
927+ if n == 0 {
928+ return Err(Error::NotFound);
929+ }
930+ Ok(())
931+}
932+
953933 fn missing_row() -> Error {
954934 Error::Database("expected a row that is not there".into())
955935 }
@@ -964,25 +944,9 @@ fn insert_err(e: turso::Error, conflict_msg: &str) -> Error {
964944 }
965945 }
966946
967-/// Makes a connection refuse writes. Turso takes `1`, not `ON`. Failure is fatal, because a
968-/// reader that can write would break the pool's rule.
969-async fn apply_query_only(conn: &Connection) -> Result<()> {
970- let mut rows = conn
971- .query("PRAGMA query_only = 1", ())
972- .await
973- .map_err(db_err)?;
974- while rows.next().await.map_err(db_err)?.is_some() {}
975- Ok(())
976-}
977-
978-/// Caps each reader's page cache at 2 MiB (negative means KiB). Turso gives every connection
979-/// its own cache, so the default 2000 pages (~8 MB) per reader adds up across the pool.
980-async fn apply_reader_cache_size(conn: &Connection) -> Result<()> {
981- let mut rows = conn
982- .query("PRAGMA cache_size = -2048", ())
983- .await
984- .map_err(db_err)?;
985- while rows.next().await.map_err(db_err)?.is_some() {}
947+async fn run_pragma(conn: &Connection, sql: &str) -> std::result::Result<(), turso::Error> {
948+ let mut rows = conn.query(sql, ()).await?;
949+ while rows.next().await?.is_some() {}
986950 Ok(())
987951 }
988952
@@ -994,13 +958,7 @@ async fn apply_pragmas(conn: &Connection) {
994958 "PRAGMA synchronous = FULL",
995959 "PRAGMA foreign_keys = ON",
996960 ] {
997- let applied = async {
998- let mut rows = conn.query(sql, ()).await?;
999- while rows.next().await?.is_some() {}
1000- Ok::<(), turso::Error>(())
1001- }
1002- .await;
1003- if let Err(e) = applied {
961+ if let Err(e) = run_pragma(conn, sql).await {
1004962 tracing::warn!(pragma = sql, error = %e, "database pragma not applied");
1005963 }
1006964 }
@@ -1085,6 +1043,14 @@ fn col_opt_text(row: &Row, i: usize) -> Result<Option<String>> {
10851043 }
10861044 }
10871045
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+
10881054 fn col_blob(row: &Row, i: usize) -> Result<Vec<u8>> {
10891055 match row.get_value(i).map_err(db_err)? {
10901056 Value::Blob(b) => Ok(b),
@@ -1092,6 +1058,10 @@ fn col_blob(row: &Row, i: usize) -> Result<Vec<u8>> {
10921058 }
10931059 }
10941060
1061+pub(crate) fn placeholders(n: usize) -> String {
1062+ vec!["?"; n].join(",")
1063+}
1064+
10951065 pub(crate) fn col_int(row: &Row, i: usize) -> Result<i64> {
10961066 match row.get_value(i).map_err(db_err)? {
10971067 Value::Integer(n) => Ok(n),
@@ -1238,7 +1208,6 @@ fn parse_role(s: &str) -> Result<Role> {
12381208 }
12391209 }
12401210
1241-/// Repo deletion. Lives in its own impl block so the existing store code stays untouched.
12421211 impl Store {
12431212 /// Deletes a repo row and every row that references it (webhooks and their deliveries, issues and their children, labels,
12441213 /// milestones, pull requests, notifications, watches and issue subscriptions, redirects, collaborators, push events,
@@ -1252,8 +1221,6 @@ impl Store {
12521221 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
12531222 let id = repo_id.to_string();
12541223 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.
12571224 notifications::delete_repo_notification_rows(&tx, &id).await?;
12581225 reviews::delete_repo_review_rows(&tx, &id).await?;
12591226 pulls::delete_repo_pull_rows(&tx, &id).await?;
@@ -1261,7 +1228,6 @@ impl Store {
12611228 discussions::delete_repo_discussion_rows(&tx, &id).await?;
12621229 releases::delete_repo_release_rows(&tx, &id).await?;
12631230 for sql in [
1264- // Deliveries before hooks, hooks before the repo.
12651231 "DELETE FROM webhook_deliveries WHERE hook_id IN (SELECT id FROM webhooks WHERE repo_id = ?1)",
12661232 "DELETE FROM webhooks WHERE repo_id = ?1",
12671233 "DELETE FROM repo_mirrors WHERE repo_id = ?1",
@@ -1279,13 +1245,11 @@ impl Store {
12791245 "DELETE FROM advisory_notifications WHERE repo_id = ?1",
12801246 "DELETE FROM repo_alerts WHERE repo_id = ?1",
12811247 "DELETE FROM repo_dependencies WHERE repo_id = ?1",
1282- // CI: artifacts and jobs before runs, runs before the repo.
12831248 "DELETE FROM ci_artifacts WHERE job_id IN (SELECT ci_jobs.id FROM ci_jobs \
12841249 JOIN ci_runs ON ci_runs.id = ci_jobs.run_id WHERE ci_runs.repo_id = ?1)",
12851250 "DELETE FROM ci_jobs WHERE run_id IN (SELECT id FROM ci_runs WHERE repo_id = ?1)",
12861251 "DELETE FROM ci_runs WHERE repo_id = ?1",
12871252 "DELETE FROM ci_secrets WHERE repo_id = ?1",
1288- // Forks of this repo stay, detached from it.
12891253 "UPDATE repos SET fork_of = NULL WHERE fork_of = ?1",
12901254 ] {
12911255 tx.execute(sql, (id.clone(),)).await.map_err(db_err)?;
@@ -1295,20 +1259,11 @@ impl Store {
12951259 .map_err(db_err)
12961260 }
12971261 .await;
1298- match outcome {
1299- Ok(1) => {
1300- tx.commit().await.map_err(db_err)?;
1301- Ok(())
1302- }
1303- Ok(_) => {
1304- let _ = tx.rollback().await;
1305- Err(Error::NotFound)
1306- }
1307- Err(e) => {
1308- let _ = tx.rollback().await;
1309- Err(e)
1310- }
1311- }
1262+ finish(
1263+ tx,
1264+ outcome.and_then(|n| if n == 1 { Ok(()) } else { Err(Error::NotFound) }),
1265+ )
1266+ .await
13121267 }
13131268 }
13141269
@@ -1316,7 +1271,6 @@ const BRANCH_RULE_COLS: &str = "id, repo_id, pattern, allow_force_push, allow_de
13161271 required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks, \
13171272 require_merge_queue";
13181273
1319-// branch protection
13201274 impl Store {
13211275 /// The repo's branch rules, ordered by pattern.
13221276 pub async fn list_branch_rules(&self, repo_id: &str) -> Result<Vec<BranchRule>> {
@@ -1395,10 +1349,7 @@ impl Store {
13951349 )
13961350 .await
13971351 .map_err(db_err)?;
1398- if n == 0 {
1399- return Err(Error::NotFound);
1400- }
1401- Ok(())
1352+ affected(n)
14021353 }
14031354 }
14041355
@@ -1421,7 +1372,6 @@ fn map_branch_rule(row: &Row) -> Result<BranchRule> {
14211372 })
14221373 }
14231374
1424-// repo renames, transfers and redirects
14251375 impl Store {
14261376 /// The repo a past owner/name points at (both folded). Chains work because a redirect always
14271377 /// points at the repo id, not at an intermediate name.
@@ -1443,65 +1393,60 @@ impl Store {
14431393 /// Renames a repo under its current owner. The old name keeps working through a redirect.
14441394 /// A name taken by another repo of the same owner gives `Conflict`.
14451395 pub async fn rename_repo(&self, repo_id: &str, new_name: &str) -> Result<()> {
1446- let folded = validate_name(new_name)?;
1447- let owner_id = self.repo_owner_id(repo_id).await?.ok_or(Error::NotFound)?;
1448- self.move_repo(repo_id, &owner_id, new_name, &folded).await
1396+ validate_name(new_name)?;
1397+ self.move_repo(repo_id, None, Some(new_name)).await
14491398 }
14501399
14511400 /// Moves a repo to another owner under the same name. The old owner/name keeps working through
14521401 /// a redirect. Collaborator rows stay, except the new owner's, which is removed. A name taken
14531402 /// by the new owner gives `Conflict`.
14541403 pub async fn transfer_repo(&self, repo_id: &str, new_owner_id: &str) -> Result<()> {
1455- let repo = self.repo_by_id(repo_id).await?.ok_or(Error::NotFound)?;
1456- self.move_repo(
1457- repo_id,
1458- new_owner_id,
1459- &repo.name,
1460- &normalize_name(&repo.name),
1461- )
1462- .await
1404+ self.move_repo(repo_id, Some(new_owner_id), None).await
14631405 }
14641406
1465- /// The owner id of a repo, or `None` if it does not exist.
1466- async fn repo_owner_id(&self, repo_id: &str) -> Result<Option<String>> {
1467- let conn = self.read_conn().await;
1468- fetch_opt(
1469- &conn,
1470- "SELECT owner_id FROM repos WHERE id = ?1",
1471- (repo_id.to_string(),),
1472- |row| col_text(row, 0),
1473- )
1474- .await
1475- }
1476-
1477- /// Shared body of rename and transfer, in one transaction: updates owner, name and folded
1478- /// name, records a redirect from the old owner/name to this repo, drops any redirect for the
1479- /// new owner/name, and removes the new owner's collaborator row when the owner changes.
1407+ /// Shared body of rename and transfer, in one transaction. `None` keeps the current owner or
1408+ /// name, which is read here under the writer lock so a concurrent move is not written back.
1409+ /// Updates owner, name and folded name, records a redirect from the old owner/name to this
1410+ /// repo, drops any redirect for the new owner/name, and removes the new owner's collaborator
1411+ /// row when the owner changes.
14801412 async fn move_repo(
14811413 &self,
14821414 repo_id: &str,
1483- new_owner_id: &str,
1484- new_name: &str,
1485- new_folded: &str,
1415+ new_owner_id: Option<&str>,
1416+ new_name: Option<&str>,
14861417 ) -> Result<()> {
14871418 let conn = self.inner.conn.lock().await;
14881419 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
14891420 let id = repo_id.to_string();
14901421 let outcome: Result<()> = async {
1491- // Old owner folded, old owner id, and old folded name.
1492- let (old_owner_id, old_owner_folded, old_folded): (String, String, String) = fetch_opt(
1422+ let (old_owner_id, old_owner_folded, old_name, old_folded): (
1423+ String,
1424+ String,
1425+ String,
1426+ String,
1427+ ) = fetch_opt(
14931428 &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 \
14951430 JOIN users u ON u.id = r.owner_id WHERE r.id = ?1",
14961431 (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+ },
14981440 )
14991441 .await?
15001442 .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);
15011446 let new_owner_folded: String = fetch_opt(
15021447 &tx,
15031448 "SELECT username_folded FROM users WHERE id = ?1",
1504- (new_owner_id.to_string(),),
1449+ (new_owner_id.clone(),),
15051450 |row| col_text(row, 0),
15061451 )
15071452 .await?
@@ -1519,7 +1464,6 @@ impl Store {
15191464 .await
15201465 .map_err(|e| insert_err(e, "a repository with this name already exists"))?;
15211466
1522- // The new owner/name is live now, so no redirect may point at it.
15231467 tx.execute(
15241468 "DELETE FROM repo_redirects WHERE owner_folded = ?1 AND name_folded = ?2",
15251469 (new_owner_folded.clone(), new_folded.to_string()),
@@ -1550,8 +1494,6 @@ impl Store {
15501494 )
15511495 .await
15521496 .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.
15551497 tx.execute(
15561498 "DELETE FROM repo_transfers WHERE repo_id = ?1",
15571499 (id.clone(),),
@@ -1562,21 +1504,10 @@ impl Store {
15621504 Ok(())
15631505 }
15641506 .await;
1565- match outcome {
1566- Ok(()) => {
1567- tx.commit().await.map_err(db_err)?;
1568- Ok(())
1569- }
1570- Err(e) => {
1571- let _ = tx.rollback().await;
1572- Err(e)
1573- }
1574- }
1507+ finish(tx, outcome).await
15751508 }
15761509 }
15771510
1578-// ---- account security: email, password, two-factor ----
1579-
15801511 /// The two-factor state of a user.
15811512 #[derive(Debug, Clone, PartialEq)]
15821513 pub struct TotpState {
@@ -1623,10 +1554,7 @@ impl Store {
16231554 )
16241555 .await
16251556 .map_err(db_err)?;
1626- if n == 0 {
1627- return Err(Error::NotFound);
1628- }
1629- Ok(())
1557+ affected(n)
16301558 }
16311559
16321560 /// Replaces the stored password hash. The caller hashes the password.
@@ -1639,10 +1567,7 @@ impl Store {
16391567 )
16401568 .await
16411569 .map_err(db_err)?;
1642- if n == 0 {
1643- return Err(Error::NotFound);
1644- }
1645- Ok(())
1570+ affected(n)
16461571 }
16471572
16481573 /// Deletes every session of the user except `keep_session_id`. Returns how many were removed.
@@ -1703,10 +1628,7 @@ impl Store {
17031628 )
17041629 .await
17051630 .map_err(db_err)?;
1706- if n == 0 {
1707- return Err(Error::NotFound);
1708- }
1709- Ok(())
1631+ affected(n)
17101632 }
17111633
17121634 /// Turns two-factor on after a confirmed code, and replaces the recovery codes with
@@ -1733,9 +1655,7 @@ impl Store {
17331655 )
17341656 .await
17351657 .map_err(db_err)?;
1736- if n == 0 {
1737- return Err(Error::NotFound);
1738- }
1658+ affected(n)?;
17391659 replace_codes_in(&tx, &uid, code_hashes).await
17401660 }
17411661 .await;
@@ -1908,14 +1828,12 @@ mod tests {
19081828 let dir = tempfile::tempdir().unwrap();
19091829 let (store, user) = store_with_user(&dir).await;
19101830
1911- // Scenario: a new user has an empty bio and UTC.
19121831 assert_eq!(user.about, "");
19131832 assert_eq!(user.timezone, "UTC");
19141833 let fetched = store.user_by_id(&user.id).await.unwrap().unwrap();
19151834 assert_eq!(fetched.about, "");
19161835 assert_eq!(fetched.timezone, "UTC");
19171836
1918- // Scenario: a valid profile is saved; invalid input is refused and changes nothing.
19191837 store
19201838 .set_profile(&user.id, "Hello *world*", "Europe/Istanbul")
19211839 .await
@@ -1949,7 +1867,6 @@ mod tests {
19491867 validate_display_name(" Ahmet Kaan Gümüş ").unwrap(),
19501868 Some("Ahmet Kaan Gümüş".to_string())
19511869 );
1952- // The limit counts characters: 80 two-byte letters fit, 81 do not.
19531870 assert!(validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS)).is_ok());
19541871 assert!(matches!(
19551872 validate_display_name(&"ğ".repeat(MAX_DISPLAY_NAME_CHARS + 1)),
@@ -1982,12 +1899,10 @@ mod tests {
19821899 let fetched = store.user_by_id(&user.id).await.unwrap().unwrap();
19831900 assert_eq!(fetched.display_name.as_deref(), Some("Ahmet Kaan Gümüş"));
19841901
1985- // Blank input clears the name back to NULL.
19861902 store.set_display_name(&user.id, " ").await.unwrap();
19871903 let cleared = store.user_by_id(&user.id).await.unwrap().unwrap();
19881904 assert_eq!(cleared.display_name, None);
19891905
1990- // A rejected name leaves the stored value alone.
19911906 store.set_display_name(&user.id, "Kept").await.unwrap();
19921907 let long = "x".repeat(MAX_DISPLAY_NAME_CHARS + 1);
19931908 assert!(matches!(
@@ -2007,7 +1922,6 @@ mod tests {
20071922 let dir = tempfile::tempdir().unwrap();
20081923 let (store, user) = store_with_user(&dir).await;
20091924
2010- // Scenario: upsert replaces the image and its hash; delete is idempotent.
20111925 assert_eq!(store.avatar(&user.id).await.unwrap(), None);
20121926 assert_eq!(store.avatar_hash(&user.id).await.unwrap(), None);
20131927 store.set_avatar(&user.id, b"png-1", "aaaa").await.unwrap();
@@ -2024,7 +1938,6 @@ mod tests {
20241938 store.delete_avatar(&user.id).await.unwrap();
20251939 assert_eq!(store.avatar(&user.id).await.unwrap(), None);
20261940
2027- // Scenario: deleting the user row removes its avatar with it.
20281941 let doomed = store
20291942 .create_user("Doomed", None, "hash", false)
20301943 .await
@@ -2045,8 +1958,6 @@ mod tests {
20451958 let (store, tahinli) = store_with_user(&dir).await;
20461959 let bob = store.create_user("Bob", None, "hash", false).await.unwrap();
20471960
2048- // Scenario: deleting a repo removes its collaborators, push events and branch
2049- // rules atomically, and leaves the other repo and its rows untouched.
20501961 let keep = store
20511962 .create_repo(&tahinli.id, "keep", "", Visibility::Public, "main")
20521963 .await
@@ -2107,7 +2018,6 @@ mod tests {
21072018 assert_eq!(col_int(&row, 0).unwrap(), 1);
21082019 }
21092020
2110- // Scenario: a missing id is NotFound; deleting twice reports NotFound the second time.
21112021 let later = store
21122022 .create_repo(&tahinli.id, "later", "", Visibility::Public, "main")
21132023 .await
@@ -2129,8 +2039,6 @@ mod tests {
21292039 let dir = tempfile::tempdir().unwrap();
21302040 let (store, owner) = store_with_user(&dir).await;
21312041
2132- // Scenario: required checks are trimmed, de-duplicated and blanks dropped;
2133- // saving without checks clears them; a control character is refused.
21342042 {
21352043 let repo = store
21362044 .create_repo(&owner.id, "checks", "", Visibility::Public, "main")
@@ -2169,7 +2077,6 @@ mod tests {
21692077 ));
21702078 }
21712079
2172- // Scenario: listing, upserting the same pattern updates in place, bad patterns refused.
21732080 {
21742081 let repo = store
21752082 .create_repo(&owner.id, "list", "", Visibility::Public, "main")
@@ -2189,7 +2096,6 @@ mod tests {
21892096 let patterns: Vec<&str> = rules.iter().map(|r| r.pattern.as_str()).collect();
21902097 assert_eq!(patterns, ["main", "release/*"]);
21912098
2192- // Same pattern updates the flags in place and keeps the id and created_at.
21932099 let updated = store
21942100 .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(true, true))
21952101 .await
@@ -2209,7 +2115,6 @@ mod tests {
22092115 ));
22102116 }
22112117
2212- // Scenario: merge and push fields round-trip; an out-of-range value is refused.
22132118 {
22142119 let repo = store
22152120 .create_repo(&owner.id, "fields", "", Visibility::Public, "main")
@@ -2238,7 +2143,6 @@ mod tests {
22382143 vec![saved]
22392144 );
22402145
2241- // Out of range is refused and stores nothing new.
22422146 let too_many = RuleFlags {
22432147 required_approvals: 21,
22442148 ..flags
@@ -2251,7 +2155,6 @@ mod tests {
22512155 assert_eq!(rules[0].required_approvals, 20);
22522156 }
22532157
2254- // Scenario: deleting a rule is scoped to its own repo.
22552158 {
22562159 let a = store
22572160 .create_repo(&owner.id, "scope-a", "", Visibility::Public, "main")
@@ -2322,7 +2225,6 @@ mod tests {
23222225 }
23232226 }
23242227
2325-// collaborators (settings page)
23262228 impl Store {
23272229 /// Every collaborator on a repo with their role, ordered by username (case-insensitive).
23282230 pub async fn list_collaborators(&self, repo_id: &str) -> Result<Vec<(User, Role)>> {
@@ -2357,7 +2259,6 @@ impl Store {
23572259 /// Longest accepted repo description, in characters.
23582260 pub const MAX_DESCRIPTION_CHARS: usize = 350;
23592261
2360-// general repo settings (description, default branch, visibility)
23612262 impl Store {
23622263 /// Saves the description and the default branch in one statement. The description must be at
23632264 /// most `MAX_DESCRIPTION_CHARS` characters with no control characters. The branch is not checked
@@ -2393,10 +2294,7 @@ impl Store {
23932294 )
23942295 .await
23952296 .map_err(db_err)?;
2396- if n == 0 {
2397- return Err(Error::NotFound);
2398- }
2399- Ok(())
2297+ affected(n)
24002298 }
24012299
24022300 /// Sets the repo's visibility. `NotFound` when the repo is gone.
@@ -2409,10 +2307,7 @@ impl Store {
24092307 )
24102308 .await
24112309 .map_err(db_err)?;
2412- if n == 0 {
2413- return Err(Error::NotFound);
2414- }
2415- Ok(())
2310+ affected(n)
24162311 }
24172312 }
24182313
@@ -2444,7 +2339,6 @@ mod collaborator_tests {
24442339 .set_collaborator(&repo.id, &amy.id, Role::Write)
24452340 .await
24462341 .unwrap();
2447- // Setting an existing collaborator again replaces the role.
24482342 store
24492343 .set_collaborator(&repo.id, &zed.id, Role::Triage)
24502344 .await
@@ -2462,7 +2356,6 @@ mod collaborator_tests {
24622356 "ordered by username, one row per user"
24632357 );
24642358
2465- // Push rights follow the role through authorize.
24662359 assert!(authorize(Some(&amy), &repo, Some(Role::Write), None, Action::Write).is_ok());
24672360 assert_eq!(
24682361 authorize(Some(&zed), &repo, Some(Role::Read), None, Action::Write),
@@ -2493,7 +2386,6 @@ pub enum RepoSort {
24932386 /// A row of the public listing: the repo, its star count and its last activity time.
24942387 pub type ListedRepo = (Repo, u64, String);
24952388
2496-// stars and the public repo listing
24972389 impl Store {
24982390 /// Stars a repo for a user. Starring a repo twice changes nothing.
24992391 pub async fn star(&self, user_id: &str, repo_id: &str) -> Result<()> {
@@ -2546,23 +2438,6 @@ impl Store {
25462438 Ok(u64::try_from(n).unwrap_or(0))
25472439 }
25482440
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-
25662441 /// One page of public repos, optionally filtered by `query`. The query matches the repo name
25672442 /// or description, case-insensitively, as a plain substring: `%`, `_` and `\` are literal.
25682443 /// Each row carries the star count and the last activity time (the latest push, or the
@@ -2633,7 +2508,6 @@ mod security_tests {
26332508 async fn account_email_password_and_session_scenarios() {
26342509 let (store, user, _dir) = store_with_user().await;
26352510
2636- // Scenario: email and password hash persist; a bad email and a missing user are refused.
26372511 store
26382512 .set_email(&user.id, "tahinli@example.com")
26392513 .await
@@ -2648,7 +2522,6 @@ mod security_tests {
26482522 Err(Error::NotFound)
26492523 ));
26502524
2651- // Scenario: deleting sessions except one keeps only the named session.
26522525 let expiry = crate::time::stamp_after(std::time::Duration::from_secs(3600));
26532526 let keep = store
26542527 .create_session(&user.id, "h1", "c1", &expiry, None, None)
@@ -2678,12 +2551,10 @@ mod security_tests {
26782551 async fn totp_scenarios() {
26792552 let (store, user, _dir) = store_with_user().await;
26802553
2681- // Scenario: enabling without a secret is refused and leaves TOTP off.
26822554 let err = store.enable_totp(&user.id, 1, &[]).await;
26832555 assert!(matches!(err, Err(Error::NotFound)));
26842556 assert!(!store.totp_state(&user.id).await.unwrap().unwrap().enabled);
26852557
2686- // Scenario: enrollment, then replay and recovery-code rules.
26872558 let fresh = store.totp_state(&user.id).await.unwrap().unwrap();
26882559 assert_eq!(fresh.sealed_secret, None);
26892560 assert!(!fresh.enabled);
@@ -2700,7 +2571,6 @@ mod security_tests {
27002571 assert_eq!(on.last_step, 100);
27012572 assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 2);
27022573
2703- // Steps must strictly increase: 100 was used, so 100 and older are refused.
27042574 assert!(!store.accept_totp_step(&user.id, 100).await.unwrap());
27052575 assert!(!store.accept_totp_step(&user.id, 99).await.unwrap());
27062576 assert!(store.accept_totp_step(&user.id, 101).await.unwrap());
@@ -2738,7 +2608,6 @@ mod security_tests {
27382608 assert_eq!(off.last_step, 0);
27392609 assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 0);
27402610
2741- // Scenario: device fields (added, last used, name) on a second user.
27422611 let device = store
27432612 .create_user("device-owner", None, "h", false)
27442613 .await
@@ -2775,14 +2644,12 @@ mod security_tests {
27752644 Some("Work phone")
27762645 );
27772646
2778- // Stamps have nanosecond precision and sort as text, so a later use compares greater.
27792647 std::thread::sleep(std::time::Duration::from_millis(5));
27802648 assert!(store.accept_totp_step(&device.id, 101).await.unwrap());
27812649 let used = store.totp_state(&device.id).await.unwrap().unwrap();
27822650 assert!(used.last_used_at.as_deref().unwrap() > added.as_str());
27832651 assert_eq!(used.created_at.as_deref(), Some(added.as_str()));
27842652
2785- // A replayed step is refused and leaves the last use alone.
27862653 std::thread::sleep(std::time::Duration::from_millis(5));
27872654 assert!(!store.accept_totp_step(&device.id, 101).await.unwrap());
27882655 assert_eq!(
crates/forge-core/src/store/notifications.rsmodified+55 -217
@@ -3,9 +3,8 @@
33 use turso::transaction::Transaction;
44 use turso::{Row, Value};
55
6-use super::issues::finish;
7-use super::repo_listing::READABLE_BY_VIEWER;
8-use super::{Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, map_user, new_id};
6+use super::repo_listing::VIEWER_ACCESS;
7+use super::{Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, finish, map_user, new_id};
98 use crate::error::{Error, Result};
109 use crate::model::{Id, User};
1110 use crate::notifications::{Notification, Reason, SubState, WatchLevel};
@@ -19,7 +18,7 @@ const MAX_NOTIFICATION_PAGE: u32 = 200;
1918 /// from, drops out of the inbox, the dashboard and the unread count at once.
2019 pub(super) fn readable_repo() -> String {
2120 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))"
2322 )
2423 }
2524
@@ -61,7 +60,7 @@ fn map_notification(row: &Row) -> Result<Notification> {
6160 number: col_int(row, 5)?,
6261 is_pull: kind == "pull",
6362 title: col_text(row, 7)?,
64- issue_state: col_text(row, 8)?,
63+ issue_state: col_text(row, 8)?.parse()?,
6564 reason: reason_from(&col_text(row, 9)?)?,
6665 last_activity: col_text(row, 10)?,
6766 last_actor_name: match row.get_value(11).map_err(db_err)? {
@@ -91,6 +90,14 @@ pub(super) async fn delete_repo_notification_rows(
9190 }
9291
9392 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+
94101 /// Sets the user's watch level on a repo, creating the row if needed.
95102 pub async fn set_watch(&self, user_id: &str, repo_id: &str, level: WatchLevel) -> Result<()> {
96103 let conn = self.inner.conn.lock().await;
@@ -405,23 +412,12 @@ impl Store {
405412 /// them.
406413 pub async fn mark_all_read(&self, user_id: &str, repo_id: Option<&str>) -> Result<()> {
407414 let conn = self.inner.conn.lock().await;
408- let result = match repo_id {
409- Some(repo) => {
410- conn.execute(
411- "UPDATE notifications SET unread = 0 WHERE user_id = ?1 AND repo_id = ?2 AND unread = 1",
412- (user_id.to_string(), repo.to_string()),
413- )
414- .await
415- }
416- None => {
417- conn.execute(
418- "UPDATE notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1",
419- (user_id.to_string(),),
420- )
421- .await
422- }
423- };
424- result.map_err(db_err)?;
415+ conn.execute(
416+ "UPDATE notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1 AND (?2 IS NULL OR repo_id = ?2)",
417+ (user_id.to_string(), repo_id.map(str::to_string)),
418+ )
419+ .await
420+ .map_err(db_err)?;
425421 Ok(())
426422 }
427423
@@ -441,6 +437,7 @@ impl Store {
441437 #[cfg(test)]
442438 mod tests {
443439 use super::*;
440+ use crate::issues::IssueState;
444441 use crate::model::Visibility;
445442
446443 struct Fixture {
@@ -517,14 +514,25 @@ mod tests {
517514 .id
518515 }
519516
520- // Scenarios share one store. Each one uses its own issue, repo or fresh users
521- // wherever the assertions read repo-wide or per-user state.
517+ async fn notify(
518+ s: &Store,
519+ user: &str,
520+ repo: &str,
521+ issue: &str,
522+ reason: Reason,
523+ activity: &str,
524+ actor: Option<&str>,
525+ ) {
526+ s.upsert_notification(user, repo, issue, reason, activity, actor)
527+ .await
528+ .unwrap();
529+ }
530+
522531 #[tokio::test]
523- async fn watch_and_subscription_rules_hold_in_each_scenario() {
532+ async fn watch_and_subscription_rules() {
524533 let fx = fixture().await;
525534 let s = &fx.store;
526535
527- // Scenario 1: watch levels default to participating; watchers lists only watchers.
528536 let repo = s
529537 .create_repo(&fx.owner, "watch", "", Visibility::Public, "main")
530538 .await
@@ -560,7 +568,6 @@ mod tests {
560568 expected.sort();
561569 assert_eq!(watchers, expected, "watch: only watching users listed");
562570
563- // Scenario 2: auto-subscribe never overrides an ignore; explicit subscribe does.
564571 let issue = s
565572 .create_issue(&fx.repo, &fx.owner, "Third", "")
566573 .await
@@ -574,7 +581,6 @@ mod tests {
574581 Some((SubState::Subscribed, Reason::Comment)),
575582 "auto: first subscription"
576583 );
577- // Existing row stays as it was.
578584 s.auto_subscribe(&fx.tahinli, &issue, Reason::Mention)
579585 .await
580586 .unwrap();
@@ -583,7 +589,6 @@ mod tests {
583589 Some((SubState::Subscribed, Reason::Comment)),
584590 "auto: existing row kept"
585591 );
586- // An explicit ignore is never replaced by auto-subscribe.
587592 s.subscribe(&fx.bob, &issue, SubState::Ignored, Reason::Subscribed)
588593 .await
589594 .unwrap();
@@ -595,7 +600,6 @@ mod tests {
595600 Some((SubState::Ignored, Reason::Subscribed)),
596601 "auto: ignore kept"
597602 );
598- // Explicit subscribe does replace.
599603 s.subscribe(&fx.bob, &issue, SubState::Subscribed, Reason::Author)
600604 .await
601605 .unwrap();
@@ -610,7 +614,6 @@ mod tests {
610614 "auto: untouched user has no row"
611615 );
612616
613- // Scenario 3: subscribers lists only subscribed users of one issue.
614617 let issue = s
615618 .create_issue(&fx.repo, &fx.owner, "Fourth", "")
616619 .await
@@ -634,32 +637,13 @@ mod tests {
634637 }
635638
636639 #[tokio::test]
637- async fn inbox_rules_hold_in_each_scenario() {
640+ async fn inbox_rules() {
638641 let fx = fixture().await;
639642 let s = &fx.store;
640643
641- // Scenario 1: a stronger reason wins while unread; a read row is replaced.
642644 let ivy = user(s, "Ivy").await;
643- s.upsert_notification(
644- &ivy,
645- &fx.repo,
646- &fx.issue_a,
647- Reason::Mention,
648- "mentioned",
649- Some(&fx.bob),
650- )
651- .await
652- .unwrap();
653- s.upsert_notification(
654- &ivy,
655- &fx.repo,
656- &fx.issue_a,
657- Reason::Comment,
658- "comment",
659- Some(&fx.bob),
660- )
661- .await
662- .unwrap();
645+ notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Mention, "mentioned", Some(&fx.bob)).await;
646+ notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&fx.bob)).await;
663647 assert_eq!(
664648 reason_of(s, &ivy, &fx.issue_a).await,
665649 Reason::Mention,
@@ -668,43 +652,16 @@ mod tests {
668652 assert_eq!(s.unread_count(&ivy).await.unwrap(), 1, "upsert: one unread");
669653
670654 s.mark_issue_read(&ivy, &fx.issue_a).await.unwrap();
671- assert_eq!(
672- s.unread_count(&ivy).await.unwrap(),
673- 0,
674- "upsert: marked read"
675- );
676- s.upsert_notification(
677- &ivy,
678- &fx.repo,
679- &fx.issue_a,
680- Reason::Comment,
681- "comment",
682- Some(&fx.bob),
683- )
684- .await
685- .unwrap();
655+ assert_eq!(s.unread_count(&ivy).await.unwrap(), 0, "upsert: marked read");
656+ notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&fx.bob)).await;
686657 assert_eq!(
687658 reason_of(s, &ivy, &fx.issue_a).await,
688659 Reason::Comment,
689660 "upsert: read row replaced"
690661 );
691- assert_eq!(
692- s.unread_count(&ivy).await.unwrap(),
693- 1,
694- "upsert: unread again"
695- );
662+ assert_eq!(s.unread_count(&ivy).await.unwrap(), 1, "upsert: unread again");
696663
697- // A stronger reason while unread still wins.
698- s.upsert_notification(
699- &ivy,
700- &fx.repo,
701- &fx.issue_a,
702- Reason::Assign,
703- "assigned",
704- None,
705- )
706- .await
707- .unwrap();
664+ notify(s, &ivy, &fx.repo, &fx.issue_a, Reason::Assign, "assigned", None).await;
708665 let inbox = s.list_notifications(&ivy, false, None, 10).await.unwrap();
709666 assert_eq!(inbox.len(), 1, "upsert: still one row");
710667 assert_eq!(
@@ -715,28 +672,9 @@ mod tests {
715672 assert_eq!(inbox[0].last_activity, "assigned", "upsert: activity text");
716673 assert_eq!(inbox[0].last_actor_name, None, "upsert: no actor given");
717674
718- // Scenario 2: listing is newest first, paged by cursor, and per user.
719675 let kim = user(s, "Kim").await;
720- s.upsert_notification(
721- &kim,
722- &fx.repo,
723- &fx.issue_a,
724- Reason::Comment,
725- "comment",
726- Some(&fx.bob),
727- )
728- .await
729- .unwrap();
730- s.upsert_notification(
731- &kim,
732- &fx.repo,
733- &fx.issue_b,
734- Reason::Comment,
735- "comment",
736- Some(&fx.bob),
737- )
738- .await
739- .unwrap();
676+ notify(s, &kim, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&fx.bob)).await;
677+ notify(s, &kim, &fx.repo, &fx.issue_b, Reason::Comment, "comment", Some(&fx.bob)).await;
740678 s.mark_issue_read(&kim, &fx.issue_b).await.unwrap();
741679
742680 let all = s.list_notifications(&kim, false, None, 50).await.unwrap();
@@ -746,7 +684,7 @@ mod tests {
746684 assert_eq!(all[0].repo_owner, "Owen", "list: repo owner");
747685 assert_eq!(all[0].repo_name, "proj", "list: repo name");
748686 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");
750688 assert!(!all[0].is_pull, "list: issue, not a pull request");
751689 assert_eq!(
752690 all[0].last_actor_name.as_deref(),
@@ -758,7 +696,6 @@ mod tests {
758696 assert_eq!(unread.len(), 1, "list: unread filter");
759697 assert_eq!(unread[0].issue_id, fx.issue_a, "list: unread row");
760698
761- // Cursor: first page of one, then the rest after its stamp.
762699 let first = s.list_notifications(&kim, false, None, 1).await.unwrap();
763700 assert_eq!(first[0].issue_id, fx.issue_b, "cursor: first page");
764701 let second = s
@@ -773,7 +710,6 @@ mod tests {
773710 .unwrap();
774711 assert!(none.is_empty(), "cursor: past the end");
775712
776- // Other users see nothing.
777713 assert!(
778714 s.list_notifications(&fx.bob, false, None, 50)
779715 .await
@@ -782,42 +718,13 @@ mod tests {
782718 "list: other user sees nothing"
783719 );
784720
785- // Scenario 3: mark-read by id and by repo only touches the right rows.
786721 let ned = user(s, "Ned").await;
787722 let olive = user(s, "Olive").await;
788- s.upsert_notification(
789- &ned,
790- &fx.repo,
791- &fx.issue_a,
792- Reason::Comment,
793- "comment",
794- None,
795- )
796- .await
797- .unwrap();
798- s.upsert_notification(
799- &ned,
800- &fx.repo,
801- &fx.issue_b,
802- Reason::Comment,
803- "comment",
804- None,
805- )
806- .await
807- .unwrap();
808- s.upsert_notification(
809- &olive,
810- &fx.repo,
811- &fx.issue_a,
812- Reason::Comment,
813- "comment",
814- None,
815- )
816- .await
817- .unwrap();
723+ notify(s, &ned, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await;
724+ notify(s, &ned, &fx.repo, &fx.issue_b, Reason::Comment, "comment", None).await;
725+ notify(s, &olive, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await;
818726 assert_eq!(s.unread_count(&ned).await.unwrap(), 2, "read: two unread");
819727
820- // mark_read by id, and another user's id does nothing.
821728 let inbox = s.list_notifications(&ned, false, None, 50).await.unwrap();
822729 let olive_inbox = s.list_notifications(&olive, false, None, 50).await.unwrap();
823730 s.mark_read(&ned, &olive_inbox[0].id).await.unwrap();
@@ -831,17 +738,7 @@ mod tests {
831738 s.mark_read(&ned, &inbox[1].id).await.unwrap();
832739 assert_eq!(s.unread_count(&ned).await.unwrap(), 0, "read: second by id");
833740
834- // mark_all_read per repo leaves other users alone.
835- s.upsert_notification(
836- &ned,
837- &fx.repo,
838- &fx.issue_a,
839- Reason::Comment,
840- "comment",
841- None,
842- )
843- .await
844- .unwrap();
741+ notify(s, &ned, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await;
845742 s.mark_all_read(&ned, Some(&fx.repo)).await.unwrap();
846743 assert_eq!(s.unread_count(&ned).await.unwrap(), 0, "read: all in repo");
847744 assert_eq!(
@@ -850,16 +747,7 @@ mod tests {
850747 "read: other user kept"
851748 );
852749
853- s.upsert_notification(
854- &ned,
855- &fx.repo,
856- &fx.issue_b,
857- Reason::Comment,
858- "comment",
859- None,
860- )
861- .await
862- .unwrap();
750+ notify(s, &ned, &fx.repo, &fx.issue_b, Reason::Comment, "comment", None).await;
863751 s.mark_all_read(&ned, None).await.unwrap();
864752 assert_eq!(s.unread_count(&ned).await.unwrap(), 0, "read: all, no repo");
865753 s.mark_all_read(&olive, Some("no-such-repo")).await.unwrap();
@@ -869,28 +757,9 @@ mod tests {
869757 "read: unknown repo"
870758 );
871759
872- // Scenario 4: mark_issue_read only touches that issue.
873760 let max = user(s, "Max").await;
874- s.upsert_notification(
875- &max,
876- &fx.repo,
877- &fx.issue_a,
878- Reason::Comment,
879- "comment",
880- None,
881- )
882- .await
883- .unwrap();
884- s.upsert_notification(
885- &max,
886- &fx.repo,
887- &fx.issue_b,
888- Reason::Comment,
889- "comment",
890- None,
891- )
892- .await
893- .unwrap();
761+ notify(s, &max, &fx.repo, &fx.issue_a, Reason::Comment, "comment", None).await;
762+ notify(s, &max, &fx.repo, &fx.issue_b, Reason::Comment, "comment", None).await;
894763 s.mark_issue_read(&max, &fx.issue_a).await.unwrap();
895764 assert_eq!(
896765 s.unread_count(&max).await.unwrap(),
@@ -904,13 +773,11 @@ mod tests {
904773 );
905774 }
906775
907- // Deletions come last in their own store scope: each removes state other scenarios need.
908776 #[tokio::test]
909- async fn delete_rules_hold_in_each_scenario() {
777+ async fn delete_rules() {
910778 let fx = fixture().await;
911779 let s = &fx.store;
912780
913- // Scenario 1: deleting a repo removes its notification rows, subs and watches.
914781 let pat = user(s, "Pat").await;
915782 let doomed = s
916783 .create_repo(&fx.owner, "doomed", "", Visibility::Public, "main")
@@ -928,16 +795,7 @@ mod tests {
928795 s.subscribe(&pat, &doomed_issue, SubState::Subscribed, Reason::Author)
929796 .await
930797 .unwrap();
931- s.upsert_notification(
932- &pat,
933- &doomed,
934- &doomed_issue,
935- Reason::Comment,
936- "comment",
937- Some(&fx.bob),
938- )
939- .await
940- .unwrap();
798+ notify(s, &pat, &doomed, &doomed_issue, Reason::Comment, "comment", Some(&fx.bob)).await;
941799
942800 s.delete_repo(&doomed).await.unwrap();
943801 assert_eq!(
@@ -976,7 +834,6 @@ mod tests {
976834 "repo: nothing unread"
977835 );
978836
979- // Scenario 2: deleting a user removes their rows and reassigns last actor to ghost.
980837 let ghost = s.ensure_ghost_user().await.unwrap();
981838 let quin = user(s, "Quin").await;
982839 let ray = user(s, "Ray").await;
@@ -986,27 +843,8 @@ mod tests {
986843 s.subscribe(&quin, &fx.issue_a, SubState::Subscribed, Reason::Author)
987844 .await
988845 .unwrap();
989- // Ray's inbox row whose last actor is Quin, and Quin's own inbox row.
990- s.upsert_notification(
991- &ray,
992- &fx.repo,
993- &fx.issue_a,
994- Reason::Comment,
995- "comment",
996- Some(&quin),
997- )
998- .await
999- .unwrap();
1000- s.upsert_notification(
1001- &quin,
1002- &fx.repo,
1003- &fx.issue_b,
1004- Reason::Comment,
1005- "comment",
1006- Some(&fx.bob),
1007- )
1008- .await
1009- .unwrap();
846+ notify(s, &ray, &fx.repo, &fx.issue_a, Reason::Comment, "comment", Some(&quin)).await;
847+ notify(s, &quin, &fx.repo, &fx.issue_b, Reason::Comment, "comment", Some(&fx.bob)).await;
1010848
1011849 s.delete_user(&quin, &ghost.id).await.unwrap();
1012850
crates/forge-core/src/store/oci.rsmodified+5 -14
@@ -33,13 +33,9 @@ impl Store {
3333 // A link made again starts its grace period over: the sweep keeps a recent link (see
3434 // `oci_sweep_unreferenced`), and the push that made it is still on its way to a manifest.
3535 conn.execute(
36- "DELETE FROM oci_blobs WHERE package_id = ?1 AND digest = ?2",
37- (package_id.to_string(), digest.to_string()),
38- )
39- .await
40- .map_err(db_err)?;
41- conn.execute(
42- "INSERT INTO oci_blobs (package_id, digest, size, created_at) VALUES (?1, ?2, ?3, ?4)",
36+ "INSERT INTO oci_blobs (package_id, digest, size, created_at) VALUES (?1, ?2, ?3, ?4) \
37+ ON CONFLICT(package_id, digest) DO UPDATE SET size = excluded.size, \
38+ created_at = excluded.created_at",
4339 (
4440 package_id.to_string(),
4541 digest.to_string(),
@@ -163,15 +159,10 @@ impl Store {
163159 /// Points `tag` of `package_id` at `manifest_id`, replacing any earlier target.
164160 pub async fn oci_set_tag(&self, package_id: &str, tag: &str, manifest_id: &str) -> Result<()> {
165161 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)?;
172162 conn.execute(
173163 "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",
175166 (
176167 package_id.to_string(),
177168 tag.to_string(),
crates/forge-core/src/store/orgs.rsmodified+1 -14
@@ -7,7 +7,7 @@
77
88 use turso::{Connection, IntoParams};
99
10-use super::issues::finish;
10+use super::finish;
1111 use super::{
1212 REPO_COLS, Store, USER_COLS, col_int, col_text, db_err, fetch_all, fetch_opt, insert_err,
1313 map_repo, map_user, missing_row, new_id, parse_role, role_str,
@@ -1117,17 +1117,4 @@ mod tests {
11171117 store.delete_org(&cyberdyne.id).await.unwrap();
11181118 assert_eq!(store.orgs_for_user(&quinn.id).await.unwrap().len(), 1);
11191119 }
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- }
11331120 }
crates/forge-core/src/store/passkeys.rsmodified+17 -28
@@ -2,7 +2,9 @@
22 //! string; the web crate owns the format. Sign counts live inside that string, so an update
33 //! replaces it.
44
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+};
68 use crate::error::{Error, Result};
79 use crate::time::now_stamp;
810
@@ -27,6 +29,17 @@ pub struct PasskeyRow {
2729
2830 const COLS: &str = "id, user_id, credential_id, passkey, name, created_at, last_used_at";
2931
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+
3043 fn map_row(row: &turso::Row) -> Result<PasskeyRow> {
3144 Ok(PasskeyRow {
3245 id: col_text(row, 0)?,
@@ -68,14 +81,7 @@ impl Store {
6881
6982 pub async fn passkey_count(&self, user_id: &str) -> Result<i64> {
7083 let conn = self.read_conn().await;
71- Ok(fetch_opt(
72- &conn,
73- "SELECT COUNT(*) FROM passkeys WHERE user_id = ?1",
74- (user_id.to_string(),),
75- |row| col_int(row, 0),
76- )
77- .await?
78- .unwrap_or(0))
84+ count_passkeys(&conn, user_id).await
7985 }
8086
8187 /// The passkey with this credential id, whoever owns it.
@@ -100,29 +106,12 @@ impl Store {
100106 ) -> Result<PasskeyRow> {
101107 let name = clean_name(name)?;
102108 let conn = self.inner.conn.lock().await;
103- let held = fetch_opt(
104- &conn,
105- "SELECT COUNT(*) FROM passkeys WHERE user_id = ?1",
106- (user_id.to_string(),),
107- |row| col_int(row, 0),
108- )
109- .await?
110- .unwrap_or(0);
109+ let held = count_passkeys(&conn, user_id).await?;
111110 if usize::try_from(held).unwrap_or(usize::MAX) >= MAX_PASSKEYS {
112111 return Err(Error::Invalid(format!(
113112 "an account can hold at most {MAX_PASSKEYS} passkeys"
114113 )));
115114 }
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- }
126115 let row = PasskeyRow {
127116 id: new_id(),
128117 user_id: user_id.to_string(),
@@ -145,7 +134,7 @@ impl Store {
145134 ),
146135 )
147136 .await
148- .map_err(db_err)?;
137+ .map_err(|e| insert_err(e, "this passkey is already registered"))?;
149138 Ok(row)
150139 }
151140
crates/forge-core/src/store/pulls.rsmodified+28 -128
@@ -1,22 +1,18 @@
1-//! Pull requests and forks. A pull request is an issues row with `kind = 'pull'`, so it shares
2-//! the per-repo numbering with issues, plus a `pull_requests` row. Every multi-row write runs in
3-//! one transaction.
4-
51 use turso::transaction::Transaction;
62 use turso::{Connection, Row};
73
8-use super::issues::{finish, insert_event, map_issue, parse_db};
4+use super::issues::{insert_event, map_issue, parse_db};
95 use super::{
6+ finish,
107 REPO_COLS, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err,
118 map_repo, new_id,
129 };
1310 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};
1512 use crate::model::{Id, Repo};
1613 use crate::pulls::{AutoMerge, MergeStyle, Mergeable, PullRequest};
1714 use crate::time::now_stamp;
1815
19-/// The issue columns (0 to 14) followed by the `pull_requests` columns (15 to 28).
2016 const PULL_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, i.state, i.state_reason, \
2117 i.author_id, i.milestone_id, i.comment_count, i.created_at, i.updated_at, \
2218 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.
2521
2622 const MERGED_MSG: &str = "pull request is already merged";
2723
28-/// Reads `PULL_COLS`.
2924 fn map_pull(row: &Row) -> Result<PullRequest> {
3025 let conflicts_raw = col_text(row, 22)?;
3126 let conflict_files: Vec<String> = serde_json::from_str(&conflicts_raw)
@@ -54,7 +49,6 @@ fn map_pull(row: &Row) -> Result<PullRequest> {
5449 })
5550 }
5651
57-/// The pull request for an issue id, or `NotFound`.
5852 async fn load_pull(conn: &Connection, issue_id: &str) -> Result<PullRequest> {
5953 fetch_opt(
6054 conn,
@@ -69,9 +63,16 @@ async fn load_pull(conn: &Connection, issue_id: &str) -> Result<PullRequest> {
6963 .ok_or(Error::NotFound)
7064 }
7165
72-/// Repo deletion for pull requests. Called from `Store::delete_repo` inside its transaction,
73-/// before the issue rows go. Pull request rows whose head was this repo keep their row, with
74-/// `head_repo_id` set to NULL.
66+fn ensure_open(pull: &PullRequest) -> Result<()> {
67+ if pull.merged_at.is_some() {
68+ return Err(Error::Conflict(MERGED_MSG.into()));
69+ }
70+ if pull.issue.state == IssueState::Closed {
71+ return Err(Error::Conflict("pull request is closed".into()));
72+ }
73+ Ok(())
74+}
75+
7576 pub(super) async fn delete_repo_pull_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {
7677 let id = repo_id.to_string();
7778 tx.execute(
@@ -89,11 +90,7 @@ pub(super) async fn delete_repo_pull_rows(tx: &Transaction<'_>, repo_id: &str) -
8990 Ok(())
9091 }
9192
92-// pull requests
9393 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.
9794 #[allow(clippy::too_many_arguments)]
9895 pub async fn create_pull(
9996 &self,
@@ -112,7 +109,6 @@ impl Store {
112109 let conn = self.inner.conn.lock().await;
113110 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
114111 let outcome: Result<PullRequest> = async {
115- // Checked here, inside the transaction, so two requests cannot both open the pull.
116112 if let Some(number) =
117113 open_pull_number(&tx, repo_id, base_branch, head_repo_id, head_branch).await?
118114 {
@@ -166,44 +162,12 @@ impl Store {
166162 )
167163 .await
168164 .map_err(db_err)?;
169- Ok(PullRequest {
170- issue: Issue {
171- id,
172- repo_id: repo_id.to_string(),
173- number,
174- title,
175- body: body.to_string(),
176- state: IssueState::Open,
177- state_reason: None,
178- author_id: author_id.to_string(),
179- milestone_id: None,
180- comment_count: 0,
181- created_at: now.clone(),
182- updated_at: now,
183- closed_at: None,
184- locked: false,
185- lock_reason: None,
186- },
187- base_branch: base_branch.to_string(),
188- head_repo_id: Some(head_repo_id.to_string()),
189- head_branch: head_branch.to_string(),
190- head_oid: head_oid.to_string(),
191- base_oid: base_oid.to_string(),
192- merge_base: None,
193- mergeable: Mergeable::Unknown,
194- conflict_files: Vec::new(),
195- merged_at: None,
196- merged_by: None,
197- merge_commit: None,
198- draft: false,
199- auto_merge: None,
200- })
165+ load_pull(&tx, &id).await
201166 }
202167 .await;
203168 finish(tx, outcome).await
204169 }
205170
206- /// The pull request with this number in the repo, if any.
207171 pub async fn pull_by_number(&self, repo_id: &str, number: i64) -> Result<Option<PullRequest>> {
208172 let conn = self.read_conn().await;
209173 fetch_opt(
@@ -218,7 +182,6 @@ impl Store {
218182 .await
219183 }
220184
221- /// One page of pull requests, filtered and sorted like `list_issues`, plus the total.
222185 pub async fn list_pulls(
223186 &self,
224187 repo_id: &str,
@@ -227,13 +190,10 @@ impl Store {
227190 self.list_of_kind(repo_id, f, "pull").await
228191 }
229192
230- /// Open and closed pull request counts. Merged pull requests count as closed.
231193 pub async fn pull_counts(&self, repo_id: &str) -> Result<(u64, u64)> {
232194 self.counts_of_kind(repo_id, "pull").await
233195 }
234196
235- /// Open pull requests whose head is this branch of this repo, as
236- /// `(base repo id, number, issue id)`.
237197 pub async fn open_pulls_for_head(
238198 &self,
239199 head_repo_id: &str,
@@ -252,7 +212,6 @@ impl Store {
252212 .await
253213 }
254214
255- /// Open pull requests into this branch of this repo, as `(number, issue id)`.
256215 pub async fn open_pulls_for_base(
257216 &self,
258217 repo_id: &str,
@@ -270,8 +229,6 @@ impl Store {
270229 .await
271230 }
272231
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.
275232 pub async fn pull_refs(&self, repo_id: &str) -> Result<Vec<(Id, i64)>> {
276233 let conn = self.read_conn().await;
277234 fetch_all(
@@ -284,7 +241,6 @@ impl Store {
284241 .await
285242 }
286243
287- /// The pull requests of a repo whose head is `sha`, open or closed, as `(issue id, number)`.
288244 pub async fn pulls_for_head_oid(&self, repo_id: &str, sha: &str) -> Result<Vec<(Id, i64)>> {
289245 let conn = self.read_conn().await;
290246 fetch_all(
@@ -298,27 +254,32 @@ impl Store {
298254 .await
299255 }
300256
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.
303257 pub async fn update_pull_head(&self, issue_id: &str, head_oid: &str) -> Result<()> {
304258 let conn = self.inner.conn.lock().await;
305259 let changed = conn
306260 .execute(
307261 "UPDATE pull_requests SET head_oid = ?2, merge_base = NULL, mergeable = 'unknown', \
308262 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",
310264 (issue_id.to_string(), head_oid.to_string()),
311265 )
312266 .await
313267 .map_err(db_err)?;
314268 if changed == 0 {
315- return Err(Error::NotFound);
269+ let exists = fetch_opt(
270+ &conn,
271+ "SELECT merged_at FROM pull_requests WHERE issue_id = ?1 LIMIT 1",
272+ (issue_id.to_string(),),
273+ |row| col_opt_text(row, 0),
274+ )
275+ .await?;
276+ if exists.is_none() {
277+ return Err(Error::NotFound);
278+ }
316279 }
317280 Ok(())
318281 }
319282
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.
322283 pub async fn set_mergeability(
323284 &self,
324285 issue_id: &str,
@@ -348,7 +309,6 @@ impl Store {
348309 .await
349310 .map_err(db_err)?;
350311 if changed == 0 {
351- // Either the pull request is missing, or it is already merged and therefore final.
352312 let exists = fetch_opt(
353313 &conn,
354314 "SELECT merged_at FROM pull_requests WHERE issue_id = ?1 LIMIT 1",
@@ -363,9 +323,6 @@ impl Store {
363323 Ok(())
364324 }
365325
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.
369326 pub async fn set_pull_draft(
370327 &self,
371328 issue_id: &str,
@@ -376,12 +333,7 @@ impl Store {
376333 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
377334 let outcome: Result<bool> = async {
378335 let current = load_pull(&tx, issue_id).await?;
379- if current.merged_at.is_some() {
380- return Err(Error::Conflict(MERGED_MSG.into()));
381- }
382- if current.issue.state == IssueState::Closed {
383- return Err(Error::Conflict("pull request is closed".into()));
384- }
336+ ensure_open(&current)?;
385337 if current.draft == draft {
386338 return Ok(false);
387339 }
@@ -405,8 +357,6 @@ impl Store {
405357 finish(tx, outcome).await
406358 }
407359
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.
410360 pub async fn enable_auto_merge(
411361 &self,
412362 issue_id: &str,
@@ -417,12 +367,7 @@ impl Store {
417367 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
418368 let outcome: Result<()> = async {
419369 let current = load_pull(&tx, issue_id).await?;
420- if current.merged_at.is_some() {
421- return Err(Error::Conflict(MERGED_MSG.into()));
422- }
423- if current.issue.state == IssueState::Closed {
424- return Err(Error::Conflict("pull request is closed".into()));
425- }
370+ ensure_open(&current)?;
426371 tx.execute(
427372 "UPDATE pull_requests SET auto_merge_style = ?2, auto_merge_user = ?3 \
428373 WHERE issue_id = ?1",
@@ -442,8 +387,6 @@ impl Store {
442387 finish(tx, outcome).await
443388 }
444389
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.
447390 pub async fn disable_auto_merge(
448391 &self,
449392 issue_id: &str,
@@ -472,7 +415,6 @@ impl Store {
472415 finish(tx, outcome).await
473416 }
474417
475- /// Open pull requests of this base repo with auto-merge enabled whose head is `sha`.
476418 pub async fn auto_merge_pulls_for_head(
477419 &self,
478420 repo_id: &str,
@@ -492,9 +434,6 @@ impl Store {
492434 .await
493435 }
494436
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.
498437 pub async fn mark_merged(
499438 &self,
500439 issue_id: &str,
@@ -505,12 +444,7 @@ impl Store {
505444 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
506445 let outcome: Result<()> = async {
507446 let current = load_pull(&tx, issue_id).await?;
508- if current.merged_at.is_some() {
509- return Err(Error::Conflict(MERGED_MSG.into()));
510- }
511- if current.issue.state == IssueState::Closed {
512- return Err(Error::Conflict("pull request is closed".into()));
513- }
447+ ensure_open(&current)?;
514448 let now = now_stamp();
515449 tx.execute(
516450 "UPDATE issues SET state = 'closed', state_reason = 'completed', closed_at = ?2, \
@@ -540,8 +474,6 @@ impl Store {
540474 finish(tx, outcome).await
541475 }
542476
543- /// The number of an open pull request for this base and head, if there is one. Used to avoid
544- /// duplicate pull requests.
545477 pub async fn find_open_pull(
546478 &self,
547479 base_repo: &str,
@@ -554,8 +486,6 @@ impl Store {
554486 }
555487 }
556488
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.
559489 async fn open_pull_number(
560490 conn: &Connection,
561491 base_repo: &str,
@@ -579,11 +509,7 @@ async fn open_pull_number(
579509 .await
580510 }
581511
582-// forks
583512 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.
587513 pub async fn create_fork(&self, source: &Repo, owner_id: &str, name: &str) -> Result<Repo> {
588514 self.insert_repo(
589515 owner_id,
@@ -596,7 +522,6 @@ impl Store {
596522 .await
597523 }
598524
599- /// Repos forked from `repo_id`, by name.
600525 pub async fn list_forks(&self, repo_id: &str) -> Result<Vec<Repo>> {
601526 let conn = self.read_conn().await;
602527 fetch_all(
@@ -611,7 +536,6 @@ impl Store {
611536 .await
612537 }
613538
614- /// How many public forks the repo has (the count of `list_forks` filtered to public).
615539 pub async fn public_fork_count(&self, repo_id: &str) -> Result<u64> {
616540 let conn = self.read_conn().await;
617541 let n = fetch_opt(
@@ -662,7 +586,6 @@ mod tests {
662586 }
663587 }
664588
665- /// A fresh repo owned by Tahinli, so each scenario has its own numbering and counts.
666589 async fn new_repo(fx: &Fixture, name: &str) -> Repo {
667590 fx.store
668591 .create_repo(&fx.tahinli.id, name, "", Visibility::Public, "main")
@@ -678,7 +601,6 @@ mod tests {
678601 }
679602 }
680603
681- /// A pull from `head_repo` into `main` of `repo`.
682604 async fn open_pull(
683605 fx: &Fixture,
684606 repo: &Repo,
@@ -702,13 +624,10 @@ mod tests {
702624 .unwrap()
703625 }
704626
705- // Numbering, counts, head and mergeability updates, merges, drafts,
706- // auto merge and events. Each scenario has its own repo.
707627 #[tokio::test]
708628 async fn pull_scenarios_share_one_store() {
709629 let fx = fixture().await;
710630
711- // Issues and pulls share one numbering; each list shows only its kind.
712631 let repo = new_repo(&fx, "numbering").await;
713632 let issue1 = fx
714633 .store
@@ -765,7 +684,6 @@ mod tests {
765684 "numbering: pull reads back"
766685 );
767686
768- // Counts: a merged pull counts as closed; issue counts are untouched.
769687 let repo = new_repo(&fx, "counts").await;
770688 fx.store
771689 .create_issue(&repo.id, &fx.tahinli.id, "issue", "")
@@ -804,7 +722,6 @@ mod tests {
804722 assert_eq!(total, 1, "counts: open filter total");
805723 assert_eq!(open[0].issue.title, "pull two", "counts: open filter row");
806724
807- // A head push resets mergeability and keeps the base.
808725 let repo = new_repo(&fx, "head").await;
809726 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;
810727 let id = pull.issue.id.clone();
@@ -832,7 +749,6 @@ mod tests {
832749 assert!(after.conflict_files.is_empty(), "head: conflicts cleared");
833750 assert_eq!(after.base_oid, "b".repeat(40), "head: base untouched");
834751
835- // Mergeability round-trips conflict files; Merged is set only by mark_merged.
836752 let repo = new_repo(&fx, "mergeability").await;
837753 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;
838754 let id = pull.issue.id.clone();
@@ -896,7 +812,6 @@ mod tests {
896812 "mergeability: missing pull"
897813 );
898814
899- // Merging closes the pull, records an event, and is final.
900815 let repo = new_repo(&fx, "merge").await;
901816 let issue = fx
902817 .store
@@ -961,7 +876,6 @@ mod tests {
961876 "merge: event actor"
962877 );
963878
964- // A second merge is refused, and a late mergeability recompute is a no-op.
965879 assert!(
966880 matches!(
967881 fx.store.mark_merged(&id, &fx.bob.id, &merge_commit).await,
@@ -981,7 +895,6 @@ mod tests {
981895 .unwrap();
982896 assert_eq!(still.mergeable, Mergeable::Merged, "merge: stays merged");
983897
984- // A second open pull for the same comparison is refused, and takes no number.
985898 let repo = new_repo(&fx, "refuse").await;
986899 let first = open_pull(&fx, &repo, &repo.id, "feature", "first").await;
987900 let second = fx
@@ -1012,7 +925,6 @@ mod tests {
1012925 "refuse: no number taken"
1013926 );
1014927
1015- // find_open_pull matches base and head, and a merged pull stops matching.
1016928 let repo = new_repo(&fx, "find").await;
1017929 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;
1018930 let found = fx
@@ -1051,7 +963,6 @@ mod tests {
1051963 "find: merged pull no longer blocks"
1052964 );
1053965
1054- // Draft flag: round trip, events, list filter and draft numbers.
1055966 let repo = new_repo(&fx, "draft").await;
1056967 let pr = open_pull(&fx, &repo, &repo.id, "feature", "wip").await;
1057968 let _ready = open_pull(&fx, &repo, &repo.id, "other", "ready").await;
@@ -1064,7 +975,6 @@ mod tests {
1064975 .unwrap(),
1065976 "draft: set changes the flag"
1066977 );
1067- // Setting the same value again changes nothing and records no event.
1068978 assert!(
1069979 !fx.store
1070980 .set_pull_draft(&pr.issue.id, Some(&fx.tahinli.id), true)
@@ -1132,7 +1042,6 @@ mod tests {
11321042 "draft: events"
11331043 );
11341044
1135- // Auto merge is cleared by a new head, a draft, or a merge.
11361045 let repo = new_repo(&fx, "auto").await;
11371046 let pr = open_pull(&fx, &repo, &repo.id, "feature", "auto").await;
11381047 let head = "a".repeat(40);
@@ -1233,7 +1142,6 @@ mod tests {
12331142 "auto: merged pull refuses auto merge"
12341143 );
12351144
1236- // Pull event kinds are accepted on pulls.
12371145 let repo = new_repo(&fx, "events").await;
12381146 let pull = open_pull(&fx, &repo, &repo.id, "feature", "t").await;
12391147 for kind in ["head_updated", "base_changed", "head_deleted"] {
@@ -1257,13 +1165,10 @@ mod tests {
12571165 );
12581166 }
12591167
1260- // Forks, fork pulls and repo deletion. Forks are created under names that
1261- // are unique for Bob, and the deletions run last.
12621168 #[tokio::test]
12631169 async fn fork_scenarios_share_one_store() {
12641170 let fx = fixture().await;
12651171
1266- // A fork copies the source settings and lists under its source.
12671172 let fork = fx
12681173 .store
12691174 .create_fork(&fx.repo, &fx.bob.id, "proj-1")
@@ -1286,7 +1191,6 @@ mod tests {
12861191 );
12871192 assert_eq!(fx.repo.fork_of, None, "fork: source is not a fork");
12881193
1289- // fork_of survives a read back through the shared repo queries.
12901194 let read = fx.store.repo_by_id(&fork.id).await.unwrap().unwrap();
12911195 assert_eq!(read.fork_of, Some(fx.repo.id.clone()), "fork: read by id");
12921196 let read = fx
@@ -1319,7 +1223,6 @@ mod tests {
13191223 "fork: name clash is a conflict"
13201224 );
13211225
1322- // A fork of a private repo is private and keeps its branch name.
13231226 let private = fx
13241227 .store
13251228 .create_repo(&fx.tahinli.id, "secret", "", Visibility::Private, "trunk")
@@ -1337,7 +1240,6 @@ mod tests {
13371240 );
13381241 assert_eq!(secret_fork.default_branch, "trunk", "private fork: branch");
13391242
1340- // Open pulls for a head or base skip closed ones; forks feed the head side.
13411243 let source = new_repo(&fx, "fork-src").await;
13421244 let fork = fx
13431245 .store
@@ -1399,8 +1301,6 @@ mod tests {
13991301 "bases: fork pull remains"
14001302 );
14011303
1402- // Deleting a fork detaches its incoming pulls; deleting a source removes
1403- // its pulls and detaches its surviving forks.
14041304 let source = new_repo(&fx, "detach-src").await;
14051305 let fork = fx
14061306 .store
crates/forge-core/src/store/pulls_list_extra.rsmodified+11 -18
@@ -10,40 +10,33 @@ use crate::error::Result;
1010 impl Store {
1111 /// Which of `numbers` are draft pull requests of this repo.
1212 pub async fn draft_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> {
13- if numbers.is_empty() {
14- return Ok(HashSet::new());
15- }
16- let placeholders: Vec<String> = (2..=numbers.len() + 1).map(|i| format!("?{i}")).collect();
17- let sql = format!(
18- "SELECT i.number FROM pull_requests p JOIN issues i ON i.id = p.issue_id \
19- WHERE i.repo_id = ?1 AND i.kind = 'pull' AND p.draft = 1 AND i.number IN ({})",
20- placeholders.join(", ")
21- );
22- let mut params: Vec<Value> = Vec::with_capacity(numbers.len() + 1);
23- params.push(Value::Text(repo_id.to_string()));
24- params.extend(numbers.iter().map(|n| Value::Integer(*n)));
25- let conn = self.read_conn().await;
26- let found = fetch_all(&conn, &sql, params, |row| col_int(row, 0)).await?;
27- Ok(found.into_iter().collect())
13+ self.pull_numbers_where(repo_id, numbers, "p.draft = 1").await
2814 }
2915
3016 /// Which of `numbers` are merged pull requests of this repo. Numbers that are issues, open
3117 /// or closed without a merge are left out.
3218 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>> {
3328 if numbers.is_empty() {
3429 return Ok(HashSet::new());
3530 }
3631 let placeholders: Vec<String> = (2..=numbers.len() + 1).map(|i| format!("?{i}")).collect();
3732 let sql = format!(
3833 "SELECT i.number FROM pull_requests p JOIN issues i ON i.id = p.issue_id \
39- WHERE i.repo_id = ?1 AND i.kind = 'pull' AND p.merged_at IS NOT NULL \
40- AND i.number IN ({})",
34+ WHERE i.repo_id = ?1 AND i.kind = 'pull' AND {predicate} AND i.number IN ({})",
4135 placeholders.join(", ")
4236 );
4337 let mut params: Vec<Value> = Vec::with_capacity(numbers.len() + 1);
4438 params.push(Value::Text(repo_id.to_string()));
4539 params.extend(numbers.iter().map(|n| Value::Integer(*n)));
46-
4740 let conn = self.read_conn().await;
4841 let found = fetch_all(&conn, &sql, params, |row| col_int(row, 0)).await?;
4942 Ok(found.into_iter().collect())
crates/forge-core/src/store/push_recent.rsmodified+6 -6
@@ -89,7 +89,7 @@ impl Store {
8989 #[cfg(test)]
9090 mod tests {
9191 use crate::model::Visibility;
92- use crate::time::{stamp_after, stamp_before};
92+ use crate::time::{stamp_after, stamp_ago};
9393 use std::time::Duration;
9494
9595 use super::*;
@@ -121,9 +121,9 @@ mod tests {
121121 #[tokio::test]
122122 async fn recent_branch_pushes_rules_and_empty_inputs() {
123123 let (_dir, store, tahinli, bob, demo, other) = store_with_repos().await;
124- let since = stamp_before(Duration::from_secs(3600));
125- let older = stamp_before(Duration::from_secs(600));
126- let newer = stamp_before(Duration::from_secs(60));
124+ let since = stamp_ago(Duration::from_secs(3600));
125+ let older = stamp_ago(Duration::from_secs(600));
126+ let newer = stamp_ago(Duration::from_secs(60));
127127
128128 store
129129 .record_push_event_at(&demo, &tahinli, "refs/heads/feature", ZERO, OID, &older)
@@ -155,7 +155,7 @@ mod tests {
155155 "refs/heads/stale",
156156 ZERO,
157157 OID,
158- &stamp_before(Duration::from_secs(7200)),
158+ &stamp_ago(Duration::from_secs(7200)),
159159 )
160160 .await
161161 .unwrap();
@@ -181,7 +181,7 @@ mod tests {
181181 .await
182182 .unwrap();
183183 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)))
185185 .await
186186 .unwrap();
187187 assert!(none.is_empty(), "empty repo list");
crates/forge-core/src/store/reactions.rsmodified+3 -7
@@ -4,17 +4,13 @@
44
55 use std::collections::{BTreeMap, HashMap};
66
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+};
810 use crate::error::{Error, Result};
911 use crate::reactions::{Reaction, ReactionMap, ReactionSummary, ReactionTarget, SUMMARY_USERS};
1012 use crate::time::now_stamp;
1113
12-const IN_CHUNK: usize = 500;
13-
14-fn placeholders(n: usize) -> String {
15- vec!["?"; n].join(",")
16-}
17-
1814 impl Store {
1915 /// Adds the reaction when the user has not put it on the target yet, removes it when they have.
2016 /// 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 @@
22 //! user's repos, a user's stars). Read access is decided in the query with the same rules as
33 //! `authz::authorize` for `Action::Read`, so no per-repo role lookup is needed.
44
5-use turso::Value;
5+use turso::{Connection, Value};
66
77 use super::{
88 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 \
2626 /// The star count of `r`.
2727 const STARS: &str = "(SELECT COUNT(*) FROM stars s WHERE s.repo_id = r.id)";
2828
29-/// The SQL condition under which a signed-in, non-admin viewer may read repo `r`, taking the
30-/// viewer id four times (bind it as four `?` parameters). It mirrors `authorize` for Read:
31-/// public repos, the viewer's own repos, repos where the viewer is a collaborator, and repos of an
32-/// org where the viewer's org role (`Store::org_repo_role`) is some role: an org owner, a member
33-/// when the default repo role is not `none`, or a member of a team covering the repo.
34-pub(crate) const READABLE_BY_VIEWER: &str = "(r.visibility = 'public' OR r.owner_id = ? \
29+/// The SQL condition under which a signed-in, non-admin viewer may read a private repo `r`, taking
30+/// the viewer id four times (bind it as four `?` parameters). It mirrors `authorize` for Read:
31+/// the viewer's own repos, repos where the viewer is a collaborator, and repos of an org where the
32+/// viewer's org role (`Store::org_repo_role`) is some role: an org owner, a member when the default
33+/// repo role is not `none`, or a member of a team covering the repo. Public repos are added by
34+/// the callers.
35+pub(crate) const VIEWER_ACCESS: &str = "(r.owner_id = ? \
3536 OR EXISTS (SELECT 1 FROM collaborators c WHERE c.repo_id = r.id AND c.user_id = ?) \
3637 OR EXISTS (SELECT 1 FROM org_members m WHERE m.org_id = r.owner_id AND m.user_id = ? AND ( \
3738 m.role = 'owner' \
@@ -58,7 +59,7 @@ impl Store {
5859 ) -> Result<(Vec<ListedRepo>, u64)> {
5960 let (from_sql, mut clauses, mut params) = scoped(scope, viewer);
6061 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());
6263 params.push(Value::Text(issues::like_pattern(&q.to_lowercase())));
6364 }
6465 self.page_of_repos(
@@ -80,37 +81,23 @@ impl Store {
8081 ) -> Result<u64> {
8182 let (from_sql, clauses, params) = scoped(scope, viewer);
8283 let conn = self.read_conn().await;
83- let n = fetch_opt(
84- &conn,
85- &format!(
86- "SELECT COUNT(*) FROM {from_sql} WHERE {}",
87- clauses.join(" AND ")
88- ),
89- params,
90- |row| col_int(row, 0),
91- )
92- .await?
93- .unwrap_or(0);
94- Ok(u64::try_from(n).unwrap_or(0))
84+ count_repos(&conn, from_sql, &clauses.join(" AND "), params).await
9585 }
9686
9787 /// Up to `limit` repos the signed-in `viewer` is part of: their own, ones they collaborate on, and
9888 /// org repos they reach. Sorted by owner and name, for the command palette. Other public repos are
9989 /// 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`.
10191 pub async fn list_viewer_repos(&self, viewer: &User, limit: u64) -> Result<Vec<Repo>> {
102- let where_sql = READABLE_BY_VIEWER.replacen("r.visibility = 'public' OR ", "", 1);
103- debug_assert_ne!(where_sql, READABLE_BY_VIEWER, "the public clause moved");
104- let params: Vec<Value> = (0..4).map(|_| Value::Text(viewer.id.clone())).collect();
92+ let mut params: Vec<Value> = (0..4).map(|_| Value::Text(viewer.id.clone())).collect();
10593 let limit = i64::try_from(limit).unwrap_or(i64::MAX);
106- let mut params = params;
10794 params.push(Value::Integer(limit));
10895 let conn = self.read_conn().await;
10996 fetch_all(
11097 &conn,
11198 &format!(
11299 "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 ?"
114101 ),
115102 params,
116103 map_repo,
@@ -138,15 +125,7 @@ impl Store {
138125 let per_page = per_page.clamp(1, 100);
139126
140127 let conn = self.read_conn().await;
141- let total = fetch_opt(
142- &conn,
143- &format!("SELECT COUNT(*) FROM {from_sql} WHERE {where_sql}"),
144- params.clone(),
145- |row| col_int(row, 0),
146- )
147- .await?
148- .unwrap_or(0);
149- let total = u64::try_from(total).unwrap_or(0);
128+ let total = count_repos(&conn, from_sql, where_sql, params.clone()).await?;
150129 let pages = total.div_ceil(per_page).max(1);
151130 let page = page.clamp(1, pages);
152131 let offset = i64::try_from((page - 1) * per_page).unwrap_or(i64::MAX);
@@ -171,11 +150,25 @@ impl Store {
171150 }
172151 }
173152
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+
174170 /// The FROM clause, the WHERE clauses and their parameters for `scope` as seen by `viewer`.
175-fn scoped(
176- scope: RepoScope<'_>,
177- viewer: Option<&User>,
178-) -> (&'static str, Vec<&'static str>, Vec<Value>) {
171+fn scoped(scope: RepoScope<'_>, viewer: Option<&User>) -> (&'static str, Vec<String>, Vec<Value>) {
179172 let (from_sql, scope_id) = match scope {
180173 RepoScope::OwnedBy(id) => ("repos r JOIN users u ON u.id = r.owner_id", id),
181174 RepoScope::StarredBy(id) => (
@@ -184,20 +177,20 @@ fn scoped(
184177 ),
185178 };
186179 let mut clauses = vec![match scope {
187- RepoScope::OwnedBy(_) => "r.owner_id = ?",
188- RepoScope::StarredBy(_) => "st.user_id = ?",
180+ RepoScope::OwnedBy(_) => "r.owner_id = ?".to_owned(),
181+ RepoScope::StarredBy(_) => "st.user_id = ?".to_owned(),
189182 }];
190183 let mut params = vec![Value::Text(scope_id.to_owned())];
191184 match viewer {
192185 // Admins read everything.
193186 Some(user) if user.is_admin => {}
194187 Some(user) => {
195- clauses.push(READABLE_BY_VIEWER);
188+ clauses.push(format!("(r.visibility = 'public' OR {VIEWER_ACCESS})"));
196189 for _ in 0..4 {
197190 params.push(Value::Text(user.id.clone()));
198191 }
199192 }
200- None => clauses.push("r.visibility = 'public'"),
193+ None => clauses.push("r.visibility = 'public'".to_owned()),
201194 }
202195 (from_sql, clauses, params)
203196 }
crates/forge-core/src/store/review_requests.rsmodified+17 -26
@@ -4,7 +4,7 @@
44
55 use std::collections::HashMap;
66
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};
88 use crate::error::Result;
99 use crate::time::now_stamp;
1010
@@ -28,29 +28,20 @@ impl Store {
2828 requested_by: &str,
2929 ) -> Result<bool> {
3030 let conn = self.inner.conn.lock().await;
31- let exists = fetch_opt(
32- &conn,
33- "SELECT 1 FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2",
34- (issue_id.to_string(), reviewer_id.to_string()),
35- |row| col_text(row, 0).or(Ok(String::new())),
36- )
37- .await?;
38- if exists.is_some() {
39- return Ok(false);
40- }
41- conn.execute(
42- "INSERT INTO review_requests (issue_id, reviewer_id, requested_by, created_at) \
43- VALUES (?1, ?2, ?3, ?4)",
44- (
45- issue_id.to_string(),
46- reviewer_id.to_string(),
47- requested_by.to_string(),
48- now_stamp(),
49- ),
50- )
51- .await
52- .map_err(db_err)?;
53- Ok(true)
31+ let n = conn
32+ .execute(
33+ "INSERT INTO review_requests (issue_id, reviewer_id, requested_by, created_at) \
34+ VALUES (?1, ?2, ?3, ?4) ON CONFLICT (issue_id, reviewer_id) DO NOTHING",
35+ (
36+ issue_id.to_string(),
37+ reviewer_id.to_string(),
38+ requested_by.to_string(),
39+ now_stamp(),
40+ ),
41+ )
42+ .await
43+ .map_err(db_err)?;
44+ Ok(n == 1)
5445 }
5546
5647 /// Withdraws a pending request. Returns whether there was one.
@@ -85,8 +76,8 @@ impl Store {
8576 return Ok(out);
8677 }
8778 let conn = self.read_conn().await;
88- for chunk in ids.chunks(500) {
89- let marks = vec!["?"; chunk.len()].join(",");
79+ for chunk in ids.chunks(IN_CHUNK) {
80+ let marks = placeholders(chunk.len());
9081 let rows = fetch_all(
9182 &conn,
9283 &format!(
crates/forge-core/src/store/reviews.rsmodified+6 -34
@@ -2,14 +2,15 @@
22 //! with `kind = 'pull'`). Every multi-row write runs in one transaction. Replies are submitted
33 //! at once through an auto-created `commented` review with no body.
44
5-use std::collections::HashMap;
5+use std::collections::{BTreeMap, HashMap};
66
77 use serde_json::json;
88 use turso::transaction::Transaction;
99 use turso::{Connection, Row};
1010
11-use super::issues::{finish, insert_event, parse_db};
11+use super::issues::{insert_event, parse_db};
1212 use super::{
13+ finish,
1314 Store, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing_row,
1415 new_id,
1516 };
@@ -287,7 +288,6 @@ pub(super) async fn delete_repo_review_rows(tx: &Transaction<'_>, repo_id: &str)
287288 Ok(())
288289 }
289290
290-// reviews
291291 impl Store {
292292 /// The author's pending review on a pull request, if any.
293293 pub async fn pending_review(&self, issue_id: &str, author_id: &str) -> Result<Option<Review>> {
@@ -487,7 +487,6 @@ impl Store {
487487 insert_review(&tx, issue_id, author_id, state, body, head_oid, &now).await?
488488 }
489489 };
490- // A submitted review answers the author's own review request.
491490 tx.execute(
492491 "DELETE FROM review_requests WHERE issue_id = ?1 AND reviewer_id = ?2",
493492 (issue_id.to_string(), author_id.to_string()),
@@ -585,7 +584,6 @@ impl Store {
585584 issue_id: &str,
586585 viewer_id: Option<&str>,
587586 ) -> Result<Vec<Thread>> {
588- // No user id is empty, so `None` matches no pending comment.
589587 let viewer = viewer_id.unwrap_or("").to_string();
590588 let conn = self.read_conn().await;
591589 let comments = fetch_all(
@@ -839,17 +837,14 @@ impl Store {
839837 },
840838 )
841839 .await?;
842- // Rows are in submission order, so the last one per reviewer is the latest.
843- let mut latest: HashMap<String, (String, ReviewState, String)> = HashMap::new();
840+ let mut latest: BTreeMap<String, (String, ReviewState, String)> = BTreeMap::new();
844841 for (author_id, name, state, commit) in rows {
845842 latest.insert(author_id, (name, state, commit));
846843 }
847- let mut out: Vec<(String, String, ReviewState, String)> = latest
844+ Ok(latest
848845 .into_iter()
849846 .map(|(id, (name, state, commit))| (id, name, state, commit))
850- .collect();
851- out.sort_unstable_by(|a, b| a.0.cmp(&b.0));
852- Ok(out)
847+ .collect())
853848 }
854849 }
855850
@@ -965,13 +960,10 @@ mod tests {
965960 .unwrap()
966961 }
967962
968- // Comment, reply, edit, delete, resolve, outdated and relocate. Each
969- // scenario has its own pull request.
970963 #[tokio::test]
971964 async fn comment_scenarios_share_one_store() {
972965 let fx = fixture().await;
973966
974- // A pending comment is visible only to its author and joins one draft.
975967 let issue = new_pull(&fx, "pending").await;
976968 let draft = comment(&fx, &issue, &fx.bob.id, true, "draft").await;
977969 assert!(draft.pending, "pending: draft is pending");
@@ -1010,7 +1002,6 @@ mod tests {
10101002 "pending: same draft review"
10111003 );
10121004
1013- // A single submitted comment creates its own commented review.
10141005 let issue = new_pull(&fx, "single").await;
10151006 let c = comment(&fx, &issue, &fx.bob.id, false, "nit").await;
10161007 assert!(!c.pending, "single: submitted");
@@ -1040,7 +1031,6 @@ mod tests {
10401031 assert_eq!(threads.len(), 1, "single: one thread");
10411032 assert!(threads[0].replies.is_empty(), "single: no replies");
10421033
1043- // A reply copies the root position and needs a submitted root.
10441034 let issue = new_pull(&fx, "reply").await;
10451035 let root = comment(&fx, &issue, &fx.bob.id, false, "question").await;
10461036 let answer = reply(&fx, &issue, &fx.carol.id, &root.id, "answer").await;
@@ -1055,7 +1045,6 @@ mod tests {
10551045 );
10561046 assert!(!answer.pending, "reply: submitted");
10571047
1058- // Each reply is submitted through its own commented review.
10591048 assert_eq!(
10601049 fx.store.list_reviews(&issue).await.unwrap().len(),
10611050 2,
@@ -1089,7 +1078,6 @@ mod tests {
10891078 );
10901079 }
10911080
1092- // Edits record the previous body.
10931081 let issue = new_pull(&fx, "edit").await;
10941082 let c = comment(&fx, &issue, &fx.bob.id, false, "old text").await;
10951083 fx.store
@@ -1135,7 +1123,6 @@ mod tests {
11351123 "edit: missing refused: {err:?}"
11361124 );
11371125
1138- // Deleting a root removes its replies; deleting a reply keeps the root.
11391126 let issue = new_pull(&fx, "delete").await;
11401127 let root = comment(&fx, &issue, &fx.bob.id, false, "root").await;
11411128 let r1 = reply(&fx, &issue, &fx.carol.id, &root.id, "one").await;
@@ -1158,7 +1145,6 @@ mod tests {
11581145 let threads = fx.store.review_threads(&issue, None).await.unwrap();
11591146 assert_eq!(threads.len(), 1, "delete root: other thread remains");
11601147 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.
11621148 let reviews = fx.store.list_reviews(&issue).await.unwrap();
11631149 assert_eq!(reviews.len(), 1, "delete root: emptied reviews removed");
11641150 assert_eq!(
@@ -1186,7 +1172,6 @@ mod tests {
11861172 "delete: missing refused: {err:?}"
11871173 );
11881174
1189- // Resolving records events, and only submitted roots can be resolved.
11901175 let issue = new_pull(&fx, "resolve").await;
11911176 let root = comment(&fx, &issue, &fx.bob.id, false, "fix this").await;
11921177
@@ -1203,7 +1188,6 @@ mod tests {
12031188 .resolved,
12041189 "resolve: resolved"
12051190 );
1206- // Already resolved: no second event.
12071191 fx.store
12081192 .set_thread_resolved(&root.id, &fx.carol.id, true)
12091193 .await
@@ -1266,7 +1250,6 @@ mod tests {
12661250 );
12671251 }
12681252
1269- // Outdated marks only submitted roots.
12701253 let issue = new_pull(&fx, "outdated").await;
12711254 let root = comment(&fx, &issue, &fx.bob.id, false, "a").await;
12721255 let r = reply(&fx, &issue, &fx.carol.id, &root.id, "b").await;
@@ -1289,7 +1272,6 @@ mod tests {
12891272 let draft_thread = own.iter().find(|t| t.root.id == draft.id).unwrap();
12901273 assert!(!draft_thread.root.outdated, "outdated: draft untouched");
12911274
1292- // Relocation moves the root and its replies, keeping the hunk.
12931275 let issue = new_pull(&fx, "relocate").await;
12941276 let root = comment(&fx, &issue, &fx.bob.id, false, "root").await;
12951277 let answer = reply(&fx, &issue, &fx.tahinli.id, &root.id, "answer").await;
@@ -1336,8 +1318,6 @@ mod tests {
13361318 );
13371319 }
13381320
1339- // Submitting, approving, dismissing and discarding reviews. Each scenario
1340- // has its own pull request.
13411321 #[tokio::test]
13421322 async fn review_scenarios_share_one_store() {
13431323 let fx = fixture().await;
@@ -1347,7 +1327,6 @@ mod tests {
13471327 .await
13481328 .unwrap();
13491329
1350- // A pending draft becomes an approved review.
13511330 let issue = new_pull(&fx, "approve").await;
13521331 let draft = comment(&fx, &issue, &fx.bob.id, true, "draft").await;
13531332 let review = fx
@@ -1393,7 +1372,6 @@ mod tests {
13931372 "approve: no requests"
13941373 );
13951374
1396- // The pull request author may comment but not approve or request changes.
13971375 let issue = new_pull(&fx, "author").await;
13981376 for state in [ReviewState::Approved, ReviewState::ChangesRequested] {
13991377 let err = fx
@@ -1427,7 +1405,6 @@ mod tests {
14271405 "author: comment allowed"
14281406 );
14291407
1430- // A commented review needs text unless it carries a pending comment.
14311408 let issue = new_pull(&fx, "empty").await;
14321409 let err = fx
14331410 .store
@@ -1455,7 +1432,6 @@ mod tests {
14551432 "empty: approval without body and comment review with draft"
14561433 );
14571434
1458- // The latest state of each reviewer counts; dismissed reviews do not.
14591435 let issue = new_pull(&fx, "summary").await;
14601436 fx.store
14611437 .submit_review(&issue, &fx.bob.id, ReviewState::Approved, "", &oid('a'))
@@ -1524,7 +1500,6 @@ mod tests {
15241500 "summary: dismissed request gone"
15251501 );
15261502
1527- // Only approvals and change requests can be dismissed, and only once.
15281503 let issue = new_pull(&fx, "dismiss").await;
15291504 let note = comment(&fx, &issue, &fx.bob.id, false, "note").await;
15301505 let err = fx
@@ -1609,7 +1584,6 @@ mod tests {
16091584 "dismiss: twice refused: {err:?}"
16101585 );
16111586
1612- // A review written before the previous-state column has none.
16131587 {
16141588 let conn = fx.store.inner.conn.lock().await;
16151589 conn.execute(
@@ -1623,7 +1597,6 @@ mod tests {
16231597 let legacy = listed.iter().find(|r| r.id == approved.id).unwrap();
16241598 assert_eq!(legacy.dismissed_from, None, "legacy: no previous state");
16251599
1626- // Discarding a draft keeps submitted comments.
16271600 let issue = new_pull(&fx, "discard").await;
16281601 let submitted = comment(&fx, &issue, &fx.bob.id, false, "done").await;
16291602 let d1 = comment(&fx, &issue, &fx.bob.id, true, "d1").await;
@@ -1664,7 +1637,6 @@ mod tests {
16641637 .unwrap();
16651638 assert_eq!(own.len(), 1, "discard: only the submitted thread");
16661639
1667- // Nothing pending left: discarding again is fine.
16681640 fx.store
16691641 .discard_pending_review(&issue, &fx.bob.id)
16701642 .await
crates/forge-core/src/store/server_settings.rsmodified+16 -15
@@ -4,17 +4,13 @@
44
55 use std::collections::BTreeMap;
66
7-use super::{Store, col_text, db_err, fetch_all};
7+use super::{Store, col_text, db_err, fetch_all, finish};
88 use crate::error::{Error, Result};
99 use crate::{secret, server_settings};
1010
1111 impl Store {
1212 fn settings_key(&self) -> Result<[u8; 32]> {
13- self.inner
14- .secret_key
15- .get()
16- .copied()
17- .ok_or_else(|| Error::Crypto("the instance key is not set".into()))
13+ self.secret_key().map(|key| *key)
1814 }
1915
2016 /// Every stored override, with secret values opened. A key this binary does not know is
@@ -59,16 +55,21 @@ impl Store {
5955 prepared.push((key.clone(), stored));
6056 }
6157 let conn = self.inner.conn.lock().await;
62- for (key, stored) in prepared {
63- conn.execute(
64- "INSERT INTO server_settings (key, value, updated_at) VALUES (?1, ?2, ?3) \
65- ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
66- (key, stored, now.clone()),
67- )
68- .await
69- .map_err(db_err)?;
58+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
59+ let outcome: Result<()> = async {
60+ for (key, stored) in prepared {
61+ tx.execute(
62+ "INSERT INTO server_settings (key, value, updated_at) VALUES (?1, ?2, ?3) \
63+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
64+ (key, stored, now.clone()),
65+ )
66+ .await
67+ .map_err(db_err)?;
68+ }
69+ Ok(())
7070 }
71- Ok(())
71+ .await;
72+ finish(tx, outcome).await
7273 }
7374
7475 /// Removes the override of `key`, so the file value (or the default) applies again.
crates/forge-core/src/store/snapshot.rsmodified+11 -12
@@ -33,6 +33,11 @@ fn sql_string_literal(text: &str) -> Result<String> {
3333 Ok(format!("'{}'", text.replace('\'', "''")))
3434 }
3535
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+
3641 impl Store {
3742 /// Writes a consistent copy of the database to `dest` with `VACUUM INTO`, then fsyncs it.
3843 /// `dest` must not exist. The store's connection is held for the whole copy.
@@ -43,10 +48,7 @@ impl Store {
4348 dest.display()
4449 )));
4550 }
46- let text = dest.to_str().ok_or_else(|| {
47- Error::Config(format!("snapshot path is not UTF-8: {}", dest.display()))
48- })?;
49- let sql = format!("VACUUM INTO {}", sql_string_literal(text)?);
51+ let sql = format!("VACUUM INTO {}", sql_string_literal(utf8_path(dest)?)?);
5052 {
5153 let conn = self.inner.conn.lock().await;
5254 conn.execute(&sql, ()).await.map_err(db_err)?;
@@ -74,10 +76,10 @@ impl Store {
7476 /// until every frame is in the main file, and then removes sidecars that are empty. A sidecar that
7577 /// still has bytes is an error. The main file alone is then the whole database.
7678 async fn make_self_contained(dest: &Path) -> Result<()> {
77- let text = dest
78- .to_str()
79- .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", dest.display())))?;
80- let db = Builder::new_local(text).build().await.map_err(db_err)?;
79+ let db = Builder::new_local(utf8_path(dest)?)
80+ .build()
81+ .await
82+ .map_err(db_err)?;
8183 let conn = db.connect().map_err(db_err)?;
8284 // Columns: busy, frames in the log, frames checkpointed.
8385 let status = fetch_all(&conn, "PRAGMA wal_checkpoint(TRUNCATE)", (), |row| {
@@ -116,10 +118,7 @@ async fn make_self_contained(dest: &Path) -> Result<()> {
116118 /// Opens a snapshot read-only with a fresh connection, runs `PRAGMA integrity_check`, checks the
117119 /// migration history and the repo rows, and returns what it found. Any problem is an error.
118120 pub async fn verify_snapshot(path: &Path) -> Result<SnapshotInfo> {
119- let text = path
120- .to_str()
121- .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", path.display())))?;
122- let db = Builder::new_local(text)
121+ let db = Builder::new_local(utf8_path(path)?)
123122 .read_only(true)
124123 .build()
125124 .await
crates/forge-core/src/store/suggest.rsmodified+15 -35
@@ -33,42 +33,22 @@ impl Store {
3333 };
3434 // `like_pattern` wraps in `%..%`; for a prefix match drop the leading one (done above).
3535 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- ];
5136 let conn = self.read_conn().await;
52- let mut out: Vec<String> = Vec::new();
53- for sql in queries {
54- let names = fetch_all(
55- &conn,
56- sql,
57- vec![
58- Value::Text(repo_id.to_string()),
59- Value::Text(pattern.clone()),
60- cap.clone(),
61- ],
62- |row| col_text(row, 0),
63- )
64- .await?;
65- for name in names {
66- if out.len() < limit && !out.contains(&name) {
67- out.push(name);
68- }
69- }
70- }
71- Ok(out)
37+ fetch_all(
38+ &conn,
39+ "SELECT username FROM (SELECT u.username, u.username_folded, CASE \
40+ WHEN u.id = (SELECT owner_id FROM repos WHERE id = ?1) OR \
41+ u.id IN (SELECT user_id FROM collaborators WHERE repo_id = ?1) THEN 0 \
42+ WHEN u.id IN (SELECT author_id FROM issues WHERE repo_id = ?1) OR \
43+ u.id IN (SELECT c.author_id FROM comments c JOIN issues i ON i.id = c.issue_id WHERE i.repo_id = ?1) THEN 1 \
44+ ELSE 2 END AS tier \
45+ FROM users u WHERE u.username_folded LIKE ?2 ESCAPE '\\' AND u.kind = 'user') \
46+ WHERE tier < 2 OR username_folded <> 'ghost' \
47+ ORDER BY tier, username_folded LIMIT ?3",
48+ vec![Value::Text(repo_id.to_string()), Value::Text(pattern), cap],
49+ |row| col_text(row, 0),
50+ )
51+ .await
7252 }
7353
7454 /// 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 @@
33 //! A suspended user keeps their data but cannot sign in. The session, token and SSH key lookups
44 //! in `store/mod.rs` skip a suspended owner, so every transport stops at once.
55
6+use turso::Connection;
7+
68 use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_opt};
79 use crate::error::{Error, Result};
810 use crate::time::now_stamp;
@@ -67,16 +69,7 @@ impl Store {
6769 return Err(Error::Invalid("an organization cannot be suspended".into()));
6870 }
6971 if row.0 {
70- let others = fetch_opt(
71- &conn,
72- "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND id != ?1 \
73- AND id NOT IN (SELECT user_id FROM user_suspensions)",
74- (uid.clone(),),
75- |row| col_int(row, 0),
76- )
77- .await?
78- .unwrap_or(0);
79- if others == 0 {
72+ if other_active_admins(&conn, &uid).await? == 0 {
8073 return Err(Error::Conflict(
8174 "cannot suspend the last active administrator".into(),
8275 ));
@@ -116,14 +109,7 @@ impl Store {
116109 /// Administrators other than `user_id`: zero means `user_id` is the last one and cannot be demoted.
117110 pub async fn other_admin_count(&self, user_id: &str) -> Result<i64> {
118111 let conn = self.read_conn().await;
119- Ok(fetch_opt(
120- &conn,
121- "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND id != ?1 AND kind = 'user'",
122- (user_id.to_string(),),
123- |row| col_int(row, 0),
124- )
125- .await?
126- .unwrap_or(0))
112+ other_active_admins(&conn, user_id).await
127113 }
128114
129115 /// Grants or revokes the admin flag. Revoking is refused for the last administrator.
@@ -144,15 +130,7 @@ impl Store {
144130 ));
145131 }
146132 if !admin {
147- let others = fetch_opt(
148- &conn,
149- "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND id != ?1 AND kind = 'user'",
150- (uid.clone(),),
151- |row| col_int(row, 0),
152- )
153- .await?
154- .unwrap_or(0);
155- if others == 0 {
133+ if other_active_admins(&conn, &uid).await? == 0 {
156134 return Err(Error::Conflict(
157135 "cannot remove the last administrator".into(),
158136 ));
@@ -203,6 +181,18 @@ impl Store {
203181 }
204182 }
205183
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+
206196 #[cfg(test)]
207197 mod tests {
208198 use super::*;
crates/forge-core/src/store/transfers.rsmodified+1 -1
@@ -8,7 +8,7 @@
88
99 use turso::Row;
1010
11-use super::issues::finish;
11+use super::finish;
1212 use super::orgs::OrgMemberRole;
1313 use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt};
1414 use crate::error::{Error, Result};
crates/forge-core/src/store/ui_prefs.rsmodified+44 -77
@@ -4,6 +4,8 @@
44 //! 0042 and 0043). The web layer decides which values it offers; the store only checks that a
55 //! value is well formed, so a new language, accent or base needs no store change.
66
7+use turso::IntoParams;
8+
79 use super::{Store, db_err};
810 use crate::error::{Error, Result};
911
@@ -51,7 +53,7 @@ pub fn valid_language(code: &str) -> bool {
5153
5254 /// True for a short lowercase slug such as `sage` or `rose-2`: 1 to 24 ASCII letters, digits or
5355 /// 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 {
5557 (1..=MAX_ACCENT_LEN).contains(&id.len())
5658 && id
5759 .bytes()
@@ -64,6 +66,15 @@ pub fn valid_sidebar(side: &str) -> bool {
6466 }
6567
6668 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+
6778 /// Sets the user's theme and language. Anything malformed is rejected and nothing is written.
6879 pub async fn set_ui_prefs(&self, user_id: &str, theme: &str, language: &str) -> Result<()> {
6980 if !THEMES.contains(&theme) {
@@ -72,38 +83,24 @@ impl Store {
7283 if !valid_language(language) {
7384 return Err(Error::Invalid(format!("language {language:?}")));
7485 }
75- let conn = self.inner.conn.lock().await;
76- let n = conn
77- .execute(
78- "UPDATE users SET theme = ?2, language = ?3 WHERE id = ?1",
79- (user_id.to_string(), theme.to_string(), language.to_string()),
80- )
81- .await
82- .map_err(db_err)?;
83- if n == 0 {
84- return Err(Error::NotFound);
85- }
86- Ok(())
86+ self.update_user(
87+ "UPDATE users SET theme = ?2, language = ?3 WHERE id = ?1",
88+ (user_id.to_string(), theme.to_string(), language.to_string()),
89+ )
90+ .await
8791 }
8892
8993 /// Sets the user's accent colour id for both themes. A malformed id is rejected and nothing is
9094 /// written.
9195 pub async fn set_accent(&self, user_id: &str, accent: &str) -> Result<()> {
92- if !valid_accent(accent) {
96+ if !valid_slug(accent) {
9397 return Err(Error::Invalid(format!("accent {accent:?}")));
9498 }
95- let conn = self.inner.conn.lock().await;
96- let n = conn
97- .execute(
98- "UPDATE users SET accent = ?2, accent_dark = ?2 WHERE id = ?1",
99- (user_id.to_string(), accent.to_string()),
100- )
101- .await
102- .map_err(db_err)?;
103- if n == 0 {
104- return Err(Error::NotFound);
105- }
106- Ok(())
99+ self.update_user(
100+ "UPDATE users SET accent = ?2, accent_dark = ?2 WHERE id = ?1",
101+ (user_id.to_string(), accent.to_string()),
102+ )
103+ .await
107104 }
108105
109106 /// Sets the four colour choices: the accent and the base for the light theme, then the accent
@@ -117,34 +114,27 @@ impl Store {
117114 base_dark: &str,
118115 ) -> Result<()> {
119116 for accent in [accent_light, accent_dark] {
120- if !valid_accent(accent) {
117+ if !valid_slug(accent) {
121118 return Err(Error::Invalid(format!("accent {accent:?}")));
122119 }
123120 }
124121 for base in [base_light, base_dark] {
125- if !valid_accent(base) {
122+ if !valid_slug(base) {
126123 return Err(Error::Invalid(format!("base {base:?}")));
127124 }
128125 }
129- let conn = self.inner.conn.lock().await;
130- let n = conn
131- .execute(
132- "UPDATE users SET accent = ?2, accent_dark = ?3, base_light = ?4, base_dark = ?5 \
133- WHERE id = ?1",
134- (
135- user_id.to_string(),
136- accent_light.to_string(),
137- accent_dark.to_string(),
138- base_light.to_string(),
139- base_dark.to_string(),
140- ),
141- )
142- .await
143- .map_err(db_err)?;
144- if n == 0 {
145- return Err(Error::NotFound);
146- }
147- Ok(())
126+ self.update_user(
127+ "UPDATE users SET accent = ?2, accent_dark = ?3, base_light = ?4, base_dark = ?5 \
128+ WHERE id = ?1",
129+ (
130+ user_id.to_string(),
131+ accent_light.to_string(),
132+ accent_dark.to_string(),
133+ base_light.to_string(),
134+ base_dark.to_string(),
135+ ),
136+ )
137+ .await
148138 }
149139
150140 /// Sets the side the shell sidebar sits on. Anything but `left` or `right` is rejected and
@@ -153,34 +143,11 @@ impl Store {
153143 if !valid_sidebar(side) {
154144 return Err(Error::Invalid(format!("sidebar {side:?}")));
155145 }
156- let conn = self.inner.conn.lock().await;
157- let n = conn
158- .execute(
159- "UPDATE users SET sidebar_side = ?2 WHERE id = ?1",
160- (user_id.to_string(), side.to_string()),
161- )
162- .await
163- .map_err(db_err)?;
164- if n == 0 {
165- return Err(Error::NotFound);
166- }
167- Ok(())
168- }
169-
170- /// Turns the email copy of notifications on or off for one user (migration 0035).
171- pub async fn set_email_notifications(&self, user_id: &str, on: bool) -> Result<()> {
172- let conn = self.inner.conn.lock().await;
173- let n = conn
174- .execute(
175- "UPDATE users SET email_notifications = ?2 WHERE id = ?1",
176- (user_id.to_string(), i64::from(on)),
177- )
178- .await
179- .map_err(db_err)?;
180- if n == 0 {
181- return Err(Error::NotFound);
182- }
183- Ok(())
146+ self.update_user(
147+ "UPDATE users SET sidebar_side = ?2 WHERE id = ?1",
148+ (user_id.to_string(), side.to_string()),
149+ )
150+ .await
184151 }
185152 }
186153
@@ -208,10 +175,10 @@ mod tests {
208175 let longest = "a".repeat(MAX_ACCENT_LEN);
209176 let too_long = "a".repeat(MAX_ACCENT_LEN + 1);
210177 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}");
212179 }
213180 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}");
215182 }
216183
217184 // Sidebar sides.
crates/forge-core/src/store/user_delete.rsmodified+17 -40
@@ -6,10 +6,10 @@
66 use turso::Connection;
77 use turso::transaction::Transaction;
88
9-use super::issues::finish;
9+use super::finish;
1010 use super::{Store, USER_COLS, col_bool, col_int, col_text, db_err, fetch_opt, map_user, new_id};
1111 use crate::error::{Error, Result};
12-use crate::model::{AccountKind, User};
12+use crate::model::User;
1313 use crate::time::now_stamp;
1414
1515 /// Login name of the reserved ghost account. `names::RESERVED` contains it, so nobody can
@@ -86,7 +86,8 @@ const REASSIGNED: &[(&str, &str, &str, &str)] = &[
8686 "created_by",
8787 "",
8888 ),
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", ""),
9091 (
9192 "notification actors",
9293 "notifications",
@@ -165,41 +166,28 @@ impl Store {
165166 if let Some(user) = existing {
166167 return Ok(user);
167168 }
168- let user = User {
169- id: new_id(),
170- username: GHOST_USERNAME.to_string(),
171- email: None,
172- password_hash: GHOST_PASSWORD_HASH.to_string(),
173- is_admin: false,
174- created_at: now_stamp(),
175- about: String::new(),
176- display_name: None,
177- timezone: "UTC".to_string(),
178- avatar_hash: None,
179- theme: "light".into(),
180- language: "auto".into(),
181- accent: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
182- accent_dark: crate::store::ui_prefs::DEFAULT_ACCENT.into(),
183- base_light: crate::store::ui_prefs::DEFAULT_BASE.into(),
184- base_dark: crate::store::ui_prefs::DEFAULT_BASE.into(),
185- sidebar_side: crate::store::ui_prefs::DEFAULT_SIDEBAR.into(),
186- kind: AccountKind::User,
187- email_notifications: true,
188- };
169+ let id = new_id();
189170 conn.execute(
190171 "INSERT INTO users (id, username, username_folded, email, password_hash, is_admin, created_at, theme) \
191172 VALUES (?1, ?2, ?3, NULL, ?4, 0, ?5, 'light')",
192173 (
193- user.id.clone(),
194- user.username.clone(),
174+ id.clone(),
195175 GHOST_USERNAME.to_string(),
196- user.password_hash.clone(),
197- user.created_at.clone(),
176+ GHOST_USERNAME.to_string(),
177+ GHOST_PASSWORD_HASH.to_string(),
178+ now_stamp(),
198179 ),
199180 )
200181 .await
201182 .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)
203191 }
204192
205193 /// 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<()
318306 let uid = user_id.to_string();
319307 let gid = ghost_id.to_string();
320308
321- // Drafts go first, with their comments and edit history. They are deleted, not moved.
322309 let draft_edits = format!(
323310 "DELETE FROM edit_history WHERE target_kind = 'review_comment' AND target_id IN ({DRAFT_COMMENTS})"
324311 );
@@ -342,7 +329,6 @@ async fn apply(tx: &Transaction<'_>, user_id: &str, ghost_id: &str) -> Result<()
342329 let sql = format!("DELETE FROM {table} WHERE {column} = ?1");
343330 tx.execute(&sql, (uid.clone(),)).await.map_err(db_err)?;
344331 }
345- // Cached commit verdicts that name the deleted account as their signer.
346332 tx.execute(
347333 "DELETE FROM commit_signatures WHERE signer_user_id = ?1",
348334 (uid.clone(),),
@@ -434,7 +420,6 @@ mod tests {
434420 async fn ghost_account_and_refused_deletions() {
435421 let fx = fixture().await;
436422
437- // Scenario: the ghost is created once and cannot log in.
438423 let again = fx.store.ensure_ghost_user().await.unwrap();
439424 assert_eq!(again.id, fx.ghost.id);
440425 assert_eq!(fx.ghost.username, "ghost");
@@ -447,13 +432,11 @@ mod tests {
447432 &fx.ghost.password_hash
448433 ));
449434
450- // Scenario: the ghost itself cannot be deleted.
451435 assert!(matches!(
452436 fx.store.delete_user(&fx.ghost.id, &fx.ghost.id).await,
453437 Err(Error::Forbidden(_))
454438 ));
455439
456- // Scenario: a user who owns a repo is refused and nothing changes.
457440 let err = fx.store.delete_user(&fx.bob.id, &fx.ghost.id).await;
458441 assert!(
459442 matches!(err, Err(Error::Conflict(ref m)) if m == "transfer or delete their repositories first"),
@@ -462,7 +445,6 @@ mod tests {
462445 assert!(fx.store.user_by_id(&fx.bob.id).await.unwrap().is_some());
463446 assert!(fx.store.repo_by_id(&fx.repo_id).await.unwrap().is_some());
464447
465- // Scenario: the last administrator is refused (before a second admin exists).
466448 let err = fx.store.delete_user(&fx.admin.id, &fx.ghost.id).await;
467449 assert!(matches!(err, Err(Error::Conflict(_))), "{err:?}");
468450 assert!(fx.store.user_by_id(&fx.admin.id).await.unwrap().is_some());
@@ -472,7 +454,6 @@ mod tests {
472454 async fn authored_content_moves_to_ghost_and_preview_changes_nothing() {
473455 let fx = fixture().await;
474456
475- // Scenario: authored content moves to the ghost and stays readable.
476457 let issue = fx
477458 .store
478459 .create_issue(&fx.repo_id, &fx.tahinli.id, "Bug", "body")
@@ -483,7 +464,6 @@ mod tests {
483464 .add_comment(&issue.id, &fx.tahinli.id, "a comment")
484465 .await
485466 .unwrap();
486- // A submitted review and a pending draft, both by Tahinli on the issue row.
487467 {
488468 let conn = fx.store.inner.conn.lock().await;
489469 for (id, state) in [("rev-done", "commented"), ("rev-draft", "pending")] {
@@ -545,7 +525,6 @@ mod tests {
545525 );
546526 assert!(fx.store.user_by_id(&fx.tahinli.id).await.unwrap().is_none());
547527
548- // Scenario: a deletion preview reports counts and changes nothing.
549528 let second_admin = fx
550529 .store
551530 .create_user("Carol", None, "hash", true)
@@ -631,7 +610,6 @@ mod tests {
631610 #[tokio::test]
632611 async fn discussions_and_comments_move_to_ghost() {
633612 let fx = fixture().await;
634- // Tahinli's discussion in Bob's repo, with Bob's reply: Tahinli's inbox row goes with her.
635613 let mine = fx
636614 .store
637615 .create_discussion(
@@ -652,7 +630,6 @@ mod tests {
652630 .add_discussion_comment(&mine.id, &fx.bob.id, None, "a reply", false)
653631 .await
654632 .unwrap();
655- // Bob's discussion that Tahinli commented on: Bob's inbox row names Tahinli as last actor.
656633 let theirs = fx
657634 .store
658635 .create_discussion(
crates/forge-core/src/store/web_push.rsmodified+2 -2
@@ -7,7 +7,7 @@ use crate::time::now_stamp;
77
88 /// Most devices one account may hold. A subscription past this is refused, so a client cannot
99 /// grow the table without bound.
10-pub const MAX_DEVICES: usize = 20;
10+pub const MAX_DEVICES: i64 = 20;
1111
1212 /// One browser or installed app that receives pushes for `user_id`.
1313 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -118,7 +118,7 @@ impl Store {
118118 )
119119 .await?
120120 .unwrap_or(0);
121- if usize::try_from(held).unwrap_or(usize::MAX) >= MAX_DEVICES {
121+ if held >= MAX_DEVICES {
122122 return Err(Error::Invalid(format!(
123123 "an account can enable push on at most {MAX_DEVICES} devices"
124124 )));
crates/forge-core/src/store/webhooks.rsmodified+63 -94
@@ -9,8 +9,8 @@ use std::time::Duration;
99 use turso::{Connection, Row, Value};
1010
1111 use super::{
12- Store, col_blob, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt,
13- finish, new_id,
12+ Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all,
13+ fetch_opt, finish, new_id, opt_int_value, opt_text,
1414 };
1515 use crate::error::{Error, Result};
1616 use crate::secret;
@@ -68,13 +68,13 @@ fn map_delivery(row: &Row) -> Result<Delivery> {
6868 attempt: u32::try_from(col_int(row, 8)?)
6969 .map_err(|_| Error::Database("negative delivery attempt count".into()))?,
7070 next_attempt_at: col_opt_text(row, 9)?,
71- response_status: opt_int(row, 10)?
71+ response_status: col_opt_int(row, 10)?
7272 .map(|n| u16::try_from(n).map_err(|_| Error::Database("bad response status".into())))
7373 .transpose()?,
7474 response_headers: col_opt_text(row, 11)?,
7575 response_body: col_opt_text(row, 12)?,
7676 error: col_opt_text(row, 13)?,
77- duration_ms: opt_int(row, 14)?
77+ duration_ms: col_opt_int(row, 14)?
7878 .map(|n| u64::try_from(n).map_err(|_| Error::Database("bad duration".into())))
7979 .transpose()?,
8080 created_at: col_text(row, 15)?,
@@ -82,15 +82,6 @@ fn map_delivery(row: &Row) -> Result<Delivery> {
8282 })
8383 }
8484
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-
9485 /// Headers the worker adds at send time. They are never kept in the stored request headers, so a
9586 /// redelivery gets a fresh GUID and signature. Keep this list in step with `WORKER_HEADERS` in
9687 /// forge-web's webhook worker.
@@ -112,14 +103,6 @@ fn strip_worker_headers(raw: &str) -> String {
112103 }
113104 }
114105
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-
123106 /// JSON array of event names, in the order given.
124107 fn events_json(events: &[WebhookEvent]) -> String {
125108 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<()> {
172155 Ok(())
173156 }
174157
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+
175187 /// Most webhooks one repository can have.
176188 pub const MAX_WEBHOOKS: i64 = 20;
177189
@@ -214,7 +226,7 @@ impl Store {
214226 "SELECT COUNT(*) FROM webhooks WHERE repo_id = ?1",
215227 repo_id,
216228 MAX_WEBHOOKS,
217- "a repository can have at most 20 webhooks",
229+ &format!("a repository can have at most {MAX_WEBHOOKS} webhooks"),
218230 )
219231 .await?;
220232 conn.execute(
@@ -240,38 +252,22 @@ impl Store {
240252 let now = now_stamp();
241253 {
242254 let conn = self.inner.conn.lock().await;
243- let n = match secret_sealed {
244- Some(sealed) => {
245- conn.execute(
246- "UPDATE webhooks SET url = ?2, secret_sealed = ?3, events = ?4, \
247- active = ?5, updated_at = ?6 WHERE id = ?1",
248- vec![
249- Value::Text(id.to_string()),
250- Value::Text(url.to_string()),
251- Value::Blob(sealed.to_vec()),
252- Value::Text(events_json(events)),
253- Value::Integer(i64::from(active)),
254- Value::Text(now),
255- ],
256- )
257- .await
258- }
259- None => {
260- conn.execute(
261- "UPDATE webhooks SET url = ?2, events = ?3, active = ?4, updated_at = ?5 \
262- WHERE id = ?1",
263- vec![
264- Value::Text(id.to_string()),
265- Value::Text(url.to_string()),
266- Value::Text(events_json(events)),
267- Value::Integer(i64::from(active)),
268- Value::Text(now),
269- ],
270- )
271- .await
272- }
273- }
274- .map_err(db_err)?;
255+ let sealed = secret_sealed.map_or(Value::Null, |s| Value::Blob(s.to_vec()));
256+ let n = conn
257+ .execute(
258+ "UPDATE webhooks SET url = ?2, secret_sealed = COALESCE(?3, secret_sealed), \
259+ events = ?4, active = ?5, updated_at = ?6 WHERE id = ?1",
260+ vec![
261+ Value::Text(id.to_string()),
262+ Value::Text(url.to_string()),
263+ sealed,
264+ Value::Text(events_json(events)),
265+ Value::Integer(i64::from(active)),
266+ Value::Text(now),
267+ ],
268+ )
269+ .await
270+ .map_err(db_err)?;
275271 if n == 0 {
276272 return Err(Error::NotFound);
277273 }
@@ -391,26 +387,13 @@ impl Store {
391387 headers_json: &str,
392388 body: &str,
393389 ) -> Result<Delivery> {
394- let now = now_stamp();
395- let delivery = Delivery {
396- id: new_id(),
397- hook_id: hook_id.to_string(),
398- guid: new_guid(),
390+ let delivery = pending_delivery(
391+ hook_id,
399392 event,
400- action: action.to_string(),
401- request_headers: headers_json.to_string(),
402- request_body: body.to_string(),
403- state: DeliveryState::Pending,
404- attempt: 0,
405- next_attempt_at: Some(now.clone()),
406- response_status: None,
407- response_headers: None,
408- response_body: None,
409- error: None,
410- duration_ms: None,
411- created_at: now,
412- delivered_at: None,
413- };
393+ action.to_string(),
394+ headers_json.to_string(),
395+ body.to_string(),
396+ );
414397 let conn = self.inner.conn.lock().await;
415398 insert_delivery(&conn, &delivery).await?;
416399 Ok(delivery)
@@ -570,27 +553,13 @@ impl Store {
570553 )
571554 .await?
572555 .ok_or(Error::NotFound)?;
573- let guid = new_guid();
574- let now = now_stamp();
575- let copy = Delivery {
576- id: new_id(),
577- hook_id: original.hook_id,
578- guid: guid.clone(),
579- event: original.event,
580- action: original.action,
581- request_headers: strip_worker_headers(&original.request_headers),
582- request_body: original.request_body,
583- state: DeliveryState::Pending,
584- attempt: 0,
585- next_attempt_at: Some(now.clone()),
586- response_status: None,
587- response_headers: None,
588- response_body: None,
589- error: None,
590- duration_ms: None,
591- created_at: now,
592- delivered_at: None,
593- };
556+ let copy = pending_delivery(
557+ &original.hook_id,
558+ original.event,
559+ original.action,
560+ strip_worker_headers(&original.request_headers),
561+ original.request_body,
562+ );
594563 insert_delivery(&conn, &copy).await?;
595564 Ok(copy)
596565 }
crates/forge-core/src/suggestions.rsmodified+2 -1
@@ -99,7 +99,7 @@ pub fn replace_line(
9999 let replacement: Vec<&str> = replacement.iter().map(String::as_str).collect();
100100 lines.splice(index..=index, replacement);
101101 let mut out = lines.join("\n");
102- if ends_with_newline {
102+ if ends_with_newline && !lines.is_empty() {
103103 out.push('\n');
104104 }
105105 Ok(out)
@@ -168,6 +168,7 @@ mod tests {
168168 ("a\nb\nc\n", 2, "b", &["B"], Ok("a\nB\nc\n")),
169169 ("a\nb", 2, "b", &["b1", "b2"], Ok("a\nb1\nb2")),
170170 ("a\nb\nc\n", 2, "b", &[], Ok("a\nc\n")),
171+ ("a\n", 1, "a", &[], Ok("")),
171172 ("a\nb\n", 2, "old", &["x"], Err(ApplyError::Changed)),
172173 ("a\nb\n", 3, "b", &["x"], Err(ApplyError::OutOfRange)),
173174 ("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 {
2626 format_stamp(OffsetDateTime::now_utc().saturating_add(delta))
2727 }
2828
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-
3629 /// The stamp for `now - ago`, in the same format as [`now_stamp`]. Saturates at the minimum
3730 /// representable time instead of panicking.
3831 pub fn stamp_ago(ago: Duration) -> String {
@@ -75,6 +68,7 @@ mod tests {
7568 #[test]
7669 fn stamps_sort_lexicographically_in_time_order() {
7770 let a = now_stamp();
71+ assert!(is_valid_stamp(&a), "bad stamp: {a}");
7872 let b = stamp_after(Duration::from_secs(3600));
7973 assert!(is_valid_stamp(&b), "bad stamp: {b}");
8074 assert!(a < b);
crates/forge-core/src/token.rsmodified+5 -1
@@ -26,8 +26,12 @@ pub fn random_readable(len: usize) -> String {
2626 .collect()
2727 }
2828
29+pub fn random_b64url() -> String {
30+ BASE64_URL_SAFE_NO_PAD.encode(random_32())
31+}
32+
2933 pub fn generate_token() -> String {
30- format!("forge_{}", BASE64_URL_SAFE_NO_PAD.encode(random_32()))
34+ format!("forge_{}", random_b64url())
3135 }
3236
3337 /// 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() {
101101 1
102102 );
103103
104- // Bob is involved in three entries: his own key, the reset of him, and nothing else.
105104 let involving = AuditFilter {
106105 involving_user: Some(bob.id.clone()),
107106 ..Default::default()
crates/forge-core/tests/integration/main.rsmodified+0 -2
@@ -1,9 +1,7 @@
11 //! Store integration tests for forge-core, built as one test binary.
22
3-#[allow(dead_code)]
43 mod common;
54
65 mod audit_store;
7-mod read_pool;
86 mod stars_store;
97 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-
31 use forge_core::Visibility;
42 use forge_core::store::RepoSort;
53 use forge_core::store::migrate::{MIGRATIONS, migrate};
@@ -22,19 +20,16 @@ async fn star_and_unstar_round_trip_with_count() {
2220
2321 assert_eq!(store.star_count(&repo.id).await.unwrap(), 0);
2422 store.star(&bob.id, &repo.id).await.unwrap();
25- store.star(&bob.id, &repo.id).await.unwrap(); // second star is a no-op
23+ store.star(&bob.id, &repo.id).await.unwrap();
2624 store.star(&tahinli.id, &repo.id).await.unwrap();
2725 assert_eq!(store.star_count(&repo.id).await.unwrap(), 2);
2826 assert!(store.is_starred(&bob.id, &repo.id).await.unwrap());
2927
3028 store.unstar(&bob.id, &repo.id).await.unwrap();
31- store.unstar(&bob.id, &repo.id).await.unwrap(); // removing twice is fine
29+ store.unstar(&bob.id, &repo.id).await.unwrap();
3230 assert!(!store.is_starred(&bob.id, &repo.id).await.unwrap());
31+ assert!(store.is_starred(&tahinli.id, &repo.id).await.unwrap());
3332 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);
3833 }
3934
4035 #[tokio::test]
@@ -53,7 +48,7 @@ async fn delete_repo_removes_its_stars() {
5348
5449 store.delete_repo(&repo.id).await.unwrap();
5550
56- assert!(store.starred_repos(&tahinli.id).await.unwrap().is_empty());
51+ assert!(!store.is_starred(&tahinli.id, &repo.id).await.unwrap());
5752 assert_eq!(store.star_count(&repo.id).await.unwrap(), 0);
5853 }
5954
@@ -96,7 +91,6 @@ async fn public_listing_hides_private_repos_and_matches_literally() {
9691 let names: Vec<&str> = all.iter().map(|(r, _, _)| r.name.as_str()).collect();
9792 assert_eq!(names, vec!["100%_done", "other", "tools"]);
9893
99- // `%` and `_` are literal: "%" alone matches only the repo whose name contains one.
10094 let (hits, total) = store
10195 .list_public_repos(Some("%"), RepoSort::Name, 1, 30)
10296 .await
@@ -108,14 +102,12 @@ async fn public_listing_hides_private_repos_and_matches_literally() {
108102 .await
109103 .unwrap();
110104 assert_eq!(hits.len(), 1);
111- // A backslash matches a literal backslash in the description.
112105 let (hits, _) = store
113106 .list_public_repos(Some("\\"), RepoSort::Name, 1, 30)
114107 .await
115108 .unwrap();
116109 assert_eq!(hits.len(), 1);
117110 assert_eq!(hits[0].0.name, "other");
118- // Private repos never match, even by exact name.
119111 let (hits, _) = store
120112 .list_public_repos(Some("secret"), RepoSort::Name, 1, 30)
121113 .await
@@ -179,7 +171,6 @@ async fn recently_updated_uses_latest_push_over_creation() {
179171 .create_repo(&tahinli.id, "newer", "", Visibility::Public, "main")
180172 .await
181173 .unwrap();
182- // Only "older" gets a push, so it is the most recently updated.
183174 store
184175 .record_push_event(&older.id, &tahinli.id, "refs/heads/main", "0", "1", "https")
185176 .await
@@ -240,7 +231,6 @@ async fn database_at_0004_gains_stars_table() {
240231 )
241232 .await
242233 .unwrap();
243- // Store::open turns foreign keys on; this raw connection must do it too.
244234 conn.execute_batch("PRAGMA foreign_keys = ON")
245235 .await
246236 .unwrap();
crates/forge-core/tests/integration/store_basic.rsmodified+4 -20
@@ -1,6 +1,6 @@
11 //! Store round-trip tests against a real turso database file in a temp directory.
22
3-use forge_core::time::{now_stamp, stamp_after};
3+use forge_core::time::{stamp_after, stamp_ago};
44 use forge_core::{Error, Role, Visibility};
55 use std::time::Duration;
66
@@ -117,14 +117,12 @@ async fn sessions_respect_expiry() {
117117 &user.id,
118118 "hash-dead",
119119 "csrf-dead",
120- &stamp_after(Duration::from_secs(0)),
120+ &stamp_ago(Duration::from_secs(1)),
121121 None,
122122 None,
123123 )
124124 .await
125125 .unwrap();
126- // Make sure the "expired" session is strictly in the past.
127- tokio::time::sleep(Duration::from_millis(5)).await;
128126
129127 let found = store
130128 .session_by_token_hash("hash-live")
@@ -186,10 +184,7 @@ async fn ssh_key_exact_blob_lookup() {
186184 .await
187185 .unwrap();
188186
189- let blob: Vec<u8> = vec![
190- 0, 0, 0, 11, b's', b's', b'h', b'-', b'e', b'd', b'2', b'5', b'5', b'1', b'9', 0, 0, 0, 32,
191- 1, 2, 3,
192- ];
187+ let blob = b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20\x01\x02\x03".to_vec();
193188 let key = store
194189 .add_ssh_key(&user.id, "laptop", "ssh-ed25519", &blob, "SHA256:abc")
195190 .await
@@ -257,11 +252,10 @@ async fn access_token_create_lookup_and_expiry() {
257252 "old",
258253 "tok-old",
259254 &[],
260- Some(&stamp_after(Duration::from_secs(0))),
255+ Some(&stamp_ago(Duration::from_secs(1))),
261256 )
262257 .await
263258 .unwrap();
264- tokio::time::sleep(Duration::from_millis(5)).await;
265259
266260 let found = store
267261 .token_by_hash("tok-live")
@@ -487,16 +481,6 @@ async fn reopening_keeps_data_and_migrations_are_idempotent() {
487481 );
488482 }
489483
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-
500484 #[tokio::test]
501485 async fn create_first_admin_only_inserts_into_empty_table() {
502486 let dir = tempfile::tempdir().unwrap();
crates/forge-git/src/backup.rsmodified+8 -14
@@ -8,7 +8,7 @@ use sha2::{Digest, Sha256};
88 use crate::command::{GitCommand, GitEnv};
99 use crate::error::{Error, Result};
1010
11-const REFS_FORMAT: &str = "--format=%(objectname) %(refname)";
11+pub const REFS_FORMAT: &str = "--format=%(objectname) %(refname)";
1212
1313 fn path_str(p: &Path) -> Result<&str> {
1414 p.to_str()
@@ -48,11 +48,11 @@ pub fn refs_checksum_of_listing(listing: &[u8]) -> String {
4848 hex::encode(hasher.finalize())
4949 }
5050
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)`
5252 /// 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.
5454 /// 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> {
5656 if std::fs::symlink_metadata(out).is_ok() {
5757 return Err(Error::InvalidInput(format!(
5858 "bundle target already exists: {}",
@@ -64,7 +64,7 @@ pub async fn bundle_create(env: &GitEnv, repo: &Path, out: &Path) -> Result<Opti
6464 .iter()
6565 .all(|b| b.is_ascii_whitespace())
6666 {
67- return Ok(None);
67+ return Ok(false);
6868 }
6969 GitCommand::new(env, "bundle")
7070 .git_dir(repo)
@@ -74,7 +74,7 @@ pub async fn bundle_create(env: &GitEnv, repo: &Path, out: &Path) -> Result<Opti
7474 .status()
7575 .await?;
7676 set_private_mode(out)?;
77- Ok(Some(()))
77+ Ok(true)
7878 }
7979
8080 fn set_private_mode(path: &Path) -> Result<()> {
@@ -163,10 +163,7 @@ mod tests {
163163 .await
164164 .expect("init");
165165 let out = dir.path().join("empty.bundle");
166- assert_eq!(
167- bundle_create(&env, &bare, &out).await.expect("create"),
168- None
169- );
166+ assert!(!bundle_create(&env, &bare, &out).await.expect("create"));
170167 assert!(!out.exists(), "nothing is written for an empty repo");
171168 assert_eq!(
172169 refs_checksum(&env, &bare).await.expect("checksum"),
@@ -180,10 +177,7 @@ mod tests {
180177 let env = env(dir.path());
181178 let git_dir = repo_with_refs(dir.path());
182179 let out = dir.path().join("r.bundle");
183- assert_eq!(
184- bundle_create(&env, &git_dir, &out).await.expect("create"),
185- Some(())
186- );
180+ assert!(bundle_create(&env, &git_dir, &out).await.expect("create"));
187181 let scratch = dir.path().join("scratch.git");
188182 crate::repo::init_bare(&env, &scratch, "main")
189183 .await
crates/forge-git/src/blame.rsmodified+1 -3
@@ -41,9 +41,7 @@ pub struct Blame {
4141 fn is_header(line: &str) -> Option<(&str, u32)> {
4242 let mut parts = line.split(' ');
4343 let oid = parts.next()?;
44- if !(oid.len() == 40 || oid.len() == 64) || !oid.bytes().all(|b| b.is_ascii_hexdigit()) {
45- return None;
46- }
44+ validate_oid(oid).ok()?;
4745 let _orig = parts.next()?.parse::<u32>().ok()?;
4846 let fin = parts.next()?.parse::<u32>().ok()?;
4947 Some((oid, fin))
crates/forge-git/src/branches.rsmodified+1 -5
@@ -4,7 +4,7 @@ use std::path::Path;
44
55 use crate::command::GitEnv;
66 use crate::error::{Error, Result};
7-use crate::history::{git, validate_oid};
7+use crate::history::{git, validate_oid, zero_oid};
88 use crate::pulls::{delete_ref_cas, update_ref_cas};
99
1010 /// `(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
3131 }
3232 }
3333
34-fn zero_oid(like: &str) -> String {
35- "0".repeat(like.len())
36-}
37-
3834 /// Creates `refs/heads/<name>` at `oid`. Fails when the branch exists already.
3935 pub async fn create_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> {
4036 validate_oid(oid)?;
crates/forge-git/src/browse.rsmodified+15 -10
@@ -350,6 +350,16 @@ fn map_kind(kind: GixEntryKind) -> EntryKind {
350350 }
351351 }
352352
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+
353363 /// Tree object for `commit` at `path` ("" is the root). Ok(None) if the commit is missing or the
354364 /// path does not exist. A path that is a blob also yields None.
355365 fn tree_at<'r>(
@@ -357,15 +367,12 @@ fn tree_at<'r>(
357367 commit: &str,
358368 path: &str,
359369 ) -> Result<Option<gix::Tree<'r>>> {
360- let id = parse_oid(commit)?;
361- if !is_commit(repo, id)? {
370+ let Some(mut root) = commit_root(repo, commit)? else {
362371 return Ok(None);
363- }
364- let root = repo.find_commit(id).map_err(gerr)?.tree().map_err(gerr)?;
372+ };
365373 if path.is_empty() {
366374 return Ok(Some(root));
367375 }
368- let mut root = root;
369376 let Some(entry) = root.peel_to_entry_by_path(path).map_err(gerr)? else {
370377 return Ok(None);
371378 };
@@ -439,11 +446,9 @@ fn blob_at(
439446 return Ok(None);
440447 }
441448 let repo = open(repo)?;
442- let id = parse_oid(commit)?;
443- if !is_commit(&repo, id)? {
449+ let Some(mut root) = commit_root(&repo, commit)? else {
444450 return Ok(None);
445- }
446- let mut root = repo.find_commit(id).map_err(gerr)?.tree().map_err(gerr)?;
451+ };
447452 let Some(entry) = root.peel_to_entry_by_path(path).map_err(gerr)? else {
448453 return Ok(None);
449454 };
@@ -496,7 +501,7 @@ pub fn read_text_blob(
496501 let Some(blob) = blob_at(repo, commit, path, max_bytes, true)? else {
497502 return Ok(None);
498503 };
499- if matches!(blob.kind, EntryKind::Tree | EntryKind::Submodule) || blob.is_binary {
504+ if blob.kind == EntryKind::Submodule || blob.is_binary {
500505 return Ok(None);
501506 }
502507 Ok(String::from_utf8(blob.data).ok())
crates/forge-git/src/command.rsmodified+9 -6
@@ -256,16 +256,19 @@ impl GitCommand {
256256 }
257257 }
258258
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+
259267 fn check_status(subcommand: &str, out: &Output) -> Result<()> {
260268 if out.status.success() {
261269 return Ok(());
262270 }
263- let stderr = String::from_utf8_lossy(&out.stderr);
264- Err(Error::Failed(format!(
265- "git {subcommand} exited with {}: {}",
266- out.status,
267- stderr.trim()
268- )))
271+ Err(failed(subcommand, out))
269272 }
270273
271274 #[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-
41 use std::collections::{HashMap, HashSet};
52 use std::path::Path;
63 use std::process::Stdio;
@@ -11,16 +8,13 @@ use crate::browse::{self, CommitInfo};
118 use crate::command::{GitCommand, GitEnv, ObjectSource};
129 use crate::error::{Error, Result};
1310
14-/// Byte cap on any single git output stream read by this module.
1511 const OUTPUT_CAP: usize = 20 * 1024 * 1024;
1612 const EMPTY_TREE_SHA1: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
1713 const EMPTY_TREE_SHA256: &str = "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321";
1814
19-/// Record start (`%x1e`), field separator (`%x1f`), end of fields (`%x1d`).
2015 const REC: u8 = 0x1e;
2116 const FIELD: u8 = 0x1f;
2217 const END: u8 = 0x1d;
23-/// Commit fields: oid, parents, author name/email/time, committer name/email/time, summary, message.
2418 const COMMIT_FORMAT: &str =
2519 "--format=%x1e%H%x1f%P%x1f%an%x1f%ae%x1f%at%x1f%cn%x1f%ce%x1f%ct%x1f%s%x1f%B%x1d";
2620
@@ -87,8 +81,6 @@ pub struct CommitDiff {
8781 pub truncated_files: bool,
8882 }
8983
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.
9284 pub(crate) fn git(env: &GitEnv, subcommand: &'static str) -> GitCommand {
9385 GitCommand::new(env, subcommand)
9486 .env("GIT_CONFIG_COUNT", "1")
@@ -96,7 +88,6 @@ pub(crate) fn git(env: &GitEnv, subcommand: &'static str) -> GitCommand {
9688 .env("GIT_CONFIG_VALUE_0", "false")
9789 }
9890
99-/// Accepts only a full SHA-1 (40) or SHA-256 (64) hex object id.
10091 pub(crate) fn validate_oid(oid: &str) -> Result<()> {
10192 let len_ok = oid.len() == 40 || oid.len() == 64;
10293 if len_ok && oid.bytes().all(|b| b.is_ascii_hexdigit()) {
@@ -108,12 +99,14 @@ pub(crate) fn validate_oid(oid: &str) -> Result<()> {
10899 }
109100 }
110101
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+
112106 fn literal_spec(path: &str) -> String {
113107 format!(":(literal){path}")
114108 }
115109
116-/// Accepts `[A-Za-z0-9._-]+`, excluding `.` and `..` and a leading `-`.
117110 fn validate_prefix(prefix: &str) -> Result<()> {
118111 let charset_ok = !prefix.is_empty()
119112 && prefix
@@ -127,11 +120,8 @@ fn validate_prefix(prefix: &str) -> Result<()> {
127120 Ok(())
128121 }
129122
130-/// Longest kept head of a child's output pipe, in bytes.
131123 const PIPE_HEAD_CAP: u64 = 64 * 1024;
132124
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.
135125 pub(crate) async fn read_pipe_head(mut pipe: impl AsyncRead + Unpin) -> Vec<u8> {
136126 let mut kept = Vec::new();
137127 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>
139129 kept
140130 }
141131
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.
145132 async fn for_each_chunk(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Result<bool> {
146133 let mut command = cmd.into_tokio();
147134 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
186173 Ok(eof)
187174 }
188175
189-/// Reads the whole stdout up to [`OUTPUT_CAP`]. The flag is `false` when the cap cut it short.
190176 pub(crate) async fn read_capped(cmd: GitCommand) -> Result<(Vec<u8>, bool)> {
191177 let mut buf = Vec::new();
192178 let complete = for_each_chunk(cmd, |c| {
@@ -197,9 +183,6 @@ pub(crate) async fn read_capped(cmd: GitCommand) -> Result<(Vec<u8>, bool)> {
197183 Ok((buf, complete))
198184 }
199185
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.
203186 async fn for_each_nul_record(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Result<bool> {
204187 let mut carry = Vec::new();
205188 for_each_chunk(cmd, |chunk| {
@@ -219,8 +202,6 @@ async fn for_each_nul_record(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool)
219202 .await
220203 }
221204
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).
224205 fn parse_record(rec: &[u8]) -> Option<(CommitInfo, &[u8])> {
225206 let end = rec.iter().position(|&b| b == END)?;
226207 let fields = &rec[..end];
@@ -260,7 +241,6 @@ fn parse_record(rec: &[u8]) -> Option<(CommitInfo, &[u8])> {
260241 Some((info, rest))
261242 }
262243
263-/// Commit history for `commit`, optionally limited to `path`, newest first.
264244 pub async fn log(
265245 env: &GitEnv,
266246 repo: &Path,
@@ -291,8 +271,6 @@ pub async fn log(
291271 .collect())
292272 }
293273
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.
296274 pub async fn count(env: &GitEnv, repo: &Path, commit: &str, path: Option<&str>) -> Result<u64> {
297275 validate_oid(commit)?;
298276 let mut cmd = git(env, "rev-list")
@@ -311,9 +289,6 @@ pub async fn count(env: &GitEnv, repo: &Path, commit: &str, path: Option<&str>)
311289 .map_err(|_| Error::Failed(format!("unexpected rev-list count: {:?}", text.trim())))
312290 }
313291
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.
317292 pub async fn new_commits(
318293 env: &GitEnv,
319294 repo: &Path,
@@ -324,7 +299,6 @@ pub async fn new_commits(
324299 new_commits_with(env, repo, ObjectSource::default(), old, new, max).await
325300 }
326301
327-/// [`new_commits`], reading objects that are missing from `repo` from `src` as well.
328302 pub async fn new_commits_with(
329303 env: &GitEnv,
330304 repo: &Path,
@@ -363,11 +337,11 @@ pub async fn new_commits_with(
363337 Ok(commits)
364338 }
365339
366-/// Which `diff-tree` output a command produces.
367340 #[derive(Clone, Copy)]
368341 enum DiffMode {
369342 NameStatus,
370343 Patch,
344+ Raw,
371345 }
372346
373347 fn diff_tree_cmd(
@@ -387,12 +361,11 @@ fn diff_tree_cmd(
387361 .arg("--no-color")
388362 .arg("--no-ext-diff")
389363 .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.
392364 let cmd = if ignore_ws { cmd.arg("-w") } else { cmd };
393365 let cmd = match mode {
394366 DiffMode::NameStatus => cmd.arg("-z").arg("--name-status"),
395367 DiffMode::Patch => cmd.arg("-p").arg("--full-index"),
368+ DiffMode::Raw => cmd.arg("-p").arg("--binary"),
396369 };
397370 cmd.objects(src)?.user_revs(&[base, oid])
398371 }
@@ -405,7 +378,6 @@ pub fn empty_tree_for(oid: &str) -> &'static str {
405378 }
406379 }
407380
408-/// First parent of `oid`, or `None` for a root commit.
409381 async fn first_parent(env: &GitEnv, repo: &Path, oid: &str) -> Result<Option<String>> {
410382 let out = git(env, "rev-list")
411383 .git_dir(repo)
@@ -426,7 +398,6 @@ async fn first_parent(env: &GitEnv, repo: &Path, oid: &str) -> Result<Option<Str
426398 }
427399 }
428400
429-/// One entry of `--name-status -z` output.
430401 struct NameEntry {
431402 status: DiffStatus,
432403 old_path: Option<String>,
@@ -444,7 +415,6 @@ fn status_of(code: u8) -> DiffStatus {
444415 }
445416 }
446417
447-/// Parses NUL-separated `--name-status -z` output. A trailing partial record is dropped.
448418 fn parse_name_status(buf: &[u8]) -> Vec<NameEntry> {
449419 let text = |p: &[u8]| String::from_utf8_lossy(p).into_owned();
450420 let mut out = Vec::new();
@@ -478,7 +448,6 @@ fn parse_name_status(buf: &[u8]) -> Vec<NameEntry> {
478448 out
479449 }
480450
481-/// Byte offsets where `diff --git` headers start at the beginning of a line.
482451 fn block_starts(text: &str) -> Vec<usize> {
483452 text.match_indices("diff --git ")
484453 .map(|(i, _)| i)
@@ -486,7 +455,6 @@ fn block_starts(text: &str) -> Vec<usize> {
486455 .collect()
487456 }
488457
489-/// `@@ -a[,b] +c[,d] @@` to the old and new start line numbers.
490458 fn parse_hunk_start(line: &str) -> (u32, u32) {
491459 let mut parts = line.split_whitespace().skip(1);
492460 let start = |p: Option<&str>, sign: char| {
@@ -500,7 +468,6 @@ fn parse_hunk_start(line: &str) -> (u32, u32) {
500468 (old, new)
501469 }
502470
503-/// Totals and hunks of one file's section of the patch.
504471 #[derive(Default)]
505472 struct BlockOut {
506473 is_binary: bool,
@@ -510,8 +477,6 @@ struct BlockOut {
510477 truncated: bool,
511478 }
512479
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.
515480 fn parse_block(block: &str, limits: &DiffLimits, total_left: &mut usize) -> BlockOut {
516481 let mut out = BlockOut::default();
517482 let mut file_lines = 0usize;
@@ -589,9 +554,6 @@ fn parse_block(block: &str, limits: &DiffLimits, total_left: &mut usize) -> Bloc
589554 out
590555 }
591556
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`].
595557 pub async fn commit_diff(
596558 env: &GitEnv,
597559 repo: &Path,
@@ -601,7 +563,6 @@ pub async fn commit_diff(
601563 commit_diff_ws(env, repo, oid, limits, false).await
602564 }
603565
604-/// [`commit_diff`], optionally ignoring whitespace changes (`git diff -w`).
605566 pub async fn commit_diff_ws(
606567 env: &GitEnv,
607568 repo: &Path,
@@ -626,8 +587,6 @@ pub async fn commit_diff_ws(
626587 .await
627588 }
628589
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.
631590 pub(crate) async fn diff_between(
632591 env: &GitEnv,
633592 repo: &Path,
@@ -672,16 +631,12 @@ pub(crate) async fn diff_between(
672631 .await?;
673632 let patch = String::from_utf8_lossy(&patch_buf);
674633 let starts = block_starts(&patch);
675- // A capped patch may end inside its last section, so that section is dropped.
676634 let usable = if patch_complete {
677635 starts.len()
678636 } else {
679637 starts.len().saturating_sub(1)
680638 };
681639
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.
685640 let mut slots: Vec<usize> = (0..entries.len()).collect();
686641 if ignore_ws && patch_complete && starts.len() != entries.len() {
687642 let mut j = 0usize;
@@ -731,7 +686,6 @@ pub(crate) async fn diff_between(
731686 });
732687 }
733688 if ignore_ws {
734- // Whatever git listed, a text file with no changed lines left is whitespace only.
735689 files.retain(|f| {
736690 f.status != DiffStatus::Modified
737691 || f.is_binary
@@ -745,14 +699,11 @@ pub(crate) async fn diff_between(
745699 })
746700 }
747701
748-/// A downloadable patch: the bytes and whether they are complete (not cut at the output cap).
749702 pub struct PatchOut {
750703 pub data: Vec<u8>,
751704 pub complete: bool,
752705 }
753706
754-/// Mbox of one commit in `format-patch` style (`/commit/{oid}.patch`). Binary changes are
755-/// included so the patch applies.
756707 pub async fn commit_patch(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchOut> {
757708 validate_oid(oid)?;
758709 let cmd = git(env, "format-patch")
@@ -768,7 +719,6 @@ pub async fn commit_patch(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchO
768719 Ok(PatchOut { data, complete })
769720 }
770721
771-/// Plain unified diff of one commit against its first parent (`/commit/{oid}.diff`).
772722 pub async fn commit_raw_diff(env: &GitEnv, repo: &Path, oid: &str) -> Result<PatchOut> {
773723 validate_oid(oid)?;
774724 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
778728 raw_diff(env, repo, ObjectSource::default(), &base, oid).await
779729 }
780730
781-/// Plain unified diff from `base` to `oid`, both full object ids.
782731 pub async fn raw_diff(
783732 env: &GitEnv,
784733 repo: &Path,
@@ -788,23 +737,11 @@ pub async fn raw_diff(
788737 ) -> Result<PatchOut> {
789738 validate_oid(base)?;
790739 validate_oid(oid)?;
791- let cmd = git(env, "diff-tree")
792- .git_dir(repo)
793- .arg("-r")
794- .arg("-p")
795- .arg("-M")
796- .arg("--binary")
797- .arg("--no-commit-id")
798- .arg("--no-color")
799- .arg("--no-ext-diff")
800- .arg("--no-textconv")
801- .objects(src)?
802- .user_revs(&[base, oid])?;
740+ let cmd = diff_tree_cmd(env, repo, src, base, oid, DiffMode::Raw, false)?;
803741 let (data, complete) = read_capped(cmd).await?;
804742 Ok(PatchOut { data, complete })
805743 }
806744
807-/// Mbox of the commits reachable from `head` but not from `base`, oldest first.
808745 pub async fn range_patch(
809746 env: &GitEnv,
810747 repo: &Path,
@@ -827,8 +764,6 @@ pub async fn range_patch(
827764 Ok(PatchOut { data, complete })
828765 }
829766
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.
832767 pub async fn list_files(
833768 env: &GitEnv,
834769 repo: &Path,
@@ -857,8 +792,6 @@ pub async fn list_files(
857792 Ok((paths, cut || !complete))
858793 }
859794
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.
862795 pub async fn list_file_sizes(
863796 env: &GitEnv,
864797 repo: &Path,
@@ -876,7 +809,6 @@ pub async fn list_file_sizes(
876809 let mut out = Vec::new();
877810 let mut cut = false;
878811 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.
880812 let Some(tab) = rec.iter().position(|&b| b == b'\t') else {
881813 return true;
882814 };
@@ -904,9 +836,6 @@ pub async fn list_file_sizes(
904836 Ok((out, cut || !complete))
905837 }
906838
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.
910839 pub async fn last_commits(
911840 env: &GitEnv,
912841 repo: &Path,
@@ -948,7 +877,6 @@ pub async fn last_commits(
948877 let Some((info, files)) = parse_record(rec) else {
949878 return true;
950879 };
951- // `-z --name-only` puts a NUL and/or newline between the format and the names.
952880 let start = files
953881 .iter()
954882 .position(|&b| b != 0 && b != b'\n')
@@ -997,7 +925,6 @@ pub async fn last_commits(
997925 Ok(found)
998926 }
999927
1000-/// `git archive` for `commit`, with every entry under `<prefix>/`. The caller streams stdout.
1001928 pub fn archive_command(
1002929 env: &GitEnv,
1003930 repo: &Path,
crates/forge-git/src/mirror.rsmodified+3 -1
@@ -223,7 +223,9 @@ async fn fetch(
223223 let head = base_command(env, Some(repo), "ls-remote", auth, allow_http, pin, local)?
224224 .arg("--symref")
225225 .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+ };
227229 let listing = String::from_utf8_lossy(&listing);
228230 let Some(default_ref) = remote_default_branch(&listing) else {
229231 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-
51 use std::path::Path;
62 use std::process::{Output, Stdio};
73
84 use tokio::io::AsyncWriteExt;
95
106 use crate::browse::{CommitInfo, validate_repo_path};
11-use crate::command::{GitCommand, GitEnv, ObjectSource};
7+use crate::command::{GitCommand, GitEnv, ObjectSource, failed};
128 use crate::error::{Error, Result};
139 use crate::history::{
1410 CommitDiff, DiffLimits, diff_between, empty_tree_for, git, new_commits_with, validate_oid,
1511 };
1612
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+
1823 #[derive(Debug, Clone, PartialEq, Eq)]
1924 pub enum MergeCheck {
20- /// The merge would be clean; `tree` is the id of the resulting tree.
2125 Clean { tree: String },
22- /// The merge would conflict; `files` are the conflicted paths, deduplicated.
2326 Conflict { files: Vec<String> },
24- /// The head is already contained in the base.
2527 UpToDate,
2628 }
2729
28-/// Author or committer identity for [`commit_tree`]. `time_unix` is written as `<unix> +0000`.
2930 #[derive(Debug, Clone, PartialEq, Eq)]
3031 pub struct Signature {
3132 pub name: String,
@@ -33,7 +34,6 @@ pub struct Signature {
3334 pub time_unix: i64,
3435 }
3536
36-/// Runs a command without turning a non-zero exit into an error, optionally feeding stdin.
3737 async fn run_raw(cmd: GitCommand, stdin: Option<&[u8]>) -> Result<Output> {
3838 let mut command = cmd.into_tokio();
3939 command.stdout(Stdio::piped()).stderr(Stdio::piped());
@@ -43,24 +43,14 @@ async fn run_raw(cmd: GitCommand, stdin: Option<&[u8]>) -> Result<Output> {
4343 let mut child = command.spawn()?;
4444 if let (Some(data), Some(mut pipe)) = (stdin, child.stdin.take()) {
4545 pipe.write_all(data).await?;
46- // `pipe` is dropped here, which closes git's stdin.
4746 }
4847 Ok(child.wait_with_output().await?)
4948 }
5049
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-
5950 fn stdout_trimmed(out: &Output) -> String {
6051 String::from_utf8_lossy(&out.stdout).trim().to_owned()
6152 }
6253
63-/// Accepts `refs/heads/<name>` and `refs/pull/<N>/head`, with a conservative character set.
6454 fn validate_ref(refname: &str) -> Result<()> {
6555 let heads_ok = refname
6656 .strip_prefix("refs/heads/")
@@ -93,7 +83,6 @@ fn valid_branch_rest(rest: &str) -> bool {
9383 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'-' | b'+'))
9484 }
9585
96-/// Rejects identity fields git would refuse or misparse.
9786 fn validate_signature(sig: &Signature) -> Result<()> {
9887 let bad = |s: &str| s.is_empty() || s.contains(['<', '>', '\n', '\0']);
9988 if bad(&sig.name) || bad(&sig.email) {
@@ -102,7 +91,6 @@ fn validate_signature(sig: &Signature) -> Result<()> {
10291 Ok(())
10392 }
10493
105-/// True when both paths name the same repository (equal, or equal after canonicalization).
10694 fn same_repo(a: &Path, b: &Path) -> bool {
10795 if a == b {
10896 return true;
@@ -113,15 +101,11 @@ fn same_repo(a: &Path, b: &Path) -> bool {
113101 }
114102 }
115103
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.
119104 async fn fetch_object(env: &GitEnv, base_repo: &Path, head_repo: &Path, oid: &str) -> Result<()> {
120105 let head_path = head_repo
121106 .to_str()
122107 .ok_or_else(|| Error::InvalidInput("repo path is not valid UTF-8".into()))?;
123108 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.
125109 let cmd = git(env, "fetch")
126110 .allow_local_transport()
127111 .git_dir(base_repo)
@@ -143,8 +127,6 @@ async fn fetch_object(env: &GitEnv, base_repo: &Path, head_repo: &Path, oid: &st
143127 }
144128 }
145129
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.
148130 pub async fn fetch_into_pull_ref(
149131 env: &GitEnv,
150132 base_repo: &Path,
@@ -171,13 +153,10 @@ pub async fn fetch_into_pull_ref(
171153 .await
172154 }
173155
174-/// Best common ancestor of `a` and `b`, or `None` when they share no history.
175156 pub async fn merge_base(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<Option<String>> {
176157 merge_base_with(env, repo, ObjectSource::default(), a, b).await
177158 }
178159
179-/// [`merge_base`], reading objects missing from `repo` (such as a fork's head commit) from `src`.
180-/// Nothing is written to `repo`.
181160 pub async fn merge_base_with(
182161 env: &GitEnv,
183162 repo: &Path,
@@ -203,42 +182,23 @@ pub async fn merge_base_with(
203182 }
204183 }
205184
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.
208185 pub async fn blob_at(
209186 env: &GitEnv,
210187 repo: &Path,
211188 commit: &str,
212189 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,
225190 ) -> Result<Option<String>> {
226191 validate_oid(commit)?;
227192 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.
231193 let spec = format!(":(literal){path}");
232194 let out = git(env, "ls-tree")
233195 .git_dir(repo)
234- .objects(src)?
235196 .arg("-z")
236197 .arg("--full-tree")
237198 .user_arg(commit)?
238199 .paths(&[spec.as_str()])
239200 .output()
240201 .await?;
241- // Pathspecs can match more than one entry, so keep only the exact path.
242202 let entry = out.split(|&b| b == 0).find_map(|rec| {
243203 let text = std::str::from_utf8(rec).ok()?;
244204 let (meta, name) = text.split_once('\t')?;
@@ -260,8 +220,6 @@ pub async fn blob_at_with(
260220 }
261221 }
262222
263-/// Rules for the path argument of [`blob_at`]: non-empty, relative, no newline, and the segment
264-/// rules of [`validate_repo_path`].
265223 fn validate_blob_path(path: &str) -> Result<()> {
266224 if path.is_empty() {
267225 return Err(Error::InvalidInput("empty path".into()));
@@ -275,7 +233,6 @@ fn validate_blob_path(path: &str) -> Result<()> {
275233 validate_repo_path(path)
276234 }
277235
278-/// True when `a` is an ancestor of `b` (or equal to it).
279236 pub async fn is_ancestor(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<bool> {
280237 validate_oid(a)?;
281238 validate_oid(b)?;
@@ -291,7 +248,6 @@ pub async fn is_ancestor(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result<
291248 }
292249 }
293250
294-/// Checks whether `head` merges cleanly into `base`, without touching any ref.
295251 pub async fn check_merge(
296252 env: &GitEnv,
297253 repo: &Path,
@@ -321,20 +277,14 @@ pub async fn check_merge(
321277 let mut lines = text.lines();
322278 let tree = lines.next().unwrap_or_default().trim().to_owned();
323279 validate_oid(&tree)?;
324- let mut files: Vec<String> = Vec::new();
325- for line in lines.map(str::trim).filter(|l| !l.is_empty()) {
326- if !files.iter().any(|f| f == line) {
327- files.push(line.to_owned());
328- }
329- }
330- Ok(MergeCheck::Conflict { files })
280+ Ok(MergeCheck::Conflict {
281+ files: conflict_files(lines),
282+ })
331283 }
332284 _ => Err(failed("merge-tree", &out)),
333285 }
334286 }
335287
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_*`.
338288 pub async fn commit_tree(
339289 env: &GitEnv,
340290 repo: &Path,
@@ -377,8 +327,6 @@ pub async fn commit_tree(
377327 Ok(oid)
378328 }
379329
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.
382330 pub async fn update_ref_cas(
383331 env: &GitEnv,
384332 repo: &Path,
@@ -406,10 +354,7 @@ pub async fn update_ref_cas(
406354 Err(failed("update-ref", &out))
407355 }
408356
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.
411357 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.
413358 let queue_ok = refname
414359 .strip_prefix("refs/forge/merge-queue/")
415360 .is_some_and(valid_branch_rest);
@@ -430,10 +375,6 @@ pub async fn set_ref(env: &GitEnv, repo: &Path, refname: &str, new: &str) -> Res
430375 Err(failed("update-ref", &out))
431376 }
432377
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.
437378 pub async fn delete_ref_cas(env: &GitEnv, repo: &Path, refname: &str, old: &str) -> Result<()> {
438379 validate_ref(refname)?;
439380 validate_oid(old)?;
@@ -453,8 +394,6 @@ pub async fn delete_ref_cas(env: &GitEnv, repo: &Path, refname: &str, old: &str)
453394 Err(failed("update-ref", &out))
454395 }
455396
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.
458397 pub async fn range_diff_files(
459398 env: &GitEnv,
460399 repo: &Path,
@@ -462,30 +401,18 @@ pub async fn range_diff_files(
462401 head_oid: &str,
463402 limits: DiffLimits,
464403 ) -> Result<CommitDiff> {
465- range_diff_files_with(
404+ range_diff_files_ws(
466405 env,
467406 repo,
468407 ObjectSource::default(),
469408 base_oid,
470409 head_oid,
471410 limits,
411+ false,
472412 )
473413 .await
474414 }
475415
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.
489416 pub async fn range_diff_files_ws(
490417 env: &GitEnv,
491418 repo: &Path,
@@ -504,8 +431,6 @@ pub async fn range_diff_files_ws(
504431 diff_between(env, repo, src, &from, head_oid, limits, ignore_ws).await
505432 }
506433
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.
509434 pub async fn range_log(
510435 env: &GitEnv,
511436 repo: &Path,
@@ -516,7 +441,6 @@ pub async fn range_log(
516441 range_log_with(env, repo, ObjectSource::default(), base_oid, head_oid, max).await
517442 }
518443
519-/// [`range_log`], reading objects missing from `repo` from `src`. Nothing is written.
520444 pub async fn range_log_with(
521445 env: &GitEnv,
522446 repo: &Path,
@@ -530,20 +454,12 @@ pub async fn range_log_with(
530454 new_commits_with(env, repo, src, Some(base_oid), head_oid, max).await
531455 }
532456
533-/// Outcome of replaying head commits onto a base tip.
534457 #[derive(Debug, Clone, PartialEq, Eq)]
535458 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.
538459 Clean { tip: String, count: usize },
539- /// A commit does not apply; `commit` is its id and `files` the conflicted paths.
540460 Conflict { commit: String, files: Vec<String> },
541461 }
542462
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.
547463 pub async fn rebase_commits(
548464 env: &GitEnv,
549465 repo: &Path,
@@ -609,18 +525,10 @@ pub async fn rebase_commits(
609525 let tree = match out.status.code() {
610526 Some(0) => text.lines().next().unwrap_or_default().trim().to_owned(),
611527 Some(1) => {
612- let mut files: Vec<String> = Vec::new();
613- for line in text
614- .lines()
615- .skip(1)
616- .map(str::trim)
617- .filter(|l| !l.is_empty())
618- {
619- if !files.iter().any(|f| f == line) {
620- files.push(line.to_owned());
621- }
622- }
623- return Ok(RebaseResult::Conflict { commit, files });
528+ return Ok(RebaseResult::Conflict {
529+ commit,
530+ files: conflict_files(text.lines().skip(1)),
531+ });
624532 }
625533 _ => return Err(failed("merge-tree", &out)),
626534 };
@@ -657,21 +565,14 @@ pub async fn rebase_commits(
657565 Ok(RebaseResult::Clean { tip, count })
658566 }
659567
660-/// One file of a commit made by [`commit_file_edit`].
661568 #[derive(Debug, Clone, Copy)]
662569 pub struct FileEdit<'a> {
663- /// Repo path of the file. It must be a regular file in the base commit.
664570 pub path: &'a str,
665- /// The new content of the file.
666571 pub content: &'a [u8],
667572 }
668573
669574 static EDIT_INDEX_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
670575
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.
675576 #[allow(clippy::too_many_arguments)]
676577 pub async fn commit_file_edit(
677578 env: &GitEnv,
@@ -692,7 +593,6 @@ pub async fn commit_file_edit(
692593 env, repo, &index, refname, base, edit, message, author, committer,
693594 )
694595 .await;
695- // The index is scratch space. A leftover file is harmless, but do not keep it.
696596 let _ = tokio::fs::remove_file(&index).await;
697597 result
698598 }
@@ -725,15 +625,13 @@ async fn edit_and_commit(
725625 .status()
726626 .await?;
727627
728- // `ls-files -s` gives `<mode> <oid> <stage>\t<path>`. The path must be the file itself, and a
729- // regular file: a symlink or a submodule is not something a suggestion can rewrite.
628+ let spec = format!(":(literal){}", edit.path);
730629 let listing = GitCommand::new(env, "ls-files")
731630 .git_dir(repo)
732631 .env("GIT_INDEX_FILE", index)
733632 .arg("-s")
734633 .arg("-z")
735- .arg("--")
736- .user_arg(edit.path)?
634+ .paths(&[spec.as_str()])
737635 .output()
738636 .await?;
739637 let entry =
@@ -786,7 +684,6 @@ mod tests {
786684 max_total_lines: 10_000,
787685 };
788686
789- /// Runs git in `dir` with a cleared environment and fixed identities.
790687 fn git_in(dir: &Path, home: &Path, args: &[&str]) -> String {
791688 let out = Command::new("/usr/bin/git")
792689 .arg("-C")
@@ -818,8 +715,6 @@ mod tests {
818715 }
819716
820717 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.
823718 fn new() -> Self {
824719 let dir = tempfile::tempdir().expect("tempdir");
825720 let home = dir.path().join("home");
@@ -835,7 +730,6 @@ mod tests {
835730 }
836731 }
837732
838- /// A non-bare repo named `name` with `main` checked out.
839733 fn repo(&self, name: &str) -> Work {
840734 let work = self._dir.path().join(name);
841735 std::fs::create_dir(&work).expect("work dir");
@@ -865,7 +759,6 @@ mod tests {
865759 std::fs::write(self.work.join(name), content).expect("write file");
866760 }
867761
868- /// Stages everything, commits, and returns the new full id.
869762 fn commit(&self, msg: &str) -> String {
870763 self.git(&["add", "-A"]);
871764 self.git(&["commit", "-q", "--allow-empty", "-m", msg]);
@@ -1001,7 +894,6 @@ mod tests {
1001894 let c2 = w.commit("c2");
1002895 let gd = w.git_dir();
1003896
1004- // The base is at c2, so a CAS expecting c0 must fail and leave the ref alone.
1005897 let stale = update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c0).await;
1006898 assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}");
1007899 assert_eq!(w.git(&["rev-parse", "main"]), c2);
@@ -1024,7 +916,6 @@ mod tests {
1024916 let c1 = w.commit("c1");
1025917 let gd = w.git_dir();
1026918
1027- // topic is at c0, so a deletion expecting c1 must fail and leave the ref alone.
1028919 let stale = delete_ref_cas(&env, &gd, "refs/heads/topic", &c1).await;
1029920 assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}");
1030921 assert_eq!(w.git(&["rev-parse", "topic"]), c0);
@@ -1035,7 +926,6 @@ mod tests {
1035926 let gone = w.git(&["for-each-ref", "refs/heads/topic"]);
1036927 assert!(gone.is_empty(), "{gone:?}");
1037928
1038- // Deleting a ref that is already gone is a refusal, not a silent success.
1039929 let missing = delete_ref_cas(&env, &gd, "refs/heads/topic", &c0).await;
1040930 assert!(matches!(missing, Err(Error::RefMoved(_))), "{missing:?}");
1041931 }
@@ -1089,7 +979,6 @@ mod tests {
1089979 assert_eq!(diff.files[0].status, DiffStatus::Added);
1090980 }
1091981
1092- /// True when the repo at `git_dir` has `oid` in its object store.
1093982 fn has_object(git_dir: &Path, oid: &str) -> bool {
1094983 Command::new("/usr/bin/git")
1095984 .arg("--git-dir")
@@ -1111,7 +1000,6 @@ mod tests {
11111000 let base = sb.repo("base");
11121001 base.write("a.txt", "1\n");
11131002 let base_tip = base.commit("base");
1114- // The fork is a clone, so both histories share `base_tip`.
11151003 let fork_dir = sb._dir.path().join("fork");
11161004 git_in(
11171005 sb._dir.path(),
@@ -1128,7 +1016,6 @@ mod tests {
11281016 let fork_objects = fork.git_dir().join("objects");
11291017 assert!(!has_object(&base_git, &fork_head));
11301018
1131- // Without the alternate the base cannot see the fork's commit.
11321019 assert!(
11331020 range_log(&env, &base_git, &base_tip, &fork_head, 10)
11341021 .await
@@ -1149,7 +1036,7 @@ mod tests {
11491036 .expect("merge base through alternate");
11501037 assert_eq!(merge.as_deref(), Some(base_tip.as_str()));
11511038
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)
11531040 .await
11541041 .expect("range diff through alternate");
11551042 let paths: Vec<String> = diff
@@ -1159,7 +1046,6 @@ mod tests {
11591046 .collect();
11601047 assert_eq!(paths, vec!["b.txt".to_owned()]);
11611048
1162- // Reading through the alternate wrote nothing into the base repo.
11631049 assert!(!has_object(&base_git, &fork_head));
11641050 }
11651051
@@ -1238,7 +1124,6 @@ mod tests {
12381124 let a1 = blob_at(&env, &gd, &c1, "a.txt").await.expect("ok");
12391125 assert_eq!(a1, Some(w.git(&["hash-object", "a.txt"])));
12401126 assert_ne!(a1, Some(a0));
1241- // The older commit still maps to the older blob.
12421127 let old_spec = format!("{c0}:a.txt");
12431128 assert_eq!(
12441129 blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"),
@@ -1273,7 +1158,6 @@ mod tests {
12731158 blob_at(&env, &gd, &c0, ":colon").await.expect("ok"),
12741159 Some(w.git(&["hash-object", ":colon"]))
12751160 );
1276- // A glob must not match other entries.
12771161 assert_eq!(blob_at(&env, &gd, &c0, "st*").await.expect("ok"), None);
12781162 assert_eq!(blob_at(&env, &gd, &c0, "*").await.expect("ok"), None);
12791163 }
crates/forge-git/src/seed.rsmodified+2 -1
@@ -6,6 +6,7 @@ use std::path::Path;
66
77 use crate::command::{GitCommand, GitEnv};
88 use crate::error::Result;
9+use crate::history::zero_oid;
910 use crate::repo::check_branch;
1011 use crate::wiki::temp_index;
1112
@@ -97,7 +98,7 @@ async fn write_commit(
9798 .arg("forge initial commit")
9899 .user_arg(&format!("refs/heads/{branch}"))?
99100 .user_arg(&oid)?
100- .user_arg(&"0".repeat(oid.len()))?
101+ .user_arg(&zero_oid(&oid))?
101102 .status()
102103 .await?;
103104 Ok(oid)
crates/forge-git/src/tags.rsmodified+5 -5
@@ -5,10 +5,10 @@ use std::path::Path;
55
66 use crate::command::GitEnv;
77 use crate::error::{Error, Result};
8-use crate::history::{git, validate_oid};
8+use crate::history::{git, validate_oid, zero_oid};
99
1010 /// Longest tag name, in bytes.
11-pub const MAX_TAG_NAME_LEN: usize = 100;
11+const MAX_TAG_NAME_LEN: usize = 100;
1212
1313 /// True for a tag name git accepts and forge allows: ASCII letters, digits and `._-+`, with no
1414 /// slash, no `..`, no leading `.` or `-`, and no trailing `.` or `.lock`.
@@ -16,7 +16,7 @@ pub fn valid_tag_name(name: &str) -> bool {
1616 !name.is_empty()
1717 && name.len() <= MAX_TAG_NAME_LEN
1818 && !name.starts_with(['.', '-'])
19- && !name.ends_with(['.', '/'])
19+ && !name.ends_with('.')
2020 && !name.ends_with(".lock")
2121 && !name.contains("..")
2222 && name
@@ -37,7 +37,7 @@ pub async fn create_lightweight_tag(
3737 }
3838 validate_oid(target)?;
3939 let refname = format!("refs/tags/{name}");
40- let zero = "0".repeat(target.len());
40+ let zero = zero_oid(target);
4141 git(env, "update-ref")
4242 .git_dir(repo)
4343 .user_arg(&refname)?
@@ -89,7 +89,7 @@ pub async fn previous_tag(
8989 env: &GitEnv,
9090 repo: &Path,
9191 oid: &str,
92-) -> crate::error::Result<Option<(String, String)>> {
92+) -> Result<Option<(String, String)>> {
9393 validate_oid(oid)?;
9494 let parent = format!("{oid}^");
9595 let described = git(env, "describe")
crates/forge-git/src/trailers.rsmodified+9 -19
@@ -16,7 +16,7 @@ pub struct CoAuthor {
1616 pub fn co_authors(message: &str) -> Vec<CoAuthor> {
1717 let lines = lines(message);
1818 let mut seen = HashSet::new();
19- trailer_lines(&lines)
19+ lines[last_paragraph_start(&lines)..]
2020 .iter()
2121 .filter_map(|line| parse(line))
2222 .filter(|author| seen.insert(author.email.to_lowercase()))
@@ -26,15 +26,14 @@ pub fn co_authors(message: &str) -> Vec<CoAuthor> {
2626 /// The message with every `Co-authored-by:` line removed and trailing blank lines trimmed.
2727 pub fn strip_co_authors(message: &str) -> String {
2828 let lines = lines(message);
29- let start = last_paragraph_start(&lines);
30- let kept: Vec<&str> = lines[..start]
29+ let (head, tail) = lines.split_at(last_paragraph_start(&lines));
30+ let kept: Vec<&str> = head
3131 .iter()
3232 .copied()
3333 .chain(
34- lines[start..]
35- .iter()
34+ tail.iter()
3635 .copied()
37- .filter(|line| !is_trailer(line)),
36+ .filter(|line| trailer_value(line).is_none()),
3837 )
3938 .collect();
4039 kept.join("\n").trim_end().to_owned()
@@ -53,23 +52,14 @@ fn last_paragraph_start(lines: &[&str]) -> usize {
5352 .map_or(0, |i| i + 1)
5453 }
5554
56-fn trailer_lines<'a>(lines: &[&'a str]) -> Vec<&'a str> {
57- lines[last_paragraph_start(lines)..].to_vec()
58-}
59-
60-/// Whether a line's key is `Co-authored-by`, in any letter case.
61-fn is_trailer(line: &str) -> bool {
62- line.split_once(':')
63- .is_some_and(|(key, _)| key.trim().eq_ignore_ascii_case(KEY))
55+fn trailer_value(line: &str) -> Option<&str> {
56+ let (key, value) = line.split_once(':')?;
57+ key.trim().eq_ignore_ascii_case(KEY).then_some(value)
6458 }
6559
6660 /// Parses `Co-authored-by: Name <email>`. Lines without a non-empty `<email>` give `None`.
6761 fn parse(line: &str) -> Option<CoAuthor> {
68- let (key, value) = line.trim().split_once(':')?;
69- if !key.trim().eq_ignore_ascii_case(KEY) {
70- return None;
71- }
72- let value = value.trim();
62+ let value = trailer_value(line.trim())?.trim();
7363 let open = value.find('<')?;
7464 let close = open + value[open..].find('>')?;
7565 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;
1111
1212 use crate::command::{GitCommand, GitEnv};
1313 use crate::error::{Error, Result};
14+use crate::history::validate_oid;
1415
1516 /// What git said about one commit's signature.
1617 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -47,19 +48,9 @@ impl RawVerify {
4748 }
4849 }
4950
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-
6051 /// The raw commit object (`git cat-file commit <oid>`).
6152 async fn commit_object(env: &GitEnv, repo: &Path, oid: &str) -> Result<Vec<u8>> {
62- check_oid(oid)?;
53+ validate_oid(oid)?;
6354 GitCommand::new(env, "cat-file")
6455 .git_dir(repo)
6556 .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.
22
33 use crate::command::{GitCommand, GitEnv};
44 use crate::error::{Error, Result};
@@ -21,7 +21,7 @@ fn leading_number(s: &str) -> Option<u32> {
2121 digits.parse().ok()
2222 }
2323
24-fn fmt_version((major, minor, patch): (u32, u32, u32)) -> String {
24+pub fn fmt_version((major, minor, patch): (u32, u32, u32)) -> String {
2525 format!("{major}.{minor}.{patch}")
2626 }
2727
crates/forge-git/src/wiki.rsmodified+16 -9
@@ -9,16 +9,17 @@ use std::sync::atomic::{AtomicU64, Ordering};
99 use crate::browse::{EntryKind, default_branch_commit, read_text_blob, read_tree};
1010 use crate::command::{GitCommand, GitEnv};
1111 use crate::error::{Error, Result};
12+use crate::history::zero_oid;
1213 use crate::repo::init_bare;
1314
1415 /// The branch that holds the pages.
1516 pub const WIKI_BRANCH: &str = "main";
1617 /// Extension of a page file.
17-pub const PAGE_EXT: &str = ".md";
18+const PAGE_EXT: &str = ".md";
1819 /// Largest page the editor accepts, and the largest one read back.
1920 pub const MAX_PAGE_BYTES: usize = 256 * 1024;
2021 /// Longest page name, in characters.
21-pub const MAX_PAGE_NAME: usize = 100;
22+const MAX_PAGE_NAME: usize = 100;
2223
2324 /// One page edit. `name` is the page name without the extension.
2425 #[derive(Debug, Clone, Copy)]
@@ -115,7 +116,7 @@ pub async fn page_history(env: &GitEnv, wiki: &Path, name: &str) -> Result<Vec<P
115116 let out = GitCommand::new(env, "log")
116117 .git_dir(wiki)
117118 .arg("--format=%H%x1f%an%x1f%at%x1f%s")
118- .arg("--max-count=200")
119+ .user_opt("--max-count", &HISTORY_LIMIT.to_string())?
119120 .user_arg(&format!("refs/heads/{WIKI_BRANCH}"))?
120121 .paths(&[file.as_str()])
121122 .output()
@@ -238,10 +239,9 @@ async fn write_commit(
238239 // Compare-and-swap: the ref must still hold `base`, or be absent when there was no base.
239240 let old = match base {
240241 Some(base) => base.to_owned(),
241- None => "0".repeat(oid.len()),
242+ None => zero_oid(&oid),
242243 };
243- // Any failure here is treated as a lost race: the only expected cause is a concurrent edit.
244- GitCommand::new(env, "update-ref")
244+ let swapped = GitCommand::new(env, "update-ref")
245245 .git_dir(wiki)
246246 .arg("-m")
247247 .arg("forge wiki edit")
@@ -249,9 +249,16 @@ async fn write_commit(
249249 .user_arg(&oid)?
250250 .user_arg(&old)?
251251 .status()
252- .await
253- .map_err(|_| Error::RefMoved(format!("wiki {WIKI_BRANCH} moved during the edit")))?;
254- Ok(oid)
252+ .await;
253+ match swapped {
254+ Ok(()) => Ok(oid),
255+ Err(Error::Failed(msg))
256+ if msg.contains("but expected") || msg.contains("unable to resolve reference") =>
257+ {
258+ Err(Error::RefMoved(format!("wiki {WIKI_BRANCH} moved during the edit")))
259+ }
260+ Err(e) => Err(e),
261+ }
255262 }
256263
257264 #[cfg(test)]
crates/forge-git/tests/integration/browse.rsmodified+0 -2
@@ -35,7 +35,6 @@ fn git(dir: &Path, args: &[&str]) -> String {
3535 String::from_utf8_lossy(&out.stdout).trim().to_string()
3636 }
3737
38-/// Builds a work repo with the real git CLI, then clones it bare so tests read a bare repo.
3938 fn fixture() -> Fixture {
4039 let dir = tempfile::tempdir().unwrap();
4140 let work = dir.path().join("work");
@@ -172,7 +171,6 @@ fn resolve_commit_rejects_revision_syntax_and_unknown() {
172171 ] {
173172 assert_eq!(resolve_commit(&f.bare, rev).unwrap(), None, "rev {rev:?}");
174173 }
175- // 3 hex chars is below the minimum prefix length.
176174 assert_eq!(resolve_commit(&f.bare, &f.head[..3]).unwrap(), None);
177175 }
178176
crates/forge-git/tests/integration/browse_tools.rsmodified+9 -81
@@ -1,88 +1,16 @@
11 //! Tests for the code-browsing helpers: whitespace-free diffs, patches, the recursive file list,
22 //! blame and branch operations.
33
4-use std::path::{Path, PathBuf};
5-use std::process::Command;
6-
7-use forge_git::GitEnv;
84 use forge_git::blame::blame;
95 use forge_git::branches::{ahead_behind, create_branch, delete_branch};
106 use forge_git::command::ObjectSource;
117 use forge_git::history::{commit_diff_ws, commit_patch, commit_raw_diff, list_files, range_patch};
128
13-use crate::common::{BIG, git_env};
14-
15-struct Fixture {
16- _dir: tempfile::TempDir,
17- work: PathBuf,
18- git_dir: PathBuf,
19- env: GitEnv,
20-}
21-
22-fn run(dir: &Path, home: &Path, args: &[&str]) -> String {
23- let out = Command::new("/usr/bin/git")
24- .arg("-C")
25- .arg(dir)
26- .args([
27- "-c",
28- "user.name=tahinli",
29- "-c",
30- "user.email=tahinli@example.com",
31- "-c",
32- "commit.gpgsign=false",
33- ])
34- .args(args)
35- .env_clear()
36- .env("PATH", "/usr/bin:/bin")
37- .env("HOME", home)
38- .env("GIT_CONFIG_NOSYSTEM", "1")
39- .env("GIT_CONFIG_GLOBAL", "/dev/null")
40- .output()
41- .unwrap();
42- assert!(
43- out.status.success(),
44- "{args:?} failed: {}",
45- String::from_utf8_lossy(&out.stderr)
46- );
47- String::from_utf8_lossy(&out.stdout).into_owned()
48-}
49-
50-fn fixture() -> Fixture {
51- let dir = tempfile::tempdir().unwrap();
52- let work = dir.path().join("work");
53- std::fs::create_dir(&work).unwrap();
54- run(&work, dir.path(), &["init", "-q", "-b", "main"]);
55- let env = git_env(dir.path());
56- let git_dir = work.join(".git");
57- Fixture {
58- _dir: dir,
59- work,
60- git_dir,
61- env,
62- }
63-}
64-
65-impl Fixture {
66- fn sh(&self, args: &[&str]) -> String {
67- run(&self.work, self._dir.path(), args)
68- }
69-
70- fn write(&self, name: &str, content: &str) {
71- let p = self.work.join(name);
72- std::fs::create_dir_all(p.parent().unwrap()).unwrap();
73- std::fs::write(p, content).unwrap();
74- }
75-
76- fn commit(&self, msg: &str) -> String {
77- self.sh(&["add", "-A"]);
78- self.sh(&["commit", "-q", "--allow-empty", "-m", msg]);
79- self.sh(&["rev-parse", "HEAD"]).trim().to_owned()
80- }
81-}
9+use crate::common::{BIG, WorkRepo};
8210
8311 #[tokio::test]
8412 async fn ignore_whitespace_drops_whitespace_only_files() {
85- let f = fixture();
13+ let f = WorkRepo::new();
8614 f.write("x.txt", "a\nb\n");
8715 f.write("y.txt", "c\n");
8816 f.commit("one");
@@ -104,7 +32,7 @@ async fn ignore_whitespace_drops_whitespace_only_files() {
10432
10533 #[tokio::test]
10634 async fn patch_and_diff_outputs() {
107- let f = fixture();
35+ let f = WorkRepo::new();
10836 f.write("x.txt", "a\n");
10937 let root = f.commit("root commit");
11038 f.write("x.txt", "a\nb\n");
@@ -139,7 +67,7 @@ async fn patch_and_diff_outputs() {
13967
14068 #[tokio::test]
14169 async fn list_files_is_recursive_and_capped() {
142- let f = fixture();
70+ let f = WorkRepo::new();
14371 f.write("a.txt", "1");
14472 f.write("dir/b.txt", "2");
14573 f.write("dir/sub/c.txt", "3");
@@ -155,7 +83,7 @@ async fn list_files_is_recursive_and_capped() {
15583
15684 #[tokio::test]
15785 async fn blame_groups_by_commit() {
158- let f = fixture();
86+ let f = WorkRepo::new();
15987 f.write("f.txt", "one\ntwo\nthree\n");
16088 let first = f.commit("first");
16189 f.write("f.txt", "one\nTWO\nthree\nfour\n");
@@ -189,14 +117,14 @@ async fn blame_groups_by_commit() {
189117
190118 #[tokio::test]
191119 async fn branch_counts_create_and_delete() {
192- let f = fixture();
120+ let f = WorkRepo::new();
193121 f.write("a.txt", "1");
194122 let base = f.commit("base");
195- f.sh(&["checkout", "-q", "-b", "feature"]);
123+ f.git(&["checkout", "-q", "-b", "feature"]);
196124 f.write("b.txt", "2");
197125 f.commit("feature 1");
198126 let tip = f.commit("feature 2");
199- f.sh(&["checkout", "-q", "main"]);
127+ f.git(&["checkout", "-q", "main"]);
200128 f.write("c.txt", "3");
201129 let main_tip = f.commit("main moved");
202130
@@ -209,7 +137,7 @@ async fn branch_counts_create_and_delete() {
209137 .await
210138 .unwrap();
211139 assert_eq!(
212- f.sh(&["rev-parse", "refs/heads/topic/x"]).trim(),
140+ f.git(&["rev-parse", "refs/heads/topic/x"]).trim(),
213141 base.as_str()
214142 );
215143 assert!(
crates/forge-git/tests/integration/common.rsmodified+66 -0
@@ -2,6 +2,7 @@
22
33 use std::path::Path;
44 use std::path::PathBuf;
5+use std::process::Command;
56
67 use forge_git::GitEnv;
78 use forge_git::history::DiffLimits;
@@ -18,3 +19,68 @@ pub fn git_env(data_dir: &Path) -> GitEnv {
1819 data_dir: data_dir.to_path_buf(),
1920 }
2021 }
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};
22 use std::process::Command;
33
44 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};
66 use forge_git::repo::{init_bare, list_branches, repo_path};
77 use forge_git::service::{GitService, service_command};
88 use forge_git::setup::{write_hook_shims, write_managed_gitconfig};
@@ -14,24 +14,22 @@ const ULID: &str = "01arz3ndektsv4rrffq69g5fav";
1414
1515 #[test]
1616 fn version_parse() {
17- assert_eq!(parse_git_version("git version 2.56.0\n"), Some((2, 56, 0)));
18- assert_eq!(
19- parse_git_version("git version 2.39.2.windows.1"),
20- Some((2, 39, 2))
21- );
22- assert_eq!(parse_git_version("git version 2.46"), Some((2, 46, 0)));
23- assert_eq!(
24- parse_git_version("git version 2.46.0-rc1"),
25- Some((2, 46, 0))
26- );
27- assert_eq!(parse_git_version("garbage"), None);
17+ let cases = [
18+ ("git version 2.56.0\n", Some((2, 56, 0))),
19+ ("git version 2.39.2.windows.1", Some((2, 39, 2))),
20+ ("git version 2.46", Some((2, 46, 0))),
21+ ("git version 2.46.0-rc1", Some((2, 46, 0))),
22+ ("garbage", None),
23+ ];
24+ for (input, expected) in cases {
25+ assert_eq!(parse_git_version(input), expected, "{input:?}");
26+ }
2827 }
2928
3029 #[test]
3130 fn pkt_line_encoding() {
3231 assert_eq!(pkt_line("a\n"), b"0006a\n".to_vec());
3332 assert_eq!(pkt_line(""), b"0004".to_vec());
34- assert_eq!(FLUSH_PKT, b"0000");
3533 let header = service_advertisement_header(GitService::UploadPack);
3634 assert_eq!(header, b"001e# service=git-upload-pack\n0000".to_vec());
3735 }
crates/forge-git/tests/integration/history.rsmodified+11 -83
@@ -1,85 +1,13 @@
11 use std::io::Write;
2-use std::path::{Path, PathBuf};
32 use std::process::{Command, Stdio};
43
4+use forge_git::Error;
55 use forge_git::history::{
66 ArchiveFormat, CommitDiff, DiffLimits, DiffStatus, FileDiff, LineKind, archive_command,
77 commit_diff, count, last_commits, log,
88 };
9-use forge_git::{Error, GitEnv};
109
11-use crate::common::{BIG, git_env};
12-
13-struct Fixture {
14- _dir: tempfile::TempDir,
15- work: PathBuf,
16- git_dir: PathBuf,
17- env: GitEnv,
18-}
19-
20-fn git_in(dir: &Path, home: &Path, args: &[&str]) -> String {
21- let out = Command::new("/usr/bin/git")
22- .arg("-C")
23- .arg(dir)
24- .args([
25- "-c",
26- "user.name=Tester",
27- "-c",
28- "user.email=tester@example.com",
29- "-c",
30- "commit.gpgsign=false",
31- ])
32- .args(args)
33- .env_clear()
34- .env("PATH", "/usr/bin:/bin")
35- .env("HOME", home)
36- .env("GIT_CONFIG_NOSYSTEM", "1")
37- .env("GIT_CONFIG_GLOBAL", "/dev/null")
38- .output()
39- .unwrap();
40- assert!(
41- out.status.success(),
42- "git {args:?} failed: {}",
43- String::from_utf8_lossy(&out.stderr)
44- );
45- String::from_utf8_lossy(&out.stdout).into_owned()
46-}
47-
48-fn fixture() -> Fixture {
49- let dir = tempfile::tempdir().unwrap();
50- let work = dir.path().join("work");
51- std::fs::create_dir(&work).unwrap();
52- git_in(&work, dir.path(), &["init", "-q", "-b", "main"]);
53- let env = git_env(dir.path());
54- let git_dir = work.join(".git");
55- Fixture {
56- _dir: dir,
57- work,
58- git_dir,
59- env,
60- }
61-}
62-
63-impl Fixture {
64- fn git(&self, args: &[&str]) -> String {
65- git_in(&self.work, self._dir.path(), args)
66- }
67-
68- fn write(&self, name: &str, content: impl AsRef<[u8]>) {
69- let p = self.work.join(name);
70- if let Some(parent) = p.parent() {
71- std::fs::create_dir_all(parent).unwrap();
72- }
73- std::fs::write(p, content).unwrap();
74- }
75-
76- /// Stages everything, commits, and returns the new full oid.
77- fn commit(&self, msg: &str) -> String {
78- self.git(&["add", "-A"]);
79- self.git(&["commit", "-q", "--allow-empty", "-m", msg]);
80- self.git(&["rev-parse", "HEAD"]).trim().to_owned()
81- }
82-}
10+use crate::common::{BIG, WorkRepo};
8311
8412 fn find<'a>(diff: &'a CommitDiff, path: &str) -> &'a FileDiff {
8513 diff.files
@@ -94,7 +22,7 @@ fn summaries(commits: &[forge_git::browse::CommitInfo]) -> Vec<&str> {
9422
9523 #[tokio::test]
9624 async fn log_path_filter_and_pagination() {
97- let f = fixture();
25+ let f = WorkRepo::new();
9826 f.write("a.txt", "1\n");
9927 f.commit("add a");
10028 f.write("b.txt", "1\n");
@@ -126,7 +54,7 @@ async fn log_path_filter_and_pagination() {
12654
12755 #[tokio::test]
12856 async fn commit_diff_modify_add_delete_rename_binary() {
129- let f = fixture();
57+ let f = WorkRepo::new();
13058 f.write("a.txt", "one\ntwo\n");
13159 f.write("gone.txt", "bye\n");
13260 f.write("old.txt", "alpha\nbeta\ngamma\ndelta\nepsilon\n");
@@ -174,7 +102,7 @@ async fn commit_diff_modify_add_delete_rename_binary() {
174102
175103 #[tokio::test]
176104 async fn commit_diff_line_numbers_on_known_hunk() {
177- let f = fixture();
105+ let f = WorkRepo::new();
178106 f.write("n.txt", "l1\nl2\nl3\nl4\nl5\n");
179107 f.commit("base");
180108 f.write("n.txt", "l1\nl2\nX3\nl4\nl5\nl6\n");
@@ -207,7 +135,7 @@ async fn commit_diff_line_numbers_on_known_hunk() {
207135
208136 #[tokio::test]
209137 async fn commit_diff_root_commit_uses_empty_tree() {
210- let f = fixture();
138+ let f = WorkRepo::new();
211139 f.write("a.txt", "x\ny\n");
212140 f.write("d/b.txt", "z\n");
213141 let oid = f.commit("root");
@@ -225,7 +153,7 @@ async fn commit_diff_root_commit_uses_empty_tree() {
225153
226154 #[tokio::test]
227155 async fn commit_diff_limits_truncate() {
228- let f = fixture();
156+ let f = WorkRepo::new();
229157 let old: String = (0..10).map(|i| format!("old{i}\n")).collect();
230158 f.write("big.txt", &old);
231159 f.commit("base");
@@ -272,7 +200,7 @@ async fn commit_diff_limits_truncate() {
272200
273201 #[tokio::test]
274202 async fn last_commits_finds_newest_touch_per_child() {
275- let f = fixture();
203+ let f = WorkRepo::new();
276204 f.write("d/x.txt", "1\n");
277205 f.commit("c1 add x");
278206 f.write("d/y.txt", "1\n");
@@ -317,7 +245,7 @@ async fn last_commits_finds_newest_touch_per_child() {
317245
318246 #[tokio::test]
319247 async fn count_counts_all_commits_or_those_touching_a_path() {
320- let f = fixture();
248+ let f = WorkRepo::new();
321249 f.write("d/x.txt", "1\n");
322250 f.commit("c1 add x");
323251 f.write("d/y.txt", "1\n");
@@ -354,7 +282,7 @@ async fn count_counts_all_commits_or_those_touching_a_path() {
354282
355283 #[tokio::test]
356284 async fn archive_command_produces_listable_tar_gz() {
357- let f = fixture();
285+ let f = WorkRepo::new();
358286 f.write("a.txt", "hello\n");
359287 f.write("d/b.txt", "world\n");
360288 let oid = f.commit("archive me");
@@ -381,7 +309,7 @@ async fn archive_command_produces_listable_tar_gz() {
381309
382310 #[tokio::test]
383311 async fn non_hex_commit_arguments_are_rejected() {
384- let f = fixture();
312+ let f = WorkRepo::new();
385313 f.write("a.txt", "1\n");
386314 let oid = f.commit("one");
387315
crates/forge-git/tests/integration/main.rsmodified+0 -1
@@ -1,6 +1,5 @@
11 //! forge-git integration tests. All modules compile into this single test binary.
22
3-#[allow(dead_code)]
43 mod common;
54
65 mod browse;
crates/forge-ssh/src/backend.rsmodified+4 -5
@@ -4,7 +4,7 @@ use std::future::Future;
44
55 use forge_git::GitService;
66
7-use crate::parse::LfsOperation;
7+use crate::parse::{LfsOperation, RepoPath};
88
99 /// Implemented by forge-web. The SSH server holds it in an `Arc`.
1010 pub trait GitBackend: Send + Sync + 'static {
@@ -21,17 +21,16 @@ pub trait GitBackend: Send + Sync + 'static {
2121 &self,
2222 user_id: &str,
2323 service: GitService,
24- repo_path: &str,
24+ repo_path: &RepoPath,
2525 git_protocol: Option<&str>,
2626 ) -> impl Future<Output = Result<tokio::process::Command, String>> + Send;
2727
2828 /// Authorizes a `git-lfs-authenticate` request and returns the JSON reply for stdout.
29- /// `repo_path` is `owner/repo` with `.git` stripped. `Err` sends the message on stderr
30- /// and exits 1.
29+ /// `Err` sends the message on stderr and exits 1.
3130 fn lfs_authenticate(
3231 &self,
3332 user_id: &str,
34- repo_path: &str,
33+ repo_path: &RepoPath,
3534 operation: LfsOperation,
3635 ) -> impl Future<Output = Result<String, String>> + Send;
3736 }
crates/forge-ssh/src/lib.rsmodified+5 -5
@@ -1,11 +1,11 @@
11 //! git-over-SSH server for forge, built on russh.
22
3-pub mod backend;
4-pub mod error;
5-pub mod parse;
6-pub mod server;
3+mod backend;
4+mod error;
5+mod parse;
6+mod server;
77
88 pub use backend::GitBackend;
99 pub use error::{Error, Result};
10-pub use parse::{LfsOperation, ParseError, parse_exec, parse_lfs_authenticate};
10+pub use parse::{LfsOperation, RepoPath};
1111 pub use server::{SshConfig, run};
crates/forge-ssh/src/parse.rsmodified+22 -19
@@ -23,9 +23,15 @@ const PREFIXES: &[(&str, GitService)] = &[
2323 ("git receive-pack ", GitService::ReceivePack),
2424 ];
2525
26-/// Returns the service and the repository path with `.git` stripped and the
27-/// leading `/` or `~/` removed. Anything else is an error.
28-pub fn parse_exec(cmd: &str) -> Result<(GitService, String), ParseError> {
26+/// Owner and repository name with `.git` stripped and the leading `/` or `~/` removed.
27+#[derive(Debug, Clone, PartialEq, Eq)]
28+pub struct RepoPath {
29+ pub owner: String,
30+ pub name: String,
31+}
32+
33+/// Returns the service and the repository path. Anything else is an error.
34+pub(crate) fn parse_exec(cmd: &str) -> Result<(GitService, RepoPath), ParseError> {
2935 let (service, rest) = split_service(cmd)?;
3036 let raw = unquote_argument(rest)?;
3137 let path = normalize_path(raw)?;
@@ -44,20 +50,14 @@ pub enum LfsOperation {
4450
4551 /// Parses `git-lfs-authenticate '<owner>/<repo>[.git]' download|upload`. The path follows the
4652 /// 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> {
4854 let rest = cmd
4955 .strip_prefix(LFS_AUTHENTICATE_PREFIX)
5056 .ok_or(ParseError::UnsupportedCommand)?;
51- // The path argument ends at its closing quote, or at the first space when it is bare.
52- let end = if let Some(quoted) = rest.strip_prefix('\'') {
53- quoted.find('\'').ok_or(ParseError::MalformedPath)? + 2
54- } else {
55- rest.find(' ').ok_or(ParseError::MalformedPath)?
56- };
57- let (arg, tail) = rest.split_at(end);
58- let operation = match tail {
59- " download" => LfsOperation::Download,
60- " upload" => LfsOperation::Upload,
57+ let (arg, op) = rest.rsplit_once(' ').ok_or(ParseError::MalformedPath)?;
58+ let operation = match op {
59+ "download" => LfsOperation::Download,
60+ "upload" => LfsOperation::Upload,
6161 _ => return Err(ParseError::MalformedPath),
6262 };
6363 let path = normalize_path(unquote_argument(arg)?)?;
@@ -96,8 +96,8 @@ fn unquote_argument(rest: &str) -> Result<&str, ParseError> {
9696 }
9797
9898 /// Strips one leading `/` or `~/`, then requires exactly `owner/repo` or
99-/// `owner/repo.git`, returning `owner/repo`.
100-fn normalize_path(raw: &str) -> Result<String, ParseError> {
99+/// `owner/repo.git`.
100+fn normalize_path(raw: &str) -> Result<RepoPath, ParseError> {
101101 let path = raw.strip_prefix('/').unwrap_or(raw);
102102 let path = path.strip_prefix("~/").unwrap_or(path);
103103
@@ -122,7 +122,10 @@ fn normalize_path(raw: &str) -> Result<String, ParseError> {
122122 if repo.is_empty() {
123123 return Err(ParseError::MalformedPath);
124124 }
125- Ok(format!("{owner}/{repo}"))
125+ Ok(RepoPath {
126+ owner: owner.to_string(),
127+ name: repo.to_string(),
128+ })
126129 }
127130
128131 #[cfg(test)]
@@ -131,7 +134,7 @@ mod tests {
131134
132135 fn ok(cmd: &str) -> (GitService, String) {
133136 match parse_exec(cmd) {
134- Ok(v) => v,
137+ Ok((service, path)) => (service, format!("{}/{}", path.owner, path.name)),
135138 Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"),
136139 }
137140 }
@@ -293,7 +296,7 @@ mod tests {
293296
294297 fn lfs_ok(cmd: &str) -> (String, LfsOperation) {
295298 match parse_lfs_authenticate(cmd) {
296- Ok(v) => v,
299+ Ok((path, operation)) => (format!("{}/{}", path.owner, path.name), operation),
297300 Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"),
298301 }
299302 }
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-
31 use std::borrow::Cow;
42 use std::collections::HashMap;
53 use std::fs::OpenOptions;
@@ -30,28 +28,20 @@ use crate::backend::GitBackend;
3028 use crate::error::{Error, Result};
3129 use crate::parse::{LFS_AUTHENTICATE_PREFIX, parse_exec, parse_lfs_authenticate};
3230
33-/// Stdout and stderr read size per message sent to the client.
3431 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.
3732 const STDIN_QUEUE: usize = 8;
38-/// Failed publickey attempts before the connection is dropped.
3933 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.
4234 const MAX_CONNECTIONS: usize = 256;
35+const AUTH_TIMEOUT: Duration = Duration::from_secs(30);
36+const INACTIVITY_TIMEOUT: Duration = Duration::from_secs(10 * 60);
4337
4438 #[derive(Debug, Clone)]
4539 pub struct SshConfig {
4640 pub listen: SocketAddr,
4741 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`).
5142 pub auth_rejection_time: Duration,
5243 }
5344
54-/// Runs the SSH server until it fails. Creates the ed25519 host key on first boot.
5545 pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()> {
5646 let host_key = load_or_create_host_key(&config.host_key_path)?;
5747 let russh_config = Arc::new(Config {
@@ -59,7 +49,7 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()
5949 methods: publickey_only(),
6050 auth_rejection_time: config.auth_rejection_time,
6151 max_auth_attempts: MAX_AUTH_ATTEMPTS,
62- inactivity_timeout: Some(config.inactivity_timeout),
52+ inactivity_timeout: Some(INACTIVITY_TIMEOUT),
6353 preferred: preferred_algorithms(),
6454 ..Config::default()
6555 });
@@ -72,13 +62,11 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()
7262 let (stream, peer) = match listener.accept().await {
7363 Ok(v) => v,
7464 Err(e) => {
75- // Typically EMFILE. Back off briefly instead of tearing the server down.
7665 tracing::warn!(error = %e, "ssh accept failed");
7766 tokio::time::sleep(Duration::from_millis(100)).await;
7867 continue;
7968 }
8069 };
81- // At the limit the socket is dropped at once rather than queued.
8270 let Ok(permit) = connection_slots.clone().try_acquire_owned() else {
8371 tracing::warn!(%peer, "ssh connection limit reached, dropping connection");
8472 continue;
@@ -86,28 +74,34 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()
8674 let authed = Arc::new(AtomicBool::new(false));
8775 let client = Client {
8876 backend: Arc::clone(&backend),
89- peer: Some(peer),
77+ peer,
9078 authed: Arc::clone(&authed),
9179 user_id: None,
9280 git_protocol: None,
9381 channels: HashMap::new(),
9482 };
9583 let russh_config = Arc::clone(&russh_config);
96- let auth_timeout = config.auth_timeout;
9784 tokio::spawn(async move {
98- // Held until the connection ends, then the slot is free for the next client.
9985 let _permit = permit;
100- let running = match run_stream(russh_config, stream, client).await {
101- Ok(running) => running,
102- Err(e) => {
86+ let running = match tokio::time::timeout(
87+ AUTH_TIMEOUT,
88+ run_stream(russh_config, stream, client),
89+ )
90+ .await
91+ {
92+ Ok(Ok(running)) => running,
93+ Ok(Err(e)) => {
10394 tracing::debug!(%peer, error = %e, "ssh handshake failed");
10495 return;
10596 }
97+ Err(_) => {
98+ tracing::debug!(%peer, "ssh handshake timed out");
99+ return;
100+ }
106101 };
107- // Drop unauthenticated connections after the auth timeout.
108102 let handle = running.handle();
109103 tokio::spawn(async move {
110- tokio::time::sleep(auth_timeout).await;
104+ tokio::time::sleep(AUTH_TIMEOUT).await;
111105 if !authed.load(Ordering::Acquire) {
112106 let _ = handle
113107 .disconnect(
@@ -125,14 +119,12 @@ pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()
125119 }
126120 }
127121
128-/// Publickey is the only accepted method.
129122 fn publickey_only() -> MethodSet {
130123 let mut methods = MethodSet::empty();
131124 methods.push(MethodKind::PublicKey);
132125 methods
133126 }
134127
135-/// Host and user key algorithms this server negotiates. RSA is not listed: russh is built without it.
136128 fn preferred_algorithms() -> Preferred {
137129 Preferred {
138130 key: Cow::Owned(vec![
@@ -153,7 +145,6 @@ fn preferred_algorithms() -> Preferred {
153145 }
154146 }
155147
156-/// Key types accepted for authentication. RSA keys are refused, as they are when a key is added.
157148 fn key_type_allowed(algorithm: &Algorithm) -> bool {
158149 matches!(
159150 algorithm,
@@ -164,7 +155,6 @@ fn key_type_allowed(algorithm: &Algorithm) -> bool {
164155 )
165156 }
166157
167-/// Accepts exactly `version=<digit>`, e.g. `version=2`.
168158 fn valid_git_protocol(value: &str) -> bool {
169159 let bytes = value.as_bytes();
170160 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> {
191181 if let Some(parent) = path.parent() {
192182 std::fs::create_dir_all(parent)?;
193183 }
194- // create_new so an existing key is never overwritten. The mode applies at creation.
195184 let mut file = OpenOptions::new()
196185 .write(true)
197186 .create_new(true)
@@ -204,15 +193,12 @@ fn load_or_create_host_key(path: &Path) -> Result<PrivateKey> {
204193 Ok(key)
205194 }
206195
207-/// Per-connection SSH handler.
208196 struct Client<B> {
209197 backend: Arc<B>,
210- peer: Option<SocketAddr>,
198+ peer: SocketAddr,
211199 authed: Arc<AtomicBool>,
212200 user_id: Option<String>,
213201 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.
216202 channels: HashMap<ChannelId, mpsc::Sender<Bytes>>,
217203 }
218204
@@ -227,8 +213,6 @@ impl<B: GitBackend> Client<B> {
227213 .await
228214 }
229215
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.
232216 async fn exec_lfs_authenticate(
233217 &self,
234218 session: &mut Session,
@@ -265,7 +249,6 @@ impl<B: GitBackend> Handler for Client<B> {
265249 _user: &str,
266250 offer: PublicKeyOffer<'_>,
267251 ) -> std::result::Result<Auth, Self::Error> {
268- // Probe before the client signs. Reject early so unknown keys never get a signature.
269252 if self.lookup(offer.public_key).await.is_some() {
270253 Ok(Auth::Accept)
271254 } else {
@@ -280,7 +263,7 @@ impl<B: GitBackend> Handler for Client<B> {
280263 ) -> std::result::Result<Auth, Self::Error> {
281264 match self.lookup(verified.public_key).await {
282265 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");
284267 self.user_id = Some(user_id);
285268 self.authed.store(true, Ordering::Release);
286269 Ok(Auth::Accept)
@@ -312,7 +295,6 @@ impl<B: GitBackend> Handler for Client<B> {
312295 variable_value: &str,
313296 _session: &mut Session,
314297 ) -> std::result::Result<(), Self::Error> {
315- // Only GIT_PROTOCOL is kept. Everything else is ignored, never forwarded.
316298 if variable_name == "GIT_PROTOCOL" && valid_git_protocol(variable_value) {
317299 self.git_protocol = Some(variable_value.to_owned());
318300 }
@@ -382,7 +364,6 @@ impl<B: GitBackend> Handler for Client<B> {
382364 _session: &mut Session,
383365 ) -> std::result::Result<(), Self::Error> {
384366 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.
386367 let _ = tx.send(Bytes::copy_from_slice(data)).await;
387368 }
388369 Ok(())
@@ -452,27 +433,8 @@ impl<B: GitBackend> Handler for Client<B> {
452433 session.channel_failure(channel)?;
453434 Ok(())
454435 }
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- }
472436 }
473437
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.
476438 fn reject_exec(
477439 session: &mut Session,
478440 channel: ChannelId,
@@ -486,27 +448,29 @@ fn reject_exec(
486448 Ok(())
487449 }
488450
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.
491451 async fn run_child(
492452 handle: Handle,
493453 channel: ChannelId,
494454 mut child: Child,
495455 stdin_rx: mpsc::Receiver<Bytes>,
496456 ) {
497- // Raised by a pump when the client has gone away, so the child is killed.
498457 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+ };
499463
500- let feeder = tokio::spawn(feed_stdin(child.stdin.take(), stdin_rx));
464+ let feeder = tokio::spawn(feed_stdin(stdin, stdin_rx));
501465 let stdout_task = tokio::spawn(pump(
502- child.stdout.take(),
466+ stdout,
503467 handle.clone(),
504468 channel,
505469 None,
506470 Arc::clone(&abort),
507471 ));
508472 let stderr_task = tokio::spawn(pump(
509- child.stderr.take(),
473+ stderr,
510474 handle.clone(),
511475 channel,
512476 Some(1),
@@ -521,7 +485,6 @@ async fn run_child(
521485 }
522486 };
523487
524- // Wait for the pumps so every byte of output is queued before exit status and EOF.
525488 let _ = stdout_task.await;
526489 let _ = stderr_task.await;
527490 feeder.abort();
@@ -531,23 +494,17 @@ async fn run_child(
531494 let _ = handle.close(channel).await;
532495 }
533496
534-async fn feed_stdin(stdin: Option<ChildStdin>, mut rx: mpsc::Receiver<Bytes>) {
535- let Some(mut stdin) = stdin else {
536- return;
537- };
497+async fn feed_stdin(mut stdin: ChildStdin, mut rx: mpsc::Receiver<Bytes>) {
538498 while let Some(chunk) = rx.recv().await {
539499 if stdin.write_all(&chunk).await.is_err() {
540500 break;
541501 }
542502 }
543- // Dropping stdin here closes the child's input.
544503 let _ = stdin.shutdown().await;
545504 }
546505
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.
549506 async fn pump<R>(
550- reader: Option<R>,
507+ mut reader: R,
551508 handle: Handle,
552509 channel: ChannelId,
553510 ext: Option<u32>,
@@ -555,17 +512,13 @@ async fn pump<R>(
555512 ) where
556513 R: AsyncRead + Unpin + Send + 'static,
557514 {
558- let Some(mut reader) = reader else {
559- return;
560- };
561515 let mut buf = vec![0u8; PUMP_CHUNK];
562516 loop {
563517 let n = match reader.read(&mut buf).await {
564518 Ok(0) | Err(_) => break,
565519 Ok(n) => n,
566520 };
567- // A right-sized copy: a chunk queued for the client holds only the bytes read.
568- let chunk = Bytes::copy_from_slice(buf.get(..n).unwrap_or_default());
521+ let chunk = Bytes::copy_from_slice(&buf[..n]);
569522 let sent = match ext {
570523 None => handle.data(channel, chunk).await.is_ok(),
571524 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;
88 use std::time::Duration;
99
1010 use forge_git::GitService;
11-use forge_ssh::{GitBackend, LfsOperation, SshConfig};
11+use forge_ssh::{GitBackend, LfsOperation, RepoPath, SshConfig};
1212 use russh::keys::PublicKey;
1313 use tokio::process::Command;
1414
@@ -30,7 +30,7 @@ impl GitBackend for TestBackend {
3030 &self,
3131 user_id: &str,
3232 service: GitService,
33- repo_path: &str,
33+ repo_path: &RepoPath,
3434 _git_protocol: Option<&str>,
3535 ) -> Result<Command, String> {
3636 if user_id != self.user_id {
@@ -38,7 +38,7 @@ impl GitBackend for TestBackend {
3838 }
3939 let repo = self
4040 .repos
41- .get(repo_path)
41+ .get(&format!("{}/{}", repo_path.owner, repo_path.name))
4242 .ok_or_else(|| "repository not found".to_owned())?;
4343 let mut cmd = Command::new("git");
4444 cmd.arg(service.name().trim_start_matches("git-")).arg(repo);
@@ -48,10 +48,11 @@ impl GitBackend for TestBackend {
4848 async fn lfs_authenticate(
4949 &self,
5050 user_id: &str,
51- repo_path: &str,
51+ repo_path: &RepoPath,
5252 operation: LfsOperation,
5353 ) -> 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) {
5556 return Err("repository not found".to_owned());
5657 }
5758 let op = match operation {
@@ -59,7 +60,7 @@ impl GitBackend for TestBackend {
5960 LfsOperation::Upload => "upload",
6061 };
6162 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}}"#
6364 ))
6465 }
6566 }
@@ -191,8 +192,6 @@ async fn clone_push_clone_over_ssh() {
191192 let config = SshConfig {
192193 listen: ([127, 0, 0, 1], port).into(),
193194 host_key_path: host_key.clone(),
194- auth_timeout: Duration::from_secs(10),
195- inactivity_timeout: Duration::from_secs(60),
196195 // Production rejects a failed auth after 1s. OpenSSH's `none` probe fails on every
197196 // connection, so the test would wait that second for each of its ~20 connections.
198197 auth_rejection_time: Duration::ZERO,
crates/forge-web-account/src/pages/banner.rsmodified+7 -9
@@ -4,8 +4,6 @@
44 //! in the `forge_banner` cookie for a signed-out visitor, and as the `banner_dismissed` account
55 //! preference for a signed-in user.
66
7-use std::time::Duration;
8-
97 use serde::Deserialize;
108 use topcoat::Result;
119 use topcoat::context::{Cx, context};
@@ -19,8 +17,6 @@ use crate::pages::theme_cookie::safe_back;
1917 use crate::state::AppState;
2018 use crate::views::{BANNER_COOKIE, BANNER_PREF};
2119
22-const BANNER_COOKIE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60);
23-
2420 #[derive(Deserialize)]
2521 struct DismissForm {
2622 #[serde(default)]
@@ -32,21 +28,22 @@ struct DismissForm {
3228 #[route(POST "/-/banner/dismiss")]
3329 async fn dismiss(cx: &Cx, Form(form): Form<DismissForm>) -> Result<SeeOther> {
3430 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? {
3635 context::<AppState>(cx)
3736 .store
3837 .set_user_pref(&user.id, BANNER_PREF, &form.hash)
3938 .await?;
40- } else if hash_ok {
41- let max_age =
42- time::Duration::seconds(i64::try_from(BANNER_COOKIE_TTL.as_secs()).unwrap_or(i64::MAX));
39+ } else {
4340 cookies(cx).add(
4441 Cookie::build((BANNER_COOKIE, form.hash))
4542 .path("/")
4643 .secure(true)
4744 .http_only(true)
4845 .same_site(SameSite::Lax)
49- .max_age(max_age)
46+ .max_age(time::Duration::days(365))
5047 .build(),
5148 );
5249 }
@@ -91,5 +88,6 @@ mod tests {
9188 Some(86_400 + 60)
9289 );
9390 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());
9492 }
9593 }
crates/forge-web-account/src/pages/passkeys.rsmodified+1 -2
@@ -12,7 +12,6 @@ use std::time::{Duration, Instant};
1212
1313 use base64::Engine;
1414 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
15-use forge_core::session::new_csrf_token;
1615 use forge_core::store::passkeys::{MAX_PASSKEYS, PasskeyRow, clean_name};
1716 use forge_core::{AuditAction, User};
1817 use http::header::{HeaderValue, RETRY_AFTER};
@@ -125,7 +124,7 @@ fn stash(ceremony: Ceremony) -> Option<String> {
125124 if map.len() >= CEREMONY_CAP {
126125 return None;
127126 }
128- let id = new_csrf_token();
127+ let id = forge_core::token::random_b64url();
129128 map.insert(id.clone(), (now, ceremony));
130129 Some(id)
131130 }
crates/forge-web-app/src/auth.rsmodified+4 -5
@@ -7,9 +7,8 @@ use std::sync::{Arc, OnceLock};
77 use std::time::Duration;
88
99 use forge_core::password::{hash_password, verify_password};
10-use forge_core::session::{new_csrf_token, new_session_token};
1110 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};
1312 use forge_core::{Session, Store, User, secret, totp};
1413 use tokio::sync::Semaphore;
1514 use topcoat::Result;
@@ -77,13 +76,13 @@ pub async fn current_user(cx: &Cx) -> forge_core::Result<Option<(User, Session)>
7776 /// Creates a session for `user` and sets the session cookie on the response.
7877 pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {
7978 let store = &context::<AppState>(cx).store;
80- let token = new_session_token();
79+ let token = random_b64url();
8180 let addr = client_addr(cx).to_string();
8281 let session = store
8382 .create_session(
8483 &user.id,
8584 &hash_token(&token),
86- &new_csrf_token(),
85+ &random_b64url(),
8786 &stamp_after(SESSION_TTL),
8887 user_agent(cx).as_deref(),
8988 Some(&addr),
@@ -134,7 +133,7 @@ pub fn pre_csrf_token(cx: &Cx) -> String {
134133 return value.to_owned();
135134 }
136135 }
137- let token = new_csrf_token();
136+ let token = random_b64url();
138137 session_jar(cx).add(pre_csrf_cookie(token.clone()));
139138 token
140139 }
crates/forge-web-app/src/backup/create.rsmodified+16 -19
@@ -265,27 +265,24 @@ async fn bundle_git_repo(
265265 ) -> Result<(String, Option<String>)> {
266266 let refs_sha256 = forge_git::backup::refs_checksum(git, repo_dir).await?;
267267 let out = staging.join(rel);
268- let bundle = match forge_git::backup::bundle_create(git, repo_dir, &out).await? {
269- None => {
270- if refs_sha256 != empty_sha256() {
271- return Err(Error::Conflict(format!(
272- "repo {label} changed while it was being bundled; run the backup again"
273- )));
274- }
275- None
268+ let bundle = if forge_git::backup::bundle_create(git, repo_dir, &out).await? {
269+ let scratch = scratch_root.join(scratch_name);
270+ forge_git::repo::init_bare(git, &scratch, "main").await?;
271+ let imported = forge_git::backup::bundle_verify(git, &scratch, &out).await?;
272+ remove_if_exists(&scratch);
273+ if imported != refs_sha256 {
274+ return Err(Error::Conflict(format!(
275+ "repo {label} changed while it was being bundled; run the backup again"
276+ )));
276277 }
277- Some(()) => {
278- let scratch = scratch_root.join(scratch_name);
279- forge_git::repo::init_bare(git, &scratch, "main").await?;
280- let imported = forge_git::backup::bundle_verify(git, &scratch, &out).await?;
281- remove_if_exists(&scratch);
282- if imported != refs_sha256 {
283- return Err(Error::Conflict(format!(
284- "repo {label} changed while it was being bundled; run the backup again"
285- )));
286- }
287- Some(rel.to_string())
278+ Some(rel.to_string())
279+ } else {
280+ if refs_sha256 != empty_sha256() {
281+ return Err(Error::Conflict(format!(
282+ "repo {label} changed while it was being bundled; run the backup again"
283+ )));
288284 }
285+ None
289286 };
290287 Ok((refs_sha256, bundle))
291288 }
crates/forge-web-app/src/ci/api.rsmodified+7 -8
@@ -7,16 +7,16 @@
77 //! Every response is JSON except the empty 204 of an empty claim and the body of a log append.
88
99 use forge_ci::config::JobSpec;
10-use forge_ci::mask::Masker;
10+use forge_ci::mask::{MaskStream, Masker};
1111 use forge_ci::proto::{
1212 BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse,
1313 JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER,
14- RegisterRequest, RegisterResponse, RequeueRequest, RestartMode as WireRestart,
15- RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch,
14+ RegisterRequest, RegisterResponse, RequeueRequest, RunnerConfigOverrides, RunnerConfigReport,
15+ RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch,
1616 };
1717 use forge_core::Error as CoreError;
1818 use forge_core::ci::{
19- CiJob, CiRun, CiRunner, JobState, MemoryOffer, QueueSkips, RunState, RunnerReport,
19+ CiJob, CiRun, CiRunner, JobState, MemoryOffer, QueueSkips, RestartMode, RunState, RunnerReport,
2020 };
2121 use futures_util::StreamExt;
2222 use http::header::HeaderValue;
@@ -308,9 +308,8 @@ async fn set_memory_headers(state: &AppState, runner_id: &str, res: &mut Respons
308308 }
309309
310310 /// The restart an admin asked for, in the wire type. `None` when nothing is pending.
311-async fn pending_restart(state: &AppState, runner_id: &str) -> Option<WireRestart> {
312- let mode = state.store.runner_restart(runner_id).await.ok().flatten()?;
313- WireRestart::parse(mode.as_str())
311+async fn pending_restart(state: &AppState, runner_id: &str) -> Option<RestartMode> {
312+ state.store.runner_restart(runner_id).await.ok().flatten()
314313 }
315314
316315 /// 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
976975 .await
977976 .map_err(api::internal)?;
978977 let masker = Masker::new(values.into_values());
979- let mut stream = masker.stream();
978+ let mut stream = MaskStream::new(masker);
980979 let mut out = stream.push(chunk);
981980 out.extend(stream.finish());
982981 Ok(out)
crates/forge-web-app/src/ci/api_tests.rsmodified+51 -103
@@ -3,7 +3,7 @@
33
44 use std::path::PathBuf;
55
6-use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, NewJob};
6+use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, NewJob, NewRun};
77 use forge_core::{Repo, Store, Visibility};
88 use http::header::{AUTHORIZATION, CONTENT_TYPE};
99 use serde_json::{Value, json};
@@ -72,12 +72,12 @@ struct Bare {
7272 _dir: tempfile::TempDir,
7373 }
7474
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 {
7676 let dir = tempfile::tempdir().expect("tempdir");
7777 let data_dir = dir.path().to_path_buf();
7878 let mut state = test_state(&data_dir).await;
7979 let mut config = (*state.config).clone();
80- tune(&mut config.ci);
80+ tune(&mut config);
8181 state.set_config(config);
8282 let store = state.store.clone();
8383 let router = app_router(state);
@@ -99,6 +99,11 @@ async fn bare(tune: impl FnOnce(&mut forge_core::config::CiConfig)) -> Bare {
9999 }
100100 }
101101
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+
102107 /// A runner registered through the store, with its secret.
103108 async fn runner(env: &Bare, labels: &[&str]) -> (CiRunner, String) {
104109 let token = env
@@ -147,15 +152,17 @@ async fn make_run(
147152 .collect();
148153 env.store
149154 .create_run(
150- &env.repo.id,
151- trigger,
152- "refs/heads/main",
153- commit,
154- pull,
155- &env.owner_id,
156- false,
155+ &NewRun {
156+ repo_id: &env.repo.id,
157+ trigger,
158+ git_ref: "refs/heads/main",
159+ commit_oid: commit,
160+ pull_number: pull,
161+ actor_id: &env.owner_id,
162+ needs_approval: false,
163+ config_error: None,
164+ },
157165 &new,
158- None,
159166 )
160167 .await
161168 .unwrap()
@@ -792,9 +799,9 @@ async fn put_artifact(
792799
793800 #[tokio::test]
794801 async fn artifact_upload_stores_and_checks_name_count_and_size() {
795- let env = bare(|ci| {
796- ci.max_artifacts_per_job = 3;
797- ci.max_artifact_mb = 1;
802+ let env = bare(|c| {
803+ c.ci.max_artifacts_per_job = 3;
804+ c.ci.max_artifact_mb = 1;
798805 })
799806 .await;
800807 let (_, secret) = runner(&env, &[]).await;
@@ -851,18 +858,22 @@ fn finish_body(outcome: &str) -> Vec<u8> {
851858 json_body(&json!({ "outcome": outcome, "exit_code": 0, "message": null }))
852859 }
853860
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+
854872 async fn finish_with(env: &Bare, secret: &str, body: Value) -> (String, Value) {
855873 let assignment = claim_job(&env.router, secret).await;
856874 let id = assignment["job_id"].as_str().unwrap().to_owned();
857875 let token = assignment["job_token"].as_str().unwrap();
858- let sent = send(
859- &env.router,
860- "POST",
861- &format!("/api/v1/ci/jobs/{id}/finish"),
862- &[bearer(token)],
863- json_body(&body),
864- )
865- .await;
876+ let sent = finish_as(&env.router, &id, token, json_body(&body)).await;
866877 assert_eq!(sent.status, 200, "{}", sent.json());
867878 (id, sent.json())
868879 }
@@ -957,14 +968,7 @@ async fn finish_queues_dependants_on_success_and_skips_them_on_failure() {
957968 let job_id = assignment["job_id"].as_str().unwrap();
958969 let token = assignment["job_token"].as_str().unwrap();
959970
960- let sent = send(
961- &env.router,
962- "POST",
963- &format!("/api/v1/ci/jobs/{job_id}/finish"),
964- &[bearer(token)],
965- finish_body("success"),
966- )
967- .await;
971+ let sent = finish_as(&env.router, job_id, token, finish_body("success")).await;
968972 assert_eq!(sent.status, 200, "{}", sent.json());
969973
970974 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() {
976980 assert_eq!(next["job_name"], "b");
977981 let b_id = next["job_id"].as_str().unwrap();
978982 let b_token = next["job_token"].as_str().unwrap();
979- let sent = send(
980- &env.router,
981- "POST",
982- &format!("/api/v1/ci/jobs/{b_id}/finish"),
983- &[bearer(b_token)],
984- finish_body("success"),
985- )
986- .await;
983+ let sent = finish_as(&env.router, b_id, b_token, finish_body("success")).await;
987984 assert_eq!(sent.status, 200, "{}", sent.json());
988985
989986 // 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() {
992989 let job_id = assignment["job_id"].as_str().unwrap();
993990 let token = assignment["job_token"].as_str().unwrap();
994991
995- let sent = send(
996- &env.router,
997- "POST",
998- &format!("/api/v1/ci/jobs/{job_id}/finish"),
999- &[bearer(token)],
1000- finish_body("failure"),
1001- )
1002- .await;
992+ let sent = finish_as(&env.router, job_id, token, finish_body("failure")).await;
1003993 assert_eq!(sent.status, 200, "{}", sent.json());
1004994 assert_eq!(sent.json()["state"], "failure");
1005995
@@ -1010,14 +1000,7 @@ async fn finish_queues_dependants_on_success_and_skips_them_on_failure() {
10101000 assert_eq!(run_now.state.as_str(), "failure");
10111001
10121002 // A finished job's token is refused.
1013- let again = send(
1014- &env.router,
1015- "POST",
1016- &format!("/api/v1/ci/jobs/{job_id}/finish"),
1017- &[bearer(token)],
1018- finish_body("success"),
1019- )
1020- .await;
1003+ let again = finish_as(&env.router, job_id, token, finish_body("success")).await;
10211004 assert_eq!(again.status, 401);
10221005 }
10231006
@@ -1025,7 +1008,7 @@ async fn finish_queues_dependants_on_success_and_skips_them_on_failure() {
10251008 /// fails. Neither finish leaves the run in a state that self-update deploys.
10261009 #[tokio::test]
10271010 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;
10291012 let (_, secret) = runner(&env, &[]).await;
10301013 let run = make_run(
10311014 &env,
@@ -1059,16 +1042,7 @@ async fn build_green_before_test_fails_never_qualifies_for_self_update() {
10591042 let job_id = assignment["job_id"].as_str().unwrap().to_owned();
10601043 let token = assignment["job_token"].as_str().unwrap().to_owned();
10611044 let router = env.router.clone();
1062- async move {
1063- send(
1064- &router,
1065- "POST",
1066- &format!("/api/v1/ci/jobs/{job_id}/finish"),
1067- &[bearer(&token)],
1068- finish_body(outcome),
1069- )
1070- .await
1071- }
1045+ async move { finish_as(&router, &job_id, &token, finish_body(outcome)).await }
10721046 };
10731047
10741048 let sent = finish(&build, "success").await;
@@ -1131,19 +1105,21 @@ async fn job_token_reads_over_smart_http_but_never_pushes() {
11311105 let owner_id = fx.store.user_by_username(OWNER).await.unwrap().unwrap().id;
11321106 fx.store
11331107 .create_run(
1134- &repo.id,
1135- "push",
1136- "refs/heads/main",
1137- &fx.root,
1138- None,
1139- &owner_id,
1140- false,
1108+ &NewRun {
1109+ repo_id: &repo.id,
1110+ trigger: "push",
1111+ git_ref: "refs/heads/main",
1112+ commit_oid: &fx.root,
1113+ pull_number: None,
1114+ actor_id: &owner_id,
1115+ needs_approval: false,
1116+ config_error: None,
1117+ },
11411118 &[NewJob {
11421119 name: "a",
11431120 spec_json: &spec(&[], &[]),
11441121 needs: &[],
11451122 }],
1146- None,
11471123 )
11481124 .await
11491125 .unwrap();
@@ -1231,34 +1207,6 @@ async fn job_token_reads_over_smart_http_but_never_pushes() {
12311207 );
12321208 }
12331209
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-}
12621210
12631211 #[tokio::test]
12641212 async fn runner_binary_needs_runner_auth_and_self_update() {
@@ -1277,7 +1225,7 @@ async fn runner_binary_needs_runner_auth_and_self_update() {
12771225 async fn runner_binary_streams_the_running_binary_with_its_sha() {
12781226 use sha2::{Digest, Sha256};
12791227
1280- let env = bare_with_self_update().await;
1228+ let env = bare(self_update_on).await;
12811229 let (_, secret) = runner(&env, &[]).await;
12821230 let uri = "/api/v1/ci/runners/binary";
12831231
@@ -1315,7 +1263,7 @@ async fn runner_binary_streams_the_running_binary_with_its_sha() {
13151263
13161264 #[tokio::test]
13171265 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;
13191267 let (_, secret) = runner(&env, &["linux"]).await;
13201268 let target = crate::self_update::target();
13211269 let claim_with = |target: Option<String>| {
crates/forge-web-app/src/ci/schedule.rsmodified+11 -9
@@ -6,7 +6,7 @@
66
77 use forge_ci::config::{CiConfig, Event, parse_config};
88 use forge_core::authz::{Action, authorize};
9-use forge_core::ci::{CiRun, NewJob};
9+use forge_core::ci::{CiRun, NewJob, NewRun};
1010 use forge_core::store::commit_status::StatusState;
1111 use forge_core::{PullRequest, Repo};
1212 use forge_git::browse::{peel_to_commit, read_blob, resolve_commit};
@@ -358,15 +358,17 @@ async fn create(
358358 let run = state
359359 .store
360360 .create_run(
361- &req.repo.id,
362- req.trigger,
363- req.git_ref,
364- req.commit,
365- req.pull_number,
366- req.actor_id,
367- req.needs_approval,
361+ &NewRun {
362+ repo_id: &req.repo.id,
363+ trigger: req.trigger,
364+ git_ref: req.git_ref,
365+ commit_oid: req.commit,
366+ pull_number: req.pull_number,
367+ actor_id: req.actor_id,
368+ needs_approval: req.needs_approval,
369+ config_error,
370+ },
368371 &new_jobs,
369- config_error,
370372 )
371373 .await?;
372374 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
249249 forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?;
250250 let bundled = bundle_create(&state.git, &git_dir, &dir.join("repo.bundle"))
251251 .await
252- .map_err(|e| format!("bundling {}: {e}", repo.name))?
253- .is_some();
252+ .map_err(|e| format!("bundling {}: {e}", repo.name))?;
254253
255254 let labels = state
256255 .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 {
131131 mod tests {
132132 use std::sync::Arc;
133133
134- use forge_core::mail::{MailKind, MailSettingsUpdate, OutboxStatus, Security};
134+ use forge_core::mail::{MailKind, MailSettingsUpdate, MailState, Security};
135135 use forge_core::time::{now_stamp, stamp_after};
136136
137137 use super::*;
@@ -207,7 +207,7 @@ mod tests {
207207 "the released row goes out without waiting"
208208 );
209209 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);
211211 }
212212
213213 #[tokio::test]
@@ -249,7 +249,7 @@ mod tests {
249249 assert_eq!(sent[0].to, "a@example.com");
250250 let row = state.store.recent_mail(10).await.expect("rows");
251251 assert_eq!(row.len(), 1);
252- assert_eq!(row[0].status(), OutboxStatus::Sent);
252+ assert_eq!(row[0].state_at(&now_stamp()), MailState::Sent);
253253 }
254254
255255 #[tokio::test]
@@ -284,7 +284,7 @@ mod tests {
284284 assert_eq!(tick(&state).await.expect("pass"), BACKSTOP);
285285 assert!(fake.sent().is_empty());
286286 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);
288288 assert_eq!(row[0].attempts, 0, "waiting costs no attempts");
289289 }
290290
@@ -322,7 +322,7 @@ mod tests {
322322 let by_key = |to: &str| rows.iter().find(|r| r.to_addr == to).expect("row").clone();
323323
324324 let retried = by_key("a@example.com");
325- assert_eq!(retried.status(), OutboxStatus::Queued);
325+ assert_eq!(retried.state_at(&now_stamp()), MailState::Retrying);
326326 assert_eq!(retried.attempts, 1);
327327 assert_eq!(retried.last_error.as_deref(), Some("timeout"));
328328 let due = retried.next_attempt_at.expect("scheduled");
@@ -330,7 +330,7 @@ mod tests {
330330 assert!(due <= stamp_after(Duration::from_secs(120)));
331331
332332 let bounced = by_key("b@example.com");
333- assert_eq!(bounced.status(), OutboxStatus::GaveUp);
333+ assert_eq!(bounced.state_at(&now_stamp()), MailState::Failed);
334334 assert_eq!(bounced.attempts, 1);
335335 assert_eq!(bounced.last_error.as_deref(), Some("550 no such user"));
336336 assert_eq!(fake.sent().len(), 0, "nothing reached the transport");
@@ -362,13 +362,13 @@ mod tests {
362362 };
363363 deliver(&state, &last).await;
364364 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);
366366 assert_eq!(after.last_error.as_deref(), Some("timeout"));
367367
368368 // The same failure on an early try is rescheduled instead.
369369 let early = OutboxEntry { attempts: 1, ..row };
370370 deliver(&state, &early).await;
371371 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);
373373 }
374374 }
crates/forge-web-app/src/merge.rsmodified+2 -2
@@ -1,7 +1,7 @@
11 //! Merging a pull request: the merge gate, the merge itself and what follows it, shared by the
22 //! merge page, auto-merge and the merge queue.
33
4-use forge_core::protection::{Protection, effective};
4+use forge_core::protection::{RuleFlags, effective};
55 use forge_core::store::commit_status::StatusState;
66 use forge_core::{MergeStyle, PullRequest, ReviewState, Role, User};
77 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
9999 /// The base branch's merge rule for a pull request, with the facts that rule checks.
100100 #[derive(Debug, Clone, PartialEq, Eq)]
101101 pub struct MergeGate {
102- pub rule: Protection,
102+ pub rule: RuleFlags,
103103 /// Distinct counting reviewers whose latest submitted review is an approval.
104104 pub approvals: u32,
105105 /// 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::{
1818 use forge_core::webhooks::WebhookEvent;
1919 use forge_core::{Repo, User};
2020 use forge_git::browse::{self, RefInfo, RefKind};
21+use forge_git::history::zero_oid;
2122 use forge_git::repo::repo_path;
2223 use forge_git::tags::{create_lightweight_tag, move_lightweight_tag, valid_tag_name};
2324 use futures_util::{Stream, StreamExt};
@@ -167,11 +168,6 @@ async fn resolve_target(
167168 )))
168169 }
169170
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-
175171 /// Tells the ref hooks, webhooks, CI and mirrors that a tag moved from `old` to `new`.
176172 async fn fire_tag_hook(
177173 state: &AppState,
@@ -202,6 +198,24 @@ fn check_fields(title: &str, body: &str) -> Result<(), ReleaseError> {
202198 Ok(())
203199 }
204200
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+
205219 /// `NotFound` when the release belongs to another repo.
206220 fn ensure_same_repo(repo: &Repo, release: &Release) -> Result<(), ReleaseError> {
207221 if release.repo_id == repo.id {
@@ -244,22 +258,9 @@ pub async fn create(
244258 actor: &User,
245259 input: CreateRelease,
246260 ) -> Result<Release, ReleaseError> {
247- if !valid_tag_name(&input.tag) {
248- return Err(ReleaseError::Invalid(
249- "the tag name may only use letters, digits and . _ - +".to_owned(),
250- ));
251- }
261+ check_tag_name(&input.tag)?;
252262 check_fields(&input.title, &input.body)?;
253- if state
254- .store
255- .release_by_tag(&repo.id, &input.tag)
256- .await?
257- .is_some()
258- {
259- return Err(ReleaseError::Conflict(
260- "a release already exists for this tag".to_owned(),
261- ));
262- }
263+ ensure_tag_unused(state, repo, &input.tag).await?;
263264 let path = path_of(state, repo)?;
264265 let refs = refs_of(path.clone()).await?;
265266 let target_oid = match tag_oid(&refs, &input.tag) {
@@ -272,7 +273,7 @@ pub async fn create(
272273 .unwrap_or(&repo.default_branch);
273274 let oid = resolve_target(&path, &refs, target).await?;
274275 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;
276277 oid
277278 }
278279 };
@@ -310,27 +311,14 @@ pub async fn update(
310311 check_fields(&edit.title, &edit.body)?;
311312 let new_tag = edit.tag.clone().unwrap_or_else(|| release.tag.clone());
312313 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- }
318314 let wanted = edit.target.as_deref().filter(|t| !t.is_empty());
319315 let path = path_of(state, repo)?;
320316 let refs = refs_of(path.clone()).await?;
321317 let mut target_oid = release.target_oid.clone();
322318
323319 if retag {
324- if state
325- .store
326- .release_by_tag(&repo.id, &new_tag)
327- .await?
328- .is_some()
329- {
330- return Err(ReleaseError::Conflict(
331- "a release already exists for this tag".to_owned(),
332- ));
333- }
320+ check_tag_name(&new_tag)?;
321+ ensure_tag_unused(state, repo, &new_tag).await?;
334322 match tag_oid(&refs, &new_tag) {
335323 Some(existing) => {
336324 if let Some(target) = wanted
@@ -348,7 +336,7 @@ pub async fn update(
348336 None => release.target_oid.clone(),
349337 };
350338 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;
352340 target_oid = oid;
353341 }
354342 }
@@ -367,7 +355,7 @@ pub async fn update(
367355 }
368356 None => {
369357 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;
371359 }
372360 }
373361 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-
101 pub mod worker;
112
123 use std::collections::HashMap;
@@ -17,31 +8,22 @@ use std::sync::{Mutex, PoisonError};
178 use std::time::{Duration, Instant};
189
1910 use forge_git::GitEnv;
11+use forge_git::backup::REFS_FORMAT;
2012 use forge_git::command::GitCommand;
2113 use tokio::process::Command;
2214 use tokio::sync::Notify;
2315
2416 use crate::state::AppState;
2517
26-/// How long a repo waits after its last ref update before it is pushed.
2718 pub const PUSH_DEBOUNCE: Duration = Duration::from_secs(5);
28-/// Newest database snapshots kept on the standby.
2919 pub const KEEP_SNAPSHOTS: usize = 24;
30-/// Name of the snapshot directory on the standby, under the base.
3120 const DB_DIR: &str = "db";
32-/// Name of the repo directory on the standby, under the base.
3321 const REPOS_DIR: &str = "repos";
34-/// Suffix of the replication status subject that names a repo's wiki.
3522 const WIKI_SUBJECT_SUFFIX: &str = ".wiki";
36-/// Prefix and suffix of a snapshot file name: `forge-<UTC stamp>.db`.
3723 const SNAPSHOT_PREFIX: &str = "forge-";
3824 const SNAPSHOT_SUFFIX: &str = ".db";
39-/// Stamp layout in snapshot names: `YYYYMMDDTHHMMSSZ`.
4025 const STAMP_LEN: usize = 16;
41-const REFS_FORMAT: &str = "--format=%(objectname) %(refname)";
4226
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.
4527 pub fn validate_remote_path(path: &str) -> Result<(), String> {
4628 let well_formed = path.starts_with('/')
4729 && path.len() > 1
@@ -60,17 +42,14 @@ pub fn validate_remote_path(path: &str) -> Result<(), String> {
6042 }
6143 }
6244
63-/// The replication status subject of a repo's wiki: `<id>.wiki`.
6445 pub fn wiki_subject(repo_id: &str) -> String {
6546 format!("{repo_id}{WIKI_SUBJECT_SUFFIX}")
6647 }
6748
68-/// The repo id a wiki subject names, or `None` for any other subject.
6949 pub fn wiki_subject_repo(subject: &str) -> Option<&str> {
7050 subject.strip_suffix(WIKI_SUBJECT_SUFFIX)
7151 }
7252
73-/// Repo ids are ULIDs: 26 ASCII alphanumerics. Checked before an id is used in a remote path.
7453 pub fn validate_repo_id(id: &str) -> Result<(), String> {
7554 if id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) {
7655 Ok(())
@@ -79,25 +58,19 @@ pub fn validate_repo_id(id: &str) -> Result<(), String> {
7958 }
8059 }
8160
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.
8461 pub fn sh_quote(arg: &str) -> String {
8562 format!("'{}'", arg.replace('\'', "'\\''"))
8663 }
8764
88-/// Where the standby is and how to reach it: `[user@]host:/absolute/base` plus the SSH port.
8965 #[derive(Debug, Clone, PartialEq, Eq)]
9066 pub struct Target {
9167 pub user: Option<String>,
9268 pub host: String,
9369 pub port: u16,
94- /// Validated absolute base directory on the standby.
9570 pub base: String,
9671 }
9772
9873 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.
10174 pub fn parse(spec: &str, port: u16) -> Result<Target, String> {
10275 let (dest, base) = spec
10376 .split_once(':')
@@ -133,7 +106,6 @@ impl Target {
133106 })
134107 }
135108
136- /// `user@host`, or `host` without a user.
137109 pub fn destination(&self) -> String {
138110 match &self.user {
139111 Some(user) => format!("{user}@{}", self.host),
@@ -141,7 +113,6 @@ impl Target {
141113 }
142114 }
143115
144- /// The `ssh://` URL git pushes a repo to.
145116 pub fn repo_url(&self, remote_repo_dir: &str) -> String {
146117 format!(
147118 "ssh://{}:{}{remote_repo_dir}",
@@ -151,8 +122,6 @@ impl Target {
151122 }
152123 }
153124
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.
156125 #[derive(Debug, Clone, PartialEq, Eq)]
157126 pub struct Layout {
158127 pub base: String,
@@ -174,19 +143,16 @@ impl Layout {
174143 format!("{}/{DB_DIR}", self.base)
175144 }
176145
177- /// `<base>/repos/<id>.git`. Fails for an id that is not a ULID.
178146 pub fn repo_dir(&self, repo_id: &str) -> Result<String, String> {
179147 validate_repo_id(repo_id)?;
180148 Ok(format!("{}/{repo_id}.git", self.repos_dir()))
181149 }
182150
183- /// `<base>/repos/<id>.wiki.git`: the standby copy of the repo's wiki.
184151 pub fn wiki_dir(&self, repo_id: &str) -> Result<String, String> {
185152 validate_repo_id(repo_id)?;
186153 Ok(format!("{}/{repo_id}.wiki.git", self.repos_dir()))
187154 }
188155
189- /// `<base>/db/forge-<stamp>.db`.
190156 pub fn snapshot_file(&self, stamp: &str) -> String {
191157 format!(
192158 "{}/{SNAPSHOT_PREFIX}{stamp}{SNAPSHOT_SUFFIX}",
@@ -199,7 +165,6 @@ impl Layout {
199165 }
200166 }
201167
202-/// A snapshot name `forge-<16-char stamp>.db` with a stamp of digits, `T` and `Z`.
203168 pub fn is_snapshot_name(name: &str) -> bool {
204169 let Some(stamp) = name
205170 .strip_prefix(SNAPSHOT_PREFIX)
@@ -215,7 +180,6 @@ pub fn is_snapshot_name(name: &str) -> bool {
215180 })
216181 }
217182
218-/// The UTC stamp used in snapshot names, `YYYYMMDDTHHMMSSZ`.
219183 pub fn snapshot_stamp() -> String {
220184 const FORMAT: &[time::format_description::FormatItem<'static>] =
221185 time::macros::format_description!("[year][month][day]T[hour][minute][second]Z");
@@ -224,23 +188,15 @@ pub fn snapshot_stamp() -> String {
224188 .unwrap_or_else(|_| "00000000T000000Z".to_owned())
225189 }
226190
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.
229191 pub trait StandbyTransport: Send + Sync {
230- /// Runs one shell command (already quoted) on the standby and returns its stdout.
231192 fn run(&self, remote_cmd: &str) -> impl Future<Output = Result<Vec<u8>, String>> + Send;
232193
233- /// The URL git pushes the repo at `remote_repo_dir` to.
234194 fn repo_url(&self, remote_repo_dir: &str) -> String;
235195
236- /// Whether git must be told to allow a plain local path as a transport.
237196 fn local_git(&self) -> bool;
238197
239- /// The `GIT_SSH_COMMAND` git must use to reach the standby, if any.
240198 fn push_ssh_command(&self) -> Option<String>;
241199
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.
244200 fn upload(
245201 &self,
246202 local: &Path,
@@ -248,7 +204,6 @@ pub trait StandbyTransport: Send + Sync {
248204 ) -> impl Future<Output = Result<(), String>> + Send;
249205 }
250206
251-/// Builds the `cat > tmp && mv tmp final` command used by every upload.
252207 fn upload_command(remote_path: &str) -> String {
253208 let (dir, name) = remote_path.rsplit_once('/').unwrap_or(("", remote_path));
254209 let tmp = format!("{dir}/.tmp-{name}");
@@ -260,7 +215,6 @@ fn upload_command(remote_path: &str) -> String {
260215 )
261216 }
262217
263-/// Runs `command` with its stdin fed from `file`, and fails on a non-zero exit.
264218 async fn pipe_file(mut command: Command, file: &Path) -> Result<(), String> {
265219 use std::process::Stdio;
266220 use tokio::io::AsyncWriteExt;
@@ -302,7 +256,6 @@ async fn pipe_file(mut command: Command, file: &Path) -> Result<(), String> {
302256 }
303257 }
304258
305-/// Runs `command` and returns stdout. A non-zero exit is an error carrying stderr.
306259 async fn capture(mut command: Command) -> Result<Vec<u8>, String> {
307260 use std::process::Stdio;
308261 command.stdin(Stdio::null()).kill_on_drop(true);
@@ -321,7 +274,6 @@ async fn capture(mut command: Command) -> Result<Vec<u8>, String> {
321274 }
322275 }
323276
324-/// Pushes every ref of the local bare repo `repo_dir` to `url` with `--mirror --force`.
325277 async fn push_mirror(
326278 git: &GitEnv,
327279 repo_dir: &Path,
@@ -348,8 +300,6 @@ async fn push_mirror(
348300 .map_err(|e| e.to_string())
349301 }
350302
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.
353303 #[derive(Debug, Clone)]
354304 pub struct SshTransport {
355305 target: Target,
@@ -366,7 +316,6 @@ impl SshTransport {
366316 }
367317 }
368318
369- /// The `-i`/`-o`/`-p` options, in order. Every one is a fixed word or a configured path.
370319 pub fn ssh_options(&self) -> Vec<String> {
371320 vec![
372321 "-i".to_owned(),
@@ -389,7 +338,6 @@ impl SshTransport {
389338 ]
390339 }
391340
392- /// The full argv after the program name: options, destination, then the remote command.
393341 pub fn ssh_argv(&self, remote_cmd: &str) -> Vec<String> {
394342 let mut argv = self.ssh_options();
395343 argv.push(self.target.destination());
@@ -397,7 +345,6 @@ impl SshTransport {
397345 argv
398346 }
399347
400- /// The value for `GIT_SSH_COMMAND`: the same ssh invocation, each word quoted for the shell.
401348 pub fn git_ssh_command(&self) -> String {
402349 std::iter::once("ssh".to_owned())
403350 .chain(self.ssh_options())
@@ -442,8 +389,6 @@ impl StandbyTransport for SshTransport {
442389 }
443390 }
444391
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.
447392 #[cfg(any(test, feature = "test-support"))]
448393 #[derive(Debug, Clone, Copy, Default)]
449394 pub struct LocalTransport;
@@ -480,8 +425,6 @@ impl StandbyTransport for LocalTransport {
480425 }
481426 }
482427
483-/// Pushes one local repo with `--mirror --force` through a transport. The remote directory must
484-/// already exist (see `worker::replicate_repo`).
485428 pub async fn push_repo<T: StandbyTransport>(
486429 transport: &T,
487430 git: &GitEnv,
@@ -498,7 +441,6 @@ pub async fn push_repo<T: StandbyTransport>(
498441 .await
499442 }
500443
501-/// The refs checksum of the bare repo at `remote_repo_dir`, read through the transport.
502444 pub async fn remote_refs_checksum<T: StandbyTransport>(
503445 transport: &T,
504446 remote_repo_dir: &str,
@@ -512,8 +454,6 @@ pub async fn remote_refs_checksum<T: StandbyTransport>(
512454 Ok(forge_git::backup::refs_checksum_of_listing(&out))
513455 }
514456
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.
517457 #[derive(Default)]
518458 pub struct ReplicationQueue {
519459 notify: Notify,
@@ -522,7 +462,6 @@ pub struct ReplicationQueue {
522462 }
523463
524464 impl ReplicationQueue {
525- /// Queues `repo_id` for a push once [`PUSH_DEBOUNCE`] has passed without another update.
526465 pub fn enqueue(&self, repo_id: &str) {
527466 let due = Instant::now() + PUSH_DEBOUNCE;
528467 self.pending
@@ -532,7 +471,6 @@ impl ReplicationQueue {
532471 self.notify.notify_one();
533472 }
534473
535- /// Removes and returns the repos whose debounce has passed at `now`, sorted by id.
536474 pub fn take_due(&self, now: Instant) -> Vec<String> {
537475 let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
538476 let mut due: Vec<String> = pending
@@ -547,7 +485,6 @@ impl ReplicationQueue {
547485 due
548486 }
549487
550- /// The earliest debounce due time among the queued repos, or `None` when nothing is queued.
551488 pub fn next_due(&self) -> Option<Instant> {
552489 self.pending
553490 .lock()
@@ -557,24 +494,20 @@ impl ReplicationQueue {
557494 .copied()
558495 }
559496
560- /// Asks the worker for a full reconcile pass as soon as it can.
561497 pub fn request_reconcile(&self) {
562498 self.reconcile.store(true, Ordering::SeqCst);
563499 self.notify.notify_one();
564500 }
565501
566- /// Returns true once per request.
567502 pub fn take_reconcile_request(&self) -> bool {
568503 self.reconcile.swap(false, Ordering::SeqCst)
569504 }
570505
571- /// Resolves when something is queued or a reconcile is requested.
572506 pub async fn wait(&self) {
573507 self.notify.notified().await;
574508 }
575509 }
576510
577-/// Queues a repo after any ref update. Does nothing when replication is disabled.
578511 pub fn enqueue_repo(state: &AppState, repo_id: &str) {
579512 if state.config.replication.enabled() {
580513 state.replication.enqueue(repo_id);
@@ -628,7 +561,6 @@ mod tests {
628561 assert_eq!(sh_quote("it's"), "'it'\\''s'");
629562 assert_eq!(sh_quote("$(rm -rf /)`x`;|&"), "'$(rm -rf /)`x`;|&'");
630563 assert_eq!(sh_quote("'"), "''\\'''");
631- // Round trip through a real shell: each quoted word comes back unchanged.
632564 let words = ["plain", "it's", "a b", "$HOME", "x'y'z", "back\\slash"];
633565 let line = words
634566 .iter()
crates/forge-web-app/src/ssh_backend.rsmodified+13 -19
@@ -6,7 +6,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
66 use forge_core::lfs_token::{self, LfsOp};
77 use forge_core::{Repo, User};
88 use forge_git::GitService;
9-use forge_ssh::{GitBackend, LfsOperation};
9+use forge_ssh::{GitBackend, LfsOperation, RepoPath};
1010
1111 use crate::access::{self, AccessError, Transport};
1212 use crate::state::AppState;
@@ -97,15 +97,12 @@ impl GitBackend for SshBackend {
9797 &self,
9898 user_id: &str,
9999 service: GitService,
100- repo_path: &str,
100+ repo_path: &RepoPath,
101101 git_protocol: Option<&str>,
102102 ) -> Result<tokio::process::Command, String> {
103- // parse_exec has already stripped the leading '/' and the trailing ".git".
104- let (owner, name) = repo_path
105- .split_once('/')
106- .ok_or_else(|| MSG_NOT_FOUND.to_string())?;
107-
108- let (user, repo, path) = self.authorize(user_id, owner, name, service).await?;
103+ let (user, repo, path) = self
104+ .authorize(user_id, &repo_path.owner, &repo_path.name, service)
105+ .await?;
109106
110107 Ok(access::git_process(
111108 &self.state,
@@ -123,20 +120,17 @@ impl GitBackend for SshBackend {
123120 async fn lfs_authenticate(
124121 &self,
125122 user_id: &str,
126- repo_path: &str,
123+ repo_path: &RepoPath,
127124 operation: LfsOperation,
128125 ) -> 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-
134126 // Download is a read and upload is a write, checked exactly as git does.
135- let service = match operation {
136- LfsOperation::Download => GitService::UploadPack,
137- LfsOperation::Upload => GitService::ReceivePack,
127+ let (service, op) = match operation {
128+ LfsOperation::Download => (GitService::UploadPack, LfsOp::Download),
129+ LfsOperation::Upload => (GitService::ReceivePack, LfsOp::Upload),
138130 };
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?;
140134
141135 if operation == LfsOperation::Upload {
142136 // Archived repos are refused by the Write check. Pull mirrors are read-only.
@@ -153,7 +147,7 @@ impl GitBackend for SshBackend {
153147 let token = lfs_token::issue(
154148 &self.state.key,
155149 &repo.id,
156- LfsOp::Any,
150+ op,
157151 now_unix() + LFS_TOKEN_TTL_SECS,
158152 );
159153 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 {
280280 let mut seen = HashSet::new();
281281 for id in ids {
282282 assert!(
283- forge_core::store::ui_prefs::valid_accent(id),
283+ forge_core::store::ui_prefs::valid_slug(id),
284284 "{kind} {id} is not a slug"
285285 );
286286 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::{
1212 releases_ci::{self as g, K},
1313 };
1414 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;
1616 use crate::state::AppState;
17+use forge_ci::steps::strip_ansi;
1718
1819 /// How far after the first error line its reason and place are looked for.
1920 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};
1212 use std::time::Duration;
1313
1414 use bytes::Bytes;
15+use forge_ci::steps::strip_ansi;
1516 use forge_core::ci::{CiArtifact, CiJob, CiRun, JobState};
1617 use forge_core::{Store, User};
1718 use futures_util::{Stream, TryStreamExt};
@@ -37,7 +38,7 @@ use crate::i18n::{
3738 use crate::live::{changed_event, events_response};
3839 use crate::pages::ci_runs::{
3940 age_text, can_write, commit_reachable_for, dock_bars, duration_text, job_href, run_href,
40- state_text, strip_ansi,
41+ state_text,
4142 };
4243 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};
4344 use crate::state::AppState;
crates/forge-web-pages/src/pages/ci_runs.rsmodified+1 -32
@@ -12,6 +12,7 @@ use std::collections::{HashMap, HashSet};
1212 use std::future::Future;
1313 use std::path::Path;
1414
15+use forge_ci::steps::strip_ansi;
1516 use forge_core::ci::{CiJob, CiRun, JobSample, JobState, JobStep, RunState, StepSample, StepState};
1617 use forge_core::{Action, Denied, Store, User, authorize};
1718 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 {
14711472 }
14721473 }
14731474
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-
15061475 /// The last non-empty line of a tail: what a job row previews.
15071476 fn last_line(tail: &[String]) -> Option<&str> {
15081477 tail.iter()
crates/forge-web-pages/src/pages/edit_history.rsmodified+15 -25
@@ -7,7 +7,7 @@
77 use std::collections::HashMap;
88 use std::sync::Arc;
99
10-use forge_core::{EditVersion, Issue, Thread};
10+use forge_core::{EditTarget, EditVersion, Issue, Thread};
1111 use similar::{ChangeTag, TextDiff};
1212 use topcoat::Result;
1313 use topcoat::context::{Cx, context};
@@ -36,35 +36,23 @@ path_param!(target_id);
3636 /// Unchanged lines shown around each change.
3737 const CONTEXT_LINES: usize = 3;
3838
39-/// The target kinds that have edit history, as the URL spells them.
40-const KINDS: [&str; 3] = ["issue", "comment", "review_comment"];
41-
4239 /// The history URL of one target of an item: `/{o}/{r}/{issues|pulls}/{n}/history/{kind}/{id}`.
4340 pub fn history_href(
4441 owner: &str,
4542 repo_name: &str,
4643 kind: ItemKind,
4744 number: i64,
48- target_kind: &str,
45+ target_kind: EditTarget,
4946 target: &str,
5047 ) -> String {
5148 repo_href(
5249 owner,
5350 repo_name,
5451 kind.segment(),
55- &format!("{number}/history/{target_kind}/{target}"),
52+ &format!("{number}/history/{}/{target}", target_kind.as_str()),
5653 )
5754 }
5855
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-
6856 /// Edit counts for the root comments and replies of `threads`, shared by every thread of a page.
6957 pub async fn thread_edit_counts(
7058 state: &AppState,
@@ -75,7 +63,7 @@ pub async fn thread_edit_counts(
7563 .flat_map(|thread| std::iter::once(&thread.root).chain(thread.replies.iter()))
7664 .map(|comment| comment.id.as_str())
7765 .collect();
78- Ok(Arc::new(edit_counts(state, "review_comment", &ids).await?))
66+ Ok(Arc::new(state.store.edit_count(EditTarget::ReviewComment, &ids).await?))
7967 }
8068
8169 /// 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(
170158 ctx: RepoCtx,
171159 kind_item: ItemKind,
172160 item: Issue,
173- target_kind: &'static str,
161+ target_kind: EditTarget,
174162 target: String,
175163 ) -> Result<impl View> {
176164 let target = target.as_str();
@@ -187,14 +175,14 @@ async fn history_page(
187175 }
188176
189177 let (current_title, current_body): (Option<String>, String) = match target_kind {
190- "issue" => (Some(item.title.clone()), item.body.clone()),
191- "comment" => {
178+ EditTarget::Issue => (Some(item.title.clone()), item.body.clone()),
179+ EditTarget::Comment => {
192180 let Some(comment) = state.store.comment_by_id(&item.id, target).await? else {
193181 return Err(not_found().into());
194182 };
195183 (None, comment.body)
196184 }
197- _ => {
185+ EditTarget::ReviewComment => {
198186 let Some(comment) = state.store.review_comment(target).await? else {
199187 return Err(not_found().into());
200188 };
@@ -214,7 +202,7 @@ async fn history_page(
214202 now,
215203 );
216204
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());
218206 let back = repo_href(&owner, &name, kind_item.segment(), &number.to_string());
219207 let page_title = g::history_title(lang, what, &format!("{owner}/{name} #{number}"));
220208 let header = ctx
@@ -305,10 +293,12 @@ async fn history_entry(cx: &Cx, lang: Lang, entry: HistoryEntry) -> Result<impl
305293 }
306294
307295 /// Parses the `{kind}` segment, or 404 for anything without edit history.
308-fn parse_kind(raw: &str) -> Result<&'static str> {
309- match KINDS.into_iter().find(|known| *known == raw) {
310- Some(known) => Ok(known),
311- None => Err(not_found().into()),
296+fn parse_kind(raw: &str) -> Result<EditTarget> {
297+ match raw {
298+ "issue" => Ok(EditTarget::Issue),
299+ "comment" => Ok(EditTarget::Comment),
300+ "review_comment" => Ok(EditTarget::ReviewComment),
301+ _ => Err(not_found().into()),
312302 }
313303 }
314304
crates/forge-web-pages/src/pages/issue_parts.rsmodified+13 -24
@@ -6,7 +6,9 @@
66 use std::collections::HashSet;
77 use topcoat::context::Cx;
88
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+};
1012 use forge_core::{Reaction, ReactionSummary, ReactionTarget};
1113 use forge_core::{ReviewState, Thread, authorize, validate_body};
1214 use serde::Deserialize;
@@ -19,7 +21,7 @@ use crate::auth::check_csrf;
1921 use crate::i18n::Lang;
2022 use crate::i18n::issues::{self as g, K};
2123 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};
2325 use crate::pages::notifications::{NotifyBox, notify_pill};
2426 use crate::pages::pull_reviews::suggest_states;
2527 use crate::pages::repo_ctx::RepoCtx;
@@ -52,7 +54,6 @@ impl ItemKind {
5254 }
5355 }
5456
55-// Permissions
5657
5758 pub fn viewer(ctx: &RepoCtx) -> Option<&User> {
5859 ctx.viewer.as_ref().map(|(user, _)| user)
@@ -116,7 +117,6 @@ pub fn csrf_of(ctx: &RepoCtx) -> String {
116117 .unwrap_or_default()
117118 }
118119
119-// Lookups
120120
121121 /// Parses an issue number: digits only, greater than zero. Anything else is 404.
122122 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
181181 .unwrap_or_default()
182182 }
183183
184-// Timeline
185184
186185 /// One comment, or the item body (which uses the same item shape without a delete action).
187186 pub struct CommentView {
@@ -343,7 +342,6 @@ fn event_line(
343342 "base_changed" => g::event_base_changed(lang, &text("from"), &text("to")),
344343 other => other.to_owned(),
345344 };
346- // A commit no branch, tag or pull request reaches keeps its short hash, as plain text.
347345 let (link_href, link_label) = if is_hex_oid(&commit) {
348346 let href = reachable
349347 .contains(&commit)
@@ -702,7 +700,6 @@ pub async fn load_discussion(
702700 let comments = store.list_comments(&item.id).await?;
703701 let events = store.list_events(&item.id).await?;
704702
705- // Every event's commit, checked against git in one walk before any row is built.
706703 let event_commits: Vec<String> = events
707704 .iter()
708705 .filter_map(|e| e.data.get("commit").and_then(Json::as_str))
@@ -711,7 +708,6 @@ pub async fn load_discussion(
711708 .collect();
712709 let reachable = reachable_among(&ctx.path, event_commits).await;
713710
714- // One batched lookup for every author and event actor on the page.
715711 let mut ids: Vec<String> = std::iter::once(item.author_id.clone())
716712 .chain(comments.iter().map(|c| c.author_id.clone()))
717713 .chain(events.iter().filter_map(|e| e.actor_id.clone()))
@@ -731,8 +727,6 @@ pub async fn load_discussion(
731727 let link = link_context(state, &ctx.repo, &ctx.repo.default_branch, "");
732728 let csrf = csrf_of(ctx);
733729
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.
736730 let viewer_id = viewer(ctx).map(|user| user.id.clone());
737731 let can_react = viewer_id.is_some() && !ctx.repo.archived && may_converse(ctx, item);
738732 let reaction_action = repo_href(&owner, &name, segment, &format!("{number}/reactions"));
@@ -752,7 +746,6 @@ pub async fn load_discussion(
752746 )
753747 .await?;
754748
755- // Body: first entry of the timeline.
756749 let (author, author_hash) = who(&item.author_id);
757750 let body_source = if item.body.trim().is_empty() {
758751 g::t(lang, K::NoDescription)
@@ -764,11 +757,11 @@ pub async fn load_discussion(
764757 ItemKind::Pull => format!("pull-{number}"),
765758 };
766759 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?;
768761 let body_history = body_edits
769762 .get(&item.id)
770763 .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));
772765 let body = CommentView {
773766 anchor: body_anchor,
774767 author: display_name(lang, &author),
@@ -797,9 +790,8 @@ pub async fn load_discussion(
797790 ),
798791 };
799792
800- // Comments and events, merged by creation time.
801793 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?;
803795 let mut keyed: Vec<(String, Entry)> = Vec::new();
804796 for comment in comments {
805797 let (who_name, hash) = who(&comment.author_id);
@@ -816,7 +808,9 @@ pub async fn load_discussion(
816808 when: When::new(lang, &comment.created_at, &tz, now),
817809 html: render_markdown(&comment.body, Some(&link)),
818810 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+ }),
820814 edit_href: mine
821815 .then(|| repo_href(&owner, &name, segment, &format!("{comment_path}/edit"))),
822816 delete_href: mine
@@ -992,7 +986,6 @@ pub fn reaction_bar_for(
992986 })
993987 }
994988
995-/// The hover text of a reaction: who made it, and how many more beyond the first names.
996989 /// A reaction's name in the viewer's language, for its picker button.
997990 fn reaction_label(lang: Lang, reaction: Reaction) -> &'static str {
998991 use crate::i18n::s;
@@ -1008,6 +1001,7 @@ fn reaction_label(lang: Lang, reaction: Reaction) -> &'static str {
10081001 }
10091002 }
10101003
1004+/// The hover text of a reaction: who made it, and how many more beyond the first names.
10111005 fn reaction_title(lang: Lang, users: &[String], count: usize) -> String {
10121006 let names = users.join(", ");
10131007 match count.saturating_sub(users.len()) {
@@ -1108,7 +1102,6 @@ async fn review_entries(
11081102 Ok(keyed)
11091103 }
11101104
1111-// Sidebar
11121105
11131106 pub struct LabelRow {
11141107 id: String,
@@ -1422,7 +1415,6 @@ pub async fn item_sidebar(
14221415 locked,
14231416 lock_reason,
14241417 } = sidebar;
1425- // "Assign to me" posts the whole list with the viewer added, since the route replaces it.
14261418 let assign_next = match viewer {
14271419 Some(me) if write && !assignees.iter().any(|a| *a == me) => {
14281420 let mut next = assignees.clone();
@@ -1447,7 +1439,6 @@ pub async fn item_sidebar(
14471439 })
14481440 }
14491441
1450-// Comment form
14511442
14521443 /// The id of the comment form. The head's Close and Reopen buttons post it with `form=`, so a
14531444 /// close can carry the draft text as its comment, as it always did.
@@ -1514,7 +1505,6 @@ pub async fn comment_form(
15141505 })
15151506 }
15161507
1517-// Comment and state POSTs
15181508
15191509 /// The form fields of a comment or state POST.
15201510 #[derive(Deserialize)]
@@ -1582,7 +1572,6 @@ pub async fn post_comment(
15821572 if !pull {
15831573 state.live.bump_issue(&ctx.repo.id, &item.id);
15841574 }
1585- // The author's contribution calendar counts the comment.
15861575 state.live.bump(&crate::live::Topic::User(user.id.clone()));
15871576 emit_comment(state, &ctx.repo, &sender, "created", pull, item, &comment).await;
15881577 notify::dispatch(
@@ -1611,11 +1600,11 @@ pub async fn post_comment(
16111600 ("reopened", Activity::Reopened)
16121601 };
16131602 emit_item_action(state, &ctx.repo, &sender, pull, item.number, action).await;
1614- if pull && action == "closed" {
1603+ if pull && next == IssueState::Closed {
16151604 crate::merge_queue::drop_pull(state, &ctx.repo, &item.id, "closed").await;
16161605 }
16171606 if pull
1618- && action == "reopened"
1607+ && next == IssueState::Open
16191608 && let Some(pr) = state
16201609 .store
16211610 .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};
1111 use forge_core::store::admin_alerts::AdminNotice;
1212 use forge_core::store::advisories::AdvisoryNotice;
1313 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};
1515 use futures_util::{Stream, StreamExt, future, stream};
1616 use serde::Deserialize;
1717 use topcoat::Result;
@@ -160,11 +160,11 @@ impl Entry {
160160
161161 /// The row for an issue or pull inbox entry.
162162 fn issue_row(lang: Lang, note: &Notification, tz: &str, now: i64) -> RowView {
163- let (kind_label, icon_class) = match (note.is_pull, note.issue_state.as_str()) {
164- (false, "open") => (g::t(lang, K::KindOpenIssue), "notif-icon issue-open"),
165- (false, _) => (g::t(lang, K::KindClosedIssue), "notif-icon issue-closed"),
166- (true, "open") => (g::t(lang, K::KindOpenPull), "notif-icon pull-open"),
167- (true, _) => (g::t(lang, K::KindClosedPull), "notif-icon pull-closed"),
163+ let (kind_label, icon_class) = match (note.is_pull, note.issue_state) {
164+ (false, IssueState::Open) => (g::t(lang, K::KindOpenIssue), "notif-icon issue-open"),
165+ (false, IssueState::Closed) => (g::t(lang, K::KindClosedIssue), "notif-icon issue-closed"),
166+ (true, IssueState::Open) => (g::t(lang, K::KindOpenPull), "notif-icon pull-open"),
167+ (true, IssueState::Closed) => (g::t(lang, K::KindClosedPull), "notif-icon pull-closed"),
168168 };
169169 let actor = note
170170 .last_actor_name
@@ -498,7 +498,11 @@ async fn inbox_fingerprint(state: &AppState, user: &User, all: bool) -> Result<S
498498 {
499499 lines.push(format!(
500500 "issue {} {} {} {} {}",
501- note.id, note.unread, note.updated_at, note.title, note.issue_state
501+ note.id,
502+ note.unread,
503+ note.updated_at,
504+ note.title,
505+ note.issue_state.as_str()
502506 ));
503507 }
504508 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-
41 use std::collections::{HashMap, HashSet};
52 use std::path::PathBuf;
63 use std::time::Duration;
74
85 use forge_core::Repo as RepoRecord;
96 use forge_core::WatchLevel;
10-use forge_core::time::stamp_before;
7+use forge_core::time::stamp_ago;
118 use forge_git::browse;
129 use forge_git::repo::repo_path;
1310 use topcoat::Result;
@@ -39,11 +36,6 @@ use crate::views::{
3936 path_param!(owner);
4037 path_param!(repo);
4138
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.
4739 #[component]
4840 pub async fn repo_head(
4941 cx: &Cx,
@@ -85,12 +77,10 @@ pub async fn repo_head(
8577 let vis = i18n::visibility_label(lang, visibility);
8678 let shown_title = title.unwrap_or_else(|| tab_title(lang, active, &name));
8779 let active = active.to_owned();
88- // The fork button posts with the same session CSRF token as the star form.
8980 let fork_control = match (can_fork, star.as_ref()) {
9081 (true, Some(star)) => Some((repo_href(&owner, &name, "fork", ""), star.csrf.clone())),
9182 _ => None,
9283 };
93- // Signed-in viewers get a button that stars or unstars; anonymous viewers see the count only.
9484 let star_control = match star {
9585 Some(star) => {
9686 let (path, label) = if star.starred {
@@ -103,7 +93,6 @@ pub async fn repo_head(
10393 None => None,
10494 };
10595 let anon_count = format!("\u{2605} {stars}");
106- // Signed-in viewers get the watch level select; everyone gets the watcher count.
10796 let watch_control = watch.map(|watch| {
10897 let level = match watch.level {
10998 WatchLevel::Participating => "participating",
@@ -114,13 +103,11 @@ pub async fn repo_head(
114103 });
115104 let watch_count = g::watching_count(lang, watchers);
116105 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.
118106 let mut parts: Vec<SubPart> = Vec::new();
119107 if is_code {
120108 if !description.is_empty() {
121109 parts.push(SubPart::text(description.as_str()));
122110 }
123- // Public is the usual case and says nothing; only a private repo says so.
124111 if private {
125112 parts.push(SubPart::text(vis));
126113 }
@@ -183,12 +170,9 @@ pub async fn repo_head(
183170 <p class="state" role="status">(g::t(lang, K::ArchivedNotice))</p>
184171 }
185172 }
186- // Boxed: this head is part of nearly every repo page's view.
187173 .boxed())
188174 }
189175
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).
192176 #[component]
193177 async fn clone_popover(
194178 cx: &Cx,
@@ -218,8 +202,6 @@ async fn clone_popover(
218202 })
219203 }
220204
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.
223205 #[component]
224206 async fn branches_card(
225207 cx: &Cx,
@@ -258,25 +240,16 @@ async fn default_commit(path: PathBuf, branch: String) -> Result<Option<String>>
258240 )
259241 }
260242
261-/// Most recent-push banners the repo home shows.
262243 const MAX_PUSH_BANNERS: usize = 3;
263-/// How far back a push still counts as recent.
264244 const RECENT_PUSH_WINDOW: Duration = Duration::from_secs(60 * 60);
265245
266-/// One "had recent pushes" banner: a branch the viewer pushed to, with its compare link.
267246 struct PushBanner {
268247 branch: String,
269248 at_unix: i64,
270- /// The push's stamp, for the `<time>` that shows its age.
271249 at: String,
272250 href: String,
273251 }
274252
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.
280253 async fn recent_push_banners(
281254 state: &AppState,
282255 ctx: &RepoCtx,
@@ -295,7 +268,6 @@ async fn recent_push_banners(
295268 None => repo.clone(),
296269 };
297270
298- // Forks the viewer owns, or that an organization they hold a role in owns.
299271 let mut forks: Vec<RepoRecord> = Vec::new();
300272 for fork in state.store.list_forks(&repo.id).await? {
301273 let mine = fork.owner_id == user.id
@@ -311,7 +283,7 @@ async fn recent_push_banners(
311283 let mut candidates: Vec<&RepoRecord> = vec![repo];
312284 candidates.extend(forks.iter());
313285 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);
315287 let pushes = state
316288 .store
317289 .recent_branch_pushes(&ids, &user.id, &since)
@@ -371,7 +343,6 @@ async fn recent_push_banners(
371343 Ok(banners)
372344 }
373345
374-/// The "had recent pushes" banners above the code tab.
375346 #[component]
376347 async fn recent_pushes(
377348 cx: &Cx,
@@ -415,7 +386,6 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
415386 let push_ssh = format!("git remote add origin {ssh}\ngit push -u origin {branch}");
416387 let title = format!("{}/{}", repo.owner_name, repo.name);
417388
418- // The tree and README exist only when the default branch has a commit.
419389 let mut tree = None;
420390 let mut readme = None;
421391 let mut bar = None;
@@ -443,7 +413,6 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
443413 ));
444414 }
445415 let follows = follows_branch(&refs, &branch);
446- // The home page follows the default branch even before its first push, so that push goes live.
447416 let live = home_live_url(&repo.owner_name, &repo.name, &branch);
448417 let owner_name = repo.owner_name.clone();
449418 let repo_name = repo.name.clone();
@@ -498,7 +467,6 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
498467 })
499468 }
500469
501-/// Other methods on a repo path get a plain 404, not a 405 that would reveal the route shape.
502470 #[route(* "/{owner}/{repo}")]
503471 async fn repo_other_methods(cx: &Cx) -> Result<&'static str> {
504472 Err(not_found().into())
crates/forge-web-repo/src/pages/authoring_tests.rsmodified+2 -2
@@ -1,6 +1,6 @@
11 //! Router-level tests for attachments, suggestions, task toggles and review requests.
22
3-use forge_core::Visibility;
3+use forge_core::{EditTarget, Visibility};
44 use topcoat::router::request::Request;
55 use topcoat::router::{Body, to_bytes};
66
@@ -206,7 +206,7 @@ async fn scenario_task_toggles(fx: &Fixture) {
206206 .unwrap()
207207 .unwrap();
208208 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();
210210 assert_eq!(history.len(), 1);
211211 assert_eq!(history[0].old_body, "- [ ] one\n- [ ] two\n");
212212
crates/forge-web-repo/src/pages/branches.rsmodified+3 -2
@@ -7,6 +7,7 @@ use std::time::{Duration, Instant};
77 use forge_core::protection::effective;
88 use forge_git::branches;
99 use forge_git::browse::{self, RefKind};
10+use forge_git::history::zero_oid;
1011 use serde::Deserialize;
1112 use topcoat::Result;
1213 use topcoat::context::{Cx, context};
@@ -372,7 +373,7 @@ async fn branch_create(cx: &Cx, Form(form): Form<CreateForm>) -> Result<SeeOther
372373 branch = %branch,
373374 "branch created from the branches page"
374375 );
375- let zero = "0".repeat(oid.len());
376+ let zero = zero_oid(&oid);
376377 let refname = format!("refs/heads/{branch}");
377378 if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &zero, &oid).await {
378379 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
430431 branch = %branch,
431432 "branch deleted from the branches page"
432433 );
433- let zero = "0".repeat(tip.len());
434+ let zero = zero_oid(&tip);
434435 let refname = format!("refs/heads/{branch}");
435436 if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &tip, &zero).await {
436437 tracing::error!(error = %e, "post-update work after branch delete failed");
crates/forge-web-repo/src/pages/ci_tests.rsmodified+48 -77
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
66 use std::sync::Arc;
77 use std::time::Duration;
88
9-use forge_core::ci::{CiJob, CiRun, JobState, NewJob, RunState};
9+use forge_core::ci::{CiJob, CiRun, JobState, NewJob, NewRun, RunState};
1010 use forge_core::{Role, Store, Visibility};
1111 use forge_git::repo::{init_bare, repo_path};
1212 use topcoat::router::request::Request;
@@ -133,6 +133,14 @@ impl Reply {
133133 }
134134 }
135135
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+
136144 async fn get(app: &Router, uri: &str, cookie: Option<&str>) -> Reply {
137145 let mut builder = Request::builder().method("GET").uri(uri);
138146 if let Some(cookie) = cookie {
@@ -183,15 +191,17 @@ async fn run_with(fx: &Fixture, jobs: &[&str], needs_approval: bool) -> CiRun {
183191 .collect();
184192 fx.store
185193 .create_run(
186- &fx.repo.id,
187- "push",
188- "refs/heads/main",
189- &fx.head,
190- None,
191- &fx.tahinli,
192- needs_approval,
194+ &NewRun {
195+ repo_id: &fx.repo.id,
196+ trigger: "push",
197+ git_ref: "refs/heads/main",
198+ commit_oid: &fx.head,
199+ pull_number: None,
200+ actor_id: &fx.tahinli,
201+ needs_approval,
202+ config_error: None,
203+ },
193204 &specs,
194- None,
195205 )
196206 .await
197207 .expect("run")
@@ -1058,12 +1068,7 @@ async fn approve_only_works_while_waiting_for_approval() {
10581068 &[],
10591069 )
10601070 .await;
1061- assert!(
1062- approved
1063- .location()
1064- .unwrap_or_default()
1065- .ends_with("?notice=approved")
1066- );
1071+ assert_notice(&approved, "approved");
10671072 let now = fx
10681073 .store
10691074 .run_by_id(&run.id)
@@ -1084,12 +1089,7 @@ async fn approve_only_works_while_waiting_for_approval() {
10841089 &[],
10851090 )
10861091 .await;
1087- assert!(
1088- again
1089- .location()
1090- .unwrap_or_default()
1091- .ends_with("?notice=not-waiting")
1092- );
1092+ assert_notice(&again, "not-waiting");
10931093 let still = fx
10941094 .store
10951095 .run_by_id(&run.id)
@@ -1112,12 +1112,7 @@ async fn cancel_and_rerun_post_and_redirect() {
11121112 &[],
11131113 )
11141114 .await;
1115- assert!(
1116- cancelled
1117- .location()
1118- .unwrap_or_default()
1119- .ends_with("?notice=cancelled")
1120- );
1115+ assert_notice(&cancelled, "cancelled");
11211116 let now = fx
11221117 .store
11231118 .run_by_id(&run.id)
@@ -1132,12 +1127,7 @@ async fn cancel_and_rerun_post_and_redirect() {
11321127 &[],
11331128 )
11341129 .await;
1135- assert!(
1136- finished
1137- .location()
1138- .unwrap_or_default()
1139- .ends_with("?notice=finished")
1140- );
1130+ assert_notice(&finished, "finished");
11411131
11421132 let rerun = post(
11431133 &fx.app,
@@ -1170,11 +1160,7 @@ async fn manual_run_refuses_an_unknown_branch() {
11701160 &[("branch", "no-such-branch")],
11711161 )
11721162 .await;
1173- assert!(
1174- res.location()
1175- .unwrap_or_default()
1176- .ends_with("?notice=no-branch")
1177- );
1163+ assert_notice(&res, "no-branch");
11781164 let reader = post(
11791165 &fx.app,
11801166 RUN_BASE,
@@ -1249,15 +1235,17 @@ async fn badge_follows_read_access_and_has_no_run_before_one_exists() {
12491235 }];
12501236 fx.store
12511237 .create_run(
1252- &open.id,
1253- "push",
1254- "refs/heads/main",
1255- SHA,
1256- None,
1257- &fx.tahinli,
1258- false,
1238+ &NewRun {
1239+ repo_id: &open.id,
1240+ trigger: "push",
1241+ git_ref: "refs/heads/main",
1242+ commit_oid: SHA,
1243+ pull_number: None,
1244+ actor_id: &fx.tahinli,
1245+ needs_approval: false,
1246+ config_error: None,
1247+ },
12591248 &specs,
1260- None,
12611249 )
12621250 .await
12631251 .expect("run");
@@ -1327,15 +1315,17 @@ async fn run_at(fx: &Fixture, commit: &str) {
13271315 }];
13281316 fx.store
13291317 .create_run(
1330- &fx.repo.id,
1331- "push",
1332- "refs/heads/main",
1333- commit,
1334- None,
1335- &fx.tahinli,
1336- false,
1318+ &NewRun {
1319+ repo_id: &fx.repo.id,
1320+ trigger: "push",
1321+ git_ref: "refs/heads/main",
1322+ commit_oid: commit,
1323+ pull_number: None,
1324+ actor_id: &fx.tahinli,
1325+ needs_approval: false,
1326+ config_error: None,
1327+ },
13371328 &specs,
1338- None,
13391329 )
13401330 .await
13411331 .expect("run");
@@ -1584,12 +1574,7 @@ async fn rerun_failed_and_rerun_job_start_partial_runs() {
15841574 let page = get(&fx.app, &run_url, Some(&writer)).await.text();
15851575 assert!(!page.contains("Re-run failed jobs"));
15861576 let early = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await;
1587- assert!(
1588- early
1589- .location()
1590- .unwrap_or_default()
1591- .ends_with("?notice=not-done")
1592- );
1577+ assert_notice(&early, "not-done");
15931578
15941579 let cancelled = post(&fx.app, &format!("{run_url}/cancel"), &writer, &[]).await;
15951580 assert_eq!(cancelled.status, 303);
@@ -1647,12 +1632,7 @@ async fn rerun_failed_and_rerun_job_start_partial_runs() {
16471632 &[],
16481633 )
16491634 .await;
1650- assert!(
1651- early
1652- .location()
1653- .unwrap_or_default()
1654- .ends_with("?notice=not-done")
1655- );
1635+ assert_notice(&early, "not-done");
16561636 let refused = post(
16571637 &fx.app,
16581638 &format!("/tahinli/proj/ci/jobs/{}/rerun", job.id),
@@ -1683,12 +1663,7 @@ async fn a_run_on_an_overwritten_commit_cannot_be_rerun() {
16831663 assert!(!page.contains(">Re-run<"));
16841664 assert!(!page.contains(&format!("/commit/{SHA}")));
16851665 let refused = post(&fx.app, &format!("{run_url}/rerun"), &writer, &[]).await;
1686- assert!(
1687- refused
1688- .location()
1689- .unwrap_or_default()
1690- .ends_with("?notice=overwritten")
1691- );
1666+ assert_notice(&refused, "overwritten");
16921667 }
16931668
16941669 #[tokio::test]
@@ -1702,11 +1677,7 @@ async fn a_run_with_no_failed_jobs_has_nothing_to_rerun() {
17021677 let page = get(&fx.app, &run_url, Some(&writer)).await.text();
17031678 assert!(!page.contains("Re-run failed jobs"));
17041679 let none = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await;
1705- assert!(
1706- none.location()
1707- .unwrap_or_default()
1708- .ends_with("?notice=no-failed")
1709- );
1680+ assert_notice(&none, "no-failed");
17101681 }
17111682
17121683 #[tokio::test]
crates/forge-web-repo/src/pages/pulls_merge.rsmodified+3 -3
@@ -166,7 +166,7 @@ mod tests {
166166 use std::path::{Path, PathBuf};
167167 use std::time::Duration;
168168
169- use forge_core::protection::Protection;
169+ use forge_core::protection::RuleFlags;
170170 use forge_core::store::commit_status::StatusState;
171171 use forge_core::{IssueState, PullRequest, Repo, Role, Store, User, Visibility};
172172 use forge_git::repo::{init_bare, repo_path};
@@ -1037,9 +1037,9 @@ mod tests {
10371037 checks: &[Option<StatusState>],
10381038 ) -> MergeGate {
10391039 MergeGate {
1040- rule: Protection {
1040+ rule: RuleFlags {
10411041 required_approvals: need,
1042- ..Protection::default()
1042+ ..RuleFlags::default()
10431043 },
10441044 approvals,
10451045 changes_requested: false,
crates/forge-web/src/boot.rsmodified+2 -8
@@ -28,7 +28,7 @@ use crate::ssh_backend::SshBackend;
2828 use crate::state::AppState;
2929
3030 /// 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);
3232
3333 /// Boots every component and serves until shutdown.
3434 pub async fn serve(
@@ -196,7 +196,7 @@ pub async fn serve(
196196 user_content = %user_content_listen,
197197 ssh = %ssh_listen,
198198 data_dir = %data_dir.display(),
199- git = %format_version(version),
199+ git = %forge_git::version::fmt_version(version),
200200 "forge starting"
201201 );
202202
@@ -213,8 +213,6 @@ pub async fn serve(
213213 let ssh_config = SshConfig {
214214 listen: ssh_listen,
215215 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),
218216 auth_rejection_time: ssh_auth_rejection_time,
219217 };
220218 let ssh_backend = Arc::new(SshBackend {
@@ -337,7 +335,3 @@ fn random_hex() -> String {
337335 rand::fill(&mut buf);
338336 hex::encode(buf)
339337 }
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;
33 use std::time::Duration;
44
55 use forge_core::Visibility;
6-use forge_core::time::stamp_before;
6+use forge_core::time::stamp_ago;
77
88 use forge_git::repo::{init_bare, repo_path};
99
@@ -13,11 +13,6 @@ use topcoat::router::{Body, Router, to_bytes};
1313 use crate::auth::SESSION_COOKIE;
1414 use crate::state::AppState;
1515
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-
2116 fn git(dir: &Path, args: &[&str]) {
2217 let status = Command::new("git")
2318 .current_dir(dir)
@@ -38,7 +33,8 @@ fn git(dir: &Path, args: &[&str]) {
3833
3934 /// `tahinli/demo` (public, default branch `main` with content) and `tahinli/secret` (private, empty).
4035 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());
4238 let tahinli = state
4339 .store
4440 .create_user("tahinli", None, "x", false)
@@ -91,18 +87,6 @@ async fn fixture(dir: &Path) -> (Router, AppState) {
9187 (router, state)
9288 }
9389
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-
10690 // The read-only tests below share one fixture: they only read the demo repo, so each scenario
10791 // sees the same pristine contents.
10892
@@ -112,7 +96,7 @@ async fn demo_pages_render_from_the_repo_contents() {
11296 let (router, _) = fixture(dir.path()).await;
11397
11498 // 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;
116100 assert_eq!(status, 200);
117101 assert!(body.contains("Hello from the README"), "README rendered");
118102 assert!(
@@ -134,16 +118,16 @@ async fn demo_pages_render_from_the_repo_contents() {
134118 assert!(body.contains("data-ref-filter"), "branch switcher rendered");
135119
136120 // 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;
138122 assert_eq!(status, 200);
139123 assert!(body.contains("main.rs"));
140124 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;
142126 assert_eq!(status, 200);
143127 assert!(body.contains("/tahinli/demo/tree/main/docs"));
144128
145129 // 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;
147131 assert_eq!(status, 200);
148132 assert!(body.contains("id=\"L1\""));
149133 assert!(body.contains("href=\"#L2\""));
@@ -151,33 +135,33 @@ async fn demo_pages_render_from_the_repo_contents() {
151135 assert!(body.contains("/assets/highlight.css?v="));
152136
153137 // 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;
155139 assert_eq!(status, 200);
156140 assert!(
157141 body.contains("markdown-body") && body.contains("<table>"),
158142 "GFM table rendered"
159143 );
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;
161145 assert_eq!(status, 200);
162146 assert!(body.contains("file-table"), "source shown as lines");
163147 assert!(!body.contains("markdown-body"), "not rendered");
164148
165149 // 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;
167151 assert_eq!(status, 200);
168152 assert!(body.contains("Binary file, 3 bytes"));
169153
170154 // 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;
172156 assert_eq!(status, 200);
173157 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;
175159 assert_eq!(status, 200);
176160 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;
178162 assert_eq!(status, 200);
179163 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;
181165 assert_eq!(status, 200);
182166 assert!(body.contains("Hello from the README"));
183167 }
@@ -193,7 +177,7 @@ async fn missing_paths_and_private_repos_are_404_for_anonymous() {
193177 "/tahinli/demo/blob/main/src",
194178 "/tahinli/demo/blob/main",
195179 ] {
196- let (status, _) = get(&router, uri).await;
180+ let (status, _) = get_as(&router, uri, None).await;
197181 assert_eq!(status, 404, "{uri}");
198182 }
199183 for uri in [
@@ -203,7 +187,7 @@ async fn missing_paths_and_private_repos_are_404_for_anonymous() {
203187 "/tahinli/secret/branches",
204188 "/tahinli/secret/tags",
205189 ] {
206- let (status, _) = get(&router, uri).await;
190+ let (status, _) = get_as(&router, uri, None).await;
207191 assert_eq!(status, 404, "{uri}");
208192 }
209193 }
@@ -237,7 +221,7 @@ fn make_branch(bare: &Path, branch: &str) {
237221
238222 /// Records a push of `branch` to `repo_id` by `actor_id`, `age` ago.
239223 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);
241225 let full = format!("refs/heads/{branch}");
242226 state
243227 .store