diff --git a/crates/forge-ci/src/config.rs b/crates/forge-ci/src/config.rs index 216b213..f0497b0 100644 --- a/crates/forge-ci/src/config.rs +++ b/crates/forge-ci/src/config.rs @@ -20,28 +20,28 @@ use serde::{Deserialize, Serialize}; use crate::error::ConfigError; /// Largest accepted `ci.toml`, in bytes. -pub const MAX_CONFIG_BYTES: usize = 64 * 1024; +const MAX_CONFIG_BYTES: usize = 64 * 1024; /// Largest number of jobs in one workflow. -pub const MAX_JOBS: usize = 20; +const MAX_JOBS: usize = 20; /// Default job timeout. -pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60; +const DEFAULT_TIMEOUT_MINUTES: u32 = 60; /// Smallest and largest allowed job timeout. -pub const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive = 1..=360; +const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive = 1..=360; /// Longest workflow `name`, in characters, after trimming. -pub const MAX_WORKFLOW_NAME_CHARS: usize = 40; +const MAX_WORKFLOW_NAME_CHARS: usize = 40; /// Largest number of `cache` entries in one job. -pub const MAX_CACHE_ENTRIES: usize = 8; +const MAX_CACHE_ENTRIES: usize = 8; /// Longest `cache` entry, in characters. -pub const MAX_CACHE_PATH_CHARS: usize = 200; +const MAX_CACHE_PATH_CHARS: usize = 200; /// Largest number of `[release] assets` entries. -pub const MAX_RELEASE_ASSETS: usize = 32; +const MAX_RELEASE_ASSETS: usize = 32; /// Longest `[release] title` template, in characters, after trimming. -pub const MAX_RELEASE_TITLE_CHARS: usize = 200; +const MAX_RELEASE_TITLE_CHARS: usize = 200; /// Most `[on] schedule` entries. -pub const MAX_SCHEDULES: usize = 8; +const MAX_SCHEDULES: usize = 8; /// Longest matrix axis value, in characters. -pub const MAX_MATRIX_VALUE_CHARS: usize = 64; +const MAX_MATRIX_VALUE_CHARS: usize = 64; /// A parsed and validated workflow. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -257,7 +257,7 @@ pub struct MatrixSpec { } /// Smallest and largest `memory` a job may declare, in bytes. -pub const MEMORY_RANGE_BYTES: std::ops::RangeInclusive = (64 << 20)..=(1024 << 30); +const MEMORY_RANGE_BYTES: std::ops::RangeInclusive = (64 << 20)..=(1024 << 30); /// Reads `memory` as a size string (`"4g"`) or as a byte count (what the stored spec holds). fn deserialize_memory<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { @@ -449,9 +449,9 @@ impl CiConfig { validate_trigger_glob("tag", pattern)?; } if self.on.schedule.len() > MAX_SCHEDULES { - return Err(ConfigError::InvalidSchedule { - expr: String::new(), - reason: format!("at most {MAX_SCHEDULES} schedules are allowed"), + return Err(ConfigError::TooManySchedules { + count: self.on.schedule.len(), + max: MAX_SCHEDULES, }); } for expr in &self.on.schedule { @@ -746,11 +746,6 @@ fn validate_release_title(title: &str) -> Result<(), ConfigError> { Ok(()) } -/// The job name without its matrix suffix: `test (stable, x86_64)` gives `test`. -pub fn base_job_name(name: &str) -> &str { - name.split_once(" (").map_or(name, |(base, _)| base) -} - /// Whether `selected` (a job name from the config) names `job`: the job itself, or any /// combination of the matrix job `selected`. fn names_job(selected: &str, job: &str) -> bool { @@ -1753,7 +1748,7 @@ artifacts = ["target/release/forge"] } let many = ["\"0 3 * * *\""; MAX_SCHEDULES + 1].join(", "); let text = format!("[on]\nschedule = [{many}]\n{}", job_toml("")); - assert!(matches!(err_of(&text), ConfigError::InvalidSchedule { .. })); + assert!(matches!(err_of(&text), ConfigError::TooManySchedules { .. })); } #[test] diff --git a/crates/forge-ci/src/error.rs b/crates/forge-ci/src/error.rs index 84e768c..35682b1 100644 --- a/crates/forge-ci/src/error.rs +++ b/crates/forge-ci/src/error.rs @@ -32,6 +32,9 @@ pub enum ConfigError { #[error("invalid schedule {expr:?}: {reason}")] InvalidSchedule { expr: String, reason: String }, + #[error("{count} schedules are defined, the limit is {max}")] + TooManySchedules { count: usize, max: usize }, + #[error("invalid job name {0:?}: must match ^[a-z0-9][a-z0-9_-]{{0,39}}$")] InvalidJobName(String), diff --git a/crates/forge-ci/src/mask.rs b/crates/forge-ci/src/mask.rs index bf13db2..f03a497 100644 --- a/crates/forge-ci/src/mask.rs +++ b/crates/forge-ci/src/mask.rs @@ -44,17 +44,6 @@ impl Masker { patterns.sort_by_key(|p| std::cmp::Reverse(p.len())); Self { patterns } } - - /// Masks every occurrence in `text`. - pub fn mask(&self, text: &str) -> String { - let (out, _) = scan(&self.patterns, text.as_bytes(), true); - bytes_to_string(out) - } - - /// Starts a streaming masker that owns a copy of this masker. - pub fn stream(&self) -> MaskStream { - MaskStream::new(self.clone()) - } } /// Masks a byte stream that arrives in chunks. @@ -98,11 +87,6 @@ fn scan(patterns: &[Vec], input: &[u8], last: bool) -> (Vec, Vec) { let mut i = 0; while i < input.len() { let tail = &input[i..]; - if let Some(p) = patterns.iter().find(|p| tail.starts_with(p)) { - out.extend_from_slice(MASK.as_bytes()); - i += p.len(); - continue; - } if !last && patterns .iter() @@ -110,19 +94,17 @@ fn scan(patterns: &[Vec], input: &[u8], last: bool) -> (Vec, Vec) { { return (out, tail.to_vec()); } + if let Some(p) = patterns.iter().find(|p| tail.starts_with(p)) { + out.extend_from_slice(MASK.as_bytes()); + i += p.len(); + continue; + } out.push(input[i]); i += 1; } (out, Vec::new()) } -fn bytes_to_string(bytes: Vec) -> String { - match String::from_utf8(bytes) { - Ok(s) => s, - Err(e) => String::from_utf8_lossy(e.as_bytes()).into_owned(), - } -} - #[cfg(test)] mod tests { use super::*; @@ -132,7 +114,7 @@ mod tests { } fn stream_all(m: &Masker, chunks: &[&[u8]]) -> String { - let mut s = m.stream(); + let mut s = MaskStream::new(m.clone()); let mut out = Vec::new(); for c in chunks { out.extend(s.push(c)); @@ -146,31 +128,36 @@ mod tests { let secret = "hunter2-secret"; let encoded = STANDARD.encode(secret.as_bytes()); let m = masker(&[secret]); - assert_eq!(m.mask(&format!("leak: {encoded}")), "leak: ***"); + assert_eq!(stream_all(&m, &[format!("leak: {encoded}").as_bytes()]), "leak: ***"); let other = masker(&["abcdefgh"]); let enc = STANDARD.encode("abcdefgh"); - assert_eq!(other.mask(&enc), "***"); + assert_eq!(stream_all(&other, &[enc.as_bytes()]), "***"); } #[test] fn short_values_are_ignored() { let m = masker(&["abc", "", "ab"]); - assert_eq!(m.mask("abc ab"), "abc ab"); + assert_eq!(stream_all(&m, &[b"abc ab"]), "abc ab"); // 4 chars is the minimum that is masked. let m = masker(&["abcd"]); - assert_eq!(m.mask("xabcdx"), "x***x"); + assert_eq!(stream_all(&m, &[b"xabcdx"]), "x***x"); } #[test] fn longest_match_wins() { let m = masker(&["secret-value", "secret"]); - assert_eq!(m.mask("a secret-value b"), "a *** b"); + assert_eq!(stream_all(&m, &[b"a secret-value b"]), "a *** b"); + } + + #[test] + fn longer_secret_wins_when_shorter_is_its_prefix() { + let m = masker(&["hunter", "hunter2-secret"]); + assert_eq!(stream_all(&m, &[b"hunter2-sec", b"ret"]), "***"); } #[test] fn empty_secret_set_is_a_no_op() { let m = Masker::new(std::iter::empty()); - assert_eq!(m.mask("anything"), "anything"); assert_eq!(stream_all(&m, &[b"anything"]), "anything"); } @@ -218,7 +205,7 @@ mod tests { #[test] fn held_bytes_are_bounded() { let m = masker(&["0123456789"]); - let mut s = m.stream(); + let mut s = MaskStream::new(m); let out = s.push(b"0123456"); assert!(out.is_empty()); assert!(s.held.len() <= 9); diff --git a/crates/forge-ci/src/steps.rs b/crates/forge-ci/src/steps.rs index 30e4eef..c27f9fc 100644 --- a/crates/forge-ci/src/steps.rs +++ b/crates/forge-ci/src/steps.rs @@ -59,19 +59,36 @@ pub fn scan(bytes: &[u8], base_offset: u64, depth: &mut u32) -> Scan { } } -/// Removes ANSI CSI sequences: `ESC [`, any parameter bytes, then one final byte. -fn strip_ansi(line: &str) -> String { +/// Drops the ANSI escape sequences and the other control characters (a tab stays) of a log line. +pub fn strip_ansi(line: &str) -> String { let mut out = String::with_capacity(line.len()); let mut chars = line.chars().peekable(); while let Some(c) = chars.next() { - if c == '\u{1b}' && chars.peek() == Some(&'[') { - chars.next(); - for f in chars.by_ref() { - if ('\u{40}'..='\u{7e}').contains(&f) { - break; + if c == '\u{1b}' { + match chars.peek() { + Some('[') => { + chars.next(); + for n in chars.by_ref() { + if ('@'..='~').contains(&n) { + break; + } + } } + Some(']') => { + chars.next(); + for n in chars.by_ref() { + if n == '\u{7}' { + break; + } + if n == '\u{1b}' { + chars.next_if_eq(&'\\'); + break; + } + } + } + _ => {} } - } else { + } else if c == '\t' || !c.is_control() { out.push(c); } } diff --git a/crates/forge-core/src/advisories.rs b/crates/forge-core/src/advisories.rs index 26768cf..a4ebd83 100644 --- a/crates/forge-core/src/advisories.rs +++ b/crates/forge-core/src/advisories.rs @@ -256,7 +256,6 @@ pub fn affects(advisory: &Advisory, version: &str) -> bool { /// `fixed` (exclusive) or `last_affected` (inclusive). `introduced` of `0` starts at the beginning. /// An interval still open at the end runs forever. fn range_affects(range: &Range, version: &semver::Version) -> bool { - // `Some(start)` while an interval is open; `start` is `None` when it began at `0`. let mut open: Option> = None; for event in &range.events { match event { @@ -264,7 +263,6 @@ fn range_affects(range: &Range, version: &semver::Version) -> bool { open = Some(if raw == "0" { None } else { - // An unreadable start is treated as "from the beginning": more alerts, never fewer. parse_version(raw) }); } diff --git a/crates/forge-core/src/alerts.rs b/crates/forge-core/src/alerts.rs index 1139a87..2c0c004 100644 --- a/crates/forge-core/src/alerts.rs +++ b/crates/forge-core/src/alerts.rs @@ -18,32 +18,6 @@ pub enum AlertKind { Replication, } -impl AlertKind { - pub const ALL: [AlertKind; 6] = [ - AlertKind::RunnerOffline, - AlertKind::Backup, - AlertKind::Disk, - AlertKind::CiKilled, - AlertKind::SelfUpdate, - AlertKind::Replication, - ]; - - pub fn as_str(self) -> &'static str { - match self { - AlertKind::RunnerOffline => "runner_offline", - AlertKind::Backup => "backup", - AlertKind::Disk => "disk", - AlertKind::CiKilled => "ci_killed", - AlertKind::SelfUpdate => "self_update", - AlertKind::Replication => "replication", - } - } - - pub fn parse(s: &str) -> Option { - AlertKind::ALL.into_iter().find(|k| k.as_str() == s) - } -} - /// Whether a job's result looks like the process was killed: SIGKILL (`signal: 9`, `SIGKILL`, /// `Killed`), the shell's `128 + 9` exit code, or an out-of-memory message. pub fn is_kill_signature(exit_code: Option, message: Option<&str>) -> bool { diff --git a/crates/forge-core/src/audit.rs b/crates/forge-core/src/audit.rs index a75e6ea..67891ab 100644 --- a/crates/forge-core/src/audit.rs +++ b/crates/forge-core/src/audit.rs @@ -6,339 +6,135 @@ use ulid::Ulid; use crate::time::now_stamp; -/// Every security-relevant action that is recorded. The `as_str` names are stored and shown. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AuditAction { - LoginSuccess, - LoginFailed, - Login2faFailed, - Logout, - PasswordChanged, - EmailChanged, - PasswordResetByAdmin, - TotpEnabled, - TotpDisabled, - RecoveryCodesRegenerated, - SshKeyAdded, - SshKeyRemoved, - GpgKeyAdded, - GpgKeyDeleted, - TokenCreated, - TokenRevoked, - SessionRevoked, - UserCreated, - UsernameChanged, - UserDeleted, - RepoCreated, - RepoDeleted, - RepoRenamed, - RepoTransferred, - RepoTransferInitiated, - RepoTransferAccepted, - RepoTransferDeclined, - RepoTransferCancelled, - RepoVisibilityChanged, - CollaboratorAdded, - CollaboratorRemoved, - CollaboratorRoleChanged, - BranchRuleCreated, - BranchRuleUpdated, - BranchRuleDeleted, - RepoArchived, - RepoUnarchived, - WebhookCreated, - WebhookUpdated, - WebhookDeleted, - MirrorCreated, - MirrorUpdated, - MirrorDeleted, - MirrorSyncFailed, - BackupStarted, - FsckStarted, - ReplicationReconcileStarted, - CiSecretSet, - CiSecretDeleted, - CiRunnerRegistered, - CiRunnerDeleted, - CiRunnerRestartRequested, - CiRunnerConfigChanged, - CiRegistrationTokenCreated, - AdvisoryAlertDismissed, - AdvisoryAlertReopened, - UiPrefsChanged, - DiscussionsEnabled, - DiscussionsDisabled, - DiscussionCreated, - DiscussionEdited, - DiscussionDeleted, - DiscussionLocked, - DiscussionUnlocked, - DiscussionAnswered, - DiscussionCommentCreated, - DiscussionCommentEdited, - DiscussionCommentDeleted, - MailSettingsUpdated, - MailTestQueued, - ServerSettingsUpdated, - ServerRestarted, - SnippetCreated, - SnippetUpdated, - SnippetDeleted, - WikiPageSaved, - WikiEnabled, - WikiDisabled, - WikiPushed, - OrgCreated, - OrgDeleted, - OrgSettingsUpdated, - OrgMemberAdded, - OrgMemberRemoved, - OrgMemberRoleChanged, - TeamCreated, - TeamUpdated, - TeamDeleted, - TeamMemberAdded, - TeamMemberRemoved, - TeamRepoAdded, - TeamRepoRemoved, - PasswordResetCompleted, - EmailVerified, - InviteSent, - InviteAccepted, - UserSuspended, - UserUnsuspended, - AdminGranted, - AdminRevoked, - TotpDisabledByAdmin, - PasskeyAdded, - PasskeyRenamed, - PasskeyDeleted, - PasskeysRemovedByAdmin, - PasskeyLogin, -} +macro_rules! audit_actions { + ($($variant:ident => $name:literal,)*) => { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub enum AuditAction { + $($variant,)* + } -impl AuditAction { - /// Every action, in declaration order. Used to parse filter values. - pub const ALL: &'static [AuditAction] = &[ - AuditAction::LoginSuccess, - AuditAction::LoginFailed, - AuditAction::Login2faFailed, - AuditAction::Logout, - AuditAction::PasswordChanged, - AuditAction::EmailChanged, - AuditAction::PasswordResetByAdmin, - AuditAction::TotpEnabled, - AuditAction::TotpDisabled, - AuditAction::RecoveryCodesRegenerated, - AuditAction::SshKeyAdded, - AuditAction::SshKeyRemoved, - AuditAction::GpgKeyAdded, - AuditAction::GpgKeyDeleted, - AuditAction::TokenCreated, - AuditAction::TokenRevoked, - AuditAction::SessionRevoked, - AuditAction::UserCreated, - AuditAction::UsernameChanged, - AuditAction::UserDeleted, - AuditAction::RepoCreated, - AuditAction::RepoDeleted, - AuditAction::RepoRenamed, - AuditAction::RepoTransferred, - AuditAction::RepoTransferInitiated, - AuditAction::RepoTransferAccepted, - AuditAction::RepoTransferDeclined, - AuditAction::RepoTransferCancelled, - AuditAction::RepoVisibilityChanged, - AuditAction::CollaboratorAdded, - AuditAction::CollaboratorRemoved, - AuditAction::CollaboratorRoleChanged, - AuditAction::BranchRuleCreated, - AuditAction::BranchRuleUpdated, - AuditAction::BranchRuleDeleted, - AuditAction::RepoArchived, - AuditAction::RepoUnarchived, - AuditAction::WebhookCreated, - AuditAction::WebhookUpdated, - AuditAction::WebhookDeleted, - AuditAction::MirrorCreated, - AuditAction::MirrorUpdated, - AuditAction::MirrorDeleted, - AuditAction::MirrorSyncFailed, - AuditAction::BackupStarted, - AuditAction::FsckStarted, - AuditAction::ReplicationReconcileStarted, - AuditAction::CiSecretSet, - AuditAction::CiSecretDeleted, - AuditAction::CiRunnerRegistered, - AuditAction::CiRunnerDeleted, - AuditAction::CiRunnerRestartRequested, - AuditAction::CiRunnerConfigChanged, - AuditAction::CiRegistrationTokenCreated, - AuditAction::AdvisoryAlertDismissed, - AuditAction::AdvisoryAlertReopened, - AuditAction::UiPrefsChanged, - AuditAction::DiscussionsEnabled, - AuditAction::DiscussionsDisabled, - AuditAction::DiscussionCreated, - AuditAction::DiscussionEdited, - AuditAction::DiscussionDeleted, - AuditAction::DiscussionLocked, - AuditAction::DiscussionUnlocked, - AuditAction::DiscussionAnswered, - AuditAction::DiscussionCommentCreated, - AuditAction::DiscussionCommentEdited, - AuditAction::DiscussionCommentDeleted, - AuditAction::MailSettingsUpdated, - AuditAction::MailTestQueued, - AuditAction::ServerSettingsUpdated, - AuditAction::ServerRestarted, - AuditAction::SnippetCreated, - AuditAction::SnippetUpdated, - AuditAction::SnippetDeleted, - AuditAction::WikiPageSaved, - AuditAction::WikiEnabled, - AuditAction::WikiDisabled, - AuditAction::WikiPushed, - AuditAction::OrgCreated, - AuditAction::OrgDeleted, - AuditAction::OrgSettingsUpdated, - AuditAction::OrgMemberAdded, - AuditAction::OrgMemberRemoved, - AuditAction::OrgMemberRoleChanged, - AuditAction::TeamCreated, - AuditAction::TeamUpdated, - AuditAction::TeamDeleted, - AuditAction::TeamMemberAdded, - AuditAction::TeamMemberRemoved, - AuditAction::TeamRepoAdded, - AuditAction::TeamRepoRemoved, - AuditAction::PasswordResetCompleted, - AuditAction::EmailVerified, - AuditAction::InviteSent, - AuditAction::InviteAccepted, - AuditAction::UserSuspended, - AuditAction::UserUnsuspended, - AuditAction::AdminGranted, - AuditAction::AdminRevoked, - AuditAction::TotpDisabledByAdmin, - AuditAction::PasskeyAdded, - AuditAction::PasskeyRenamed, - AuditAction::PasskeyDeleted, - AuditAction::PasskeysRemovedByAdmin, - AuditAction::PasskeyLogin, - ]; + impl AuditAction { + pub const ALL: &'static [AuditAction] = &[$(AuditAction::$variant,)*]; - pub fn as_str(self) -> &'static str { - match self { - AuditAction::LoginSuccess => "login_success", - AuditAction::LoginFailed => "login_failed", - AuditAction::Login2faFailed => "login_2fa_failed", - AuditAction::Logout => "logout", - AuditAction::PasswordChanged => "password_changed", - AuditAction::EmailChanged => "email_changed", - AuditAction::PasswordResetByAdmin => "password_reset_by_admin", - AuditAction::TotpEnabled => "totp_enabled", - AuditAction::TotpDisabled => "totp_disabled", - AuditAction::RecoveryCodesRegenerated => "recovery_codes_regenerated", - AuditAction::SshKeyAdded => "ssh_key_added", - AuditAction::SshKeyRemoved => "ssh_key_removed", - AuditAction::GpgKeyAdded => "gpg_key_added", - AuditAction::GpgKeyDeleted => "gpg_key_deleted", - AuditAction::TokenCreated => "token_created", - AuditAction::TokenRevoked => "token_revoked", - AuditAction::SessionRevoked => "session_revoked", - AuditAction::UserCreated => "user_created", - AuditAction::UsernameChanged => "username_changed", - AuditAction::UserDeleted => "user_deleted", - AuditAction::RepoCreated => "repo_created", - AuditAction::RepoDeleted => "repo_deleted", - AuditAction::RepoRenamed => "repo_renamed", - AuditAction::RepoTransferred => "repo_transferred", - AuditAction::RepoTransferInitiated => "repo_transfer_initiated", - AuditAction::RepoTransferAccepted => "repo_transfer_accepted", - AuditAction::RepoTransferDeclined => "repo_transfer_declined", - AuditAction::RepoTransferCancelled => "repo_transfer_cancelled", - AuditAction::RepoVisibilityChanged => "repo_visibility_changed", - AuditAction::CollaboratorAdded => "collaborator_added", - AuditAction::CollaboratorRemoved => "collaborator_removed", - AuditAction::CollaboratorRoleChanged => "collaborator_role_changed", - AuditAction::BranchRuleCreated => "branch_rule_created", - AuditAction::BranchRuleUpdated => "branch_rule_updated", - AuditAction::BranchRuleDeleted => "branch_rule_deleted", - AuditAction::RepoArchived => "repo_archived", - AuditAction::RepoUnarchived => "repo_unarchived", - AuditAction::WebhookCreated => "webhook_created", - AuditAction::WebhookUpdated => "webhook_updated", - AuditAction::WebhookDeleted => "webhook_deleted", - AuditAction::MirrorCreated => "mirror_created", - AuditAction::MirrorUpdated => "mirror_updated", - AuditAction::MirrorDeleted => "mirror_deleted", - AuditAction::MirrorSyncFailed => "mirror_sync_failed", - AuditAction::BackupStarted => "backup_started", - AuditAction::FsckStarted => "fsck_started", - AuditAction::ReplicationReconcileStarted => "replication_reconcile_started", - AuditAction::CiSecretSet => "ci_secret_set", - AuditAction::CiSecretDeleted => "ci_secret_deleted", - AuditAction::CiRunnerRegistered => "ci_runner_registered", - AuditAction::CiRunnerDeleted => "ci_runner_deleted", - AuditAction::CiRunnerRestartRequested => "ci_runner_restart_requested", - AuditAction::CiRunnerConfigChanged => "ci_runner_config_changed", - AuditAction::CiRegistrationTokenCreated => "ci_registration_token_created", - AuditAction::AdvisoryAlertDismissed => "advisory_alert_dismissed", - AuditAction::AdvisoryAlertReopened => "advisory_alert_reopened", - AuditAction::UiPrefsChanged => "ui_prefs_changed", - AuditAction::DiscussionsEnabled => "discussions_enabled", - AuditAction::DiscussionsDisabled => "discussions_disabled", - AuditAction::DiscussionCreated => "discussion_created", - AuditAction::DiscussionEdited => "discussion_edited", - AuditAction::DiscussionDeleted => "discussion_deleted", - AuditAction::DiscussionLocked => "discussion_locked", - AuditAction::DiscussionUnlocked => "discussion_unlocked", - AuditAction::DiscussionAnswered => "discussion_answered", - AuditAction::DiscussionCommentCreated => "discussion_comment_created", - AuditAction::DiscussionCommentEdited => "discussion_comment_edited", - AuditAction::DiscussionCommentDeleted => "discussion_comment_deleted", - AuditAction::MailSettingsUpdated => "mail_settings_updated", - AuditAction::MailTestQueued => "mail_test_queued", - AuditAction::ServerSettingsUpdated => "server_settings_updated", - AuditAction::ServerRestarted => "server_restarted", - AuditAction::SnippetCreated => "snippet_created", - AuditAction::SnippetUpdated => "snippet_updated", - AuditAction::SnippetDeleted => "snippet_deleted", - AuditAction::WikiPageSaved => "wiki_page_saved", - AuditAction::WikiEnabled => "wiki_enabled", - AuditAction::WikiDisabled => "wiki_disabled", - AuditAction::WikiPushed => "wiki_pushed", - AuditAction::OrgCreated => "org_created", - AuditAction::OrgDeleted => "org_deleted", - AuditAction::OrgSettingsUpdated => "org_settings_updated", - AuditAction::OrgMemberAdded => "org_member_added", - AuditAction::OrgMemberRemoved => "org_member_removed", - AuditAction::OrgMemberRoleChanged => "org_member_role_changed", - AuditAction::TeamCreated => "team_created", - AuditAction::TeamUpdated => "team_updated", - AuditAction::TeamDeleted => "team_deleted", - AuditAction::TeamMemberAdded => "team_member_added", - AuditAction::TeamMemberRemoved => "team_member_removed", - AuditAction::TeamRepoAdded => "team_repo_added", - AuditAction::TeamRepoRemoved => "team_repo_removed", - AuditAction::PasswordResetCompleted => "password_reset_completed", - AuditAction::EmailVerified => "email_verified", - AuditAction::InviteSent => "invite_sent", - AuditAction::InviteAccepted => "invite_accepted", - AuditAction::UserSuspended => "user_suspended", - AuditAction::UserUnsuspended => "user_unsuspended", - AuditAction::AdminGranted => "admin_granted", - AuditAction::AdminRevoked => "admin_revoked", - AuditAction::TotpDisabledByAdmin => "totp_disabled_by_admin", - AuditAction::PasskeyAdded => "passkey_added", - AuditAction::PasskeyRenamed => "passkey_renamed", - AuditAction::PasskeyDeleted => "passkey_deleted", - AuditAction::PasskeysRemovedByAdmin => "passkeys_removed_by_admin", - AuditAction::PasskeyLogin => "passkey_login", + pub fn as_str(self) -> &'static str { + match self { + $(AuditAction::$variant => $name,)* + } + } } - } + }; +} + +audit_actions! { + LoginSuccess => "login_success", + LoginFailed => "login_failed", + Login2faFailed => "login_2fa_failed", + Logout => "logout", + PasswordChanged => "password_changed", + EmailChanged => "email_changed", + PasswordResetByAdmin => "password_reset_by_admin", + TotpEnabled => "totp_enabled", + TotpDisabled => "totp_disabled", + RecoveryCodesRegenerated => "recovery_codes_regenerated", + SshKeyAdded => "ssh_key_added", + SshKeyRemoved => "ssh_key_removed", + GpgKeyAdded => "gpg_key_added", + GpgKeyDeleted => "gpg_key_deleted", + TokenCreated => "token_created", + TokenRevoked => "token_revoked", + SessionRevoked => "session_revoked", + UserCreated => "user_created", + UsernameChanged => "username_changed", + UserDeleted => "user_deleted", + RepoCreated => "repo_created", + RepoDeleted => "repo_deleted", + RepoRenamed => "repo_renamed", + RepoTransferred => "repo_transferred", + RepoTransferInitiated => "repo_transfer_initiated", + RepoTransferAccepted => "repo_transfer_accepted", + RepoTransferDeclined => "repo_transfer_declined", + RepoTransferCancelled => "repo_transfer_cancelled", + RepoVisibilityChanged => "repo_visibility_changed", + CollaboratorAdded => "collaborator_added", + CollaboratorRemoved => "collaborator_removed", + CollaboratorRoleChanged => "collaborator_role_changed", + BranchRuleCreated => "branch_rule_created", + BranchRuleUpdated => "branch_rule_updated", + BranchRuleDeleted => "branch_rule_deleted", + RepoArchived => "repo_archived", + RepoUnarchived => "repo_unarchived", + WebhookCreated => "webhook_created", + WebhookUpdated => "webhook_updated", + WebhookDeleted => "webhook_deleted", + MirrorCreated => "mirror_created", + MirrorUpdated => "mirror_updated", + MirrorDeleted => "mirror_deleted", + MirrorSyncFailed => "mirror_sync_failed", + BackupStarted => "backup_started", + FsckStarted => "fsck_started", + ReplicationReconcileStarted => "replication_reconcile_started", + CiSecretSet => "ci_secret_set", + CiSecretDeleted => "ci_secret_deleted", + CiRunnerRegistered => "ci_runner_registered", + CiRunnerDeleted => "ci_runner_deleted", + CiRunnerRestartRequested => "ci_runner_restart_requested", + CiRunnerConfigChanged => "ci_runner_config_changed", + CiRegistrationTokenCreated => "ci_registration_token_created", + AdvisoryAlertDismissed => "advisory_alert_dismissed", + AdvisoryAlertReopened => "advisory_alert_reopened", + UiPrefsChanged => "ui_prefs_changed", + DiscussionsEnabled => "discussions_enabled", + DiscussionsDisabled => "discussions_disabled", + DiscussionCreated => "discussion_created", + DiscussionEdited => "discussion_edited", + DiscussionDeleted => "discussion_deleted", + DiscussionLocked => "discussion_locked", + DiscussionUnlocked => "discussion_unlocked", + DiscussionAnswered => "discussion_answered", + DiscussionCommentCreated => "discussion_comment_created", + DiscussionCommentEdited => "discussion_comment_edited", + DiscussionCommentDeleted => "discussion_comment_deleted", + MailSettingsUpdated => "mail_settings_updated", + MailTestQueued => "mail_test_queued", + ServerSettingsUpdated => "server_settings_updated", + ServerRestarted => "server_restarted", + SnippetCreated => "snippet_created", + SnippetUpdated => "snippet_updated", + SnippetDeleted => "snippet_deleted", + WikiPageSaved => "wiki_page_saved", + WikiEnabled => "wiki_enabled", + WikiDisabled => "wiki_disabled", + WikiPushed => "wiki_pushed", + OrgCreated => "org_created", + OrgDeleted => "org_deleted", + OrgSettingsUpdated => "org_settings_updated", + OrgMemberAdded => "org_member_added", + OrgMemberRemoved => "org_member_removed", + OrgMemberRoleChanged => "org_member_role_changed", + TeamCreated => "team_created", + TeamUpdated => "team_updated", + TeamDeleted => "team_deleted", + TeamMemberAdded => "team_member_added", + TeamMemberRemoved => "team_member_removed", + TeamRepoAdded => "team_repo_added", + TeamRepoRemoved => "team_repo_removed", + PasswordResetCompleted => "password_reset_completed", + EmailVerified => "email_verified", + InviteSent => "invite_sent", + InviteAccepted => "invite_accepted", + UserSuspended => "user_suspended", + UserUnsuspended => "user_unsuspended", + AdminGranted => "admin_granted", + AdminRevoked => "admin_revoked", + TotpDisabledByAdmin => "totp_disabled_by_admin", + PasskeyAdded => "passkey_added", + PasskeyRenamed => "passkey_renamed", + PasskeyDeleted => "passkey_deleted", + PasskeysRemovedByAdmin => "passkeys_removed_by_admin", + PasskeyLogin => "passkey_login", +} +impl AuditAction { /// The action with this stored name, if any. pub fn parse(name: &str) -> Option { AuditAction::ALL @@ -436,13 +232,12 @@ mod tests { #[test] fn names_are_unique_and_round_trip() { let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect(); - assert_eq!(names.len(), 106); for action in AuditAction::ALL { assert_eq!(AuditAction::parse(action.as_str()), Some(*action)); } names.sort(); names.dedup(); - assert_eq!(names.len(), 106); + assert_eq!(names.len(), AuditAction::ALL.len()); assert_eq!(AuditAction::parse("nope"), None); } diff --git a/crates/forge-core/src/authz.rs b/crates/forge-core/src/authz.rs index eb8e32e..9cf9d16 100644 --- a/crates/forge-core/src/authz.rs +++ b/crates/forge-core/src/authz.rs @@ -23,20 +23,7 @@ pub enum Denied { /// The higher of two optional roles. `Read < Triage < Write < Maintain < Admin`. pub fn max_role(a: Option, b: Option) -> Option { - fn rank(role: Role) -> u8 { - match role { - Role::Read => 1, - Role::Triage => 2, - Role::Write => 3, - Role::Maintain => 4, - Role::Admin => 5, - } - } - match (a, b) { - (Some(x), Some(y)) => Some(if rank(y) > rank(x) { y } else { x }), - (x, None) => x, - (None, y) => y, - } + a.max(b) } /// Owner or instance admin: all actions. Public repo: Read for anyone. diff --git a/crates/forge-core/src/cargo.rs b/crates/forge-core/src/cargo.rs index 8a098ed..ad1d4dd 100644 --- a/crates/forge-core/src/cargo.rs +++ b/crates/forge-core/src/cargo.rs @@ -193,8 +193,9 @@ pub fn crate_readme(crate_file: &[u8]) -> Option { let entry = entry.ok()?; let path = entry.path().ok()?.into_owned(); let mut parts = path.components(); - parts.next()?; - let file = parts.next()?; + let (Some(_), Some(file)) = (parts.next(), parts.next()) else { + continue; + }; let is_top = parts.next().is_none(); let file_name = file.as_os_str().to_string_lossy().to_ascii_lowercase(); if is_top && file_name.starts_with("readme") && entry.header().entry_type().is_file() { diff --git a/crates/forge-core/src/ci.rs b/crates/forge-core/src/ci.rs index 11d4784..468fd9f 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -2,11 +2,15 @@ //! migrations/0024_ci.sql; the store functions live in store/ci.rs. //! //! Job specs are kept as JSON text (`CiJob::spec_json`). The store reads only the `needs` and -//! `runs_on` arrays out of it, so this crate does not depend on forge-ci. +//! `runs_on` arrays out of it. use std::collections::BTreeMap; use std::str::FromStr; +use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY}; + +pub use forge_ci::proto::RestartMode; + use crate::error::{Error, Result}; /// State of a run. Stored as the `as_str` name. @@ -142,35 +146,6 @@ pub struct CiRunner { pub config_overrides: BTreeMap, } -/// How a runner restarts when an admin asks. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum RestartMode { - /// Stop claiming, let the running jobs finish, then restart. - Drain, - /// Cancel the running jobs and restart at once. - Now, -} - -impl RestartMode { - pub fn as_str(self) -> &'static str { - match self { - Self::Drain => "drain", - Self::Now => "now", - } - } -} - -impl std::str::FromStr for RestartMode { - type Err = (); - fn from_str(s: &str) -> std::result::Result { - match s { - "drain" => Ok(Self::Drain), - "now" => Ok(Self::Now), - _ => Err(()), - } - } -} - /// A pending runner restart: asked for, not yet seen to happen. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RunnerRestart { @@ -319,8 +294,8 @@ pub fn validate_runner_field( match key { "concurrency" => int_in( raw, - i64::from(MIN_RUNNER_CONCURRENCY), - i64::from(MAX_RUNNER_CONCURRENCY), + i64::from(MIN_CONCURRENCY), + i64::from(MAX_CONCURRENCY), "concurrency", ), "labels" => { @@ -529,10 +504,6 @@ impl CiRunner { } } -/// The smallest and largest concurrency an admin may set. -pub const MIN_RUNNER_CONCURRENCY: u32 = 1; -pub const MAX_RUNNER_CONCURRENCY: u32 = 64; - /// One run of the workflow for a commit. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CiRun { @@ -673,6 +644,17 @@ pub struct NewJob<'a> { pub needs: &'a [String], } +pub struct NewRun<'a> { + pub repo_id: &'a str, + pub trigger: &'a str, + pub git_ref: &'a str, + pub commit_oid: &'a str, + pub pull_number: Option, + pub actor_id: &'a str, + pub needs_approval: bool, + pub config_error: Option<&'a str>, +} + #[cfg(test)] mod memory_tests { use super::*; diff --git a/crates/forge-core/src/config.rs b/crates/forge-core/src/config.rs index af70ab1..8e690c7 100644 --- a/crates/forge-core/src/config.rs +++ b/crates/forge-core/src/config.rs @@ -233,30 +233,12 @@ impl BannerConfig { /// Parses `YYYY-MM-DD HH:MM` (UTC) into unix seconds. pub fn parse_banner_expiry(raw: &str) -> Option { - let raw = raw.trim(); - let (date, time) = raw.split_once(' ')?; - let mut d = date.split('-'); - let (y, m, day): (i64, i64, i64) = ( - d.next()?.parse().ok()?, - d.next()?.parse().ok()?, - d.next()?.parse().ok()?, - ); - if d.next().is_some() || !(1..=12).contains(&m) || !(1..=31).contains(&day) { + let dt = jiff::civil::DateTime::strptime("%Y-%m-%d %H:%M", raw.trim()).ok()?; + if dt.year() < 1970 { return None; } - let (hh, mm) = time.split_once(':')?; - let (hh, mm): (i64, i64) = (hh.parse().ok()?, mm.parse().ok()?); - if !(0..24).contains(&hh) || !(0..60).contains(&mm) || y < 1970 { - return None; - } - // Days from civil (Howard Hinnant). - let y2 = if m <= 2 { y - 1 } else { y }; - let era = y2 / 400; - let yoe = y2 - era * 400; - let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day - 1; - let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; - let days = era * 146_097 + doe - 719_468; - Some(days * 86_400 + hh * 3_600 + mm * 60) + let zoned = dt.to_zoned_datetime(jiff::tz::TimeZone::UTC).ok()?; + Some(zoned.timestamp().as_second()) } /// Self-update, from the `[self_update]` section. When enabled, a successful push run of `repo` @@ -423,6 +405,21 @@ impl Default for AdvisoriesConfig { } } +impl AdvisoriesConfig { + fn validate(&self) -> Result<()> { + match self + .ecosystems + .iter() + .find(|name| !crate::advisories::KNOWN_ECOSYSTEMS.contains(&name.as_str())) + { + Some(name) => Err(Error::Config(format!( + "[advisories] unknown ecosystem `{name}`" + ))), + None => Ok(()), + } + } +} + /// Git LFS limits, from the `[lfs]` section. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] @@ -804,6 +801,7 @@ impl Config { self.backup.validate()?; self.replication.validate()?; self.self_update.validate()?; + self.advisories.validate()?; self.storage.validate()?; Ok(()) } diff --git a/crates/forge-core/src/issue_refs.rs b/crates/forge-core/src/issue_refs.rs index d8d93b7..108b3cc 100644 --- a/crates/forge-core/src/issue_refs.rs +++ b/crates/forge-core/src/issue_refs.rs @@ -11,25 +11,13 @@ const CLOSING_KEYWORDS: [&str; 9] = [ /// Maximum number of digits in an issue number. const MAX_DIGITS: usize = 9; -/// Byte range (including the `#`) and value of every valid `#N` reference in `text`, in order. -/// Duplicates are kept. Used to link references in rendered markdown with the same rules. -pub fn issue_ref_spans(text: &str) -> Vec<(Range, i64)> { - scan_refs(text) -} - /// Every `#N` reference in `text`, deduplicated, in order of first appearance. /// /// A reference is `#` followed by 1 to 9 digits. It is not recognised when the `#` is preceded by /// an alphanumeric char, `&` or `/`, or when the digits are followed by an alphanumeric char. /// `#0` is not an issue number and is ignored. pub fn find_issue_refs(text: &str) -> Vec { - let mut out: Vec = Vec::new(); - for (_, n) in scan_refs(text) { - if !out.contains(&n) { - out.push(n); - } - } - out + dedup(issue_ref_spans(text).into_iter().map(|(_, n)| n)) } /// Issue numbers closed by closing keywords in `text`, deduplicated, in order. @@ -38,11 +26,17 @@ pub fn find_issue_refs(text: &str) -> Vec { /// separated by a `:`, with at least one whitespace char between the keyword (or colon) and `#`. /// Example: `"Fixes: #3, closes #4"` gives `[3, 4]`; `"unfixes #2"` gives nothing. pub fn find_closing_refs(text: &str) -> Vec { + dedup( + issue_ref_spans(text) + .into_iter() + .filter(|(range, _)| preceded_by_closing_keyword(&text[..range.start])) + .map(|(_, n)| n), + ) +} + +fn dedup(values: impl Iterator) -> Vec { let mut out: Vec = Vec::new(); - for (range, n) in scan_refs(text) { - if !preceded_by_closing_keyword(&text[..range.start]) { - continue; - } + for n in values { if !out.contains(&n) { out.push(n); } @@ -50,8 +44,9 @@ pub fn find_closing_refs(text: &str) -> Vec { out } -/// Byte range of each valid `#N` reference and its value, in order of appearance. -fn scan_refs(text: &str) -> Vec<(Range, i64)> { +/// Byte range (including the `#`) and value of every valid `#N` reference in `text`, in order. +/// Duplicates are kept. Used to link references in rendered markdown with the same rules. +pub fn issue_ref_spans(text: &str) -> Vec<(Range, i64)> { let bytes = text.as_bytes(); let mut refs = Vec::new(); let mut i = 0; diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs index 9d694e9..37c056a 100644 --- a/crates/forge-core/src/lib.rs +++ b/crates/forge-core/src/lib.rs @@ -30,7 +30,6 @@ pub mod releases; pub mod reviews; pub mod secret; pub mod server_settings; -pub mod session; pub mod store; pub mod suggestions; pub mod time; @@ -50,4 +49,4 @@ pub use pulls::*; pub use reactions::{Reaction, ReactionMap, ReactionSummary, ReactionTarget}; pub use reviews::*; pub use store::Store; -pub use store::edit_history_read::EditVersion; +pub use store::edit_history_read::{EditTarget, EditVersion}; diff --git a/crates/forge-core/src/mail.rs b/crates/forge-core/src/mail.rs index bbb3c3a..bef4e98 100644 --- a/crates/forge-core/src/mail.rs +++ b/crates/forge-core/src/mail.rs @@ -271,35 +271,7 @@ pub struct MailStatus { pub last_error: Option, } -/// Where a message stands. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum OutboxStatus { - Sent, - Queued, - GaveUp, -} - -impl OutboxStatus { - pub fn label(self) -> &'static str { - match self { - OutboxStatus::Sent => "sent", - OutboxStatus::Queued => "queued", - OutboxStatus::GaveUp => "gave up", - } - } -} - impl OutboxEntry { - pub fn status(&self) -> OutboxStatus { - if self.sent_at.is_some() { - OutboxStatus::Sent - } else if self.next_attempt_at.is_some() { - OutboxStatus::Queued - } else { - OutboxStatus::GaveUp - } - } - /// The state of the row at `now` (an RFC 3339-style stamp, compared as text). pub fn state_at(&self, now: &str) -> MailState { if self.sent_at.is_some() { @@ -527,31 +499,4 @@ mod tests { entry.sent_at = Some(now.into()); assert_eq!(entry.state_at(now), MailState::Sent); } - - #[test] - fn status_follows_sent_at_and_next_attempt() { - let mut entry = OutboxEntry { - id: "1".into(), - idem_key: "k".into(), - to_addr: "a@example.com".into(), - subject: "s".into(), - body: "b".into(), - message_id: None, - in_reply_to: None, - kind: MailKind::Other, - user_id: None, - created_at: "t".into(), - attempts: 0, - next_attempt_at: Some("t".into()), - lease_until: None, - sent_at: None, - discarded_at: None, - last_error: None, - }; - assert_eq!(entry.status(), OutboxStatus::Queued); - entry.next_attempt_at = None; - assert_eq!(entry.status(), OutboxStatus::GaveUp); - entry.sent_at = Some("t".into()); - assert_eq!(entry.status(), OutboxStatus::Sent); - } } diff --git a/crates/forge-core/src/merge_queue.rs b/crates/forge-core/src/merge_queue.rs index 5688d78..8c2a92c 100644 --- a/crates/forge-core/src/merge_queue.rs +++ b/crates/forge-core/src/merge_queue.rs @@ -25,14 +25,6 @@ impl QueueState { QueueState::Removed => "removed", } } - - /// Whether the entry still waits for the queue (queued, testing or merging). - pub fn is_active(self) -> bool { - matches!( - self, - QueueState::Queued | QueueState::Testing | QueueState::Merging - ) - } } impl std::str::FromStr for QueueState { diff --git a/crates/forge-core/src/model.rs b/crates/forge-core/src/model.rs index ec5d771..9de0420 100644 --- a/crates/forge-core/src/model.rs +++ b/crates/forge-core/src/model.rs @@ -9,7 +9,7 @@ pub enum Visibility { Private, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "lowercase")] pub enum Role { Read, diff --git a/crates/forge-core/src/names.rs b/crates/forge-core/src/names.rs index 196708c..460e672 100644 --- a/crates/forge-core/src/names.rs +++ b/crates/forge-core/src/names.rs @@ -43,10 +43,6 @@ pub const RESERVED: &[&str] = &[ "favicon.ico", "robots.txt", "security.txt", - ".well-known", - "-", - ".", - "..", ]; /// NFKC normalization plus case fold. diff --git a/crates/forge-core/src/notifications.rs b/crates/forge-core/src/notifications.rs index cfb1b56..be2acc5 100644 --- a/crates/forge-core/src/notifications.rs +++ b/crates/forge-core/src/notifications.rs @@ -1,5 +1,6 @@ //! Notification models: repo watch levels, issue subscriptions and inbox entries. +use crate::issues::IssueState; use crate::model::Id; /// How much activity a user hears about in a repo. A user with no row is `Participating`. @@ -126,8 +127,7 @@ pub struct Notification { /// True for pull requests (`issues.kind = 'pull'`). pub is_pull: bool, pub title: String, - /// `open` or `closed`. - pub issue_state: String, + pub issue_state: IssueState, pub reason: Reason, pub last_activity: String, /// `None` when the actor was deleted without a ghost reassignment or the activity had none. diff --git a/crates/forge-core/src/protection.rs b/crates/forge-core/src/protection.rs index eba47c3..d1f3bd3 100644 --- a/crates/forge-core/src/protection.rs +++ b/crates/forge-core/src/protection.rs @@ -32,7 +32,22 @@ pub struct BranchRule { pub created_at: String, } -/// The settings a rule saves, without its identity. +impl BranchRule { + pub fn flags(&self) -> RuleFlags { + RuleFlags { + allow_force_push: self.allow_force_push, + allow_deletion: self.allow_deletion, + required_approvals: self.required_approvals, + block_on_changes_requested: self.block_on_changes_requested, + require_up_to_date: self.require_up_to_date, + restrict_push: self.restrict_push, + require_merge_queue: self.require_merge_queue, + required_checks: self.required_checks.clone(), + } + } +} + +/// The settings a rule saves, without its identity. `Default` is the unprotected branch. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RuleFlags { pub allow_force_push: bool, @@ -56,19 +71,6 @@ impl RuleFlags { } } -/// The settings that apply to one branch. `Default` is the unprotected branch. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct Protection { - pub allow_force_push: bool, - pub allow_deletion: bool, - pub required_approvals: u32, - pub block_on_changes_requested: bool, - pub require_up_to_date: bool, - pub restrict_push: bool, - pub require_merge_queue: bool, - pub required_checks: Vec, -} - /// Rejects `required_approvals` above `MAX_REQUIRED_APPROVALS`. pub fn validate_required_approvals(n: u32) -> Result<()> { if n > MAX_REQUIRED_APPROVALS { @@ -219,7 +221,7 @@ fn is_literal(pattern: &str) -> bool { /// longest pattern wins, and ties go to the earliest created_at. /// 2. Otherwise, if `branch == default_branch`: built-in protection {force_push: false, deletion: false}. /// 3. Otherwise: unprotected {force_push: true, deletion: true}. -pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> Protection { +pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> RuleFlags { let best = rules .iter() .filter(|r| pattern_matches(&r.pattern, branch)) @@ -233,29 +235,12 @@ pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> Pr .then_with(|| a.pattern.cmp(&b.pattern)) }); if let Some(rule) = best { - return Protection { - allow_force_push: rule.allow_force_push, - allow_deletion: rule.allow_deletion, - required_approvals: rule.required_approvals, - block_on_changes_requested: rule.block_on_changes_requested, - require_up_to_date: rule.require_up_to_date, - restrict_push: rule.restrict_push, - require_merge_queue: rule.require_merge_queue, - required_checks: rule.required_checks.clone(), - }; + return rule.flags(); } if branch == default_branch { - Protection { - allow_force_push: false, - allow_deletion: false, - ..Protection::default() - } + RuleFlags::basic(false, false) } else { - Protection { - allow_force_push: true, - allow_deletion: true, - ..Protection::default() - } + RuleFlags::basic(true, true) } } @@ -280,14 +265,6 @@ mod tests { } } - fn flags(force: bool, deletion: bool) -> Protection { - Protection { - allow_force_push: force, - allow_deletion: deletion, - ..Protection::default() - } - } - #[test] fn pattern_matches_cases() { assert!(pattern_matches("main", "main")); @@ -335,27 +312,27 @@ mod tests { #[test] fn effective_without_rules_protects_only_default() { let none: &[BranchRule] = &[]; - assert_eq!(effective(none, "main", "main"), flags(false, false)); - assert_eq!(effective(none, "main", "feature"), flags(true, true)); + assert_eq!(effective(none, "main", "main"), RuleFlags::basic(false, false)); + assert_eq!(effective(none, "main", "feature"), RuleFlags::basic(true, true)); } #[test] fn effective_literal_allows_force_push_on_main() { let rules = [rule("main", true, false, "1")]; - assert_eq!(effective(&rules, "main", "main"), flags(true, false)); + assert_eq!(effective(&rules, "main", "main"), RuleFlags::basic(true, false)); } #[test] fn effective_literal_beats_glob() { let rules = [rule("*", false, false, "1"), rule("main", true, true, "2")]; - assert_eq!(effective(&rules, "main", "main"), flags(true, true)); + assert_eq!(effective(&rules, "main", "main"), RuleFlags::basic(true, true)); } #[test] fn effective_longer_glob_wins() { // Both `*` and `rel*` match `release`; the longer `rel*` wins even though `*` is older. let rules = [rule("*", true, true, "0"), rule("rel*", false, false, "1")]; - assert_eq!(effective(&rules, "main", "release"), flags(false, false)); + assert_eq!(effective(&rules, "main", "release"), RuleFlags::basic(false, false)); // `release/**` is longer than `release/*`, so it wins for nested names. let rules = [ rule("release/*", true, true, "1"), @@ -363,7 +340,7 @@ mod tests { ]; assert_eq!( effective(&rules, "main", "release/a/b"), - flags(false, false) + RuleFlags::basic(false, false) ); } @@ -377,7 +354,7 @@ mod tests { let rules = [gated]; assert_eq!( effective(&rules, "main", "main"), - Protection { + RuleFlags { allow_force_push: false, allow_deletion: false, required_approvals: 2, diff --git a/crates/forge-core/src/reactions.rs b/crates/forge-core/src/reactions.rs index 0e80c7a..04ab544 100644 --- a/crates/forge-core/src/reactions.rs +++ b/crates/forge-core/src/reactions.rs @@ -1,7 +1,6 @@ //! Emoji reactions: the fixed set a user can put on an issue, a pull request or a comment, and //! the summaries the pages show. Stored as the short name (`+1`, `heart`, ...). -use crate::error::{Error, Result}; use crate::model::Id; /// The fixed reaction set, in the order the pages list them. @@ -64,14 +63,6 @@ impl Reaction { } } -impl std::str::FromStr for Reaction { - type Err = Error; - - fn from_str(s: &str) -> Result { - Reaction::parse(s).ok_or_else(|| Error::Invalid(format!("unknown reaction: {s}"))) - } -} - /// What a reaction is attached to. Pull requests are issue rows, so they use `Issue`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ReactionTarget { diff --git a/crates/forge-core/src/secret.rs b/crates/forge-core/src/secret.rs index 1612dd9..5ea9524 100644 --- a/crates/forge-core/src/secret.rs +++ b/crates/forge-core/src/secret.rs @@ -24,8 +24,6 @@ pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> { } fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { - use std::io::Write; - use rand::TryRng; let mut key = [0u8; 32]; @@ -33,6 +31,16 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { .try_fill_bytes(&mut key) .map_err(std::io::Error::other)?; + let tmp = path.with_extension(format!("{}.tmp", std::process::id())); + let _ = std::fs::remove_file(&tmp); + let linked = write_private(&tmp, &key).and_then(|()| std::fs::hard_link(&tmp, path)); + let _ = std::fs::remove_file(&tmp); + linked.map(|()| key) +} + +fn write_private(path: &Path, key: &[u8; 32]) -> std::io::Result<()> { + use std::io::Write; + let mut options = std::fs::OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] @@ -41,14 +49,8 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { options.mode(0o600); } let mut file = options.open(path)?; - let written = file.write_all(&key).and_then(|()| file.sync_all()); - if let Err(e) = written { - // Do not leave a truncated key behind; the next start would reject it. - drop(file); - let _ = std::fs::remove_file(path); - return Err(e); - } - Ok(key) + file.write_all(key)?; + file.sync_all() } fn read_key(path: &Path) -> Result<[u8; 32]> { diff --git a/crates/forge-core/src/server_settings.rs b/crates/forge-core/src/server_settings.rs index e9d11e8..692ea81 100644 --- a/crates/forge-core/src/server_settings.rs +++ b/crates/forge-core/src/server_settings.rs @@ -1,29 +1,13 @@ -//! Admin-editable server settings, layered on the config file. -//! -//! Precedence per field: a UI override (table `server_settings`), then the config file, then the -//! built-in default. The config file is never rewritten. Every field has a [`Kind`]: -//! -//! - `Live`: applied to the running process at once. Consumers read [`Live::current`]. -//! - `Restart`: saved and shown as pending until the process restarts. Boot layers the stored -//! overrides on the file config, so they take effect then. -//! - `ReadOnly`: shown, never editable (listen addresses, database path, data dir). -//! -//! A secret field is write-only: the page shows whether it is set, never the value, and the stored -//! value is sealed with the instance key. -//! -//! Values travel as canonical strings (`true`, `42`, `a, b`) so one table holds every field and a -//! new field needs no migration. [`get`] and [`set`] convert between those strings and [`Config`]. - use std::collections::{BTreeMap, BTreeSet}; use std::net::IpAddr; use std::sync::{Arc, RwLock}; use ipnet::IpNet; +use crate::advisories::KNOWN_ECOSYSTEMS; use crate::config::{Config, MailTransport, OrgCreation, Registration, StorageBackend}; use crate::error::{Error, Result}; -/// How a field reaches the running process. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { Live, @@ -31,7 +15,6 @@ pub enum Kind { ReadOnly, } -/// The page tab a field belongs to. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Group { General, @@ -68,21 +51,15 @@ impl Group { } } -/// The value type of a field, which decides the input and the server-side check. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Ty { Bool, - /// Whole number in `min..=max`. Uint(u64, u64), Text, - /// A filesystem path. Empty is allowed and usually means "off". Path, Choice(&'static [&'static str]), - /// Comma separated entries. List, - /// Write-only text. Secret, - /// Socket address (read-only fields only). Addr, } @@ -132,7 +109,6 @@ const JURISDICTION: &[&str] = &["", "eu", "fedramp"]; const MB: Ty = Ty::Uint(1, 1_048_576); const PORT: Ty = Ty::Uint(1, 65_535); -/// Every setting, in display order. pub static FIELDS: &[Field] = &[ f( "registration", @@ -723,7 +699,6 @@ pub static FIELDS: &[Field] = &[ ), ]; -/// The field for a dotted key. pub fn field(key: &str) -> Option<&'static Field> { FIELDS.iter().find(|f| f.key == key) } @@ -740,7 +715,6 @@ fn split_list(raw: &str) -> Vec { .collect() } -/// Checks `raw` against the field's type and returns its canonical string. pub fn normalize(field: &Field, raw: &str) -> Result { let raw = raw.trim(); match field.ty { @@ -807,7 +781,7 @@ pub fn normalize(field: &Field, raw: &str) -> Result { } if field.key == "advisories.ecosystems" { for item in &items { - if !matches!(item.as_str(), "crates.io" | "npm" | "Go") { + if !KNOWN_ECOSYSTEMS.contains(&item.as_str()) { return Err(invalid(field, &format!("unknown ecosystem `{item}`"))); } } @@ -840,8 +814,6 @@ fn backend_name(b: StorageBackend) -> &'static str { } } -/// The canonical string of a field's value in `cfg`. Secrets return their real value, so callers -/// that render must not call this for a secret field. pub fn get(cfg: &Config, key: &str) -> String { let path = |p: &std::path::Path| p.to_string_lossy().into_owned(); let list = |v: &[String]| v.join(", "); @@ -944,7 +916,6 @@ pub fn get(cfg: &Config, key: &str) -> String { } } -/// Checks `raw` and stores it into `cfg`. A read-only or unknown key is refused. pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { let field = field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?; if field.kind == Kind::ReadOnly { @@ -1072,8 +1043,6 @@ pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { Ok(()) } -/// `file` with every override applied. Read-only keys in `overrides` are ignored. Does not -/// validate the result; see [`Config::validate`]. pub fn apply(file: &Config, overrides: &BTreeMap) -> Result { let mut cfg = file.clone(); for (key, value) in overrides { @@ -1084,9 +1053,6 @@ pub fn apply(file: &Config, overrides: &BTreeMap) -> Result) -> (Config, Option) { match apply(file, overrides).and_then(|c| c.validate().map(|()| c)) { Ok(config) => (config, None), @@ -1094,17 +1060,14 @@ pub fn boot_config(file: &Config, overrides: &BTreeMap) -> (Conf } } -/// `boot` with the `Live` fields taken from `pending`: what the running process uses. pub fn live_view(boot: &Config, pending: &Config) -> Config { let mut cfg = boot.clone(); for f in FIELDS.iter().filter(|f| f.kind == Kind::Live) { - // Values from `get` always pass `normalize`, so this cannot fail. let _ = set(&mut cfg, f.key, &get(pending, f.key)); } cfg } -/// Where a field's effective value comes from. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Source { Default, @@ -1112,23 +1075,16 @@ pub enum Source { Ui, } -/// One field as the page shows it. #[derive(Debug, Clone)] pub struct FieldView { pub field: &'static Field, - /// Effective value. Empty for a secret. pub value: String, - /// The value the file (or default) gives. Empty for a secret. pub file_value: String, pub source: Source, - /// For a secret: whether a value is set. pub secret_set: bool, - /// Saved but not yet running: a restart field whose value differs from the running one. pub restart_pending: bool, } -/// The process-wide settings handle: the file config, the config boot ran with, and the live view -/// consumers read. pub struct Live { file: Arc, file_keys: BTreeSet, @@ -1146,7 +1102,6 @@ impl Live { } } - /// The config the running process uses right now. pub fn current(&self) -> Arc { self.current .read() @@ -1154,15 +1109,6 @@ impl Live { .clone() } - pub fn file(&self) -> &Config { - &self.file - } - - pub fn boot(&self) -> &Config { - &self.boot - } - - /// Validates `file + overrides`, then publishes its live fields. Nothing changes on error. pub fn publish(&self, overrides: &BTreeMap) -> Result<()> { let pending = apply(&self.file, overrides)?; pending.validate()?; @@ -1174,7 +1120,6 @@ impl Live { Ok(()) } - /// Every field with its effective value and source. pub fn views(&self, overrides: &BTreeMap) -> Vec { let pending = apply(&self.file, overrides).unwrap_or_else(|_| (*self.file).clone()); FIELDS @@ -1210,9 +1155,6 @@ impl Live { .collect() } - /// Plans a save of one tab. `submitted` maps key to the raw form value. Returns the keys to - /// store, the keys to clear (submitted equal to the file value), and the validated result. - /// A blank secret keeps what is stored. Nothing is stored on error. pub fn plan_save( &self, existing: &BTreeMap, @@ -1262,7 +1204,6 @@ impl Live { }) } - /// The overrides after dropping `key`, validated. pub fn plan_reset( &self, existing: &BTreeMap, @@ -1276,12 +1217,10 @@ impl Live { } } -/// The outcome of [`Live::plan_save`]. #[derive(Debug)] pub struct SavePlan { pub sets: Vec<(String, String)>, pub clears: Vec, - /// All overrides once the plan is applied. pub overrides: BTreeMap, } @@ -1379,7 +1318,7 @@ max_log_mb = 20 let v = live.views(&over); let v = v.iter().find(|v| v.field.key == "base_url").unwrap(); assert!(v.restart_pending); - let (boot, err) = boot_config(live.file(), &over); + let (boot, err) = boot_config(&base(), &over); assert!(err.is_none()); assert_eq!(boot.base_url, "https://new.example"); let after = Live::new(Arc::new(base()), Default::default(), Arc::new(boot)); @@ -1402,7 +1341,6 @@ max_log_mb = 20 let mut cfg = base(); assert!(set(&mut cfg, key, value).is_err(), "{key}={value}"); } - // Cross-field loader rules apply to a whole save. let group_form = form(&[("storage.backend", "r2")]); assert!( live.plan_save(&BTreeMap::new(), Group::Storage, &group_form) diff --git a/crates/forge-core/src/session.rs b/crates/forge-core/src/session.rs deleted file mode 100644 index e7a19c6..0000000 --- a/crates/forge-core/src/session.rs +++ /dev/null @@ -1,32 +0,0 @@ -//! Session and CSRF token generation. - -use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; - -use crate::token::random_32; - -/// base64url(32 random bytes), used as the cookie value. The DB stores its sha256. -pub fn new_session_token() -> String { - BASE64_URL_SAFE_NO_PAD.encode(random_32()) -} - -pub fn new_csrf_token() -> String { - BASE64_URL_SAFE_NO_PAD.encode(random_32()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn tokens_are_unique_base64url_of_32_bytes() { - let a = new_session_token(); - let b = new_csrf_token(); - assert_eq!(a.len(), 43); - assert_eq!(b.len(), 43); - assert_ne!(a, b); - assert!( - a.bytes() - .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') - ); - } -} diff --git a/crates/forge-core/src/store/account_tokens.rs b/crates/forge-core/src/store/account_tokens.rs index ba13dd2..4666b5c 100644 --- a/crates/forge-core/src/store/account_tokens.rs +++ b/crates/forge-core/src/store/account_tokens.rs @@ -5,9 +5,10 @@ use std::time::Duration; -use super::issues::finish; +use super::finish; use super::{ - Store, col_int, col_opt_text, col_text, db_err, fetch_opt, insert_err, map_user, new_id, + USER_COLS, Store, col_int, col_opt_text, col_text, db_err, fetch_opt, insert_err, map_user, + new_id, }; use crate::error::{Error, Result}; use crate::model::{AccountKind, User}; @@ -98,10 +99,10 @@ impl Store { let conn = self.read_conn().await; fetch_opt( &conn, - "SELECT id, username, email, password_hash, is_admin, created_at, about, timezone, \ - (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \ - theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark, sidebar_side FROM users WHERE LOWER(email) = LOWER(?1) \ - AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1", + &format!( + "SELECT {USER_COLS} FROM users WHERE LOWER(email) = LOWER(?1) \ + AND email_verified_at IS NOT NULL AND kind = 'user' LIMIT 1" + ), (email.to_owned(),), map_user, ) diff --git a/crates/forge-core/src/store/admin_alerts.rs b/crates/forge-core/src/store/admin_alerts.rs index 273b6e1..e5eca56 100644 --- a/crates/forge-core/src/store/admin_alerts.rs +++ b/crates/forge-core/src/store/admin_alerts.rs @@ -6,8 +6,8 @@ use turso::{Row, Value}; -use super::issues::finish; -use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id}; +use super::finish; +use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id, text}; use crate::error::Result; use crate::time::now_stamp; @@ -59,10 +59,6 @@ fn map_notice(row: &Row) -> Result { }) } -fn text(s: &str) -> Value { - Value::Text(s.to_owned()) -} - impl Store { /// Marks the condition `key` active. Returns true when it was not active before, which is /// when the admins are told. An alert already active keeps its first `raised_at`; only its diff --git a/crates/forge-core/src/store/advisories.rs b/crates/forge-core/src/store/advisories.rs index 7f25999..e71d9aa 100644 --- a/crates/forge-core/src/store/advisories.rs +++ b/crates/forge-core/src/store/advisories.rs @@ -302,7 +302,7 @@ impl Store { outcome.opened += 1; } Some(AlertState::Fixed) => { - set_state(&tx, &rid, key, AlertState::Open, &now).await?; + set_state(&tx, &rid, key, AlertState::Fixed, AlertState::Open, &now).await?; outcome.opened += 1; } Some(AlertState::Open | AlertState::Dismissed) => {} @@ -310,7 +310,7 @@ impl Store { } for (key, state) in &existing { if *state == AlertState::Open && !matched.contains(key) { - set_state(&tx, &rid, key, AlertState::Fixed, &now).await?; + set_state(&tx, &rid, key, AlertState::Open, AlertState::Fixed, &now).await?; outcome.fixed += 1; } } @@ -333,21 +333,7 @@ impl Store { let rid = repo_id.to_string(); let now = now_stamp(); let outcome: Result = async { - let mut params = key_params(&rid, key); - params.extend([ - Value::Text(to.as_str().to_string()), - Value::Text(now.clone()), - Value::Text(from.as_str().to_string()), - ]); - let changed = tx - .execute( - "UPDATE repo_alerts SET state = ?6, updated_at = ?7 WHERE repo_id = ?1 AND \ - advisory_id = ?2 AND ecosystem = ?3 AND package = ?4 AND version = ?5 AND \ - state = ?8", - params, - ) - .await - .map_err(db_err)?; + let changed = set_state(&tx, &rid, key, from, to, &now).await?; Ok(changed > 0) } .await; @@ -531,22 +517,23 @@ async fn set_state( tx: &turso::transaction::Transaction<'_>, repo_id: &str, key: &AlertKey, - state: AlertState, + from: AlertState, + to: AlertState, now: &str, -) -> Result<()> { +) -> Result { let mut params = key_params(repo_id, key); params.extend([ - Value::Text(state.as_str().to_string()), + Value::Text(to.as_str().to_string()), Value::Text(now.to_string()), + Value::Text(from.as_str().to_string()), ]); tx.execute( "UPDATE repo_alerts SET state = ?6, updated_at = ?7 WHERE repo_id = ?1 AND advisory_id = ?2 \ - AND ecosystem = ?3 AND package = ?4 AND version = ?5", + AND ecosystem = ?3 AND package = ?4 AND version = ?5 AND state = ?8", params, ) .await - .map_err(db_err)?; - Ok(()) + .map_err(db_err) } #[cfg(test)] diff --git a/crates/forge-core/src/store/audit.rs b/crates/forge-core/src/store/audit.rs index 3f316c6..59668d1 100644 --- a/crates/forge-core/src/store/audit.rs +++ b/crates/forge-core/src/store/audit.rs @@ -2,7 +2,7 @@ use turso::{Row, Value}; -use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt}; +use super::{Store, col_opt_text, col_text, db_err, fetch_all}; use crate::audit::{AuditAction, AuditCursor, AuditEntry, AuditFilter}; use crate::error::{Error, Result}; @@ -142,15 +142,6 @@ impl Store { fetch_all(&conn, &sql, params, map_audit).await } - /// How many entries match `filter`, for the page count. - pub async fn count_audit(&self, filter: &AuditFilter) -> Result { - let (where_sql, params) = audit_where(filter, None); - let sql = format!("SELECT COUNT(*) FROM audit_log {where_sql}"); - let conn = self.read_conn().await; - let count = fetch_opt(&conn, &sql, params, |row| col_int(row, 0)).await?; - Ok(count.unwrap_or(0).max(0) as u64) - } - /// Retention: deletes entries stamped before `cutoff` (an RFC 3339 UTC stamp). Returns the /// number of entries removed. This is the only delete on the audit log. pub async fn purge_audit_before(&self, cutoff: &str) -> Result { diff --git a/crates/forge-core/src/store/backup_runs.rs b/crates/forge-core/src/store/backup_runs.rs index f23961d..4d00496 100644 --- a/crates/forge-core/src/store/backup_runs.rs +++ b/crates/forge-core/src/store/backup_runs.rs @@ -3,7 +3,7 @@ use turso::{Row, Value}; -use super::{Store, col_text, db_err, fetch_all, new_id}; +use super::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all, new_id}; use crate::error::{Error, Result}; use crate::time::now_stamp; @@ -76,29 +76,12 @@ pub struct BackupRun { pub error: Option, } -fn opt_int(row: &Row, i: usize) -> Result> { - match row.get_value(i).map_err(db_err)? { - Value::Integer(n) => Ok(Some(n)), - Value::Null => Ok(None), - _ => Err(Error::Database(format!("column {i} is not an integer"))), - } -} - -fn opt_text(row: &Row, i: usize) -> Result> { - match row.get_value(i).map_err(db_err)? { - Value::Text(s) => Ok(Some(s)), - Value::Null => Ok(None), - _ => Err(Error::Database(format!("column {i} is not text"))), - } -} - fn map_run(row: &Row) -> Result { let kind = col_text(row, 1)?; let trigger = col_text(row, 8)?; - let bytes = match opt_int(row, 6)? { - Some(n) => Some(u64::try_from(n).map_err(|_| Error::Database("negative run size".into()))?), - None => None, - }; + let bytes = col_opt_int(row, 6)? + .map(|n| u64::try_from(n).map_err(|_| Error::Database("negative run size".into()))) + .transpose()?; Ok(BackupRun { id: col_text(row, 0)?, kind: RunKind::parse(&kind) @@ -106,11 +89,11 @@ fn map_run(row: &Row) -> Result { trigger: RunTrigger::parse(&trigger) .ok_or_else(|| Error::Database(format!("unknown run trigger {trigger:?}")))?, started_at: col_text(row, 2)?, - finished_at: opt_text(row, 3)?, - ok: opt_int(row, 4)?.map(|n| n != 0), - path: opt_text(row, 5)?, + finished_at: col_opt_text(row, 3)?, + ok: col_opt_int(row, 4)?.map(|n| n != 0), + path: col_opt_text(row, 5)?, bytes, - error: opt_text(row, 7)?, + error: col_opt_text(row, 7)?, }) } diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index 7e53ee1..2fda14c 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -10,19 +10,19 @@ use std::time::Duration; use turso::{Connection, Row, Value}; use super::{ - Store, col_blob, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, - finish, insert_err, missing_row, new_id, + Store, col_blob, col_bool, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_all, + fetch_opt, finish, insert_err, missing_row, new_id, opt_int_value, opt_text, text, }; use crate::ci::{ CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, JobStep, - MAX_RUNNER_CONCURRENCY, MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, - RunState, RunnerJob, RunnerReport, RunnerRestart, STARVE_AFTER_SECS, StepSample, - pick_by_memory, validate_runner_field, + MemoryOffer, NewJob, NewRun, QueueSkips, RestartMode, RunState, RunnerJob, RunnerReport, + RunnerRestart, STARVE_AFTER_SECS, StepSample, pick_by_memory, validate_runner_field, }; use crate::error::{Error, Result}; use crate::secret; use crate::time::{now_stamp, stamp_after, stamp_to_unix}; use crate::token::{generate_token, hash_token}; +use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY}; use forge_ci::steps::{MAX_STEPS, StepMark}; 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; /// Longest page `list_runs` returns. const MAX_PER_PAGE: u32 = 100; -fn text(s: &str) -> Value { - Value::Text(s.to_string()) -} - -fn opt_text(v: Option<&str>) -> Value { - v.map_or(Value::Null, text) -} - -fn opt_int_value(v: Option) -> Value { - v.map_or(Value::Null, Value::Integer) -} - -/// An integer column that may be NULL. -fn opt_int(row: &Row, i: usize) -> Result> { - match row.get_value(i).map_err(db_err)? { - Value::Integer(n) => Ok(Some(n)), - Value::Null => Ok(None), - _ => Err(Error::Database(format!("column {i} is not an integer"))), - } -} - fn map_runner(row: &Row) -> Result { let labels = serde_json::from_str::>(&col_text(row, 2)?) .map_err(|e| Error::Database(format!("runner labels are not a string list: {e}")))?; @@ -86,7 +65,7 @@ fn map_runner(row: &Row) -> Result { concurrency: opt_u32(row, 7)?, version: col_opt_text(row, 8)?, cpus: opt_u32(row, 9)?, - memory_bytes: opt_int(row, 10)?.and_then(|n| u64::try_from(n).ok()), + memory_bytes: col_opt_int(row, 10)?.and_then(|n| u64::try_from(n).ok()), build: col_opt_text(row, 14)?, boot_id: col_opt_text(row, 15)?, capabilities: col_opt_text(row, 18)? @@ -97,15 +76,14 @@ fn map_runner(row: &Row) -> Result { .collect() }) .unwrap_or_default(), - memory_budget: opt_int(row, 19)?.and_then(|n| u64::try_from(n).ok()), - memory_free: opt_int(row, 20)?.and_then(|n| u64::try_from(n).ok()), - memory_reserve: opt_int(row, 21)?.and_then(|n| u64::try_from(n).ok()), + memory_budget: col_opt_int(row, 19)?.and_then(|n| u64::try_from(n).ok()), + memory_free: col_opt_int(row, 20)?.and_then(|n| u64::try_from(n).ok()), + memory_reserve: col_opt_int(row, 21)?.and_then(|n| u64::try_from(n).ok()), }, restart: match (col_opt_text(row, 16)?, col_opt_text(row, 17)?) { - (Some(mode), Some(requested_at)) => mode - .parse::() - .ok() - .map(|mode| RunnerRestart { mode, requested_at }), + (Some(mode), Some(requested_at)) => { + RestartMode::parse(&mode).map(|mode| RunnerRestart { mode, requested_at }) + } _ => None, }, running_jobs: opt_u32(row, 13)?.unwrap_or(0), @@ -123,7 +101,7 @@ fn json_map(row: &Row, i: usize) -> Result> /// A NULL-able integer column that holds a count. fn opt_u32(row: &Row, i: usize) -> Result> { - Ok(opt_int(row, i)?.and_then(|n| u32::try_from(n).ok())) + Ok(col_opt_int(row, i)?.and_then(|n| u32::try_from(n).ok())) } fn map_run(row: &Row) -> Result { @@ -134,7 +112,7 @@ fn map_run(row: &Row) -> Result { trigger: col_text(row, 3)?, git_ref: col_text(row, 4)?, commit_oid: col_text(row, 5)?, - pull_number: opt_int(row, 6)?, + pull_number: col_opt_int(row, 6)?, actor_id: col_text(row, 7)?, state: col_text(row, 8)?.parse::()?, config_error: col_opt_text(row, 9)?, @@ -151,7 +129,7 @@ fn map_job(row: &Row) -> Result { spec_json: col_text(row, 3)?, state: col_text(row, 4)?.parse::()?, runner_id: col_opt_text(row, 5)?, - exit_code: opt_int(row, 6)?, + exit_code: col_opt_int(row, 6)?, message: col_opt_text(row, 7)?, queued_at: col_opt_text(row, 8)?, started_at: col_opt_text(row, 9)?, @@ -411,14 +389,54 @@ async fn recompute_run(conn: &Connection, run_id: &str, now: &str) -> Result<()> Ok(()) } +const DONE_RUNS: &str = "WITH done AS ( \ + SELECT id, git_ref, \ + ROW_NUMBER() OVER (PARTITION BY git_ref ORDER BY number DESC) AS branch_rank, \ + ROW_NUMBER() OVER (ORDER BY number DESC) AS repo_rank \ + FROM ci_runs WHERE repo_id = ?1 AND state = 'success' \ + )"; + +fn recent_done_scope(repo_id: &str, git_refs: &[String]) -> (Vec, String) { + let mut params = vec![text(repo_id)]; + params.extend(git_refs.iter().map(|git_ref| text(git_ref))); + let scope = if git_refs.is_empty() { + "done.repo_rank <= 5".to_owned() + } else { + let marks: Vec = (2..=git_refs.len() + 1).map(|i| format!("?{i}")).collect(); + format!( + "(done.branch_rank <= 5 AND done.git_ref IN ({})) OR done.repo_rank <= 5", + marks.join(", ") + ) + }; + (params, scope) +} + +fn waited_secs(queued_at: Option<&str>, now: i64) -> u64 { + queued_at + .and_then(stamp_to_unix) + .map_or(0, |at| u64::try_from(now - at).unwrap_or(0)) +} + +async fn cancel_open_jobs(conn: &Connection, run_id: &str, now: &str) -> Result<()> { + conn.execute( + "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \ + WHERE run_id = ?1 AND state IN ('queued', 'blocked')", + (run_id.to_string(), now.to_string()), + ) + .await + .map_err(db_err)?; + conn.execute( + "UPDATE ci_jobs SET cancel_requested = 1 WHERE run_id = ?1 AND state = 'running'", + (run_id.to_string(),), + ) + .await + .map_err(db_err)?; + Ok(()) +} + impl Store { fn seal_ci_secret(&self, plain: &[u8]) -> Result> { - let key = self - .inner - .secret_key - .get() - .ok_or_else(|| Error::Crypto("instance secret key is not set".into()))?; - Ok(secret::seal(key, plain)?.into_bytes()) + Ok(secret::seal(self.secret_key()?, plain)?.into_bytes()) } /// Creates a single-use registration token valid for `ttl_hours`. Returns the plaintext, @@ -457,8 +475,9 @@ impl Store { let conn = self.inner.conn.lock().await; let mut rows = conn .query( - "SELECT 1 FROM ci_registration_tokens WHERE token_hash = ?1 AND used_at IS NULL", - vec![text(token_hash)], + "SELECT 1 FROM ci_registration_tokens \ + WHERE token_hash = ?1 AND used_at IS NULL AND expires_at > ?2", + vec![text(token_hash), text(&now_stamp())], ) .await .map_err(db_err)?; @@ -655,10 +674,10 @@ impl Store { /// must be 1 to 64, else `Invalid`. `NotFound` if the runner does not exist. pub async fn set_runner_concurrency(&self, id: &str, value: Option) -> Result<()> { if let Some(n) = value - && !(MIN_RUNNER_CONCURRENCY..=MAX_RUNNER_CONCURRENCY).contains(&n) + && !(MIN_CONCURRENCY..=MAX_CONCURRENCY).contains(&n) { return Err(Error::Invalid(format!( - "concurrency must be {MIN_RUNNER_CONCURRENCY} to {MAX_RUNNER_CONCURRENCY}" + "concurrency must be {MIN_CONCURRENCY} to {MAX_CONCURRENCY}" ))); } let conn = self.inner.conn.lock().await; @@ -695,14 +714,7 @@ impl Store { .await; } let conn = self.inner.conn.lock().await; - let mut runner = fetch_opt( - &conn, - &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"), - (id.to_string(),), - map_runner, - ) - .await? - .ok_or(Error::NotFound)?; + let mut runner = load_runner(&conn, id).await?.ok_or(Error::NotFound)?; match parsed { Some(v) => { runner.config_overrides.insert(key.to_owned(), v); @@ -719,7 +731,6 @@ impl Store { .map_err(|e| Error::Database(e.to_string()))?, ) }; - // The forge claims with the labels it stores, so a labels override is live at once. let labels = if key == "labels" { let chosen = runner .config_overrides @@ -762,14 +773,7 @@ impl Store { config: &BTreeMap, ) -> Result { let conn = self.inner.conn.lock().await; - let current = fetch_opt( - &conn, - &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"), - (id.to_string(),), - map_runner, - ) - .await?; - let Some(current) = current else { + let Some(current) = load_runner(&conn, id).await? else { return Ok(false); }; if ¤t.reported_config == config { @@ -831,14 +835,7 @@ impl Store { /// value. Returns true when a stored value changed, so the caller can tell live pages. pub async fn record_runner_report(&self, id: &str, report: &RunnerReport) -> Result { let conn = self.inner.conn.lock().await; - let current = fetch_opt( - &conn, - &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"), - (id.to_string(),), - map_runner, - ) - .await?; - let Some(current) = current else { + let Some(current) = load_runner(&conn, id).await? else { return Ok(false); }; let merged = RunnerReport { @@ -860,7 +857,6 @@ impl Store { if merged == current.reported { return Ok(false); } - // A new boot id while a restart is pending means the runner came back. if merged.boot_id != current.reported.boot_id && current.restart.is_some() { conn.execute( "UPDATE ci_runners SET restart_mode = NULL, restart_requested_at = NULL \ @@ -924,7 +920,7 @@ impl Store { |row| col_opt_text(row, 0), ) .await?; - Ok(found.flatten().and_then(|m| m.parse().ok())) + Ok(found.flatten().and_then(|m| RestartMode::parse(&m))) } /// Removes a runner. `NotFound` if it does not exist. @@ -947,18 +943,17 @@ impl Store { /// `Blocked` until `approve_run`. Otherwise need-less jobs are `Queued` and the run is /// `Queued`. Jobs with needs are always `Blocked` at first. #[allow(clippy::too_many_arguments)] - pub async fn create_run( - &self, - repo_id: &str, - trigger: &str, - git_ref: &str, - commit_oid: &str, - pull_number: Option, - actor_id: &str, - needs_approval: bool, - jobs: &[NewJob<'_>], - config_error: Option<&str>, - ) -> Result { + pub async fn create_run(&self, run: &NewRun<'_>, jobs: &[NewJob<'_>]) -> Result { + let NewRun { + repo_id, + trigger, + git_ref, + commit_oid, + pull_number, + actor_id, + needs_approval, + config_error, + } = *run; let id = new_id(); let now = now_stamp(); let conn = self.inner.conn.lock().await; @@ -1099,11 +1094,10 @@ impl Store { let candidates: Vec<(Option, u64)> = compatible .iter() .map(|(_, spec, queued_at)| { - let waited = queued_at - .as_deref() - .and_then(stamp_to_unix) - .map_or(0, |at| u64::try_from(now - at).unwrap_or(0)); - (declared_memory(spec), waited) + ( + declared_memory(spec), + waited_secs(queued_at.as_deref(), now), + ) }) .collect(); compatible = pick_by_memory(&candidates, &offer, STARVE_AFTER_SECS) @@ -1168,7 +1162,6 @@ impl Store { ..QueueSkips::default() }; let mut missing = BTreeSet::new(); - // The same walk as `pick_by_memory`, oldest first, counting instead of picking. for (spec, queued_at) in &queued { if !runs_on_covered(spec, &runner.labels) { skips.lacking_labels += 1; @@ -1191,11 +1184,7 @@ impl Store { let need = offer.reservation(declared); skips.too_big += 1; skips.smallest_need = Some(skips.smallest_need.map_or(need, |n| n.min(need))); - let waited = queued_at - .as_deref() - .and_then(stamp_to_unix) - .map_or(0, |at| u64::try_from(now - at).unwrap_or(0)); - if waited >= STARVE_AFTER_SECS { + if waited_secs(queued_at.as_deref(), now) >= STARVE_AFTER_SECS { skips.starved_need = Some(need); } } @@ -1280,7 +1269,8 @@ impl Store { /// Finishes a job with a terminal state. Dependants are then unblocked or skipped, and the /// run state is recomputed. A `Failure` or `Error` fails the run fast: the run's queued and - /// blocked jobs are cancelled and its running jobs get `cancel_requested`. Returns the run. `Conflict` if the job already finished. + /// blocked jobs are cancelled and its running jobs get `cancel_requested`. Returns the run. + /// `Conflict` if the job already finished. pub async fn finish_job( &self, job_id: &str, @@ -1316,21 +1306,7 @@ impl Store { .map_err(db_err)?; propagate(&tx, &job.run_id, &now).await?; if matches!(state, JobState::Failure | JobState::Error) { - // Fail fast: the run cannot succeed any more, so stop the sibling jobs now. - tx.execute( - "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \ - WHERE run_id = ?1 AND state IN ('queued', 'blocked')", - (job.run_id.clone(), now.clone()), - ) - .await - .map_err(db_err)?; - tx.execute( - "UPDATE ci_jobs SET cancel_requested = 1 \ - WHERE run_id = ?1 AND state = 'running'", - (job.run_id.clone(),), - ) - .await - .map_err(db_err)?; + cancel_open_jobs(&tx, &job.run_id, &now).await?; } recompute_run(&tx, &job.run_id, &now).await?; load_run(&tx, &job.run_id).await?.ok_or_else(missing_row) @@ -1388,19 +1364,7 @@ impl Store { if run.state.is_terminal() { return Ok(()); } - tx.execute( - "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \ - WHERE run_id = ?1 AND state IN ('queued', 'blocked')", - (run_id.to_string(), now.clone()), - ) - .await - .map_err(db_err)?; - tx.execute( - "UPDATE ci_jobs SET cancel_requested = 1 WHERE run_id = ?1 AND state = 'running'", - (run_id.to_string(),), - ) - .await - .map_err(db_err)?; + cancel_open_jobs(&tx, run_id, &now).await?; recompute_run(&tx, run_id, &now).await } .await; @@ -1507,15 +1471,17 @@ impl Store { .collect(); let created = self .create_run( - &run.repo_id, - &run.trigger, - &run.git_ref, - &run.commit_oid, - run.pull_number, - actor_id, - false, + &NewRun { + repo_id: &run.repo_id, + trigger: &run.trigger, + git_ref: &run.git_ref, + commit_oid: &run.commit_oid, + pull_number: run.pull_number, + actor_id, + needs_approval: false, + config_error: run.config_error.as_deref(), + }, &new_jobs, - run.config_error.as_deref(), ) .await?; let warnings = self.run_warnings(&run.id).await?; @@ -1527,7 +1493,11 @@ impl Store { /// Stores the config warnings of a run, replacing any earlier ones. pub async fn set_run_warnings(&self, run_id: &str, warnings: &[String]) -> Result<()> { - let joined = (!warnings.is_empty()).then(|| warnings.join("\n")); + let lines: Vec = warnings + .iter() + .map(|w| w.replace(['\n', '\r'], " ")) + .collect(); + let joined = (!lines.is_empty()).then(|| lines.join("\n")); let conn = self.inner.conn.lock().await; conn.execute( "UPDATE ci_runs SET config_warnings = ?2 WHERE id = ?1", @@ -1599,6 +1569,7 @@ impl Store { ) .await?; let mut runs: Vec = Vec::new(); + let mut failed_runs: Vec = Vec::new(); for job in &lost { tx.execute( "UPDATE ci_jobs SET \ @@ -1613,9 +1584,15 @@ impl Store { if !runs.contains(&job.run_id) { runs.push(job.run_id.clone()); } + if !job.cancel_requested && !failed_runs.contains(&job.run_id) { + failed_runs.push(job.run_id.clone()); + } } for run_id in &runs { propagate(&tx, run_id, &now).await?; + if failed_runs.contains(run_id) { + cancel_open_jobs(&tx, run_id, &now).await?; + } recompute_run(&tx, run_id, &now).await?; } let mut out = Vec::with_capacity(lost.len()); @@ -1708,27 +1685,10 @@ impl Store { repo_id: &str, git_refs: &[String], ) -> Result> { - let mut params: Vec = Vec::with_capacity(git_refs.len() + 1); - params.push(Value::Text(repo_id.to_string())); - params.extend(git_refs.iter().map(|git_ref| Value::Text(git_ref.clone()))); - let scope = if git_refs.is_empty() { - "done.repo_rank <= 5".to_owned() - } else { - let marks: Vec = (2..=git_refs.len() + 1).map(|i| format!("?{i}")).collect(); - format!( - "(done.branch_rank <= 5 AND done.git_ref IN ({})) OR done.repo_rank <= 5", - marks.join(", ") - ) - }; + let (params, scope) = recent_done_scope(repo_id, git_refs); let sql = format!( - "WITH done AS ( \ - SELECT id, git_ref, \ - ROW_NUMBER() OVER (PARTITION BY git_ref ORDER BY number DESC) AS branch_rank, \ - ROW_NUMBER() OVER (ORDER BY number DESC) AS repo_rank \ - FROM ci_runs WHERE repo_id = ?1 AND state = 'success' \ - ) \ - SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, j.started_at, \ - j.finished_at \ + "{DONE_RUNS} SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, \ + j.started_at, j.finished_at \ FROM done JOIN ci_jobs j ON j.run_id = done.id \ WHERE ({scope}) \ AND j.state = 'success' AND j.started_at IS NOT NULL AND j.finished_at IS NOT NULL" @@ -1868,26 +1828,9 @@ impl Store { repo_id: &str, git_refs: &[String], ) -> Result> { - let mut params: Vec = Vec::with_capacity(git_refs.len() + 1); - params.push(Value::Text(repo_id.to_string())); - params.extend(git_refs.iter().map(|git_ref| Value::Text(git_ref.clone()))); - let scope = if git_refs.is_empty() { - "done.repo_rank <= 5".to_owned() - } else { - let marks: Vec = (2..=git_refs.len() + 1).map(|i| format!("?{i}")).collect(); - format!( - "(done.branch_rank <= 5 AND done.git_ref IN ({})) OR done.repo_rank <= 5", - marks.join(", ") - ) - }; + let (params, scope) = recent_done_scope(repo_id, git_refs); let sql = format!( - "WITH done AS ( \ - SELECT id, git_ref, \ - ROW_NUMBER() OVER (PARTITION BY git_ref ORDER BY number DESC) AS branch_rank, \ - ROW_NUMBER() OVER (ORDER BY number DESC) AS repo_rank \ - FROM ci_runs WHERE repo_id = ?1 AND state = 'success' \ - ) \ - SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, s.name, \ + "{DONE_RUNS} SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, s.name, \ s.started_at, s.finished_at \ FROM done JOIN ci_jobs j ON j.run_id = done.id \ JOIN ci_job_steps s ON s.job_id = j.id \ @@ -2031,7 +1974,6 @@ impl Store { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result<(Vec, Vec, Vec)> = async { - // Which run owns each artifact, read before the rows go. let owners: BTreeMap = fetch_all( &tx, "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 { .await .map_err(db_err)?; - // Keep only the newest `keep_runs` runs (per repo) that still have artifacts. if keep_runs > 0 { let old = fetch_all( &tx, "SELECT a.id FROM ci_artifacts a JOIN ci_jobs j ON j.id = a.job_id \ WHERE j.run_id NOT IN ( \ SELECT id FROM ( \ - SELECT r.id, ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY r.id DESC) \ + SELECT r.id, ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY r.number DESC) \ AS rn \ FROM ci_runs r \ WHERE EXISTS (SELECT 1 FROM ci_artifacts a2 JOIN ci_jobs j2 \ @@ -2099,10 +2040,8 @@ impl Store { artifact_ids.extend(old); } - // Over the disk limit: drop the oldest runs' artifacts, one whole run at a time. if max_total_bytes > 0 { let limit = i64::try_from(max_total_bytes).unwrap_or(i64::MAX); - // (artifact id, run id, size), oldest run first. let rows = fetch_all( &tx, "SELECT a.id, j.run_id, a.size FROM ci_artifacts a \ @@ -2215,14 +2154,9 @@ impl Store { if !names.contains(&name) { continue; } - let key = self - .inner - .secret_key - .get() - .ok_or_else(|| Error::Crypto("instance secret key is not set".into()))?; let sealed = String::from_utf8(sealed) .map_err(|_| Error::Crypto("sealed CI secret is not UTF-8".into()))?; - let plain = secret::open(key, &sealed)?; + let plain = secret::open(self.secret_key()?, &sealed)?; let value = String::from_utf8(plain) .map_err(|_| Error::Crypto("CI secret is not UTF-8".into()))?; out.insert(name, value); @@ -2305,15 +2239,17 @@ mod tests { .collect(); store .create_run( - repo_id, - "push", - "refs/heads/main", - "abc123", - None, - actor, - approval, + &NewRun { + repo_id, + trigger: "push", + git_ref: "refs/heads/main", + commit_oid: "abc123", + pull_number: None, + actor_id: actor, + needs_approval: approval, + config_error: None, + }, &new, - None, ) .await .unwrap() @@ -2363,7 +2299,6 @@ mod tests { .create_registration_token(&fx.tahinli.id, 1) .await .unwrap(); - // Only the hash is stored. { let conn = fx.store.inner.conn.lock().await; let n = fetch_opt( @@ -2511,7 +2446,6 @@ mod tests { assert_eq!(found.config_overrides["limits.memory"], "8g"); assert_eq!(found.reported_config["limits.memory"], "4g"); - // Labels are claimed with at once, and a reset restores what the runner reported. fx.store .set_runner_field(&runner.id, "labels", Some("linux, arm")) .await @@ -2530,7 +2464,6 @@ mod tests { assert_eq!(after.labels, vec!["linux".to_string()]); assert!(after.config_overrides.is_empty()); - // Concurrency goes through the same entry point. fx.store .set_runner_field(&runner.id, "concurrency", Some("6")) .await @@ -2566,7 +2499,6 @@ mod tests { .await, Err(Error::Invalid(_)) )); - // A boot id alone is not enough, the version is the same for every build. fx.store .record_runner_report(&runner.id, &boot_report("b1", &[])) .await @@ -2606,13 +2538,11 @@ mod tests { assert_eq!(listed.restart.as_ref().unwrap().mode, RestartMode::Drain); assert!(listed.supports_restart()); - // The same process reporting again changes nothing. fx.store .record_runner_report(&runner.id, &boot_report("b1", &["restart"])) .await .unwrap(); assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some()); - // A heartbeat without a boot id changes nothing either. let beat = RunnerReport { concurrency: Some(2), ..RunnerReport::default() @@ -2623,7 +2553,6 @@ mod tests { .unwrap(); assert!(fx.store.runner_restart(&runner.id).await.unwrap().is_some()); - // "Restart now" replaces the pending drain. fx.store .request_runner_restart(&runner.id, RestartMode::Now) .await @@ -2633,7 +2562,6 @@ mod tests { Some(RestartMode::Now) ); - // The runner comes back with a new boot id: the request is cleared, capability kept. assert!( fx.store .record_runner_report(&runner.id, &boot_report("b2", &["restart"])) @@ -2678,7 +2606,6 @@ mod tests { .unwrap(), "an identical report is not a change" ); - // A heartbeat reports only the concurrency and keeps the host facts. let beat = RunnerReport { concurrency: Some(3), ..RunnerReport::default() @@ -2699,7 +2626,6 @@ mod tests { ); assert_eq!(listed.running_jobs, 0); - // The running count comes from the job table, and drops when the job finishes. create( &fx.store, &fx.repo.id, @@ -2801,15 +2727,17 @@ mod tests { let broken = fx .store .create_run( - &repo.id, - "push", - "refs/heads/main", - "abc123", - None, - &fx.tahinli.id, - false, + &NewRun { + repo_id: &repo.id, + trigger: "push", + git_ref: "refs/heads/main", + commit_oid: "abc123", + pull_number: None, + actor_id: &fx.tahinli.id, + needs_approval: false, + config_error: Some("line 3: unknown key"), + }, &[], - Some("line 3: unknown key"), ) .await .unwrap(); @@ -2842,15 +2770,17 @@ mod tests { let dev = fx .store .create_run( - &repo.id, - "push", - "refs/heads/dev", - "abc123", - None, - &fx.tahinli.id, - false, + &NewRun { + repo_id: &repo.id, + trigger: "push", + git_ref: "refs/heads/dev", + commit_oid: "abc123", + pull_number: None, + actor_id: &fx.tahinli.id, + needs_approval: false, + config_error: Some("broken"), + }, &[], - Some("broken"), ) .await .unwrap(); @@ -2922,7 +2852,7 @@ mod tests { let run = create(store, repo_id, actor, jobs, approval).await; let conn = store.inner.conn.lock().await; for (i, j) in jobs.iter().enumerate() { - let at = crate::time::stamp_before(Duration::from_secs(10 - i as u64)); + let at = crate::time::stamp_ago(Duration::from_secs(10 - i as u64)); conn.execute( "UPDATE ci_jobs SET queued_at = ?1 WHERE name = ?2", (at, j.name.clone()), @@ -2971,7 +2901,6 @@ mod tests { ) .await; let runner = bare_runner(&["linux"]); - // 2 GiB free: the 4 GiB job is skipped (it is young), the 1 GiB one runs. let first = fx .store .claim_job_fitting(&runner, offer(2)) @@ -2979,7 +2908,6 @@ mod tests { .unwrap() .unwrap(); assert_eq!(first.0.name, "small"); - // 1 GiB left: a job with no memory reserves the default 1 GiB and fits. let second = fx .store .claim_job_fitting(&runner, offer(1)) @@ -2987,7 +2915,6 @@ mod tests { .unwrap() .unwrap(); assert_eq!(second.0.name, "plain"); - // Nothing fits in 0 GiB, and the big job is still queued. assert!( fx.store .claim_job_fitting(&runner, offer(0)) @@ -2995,7 +2922,6 @@ mod tests { .unwrap() .is_none() ); - // An idle runner takes it. let big = fx .store .claim_job_fitting(&runner, offer(6)) @@ -3068,7 +2994,7 @@ mod tests { false, ) .await; - let old = crate::time::stamp_before(Duration::from_secs(STARVE_AFTER_SECS + 60)); + let old = crate::time::stamp_ago(Duration::from_secs(STARVE_AFTER_SECS + 60)); { let conn = fx.store.inner.conn.lock().await; conn.execute( @@ -3087,7 +3013,6 @@ mod tests { .is_none(), "the old big job holds the line" ); - // Once enough memory is free the big job goes first. let claimed = fx .store .claim_job_fitting(&runner, offer(5)) @@ -3128,7 +3053,6 @@ mod tests { assert_eq!(back.oom_kills, None); let run = fx.store.run_by_id(&run.id).await.unwrap().unwrap(); assert_eq!(run.state, RunState::Running); - // The old token no longer matches, and only a running job can be requeued. assert!(!fx.store.requeue_job(&claimed.id).await.unwrap()); assert!(!fx.store.requeue_job("missing").await.unwrap()); let (again, _, token) = fx @@ -3292,7 +3216,6 @@ mod tests { second.0.id.clone() }; - // Success unblocks b; c still waits on b. let after_a = fx .store .finish_job(&a_id, JobState::Success, Some(0), None) @@ -3308,7 +3231,6 @@ mod tests { JobState::Blocked ); - // Failure of b skips c transitively once b is done. let b_claim = fx.store.claim_job(&runner).await.unwrap().unwrap(); assert_eq!(b_claim.0.name, "b"); fx.store @@ -3467,7 +3389,6 @@ mod tests { .unwrap(); assert_eq!(done.state, RunState::Cancelled); assert!(done.finished_at.is_some()); - // A finished run does not change again. fx.store.request_cancel(&run.id).await.unwrap(); assert_eq!( fx.store.run_by_id(&run.id).await.unwrap().unwrap().state, @@ -3528,7 +3449,6 @@ mod tests { .finish_job(&b.id, JobState::Failure, Some(1), None) .await .unwrap(); - // Fail fast cancels the queued `d` and skips `c`. let done = fx.store.run_by_id(&first.id).await.unwrap().unwrap(); assert_eq!(done.state, RunState::Failure); assert_eq!( @@ -3557,7 +3477,6 @@ mod tests { assert_eq!(c2.state, JobState::Blocked); assert_eq!(spec_needs(&c2.spec_json), ["b"]); - // One finished job brings its dependants; a live one is refused. let single = fx .store .rerun_job(&first.id, &a.id, &fx.tahinli.id) @@ -3628,7 +3547,6 @@ mod tests { .await .unwrap() .unwrap(); - // Nothing is older than the epoch. assert!(fx.store.reap_lost_jobs(DAWN).await.unwrap().is_empty()); let future = stamp_after(Duration::from_secs(3600)); let reaped = fx.store.reap_lost_jobs(&future).await.unwrap(); @@ -3739,13 +3657,10 @@ mod tests { .await .unwrap(); artifacts.push(made.id); - // ULIDs made in the same millisecond do not sort by creation order. tokio::time::sleep(Duration::from_millis(2)).await; } - // Keep the newest two runs: the oldest run's artifact goes. let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 2, 0).await.unwrap(); assert_eq!(deleted, vec![artifacts[0].clone()]); - // 20 + 30 bytes left against a 35 byte limit: the older run (20 bytes) goes. let (_, deleted, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); assert_eq!(deleted, vec![artifacts[1].clone()]); let (_, again, _) = fx.store.purge_old(DAWN, DAWN, 0, 35).await.unwrap(); @@ -3795,7 +3710,6 @@ mod tests { .await .unwrap(); - // Raw storage is sealed, not plaintext. { let conn = fx.store.inner.conn.lock().await; let raw = fetch_opt( @@ -3827,7 +3741,6 @@ mod tests { assert_eq!(values.len(), 1); assert_eq!(values.get("DEPLOY_KEY").map(String::as_str), Some(plain)); - // Replacing keeps one row. fx.store .set_ci_secret(&repo.id, "DEPLOY_KEY", b"rotated") .await diff --git a/crates/forge-core/src/store/contributions.rs b/crates/forge-core/src/store/contributions.rs index 4ccde3e..7332386 100644 --- a/crates/forge-core/src/store/contributions.rs +++ b/crates/forge-core/src/store/contributions.rs @@ -13,6 +13,27 @@ use crate::tz::local_date; /// Most contributions `contributions_between` returns for one day. const DAY_LIMIT: u32 = 200; +fn activity_sql() -> String { + format!( + "SELECT 'push' AS kind, actor_id AS user_id, repo_id, created_at, ref_name, \ + 0 AS number, '' AS title, '' AS commit_oid FROM push_events \ + WHERE new_oid NOT IN ('{ZERO_OID_SHA1}', '{ZERO_OID_SHA256}') \ + AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ + UNION ALL \ + SELECT kind, author_id, repo_id, created_at, '', number, title, '' FROM issues \ + WHERE kind IN ('issue', 'pull') \ + AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ + UNION ALL \ + SELECT 'comment', c.author_id, i.repo_id, c.created_at, '', i.number, i.title, '' \ + FROM comments c JOIN issues i ON i.id = c.issue_id \ + WHERE i.repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ + UNION ALL \ + SELECT 'coauthored', user_id, repo_id, created_at, '', 0, summary, commit_oid \ + FROM coauthored_commits \ + WHERE repo_id IN (SELECT id FROM repos WHERE visibility = 'public')" + ) +} + /// What a contribution was: a branch push, an issue, pull request or comment the user wrote, or /// a commit the user was credited with as a co-author. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -81,35 +102,21 @@ impl Store { since: &str, tz: &str, ) -> Result> { - // Parameters: ?1 user, ?2 since, ?3 and ?4 zero oids. - let sql = "SELECT minute, COUNT(*) FROM ( \ - SELECT substr(created_at, 1, 16) AS minute FROM push_events \ - WHERE actor_id = ?1 AND created_at >= ?2 AND new_oid NOT IN (?3, ?4) \ - AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ - UNION ALL \ - SELECT substr(created_at, 1, 16) FROM issues \ - WHERE author_id = ?1 AND created_at >= ?2 AND kind IN ('issue', 'pull') \ - AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ - UNION ALL \ - SELECT substr(c.created_at, 1, 16) FROM comments c JOIN issues i ON i.id = c.issue_id \ - WHERE c.author_id = ?1 AND c.created_at >= ?2 AND i.repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ - UNION ALL \ - SELECT substr(created_at, 1, 16) FROM coauthored_commits \ - WHERE user_id = ?1 AND created_at >= ?2 AND repo_id IN (SELECT id FROM repos WHERE visibility = 'public') \ - ) GROUP BY minute"; + let sql = format!( + "SELECT substr(created_at, 1, 16) AS minute, COUNT(*) FROM ({}) \ + WHERE user_id = ?1 AND created_at >= ?2 GROUP BY minute", + activity_sql() + ); let params = vec![ Value::Text(user_id.to_string()), Value::Text(since.to_string()), - Value::Text(ZERO_OID_SHA1.to_string()), - Value::Text(ZERO_OID_SHA256.to_string()), ]; let conn = self.read_conn().await; - let rows = fetch_all(&conn, sql, params, |row| { + let rows = fetch_all(&conn, &sql, params, |row| { Ok((col_text(row, 0)?, col_int(row, 1)?)) }) .await?; - // `minute` is `YYYY-MM-DDTHH:MM` in UTC; the stamp is completed with seconds to parse. let mut days: BTreeMap = BTreeMap::new(); for (minute, count) in rows { let Ok(ts) = format!("{minute}:00Z").parse::() else { @@ -131,41 +138,23 @@ impl Store { from: &str, to: &str, ) -> Result> { - // Parameters: ?1 user, ?2 from, ?3 to, ?4 and ?5 zero oids. - let sql = "SELECT 'push' AS created_kind, o.username, r.name, p.created_at, p.ref_name, \ - 0, '', '' FROM push_events p \ - JOIN repos r ON r.id = p.repo_id JOIN users o ON o.id = r.owner_id \ - WHERE p.actor_id = ?1 AND p.created_at >= ?2 AND p.created_at < ?3 \ - AND p.new_oid NOT IN (?4, ?5) AND r.visibility = 'public' \ - UNION ALL \ - SELECT i.kind, o.username, r.name, i.created_at, '', i.number, i.title, '' FROM issues i \ - JOIN repos r ON r.id = i.repo_id JOIN users o ON o.id = r.owner_id \ - WHERE i.author_id = ?1 AND i.created_at >= ?2 AND i.created_at < ?3 \ - AND i.kind IN ('issue', 'pull') AND r.visibility = 'public' \ - UNION ALL \ - SELECT 'comment', o.username, r.name, c.created_at, '', i.number, i.title, '' \ - FROM comments c JOIN issues i ON i.id = c.issue_id \ - JOIN repos r ON r.id = i.repo_id JOIN users o ON o.id = r.owner_id \ - WHERE c.author_id = ?1 AND c.created_at >= ?2 AND c.created_at < ?3 \ - AND r.visibility = 'public' \ - UNION ALL \ - SELECT 'coauthored', o.username, r.name, k.created_at, '', 0, k.summary, k.commit_oid \ - FROM coauthored_commits k \ - JOIN repos r ON r.id = k.repo_id JOIN users o ON o.id = r.owner_id \ - WHERE k.user_id = ?1 AND k.created_at >= ?2 AND k.created_at < ?3 \ - AND r.visibility = 'public' \ - ORDER BY created_at DESC LIMIT ?6"; + let sql = format!( + "SELECT a.kind, o.username, r.name, a.created_at, a.ref_name, a.number, a.title, \ + a.commit_oid FROM ({}) a \ + JOIN repos r ON r.id = a.repo_id JOIN users o ON o.id = r.owner_id \ + WHERE a.user_id = ?1 AND a.created_at >= ?2 AND a.created_at < ?3 \ + ORDER BY a.created_at DESC LIMIT ?4", + activity_sql() + ); let params = vec![ Value::Text(user_id.to_string()), Value::Text(from.to_string()), Value::Text(to.to_string()), - Value::Text(ZERO_OID_SHA1.to_string()), - Value::Text(ZERO_OID_SHA256.to_string()), Value::Integer(i64::from(DAY_LIMIT)), ]; let conn = self.read_conn().await; - fetch_all(&conn, sql, params, map_item).await + fetch_all(&conn, &sql, params, map_item).await } /// Credits `user_id` with a co-authored commit in `repo_id`. A commit is recorded once per @@ -311,7 +300,6 @@ mod tests { .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at) .await .unwrap(); - // A repeat of the same commit is ignored. store .record_coauthored_commit(&tahinli.id, &demo.id, OID, "pair session", at) .await @@ -349,7 +337,6 @@ mod tests { .await .unwrap(); - // Day one: a push and an issue. let day1 = "2026-03-01T10:00:00.000000000Z"; let day2 = "2026-03-02T10:00:00.000000000Z"; let before = "2026-02-28T10:00:00.000000000Z"; @@ -363,7 +350,6 @@ mod tests { .unwrap(); set_created_at(&store, "issues", &issue.id, day1).await; - // Day two: a branch update, a deletion (not counted), a pull request, a comment. store .record_push_event_at(&demo.id, &tahinli.id, "refs/heads/main", OID, OID, day2) .await @@ -393,7 +379,6 @@ mod tests { .unwrap(); set_created_at(&store, "comments", &comment.id, day2).await; - // Before `since`, and someone else's activity: left out. store .record_push_event_at(&demo.id, &tahinli.id, "refs/heads/main", OID, OID, before) .await @@ -413,8 +398,6 @@ mod tests { vec![("2026-03-01".to_string(), 2), ("2026-03-02".to_string(), 3)] ); - // `since` filters out the first day. In Kiritimati (+14) the 10:00 UTC events fall on - // the next local day. let later = store .contribution_counts( &tahinli.id, @@ -425,7 +408,6 @@ mod tests { .unwrap(); assert_eq!(later, vec![("2026-03-03".to_string(), 3)]); - // A user with nothing in range gets an empty list. assert!( store .contribution_counts(&bob.id, "2026-03-03T00:00:00.000000000Z", "UTC") diff --git a/crates/forge-core/src/store/discussions.rs b/crates/forge-core/src/store/discussions.rs index 925ca3b..50ab4c2 100644 --- a/crates/forge-core/src/store/discussions.rs +++ b/crates/forge-core/src/store/discussions.rs @@ -5,7 +5,7 @@ use turso::transaction::Transaction; use turso::{Connection, Row, Value}; -use super::issues::finish; +use super::finish; use super::{ Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id, }; @@ -452,23 +452,16 @@ impl Store { .await .map_err(db_err)?; if discussion.author_id != author_id { - tx.execute( - "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \ - last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, 'reply', ?4, 1, ?5) \ - ON CONFLICT (user_id, discussion_id) DO UPDATE SET \ - reason = CASE WHEN discussion_notifications.reason = 'mention' THEN 'mention' \ - ELSE 'reply' END, last_actor_id = excluded.last_actor_id, unread = 1, \ - updated_at = excluded.updated_at", - ( - discussion.author_id.clone(), - discussion_id.to_string(), - discussion.repo_id.clone(), - author_id.to_string(), - now, - ), + upsert_discussion_notification( + &tx, + &discussion.author_id, + &discussion.repo_id, + discussion_id, + "reply", + author_id, + &now, ) - .await - .map_err(db_err)?; + .await?; } Ok(comment) } @@ -598,21 +591,16 @@ impl Store { let conn = self.inner.conn.lock().await; let now = now_stamp(); for user_id in user_ids { - conn.execute( - "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \ - last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, 'mention', ?4, 1, ?5) \ - ON CONFLICT (user_id, discussion_id) DO UPDATE SET reason = 'mention', \ - last_actor_id = excluded.last_actor_id, unread = 1, updated_at = excluded.updated_at", - ( - user_id.clone(), - discussion_id.to_string(), - repo_id.to_string(), - actor_id.to_string(), - now.clone(), - ), + upsert_discussion_notification( + &conn, + user_id, + repo_id, + discussion_id, + "mention", + actor_id, + &now, ) - .await - .map_err(db_err)?; + .await?; } Ok(()) } @@ -696,27 +684,47 @@ impl Store { repo_id: Option<&str>, ) -> Result<()> { let conn = self.inner.conn.lock().await; - let result = match repo_id { - Some(repo) => { - conn.execute( - "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND repo_id = ?2 AND unread = 1", - (user_id.to_string(), repo.to_string()), - ) - .await - } - None => { - conn.execute( - "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1", - (user_id.to_string(),), - ) - .await - } - }; - result.map_err(db_err)?; + conn.execute( + "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1 \ + AND (?2 IS NULL OR repo_id = ?2)", + (user_id.to_string(), repo_id.map(str::to_string)), + ) + .await + .map_err(db_err)?; Ok(()) } } +async fn upsert_discussion_notification( + conn: &Connection, + user_id: &str, + repo_id: &str, + discussion_id: &str, + reason: &str, + actor_id: &str, + now: &str, +) -> Result<()> { + conn.execute( + "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \ + last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, 1, ?6) \ + ON CONFLICT (user_id, discussion_id) DO UPDATE SET \ + reason = CASE WHEN excluded.reason = 'mention' OR discussion_notifications.reason = 'mention' \ + THEN 'mention' ELSE 'reply' END, last_actor_id = excluded.last_actor_id, unread = 1, \ + updated_at = excluded.updated_at", + ( + user_id.to_string(), + discussion_id.to_string(), + repo_id.to_string(), + reason.to_string(), + actor_id.to_string(), + now.to_string(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/forge-core/src/store/edit_history_read.rs b/crates/forge-core/src/store/edit_history_read.rs index 807b8ac..1c160ea 100644 --- a/crates/forge-core/src/store/edit_history_read.rs +++ b/crates/forge-core/src/store/edit_history_read.rs @@ -4,11 +4,26 @@ use std::collections::HashMap; -use super::{Store, col_int, col_opt_text, col_text, fetch_all, fetch_opt}; +use super::{IN_CHUNK, Store, col_int, col_opt_text, col_text, fetch_all, fetch_opt, placeholders}; use crate::error::Result; -/// Longest id list sent in one `IN (...)` query. -const CHUNK: usize = 500; +/// The kinds of target that have edit history. `as_str` is the stored text. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EditTarget { + Issue, + Comment, + ReviewComment, +} + +impl EditTarget { + pub fn as_str(self) -> &'static str { + match self { + Self::Issue => "issue", + Self::Comment => "comment", + Self::ReviewComment => "review_comment", + } + } +} /// One previous version of an issue, pull request, comment or review comment. #[derive(Debug, Clone, PartialEq)] @@ -22,15 +37,11 @@ pub struct EditVersion { pub old_body: String, } -fn placeholders(n: usize) -> String { - vec!["?"; n].join(",") -} - impl Store { /// The previous versions of one target, newest first. pub async fn edit_history( &self, - target_kind: &str, + target_kind: EditTarget, target_id: &str, ) -> Result> { let conn = self.read_conn().await; @@ -40,7 +51,7 @@ impl Store { FROM edit_history h JOIN users u ON u.id = h.editor_id \ WHERE h.target_kind = ?1 AND h.target_id = ?2 \ ORDER BY h.edited_at DESC, h.id DESC", - (target_kind.to_string(), target_id.to_string()), + (target_kind.as_str().to_string(), target_id.to_string()), |row| { Ok(EditVersion { id: col_text(row, 0)?, @@ -58,7 +69,7 @@ impl Store { /// absent from the map. One query per 500 ids. pub async fn edit_count( &self, - target_kind: &str, + target_kind: EditTarget, target_ids: &[&str], ) -> Result> { let mut out = HashMap::new(); @@ -66,14 +77,14 @@ impl Store { return Ok(out); } let conn = self.read_conn().await; - for chunk in target_ids.chunks(CHUNK) { + for chunk in target_ids.chunks(IN_CHUNK) { let sql = format!( "SELECT target_id, COUNT(*) FROM edit_history \ WHERE target_kind = ?1 AND target_id IN ({}) GROUP BY target_id", placeholders(chunk.len()) ); let mut params: Vec = Vec::with_capacity(chunk.len() + 1); - params.push(turso::Value::Text(target_kind.to_string())); + params.push(turso::Value::Text(target_kind.as_str().to_string())); params.extend(chunk.iter().map(|id| turso::Value::Text((*id).to_string()))); let rows = fetch_all(&conn, &sql, params, |row| { let count = u64::try_from(col_int(row, 1)?).unwrap_or(0); @@ -89,14 +100,15 @@ impl Store { /// target does not exist (a deleted comment has no history either). pub async fn edit_target_issue( &self, - target_kind: &str, + target_kind: EditTarget, target_id: &str, ) -> Result> { let sql = match target_kind { - "issue" => "SELECT id FROM issues WHERE id = ?1 LIMIT 1", - "comment" => "SELECT issue_id FROM comments WHERE id = ?1 LIMIT 1", - "review_comment" => "SELECT issue_id FROM review_comments WHERE id = ?1 LIMIT 1", - _ => return Ok(None), + EditTarget::Issue => "SELECT id FROM issues WHERE id = ?1 LIMIT 1", + EditTarget::Comment => "SELECT issue_id FROM comments WHERE id = ?1 LIMIT 1", + EditTarget::ReviewComment => { + "SELECT issue_id FROM review_comments WHERE id = ?1 LIMIT 1" + } }; let conn = self.read_conn().await; fetch_opt(&conn, sql, (target_id.to_string(),), |row| col_text(row, 0)).await diff --git a/crates/forge-core/src/store/health.rs b/crates/forge-core/src/store/health.rs index d291844..70747a0 100644 --- a/crates/forge-core/src/store/health.rs +++ b/crates/forge-core/src/store/health.rs @@ -5,17 +5,16 @@ use crate::error::{Error, Result}; use crate::time::{stamp_ago, stamp_to_unix}; /// Window in which a runner's last report counts as online. -pub const RUNNER_ONLINE_SECS: u64 = 90; +pub const RUNNER_ONLINE_SECS: i64 = 90; /// Whether a runner counts as online at `now_unix`: enabled, and its last report within /// [`RUNNER_ONLINE_SECS`]. The runners page dot and the live signal of the runners page both use /// this one rule. pub fn runner_is_online(disabled: bool, last_seen_at: Option<&str>, now_unix: i64) -> bool { - let limit = i64::try_from(RUNNER_ONLINE_SECS).unwrap_or(i64::MAX); !disabled && last_seen_at .and_then(stamp_to_unix) - .is_some_and(|seen| now_unix.saturating_sub(seen) <= limit) + .is_some_and(|seen| now_unix.saturating_sub(seen) <= RUNNER_ONLINE_SECS) } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] @@ -31,7 +30,7 @@ impl Store { /// Counts of repos, users, queued CI jobs and runners. Five indexed `COUNT(*)` queries. pub async fn health_counts(&self) -> Result { let conn = self.read_conn().await; - let since = stamp_ago(std::time::Duration::from_secs(RUNNER_ONLINE_SECS)); + let since = stamp_ago(std::time::Duration::from_secs(RUNNER_ONLINE_SECS.unsigned_abs())); let plain = |sql: &'static str| { let conn = &conn; async move { diff --git a/crates/forge-core/src/store/imports.rs b/crates/forge-core/src/store/imports.rs index efad12b..51429d9 100644 --- a/crates/forge-core/src/store/imports.rs +++ b/crates/forge-core/src/store/imports.rs @@ -3,7 +3,7 @@ use turso::{Row, Value}; -use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; +use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id, text}; use crate::error::{Error, Result}; use crate::time::now_stamp; @@ -100,10 +100,6 @@ fn map_job(row: &Row) -> Result { }) } -fn text(s: &str) -> Value { - Value::Text(s.to_owned()) -} - impl Store { /// Creates a queued job. `source_ref` must not hold a credential. pub async fn create_import_job( @@ -186,7 +182,11 @@ impl Store { error: Option<&str>, ) -> Result<()> { let now = now_stamp(); - let finished = state.is_finished().then(|| now.clone()); + let finished = if state.is_finished() { + text(&now) + } else { + Value::Null + }; let conn = self.inner.conn.lock().await; conn.execute( "UPDATE import_jobs SET state = ?2, error = ?3, updated_at = ?4, finished_at = ?5 \ @@ -196,7 +196,7 @@ impl Store { text(state.as_str()), error.map_or(Value::Null, text), text(&now), - finished.as_deref().map_or(Value::Null, text), + finished, ], ) .await diff --git a/crates/forge-core/src/store/issues.rs b/crates/forge-core/src/store/issues.rs index 0ab90b7..045216c 100644 --- a/crates/forge-core/src/store/issues.rs +++ b/crates/forge-core/src/store/issues.rs @@ -1,6 +1,3 @@ -//! Issues, comments, timeline events and milestones. Every multi-row write runs in one -//! transaction. Numbers come from `repos.next_issue_number` in the same transaction as the insert. - use std::collections::HashMap; use serde_json::{Map, Value as Json}; @@ -8,8 +5,8 @@ use turso::transaction::Transaction; use turso::{Connection, Row, Value}; use super::{ - Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, missing_row, - new_id, + IN_CHUNK, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, + insert_err, missing_row, new_id, placeholders, }; use crate::error::{Error, Result}; use crate::issues::{ @@ -19,7 +16,6 @@ use crate::issues::{ use crate::names::normalize_name; use crate::time::now_stamp; -/// Event kinds the timeline knows. Anything else is rejected by `add_event`. const EVENT_KINDS: &[&str] = &[ "closed", "reopened", @@ -33,7 +29,6 @@ const EVENT_KINDS: &[&str] = &[ "referenced", "locked", "unlocked", - // Pull requests (store/pulls.rs). "merged", "head_updated", "base_changed", @@ -44,11 +39,9 @@ const EVENT_KINDS: &[&str] = &[ "converted_to_draft", "auto_merge_enabled", "auto_merge_disabled", - // Pull request reviews (store/reviews.rs). "review_dismissed", "thread_resolved", "thread_unresolved", - // Pinned issues (store/pinned.rs). "pinned", "unpinned", ]; @@ -59,15 +52,11 @@ pub(super) const ISSUE_COLS: &str = "i.id, i.repo_id, i.number, i.title, i.body, const COMMENT_COLS: &str = "id, issue_id, author_id, body, created_at, updated_at, edited"; const LABEL_COLS: &str = "l.id, l.repo_id, l.name, l.color, l.description"; -/// Caps the number of placeholders in one `IN (...)` list. -const IN_CHUNK: usize = 500; - pub(super) fn parse_db>(s: &str) -> Result { s.parse::() .map_err(|e| Error::Database(format!("stored value {s:?}: {e}"))) } -/// Reads `ISSUE_COLS` (columns 0 to 14). pub(super) fn map_issue(row: &Row) -> Result { Ok(Issue { id: col_text(row, 0)?, @@ -117,7 +106,6 @@ fn map_event(row: &Row) -> Result { }) } -/// A label read from `LABEL_COLS` (or any five columns) starting at `base`. fn map_label(row: &Row, base: usize) -> Result