use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
pub const PROJECT_COLUMNS: &[(&str, &str)] = &[
("backlog", "Backlog"),
("in_progress", "In Progress"),
("review", "Review"),
("done", "Done"),
];
pub const CURRENT_SCHEMA_VERSION: u32 = 1;
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ForgeStore {
#[serde(default)]
pub schema_version: u32,
pub next_id: u64,
pub issues: Vec<ForgeIssue>,
#[serde(default)]
pub pr_comments: Vec<PrComment>,
#[serde(default)]
pub next_card_id: u64,
#[serde(default)]
pub project_cards: Vec<ProjectCard>,
#[serde(default)]
pub wiki_pages: Vec<WikiPage>,
#[serde(default)]
pub next_run_id: u64,
#[serde(default)]
pub workflow_runs: Vec<WorkflowRun>,
#[serde(default)]
pub users: Vec<UserAccount>,
#[serde(default)]
pub sessions: Vec<SessionRecord>,
#[serde(default)]
pub next_pat_id: u64,
#[serde(default)]
pub pats: Vec<PatRecord>,
#[serde(default)]
pub device_codes: Vec<DeviceCodeRecord>,
#[serde(default)]
pub next_pr_number: u64,
#[serde(default)]
pub pull_requests: Vec<PullRequestRecord>,
#[serde(default)]
pub next_release_id: u64,
#[serde(default)]
pub releases: Vec<ReleaseRecord>,
#[serde(default)]
pub next_webhook_id: u64,
#[serde(default)]
pub webhooks: Vec<WebhookRecord>,
#[serde(default)]
pub webhook_deliveries: Vec<WebhookDelivery>,
#[serde(default)]
pub branch_rules: Vec<BranchRule>,
#[serde(default)]
pub pr_reviews: Vec<PrReviewVerdict>,
#[serde(default)]
pub visibility: String,
#[serde(default)]
pub org_name: Option<String>,
#[serde(default)]
pub collaborators: Vec<String>,
#[serde(default)]
pub watchers: Vec<String>,
#[serde(default)]
pub read_notifications: Vec<String>,
#[serde(default)]
pub audit_log: Vec<AuditEntry>,
#[serde(default)]
pub action_artifacts: Vec<ActionArtifact>,
#[serde(default)]
pub action_secrets: BTreeMap<String, String>,
#[serde(default)]
pub archived: bool,
#[serde(default)]
pub next_deploy_key_id: u64,
#[serde(default)]
pub deploy_keys: Vec<DeployKeyRecord>,
#[serde(default)]
pub oauth_clients: Vec<OAuthClientRecord>,
#[serde(default)]
pub oauth_codes: Vec<OAuthCodeRecord>,
#[serde(default)]
pub oauth_tokens: Vec<OAuthTokenRecord>,
#[serde(default)]
pub repo_members: BTreeMap<String, String>,
#[serde(default)]
pub teams: Vec<TeamRecord>,
#[serde(skip)]
pub corrupt: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuditEntry {
pub id: u64,
pub actor: String,
pub action: String,
pub target: String,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ActionArtifact {
pub run_id: u64,
pub name: String,
pub sha256: String,
pub size_bytes: usize,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrReviewVerdict {
pub id: u64,
pub branch: String,
pub author: String,
pub state: String,
pub body: String,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ForgeIssue {
pub id: u64,
pub title: String,
pub body: String,
pub state: String,
pub author: String,
pub created_at: i64,
#[serde(default)]
pub labels: Vec<String>,
#[serde(default)]
pub assignee: Option<String>,
#[serde(default)]
pub comments: Vec<ForgeComment>,
#[serde(default)]
pub reactions: BTreeMap<String, Vec<String>>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ForgeComment {
pub author: String,
pub body: String,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrComment {
pub branch: String,
pub author: String,
pub body: String,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ProjectCard {
pub id: u64,
pub title: String,
pub column: String,
#[serde(default)]
pub issue_id: Option<u64>,
#[serde(default)]
pub assignee: Option<String>,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WikiPage {
pub slug: String,
pub title: String,
pub body: String,
pub author: String,
pub updated_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WorkflowRun {
pub id: u64,
pub workflow: String,
pub status: String,
pub exit_code: i32,
pub log: String,
pub started_at: i64,
pub finished_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UserAccount {
pub username: String,
pub password_hash: String,
pub role: String,
#[serde(default)]
pub ssh_keys: Vec<SshKeyRecord>,
pub created_at: i64,
#[serde(default)]
pub totp_secret_b32: Option<String>,
#[serde(default)]
pub recovery_codes: Vec<String>,
#[serde(default)]
pub external_ids: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OAuthClientRecord {
pub client_id: String,
#[serde(default)]
pub name: String,
#[serde(default)]
pub redirect_uris: Vec<String>,
#[serde(default = "default_true")]
pub public: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OAuthCodeRecord {
pub code_hash: String,
pub client_id: String,
pub username: String,
pub redirect_uri: String,
pub scope: String,
#[serde(default)]
pub code_challenge: String,
#[serde(default)]
pub nonce: Option<String>,
pub expires_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OAuthTokenRecord {
pub access_hash: String,
pub refresh_hash: String,
pub family_id: String,
pub client_id: String,
pub username: String,
pub scope: String,
pub expires_at: i64,
#[serde(default)]
pub refresh_used: bool,
#[serde(default)]
pub revoked: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TeamRecord {
pub name: String,
#[serde(default)]
pub members: Vec<String>,
pub permission: String,
}
fn default_device_interval() -> u64 {
5
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SshKeyRecord {
pub title: String,
pub public_key: String,
pub added_at: i64,
#[serde(default)]
pub fingerprint: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeployKeyRecord {
pub id: u64,
pub title: String,
pub public_key: String,
#[serde(default)]
pub fingerprint: String,
#[serde(default = "default_true")]
pub read_only: bool,
pub added_at: i64,
}
fn default_true() -> bool {
true
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SessionRecord {
pub token: String,
pub username: String,
pub csrf_token: String,
pub expires_at: i64,
#[serde(default)]
pub last_seen_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PatRecord {
pub id: u64,
pub username: String,
pub name: String,
pub token_hash: String,
pub prefix: String,
pub created_at: i64,
#[serde(default)]
pub scopes: Vec<String>,
#[serde(default)]
pub expires_at: Option<i64>,
#[serde(default)]
pub last_used_at: Option<i64>,
}
impl PatRecord {
pub fn is_expired(&self, now: i64) -> bool {
self.expires_at.is_some_and(|exp| exp <= now)
}
pub fn has_scope(&self, required: &str) -> bool {
if self.scopes.is_empty() {
return required != "admin";
}
if self.scopes.iter().any(|s| s == "admin" || s == required) {
return true;
}
if required == "repo:read" && self.scopes.iter().any(|s| s == "repo:write") {
return true;
}
false
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeviceCodeRecord {
pub device_code: String,
pub user_code: String,
#[serde(default)]
pub approved_user: Option<String>,
pub expires_at: i64,
#[serde(default)]
pub denied: bool,
#[serde(default)]
pub last_polled_at: i64,
#[serde(default = "default_device_interval")]
pub interval: u64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PullRequestRecord {
pub number: u64,
pub title: String,
pub body: String,
pub head_branch: String,
pub base_branch: String,
#[serde(default)]
pub draft: bool,
pub state: String,
pub author: String,
pub created_at: i64,
#[serde(default)]
pub inline_comments: Vec<InlineComment>,
#[serde(default)]
pub reviewers: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InlineComment {
pub id: u64,
pub path: String,
pub line: usize,
pub author: String,
pub body: String,
#[serde(default)]
pub resolved: bool,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReleaseRecord {
pub id: u64,
pub tag: String,
pub title: String,
pub notes: String,
#[serde(default)]
pub draft: bool,
#[serde(default)]
pub prerelease: bool,
pub author: String,
pub created_at: i64,
#[serde(default)]
pub assets: Vec<ReleaseAsset>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReleaseAsset {
pub name: String,
pub size: u64,
pub sha256: String,
pub uploaded_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WebhookRecord {
pub id: u64,
pub url: String,
pub secret: String,
#[serde(default)]
pub events: Vec<String>,
#[serde(default)]
pub active: bool,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WebhookDelivery {
pub id: u64,
pub webhook_id: u64,
pub event: String,
pub status: u16,
pub created_at: i64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BranchRule {
pub pattern: String,
#[serde(default)]
pub require_pr: bool,
#[serde(default)]
pub block_force_push: bool,
#[serde(default)]
pub block_delete: bool,
#[serde(default)]
pub required_reviews: u32,
}
fn store_path(git_dir: &Path) -> PathBuf {
git_dir.join("arks-forge").join("store.json")
}
pub fn now_unix() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
pub fn sanitize_slug(input: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut prev_dash = false;
for ch in input.trim().chars() {
let c = ch.to_ascii_lowercase();
if c.is_ascii_alphanumeric() {
out.push(c);
prev_dash = false;
} else if (c == '-' || c == '_' || c == ' ') && !prev_dash && !out.is_empty() {
out.push('-');
prev_dash = true;
}
}
out.trim_end_matches('-').to_string()
}
pub fn parse_labels_csv(raw: &str) -> Vec<String> {
let mut out = Vec::new();
for part in raw.split(',') {
let trimmed = part.trim();
if !trimmed.is_empty() && !out.iter().any(|existing: &String| existing == trimmed) {
out.push(trimmed.to_string());
}
}
out
}
pub fn is_valid_project_column(col: &str) -> bool {
PROJECT_COLUMNS.iter().any(|(key, _)| *key == col)
}
#[derive(Default)]
struct StoreSlot {
locked: std::sync::Mutex<bool>,
cvar: std::sync::Condvar,
}
struct OwnedStoreSlotGuard {
slot: Arc<StoreSlot>,
}
impl OwnedStoreSlotGuard {
fn lock(slot: Arc<StoreSlot>) -> Self {
let mut locked = slot.locked.lock().unwrap_or_else(|e| e.into_inner());
while *locked {
locked = slot.cvar.wait(locked).unwrap_or_else(|e| e.into_inner());
}
*locked = true;
drop(locked);
Self { slot }
}
}
impl Drop for OwnedStoreSlotGuard {
fn drop(&mut self) {
let mut locked = self.slot.locked.lock().unwrap_or_else(|e| e.into_inner());
*locked = false;
self.slot.cvar.notify_one();
}
}
fn acquire_in_process_store_lock(git_dir: &Path) -> OwnedStoreSlotGuard {
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock, Weak};
static LOCKS: OnceLock<Mutex<HashMap<PathBuf, Weak<StoreSlot>>>> = OnceLock::new();
let map_lock = LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
let key = store_path(git_dir);
let slot = {
let mut map = map_lock.lock().unwrap_or_else(|e| e.into_inner());
match map.get(&key).and_then(Weak::upgrade) {
Some(existing) => existing,
None => {
if map.len() > 64 {
map.retain(|_, w| w.strong_count() > 0);
}
let fresh = Arc::new(StoreSlot::default());
map.insert(key, Arc::downgrade(&fresh));
fresh
}
}
};
OwnedStoreSlotGuard::lock(slot)
}
const STORE_LOCK_STALE_SECS: u64 = 30;
const STORE_LOCK_TIMEOUT_SECS: u64 = 15;
struct StoreFileLock {
lock_path: PathBuf,
}
impl Drop for StoreFileLock {
fn drop(&mut self) {
let _ = fs::remove_file(&self.lock_path);
}
}
pub(crate) fn parse_lockfile_pid(path: &Path) -> Option<u32> {
let text = fs::read_to_string(path).ok()?;
let pid_str = text.trim().strip_prefix("pid=")?;
let pid = pid_str.trim().parse::<u32>().ok()?;
if pid == 0 { None } else { Some(pid) }
}
pub(crate) fn is_other_pid_alive_strict(pid: u32) -> Option<bool> {
if pid == std::process::id() {
return Some(true);
}
#[cfg(target_os = "linux")]
{
if Path::new("/proc/self").exists() {
return Some(Path::new(&format!("/proc/{pid}")).exists());
}
None
}
#[cfg(not(target_os = "linux"))]
{
None
}
}
fn is_store_lock_stale(lock_path: &Path, stale_after: std::time::Duration) -> bool {
if let Some(pid) = parse_lockfile_pid(lock_path) {
if is_other_pid_alive_strict(pid) == Some(false) {
return true;
}
}
match fs::metadata(lock_path).and_then(|m| m.modified()) {
Ok(mtime) => mtime
.elapsed()
.map(|age| age >= stale_after)
.unwrap_or(false),
Err(_) => false,
}
}
fn acquire_store_file_lock_with(
lock_path: &Path,
stale_after: std::time::Duration,
timeout: std::time::Duration,
) -> std::io::Result<StoreFileLock> {
use std::io::Write as _;
if let Some(parent) = lock_path.parent() {
fs::create_dir_all(parent)?;
}
let deadline = std::time::Instant::now() + timeout;
let mut backoff_ms = 2u64;
loop {
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(lock_path)
{
Ok(mut f) => {
let payload = format!("pid={}\n", std::process::id());
let _ = f.write_all(payload.as_bytes());
drop(f);
return Ok(StoreFileLock {
lock_path: lock_path.to_path_buf(),
});
}
Err(e)
if e.kind() == std::io::ErrorKind::AlreadyExists
|| (cfg!(windows) && e.kind() == std::io::ErrorKind::PermissionDenied) =>
{
if e.kind() == std::io::ErrorKind::AlreadyExists
&& is_store_lock_stale(lock_path, stale_after)
{
let _ = fs::remove_file(lock_path);
continue;
}
if std::time::Instant::now() >= deadline {
return Err(std::io::Error::new(
std::io::ErrorKind::WouldBlock,
format!(
"timed out waiting for forge store lock {}",
lock_path.display()
),
));
}
std::thread::sleep(std::time::Duration::from_millis(backoff_ms));
backoff_ms = (backoff_ms * 2).min(20);
}
Err(e) => return Err(e),
}
}
}
fn store_lock_path(git_dir: &Path) -> PathBuf {
git_dir.join("arks-forge").join("store.json.lock")
}
pub struct ForgeStoreTx {
git_dir: PathBuf,
store: ForgeStore,
lock_err: Option<String>,
_file_lock: Option<StoreFileLock>,
_in_proc: OwnedStoreSlotGuard,
}
impl std::ops::Deref for ForgeStoreTx {
type Target = ForgeStore;
fn deref(&self) -> &Self::Target {
&self.store
}
}
impl std::ops::DerefMut for ForgeStoreTx {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.store
}
}
impl ForgeStoreTx {
pub fn commit(self) -> std::io::Result<()> {
if let Some(ref err) = self.lock_err {
return Err(std::io::Error::new(
std::io::ErrorKind::WouldBlock,
err.clone(),
));
}
self.store.save_owned_unlocked(&self.git_dir)
}
}
pub(crate) fn atomic_write_file(path: &Path, data: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
use std::sync::atomic::{AtomicU64, Ordering};
static WRITE_SEQ: AtomicU64 = AtomicU64::new(1);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let seq = WRITE_SEQ.fetch_add(1, Ordering::Relaxed);
let file_name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("arks-file");
let tmp = path.with_file_name(format!(".{file_name}.{}.{seq}.tmp", std::process::id()));
let write_res = (|| -> std::io::Result<()> {
let mut f = fs::File::create(&tmp)?;
f.write_all(data)?;
f.sync_all()?;
Ok(())
})();
if let Err(e) = write_res {
let _ = fs::remove_file(&tmp);
return Err(e);
}
#[cfg(windows)]
{
let mut last_err = None;
for attempt in 0..5u32 {
match fs::rename(&tmp, path) {
Ok(()) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied && attempt < 4 => {
last_err = Some(e);
std::thread::sleep(std::time::Duration::from_millis(10));
}
Err(e) => {
let _ = fs::remove_file(&tmp);
return Err(e);
}
}
}
let _ = fs::remove_file(&tmp);
Err(last_err.unwrap_or_else(|| {
std::io::Error::new(std::io::ErrorKind::PermissionDenied, "atomic rename failed")
}))
}
#[cfg(not(windows))]
{
if let Err(e) = fs::rename(&tmp, path) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
}
fn parse_store_temp_pid(file_name: &str) -> Option<u32> {
let rest = file_name.strip_prefix(".store.json.")?;
let stem = rest.strip_suffix(".tmp")?;
let (pid_str, seq_str) = stem.split_once('.')?;
let pid = pid_str.parse::<u32>().ok()?;
let _seq = seq_str.parse::<u64>().ok()?;
if pid == 0 { None } else { Some(pid) }
}
fn is_other_pid_alive(pid: u32, path: &Path) -> bool {
if pid == std::process::id() {
return true;
}
#[cfg(target_os = "linux")]
{
let _ = path;
if Path::new("/proc/self").exists() {
return Path::new(&format!("/proc/{pid}")).exists();
}
true
}
#[cfg(not(target_os = "linux"))]
{
match fs::metadata(path).and_then(|m| m.modified()) {
Ok(mtime) => mtime
.elapsed()
.map(|age| age < std::time::Duration::from_secs(60))
.unwrap_or(true),
Err(_) => true,
}
}
}
pub(crate) fn sweep_stale_temps_in_dir_with<F>(forge_dir: &Path, mut is_alive: F) -> usize
where
F: FnMut(u32, &Path) -> bool,
{
let Ok(entries) = fs::read_dir(forge_dir) else {
return 0;
};
let mut removed = 0usize;
for entry in entries.flatten() {
let path = entry.path();
let Some(name) = entry.file_name().to_str().map(str::to_string) else {
continue;
};
let pid = if name == "store.json.lock" {
parse_lockfile_pid(&path)
} else {
parse_store_temp_pid(&name)
};
let Some(pid) = pid else {
continue;
};
if !is_alive(pid, &path) && fs::remove_file(&path).is_ok() {
removed += 1;
}
}
removed
}
fn sweep_stale_ref_gate_lock<F>(repo_dir: &Path, mut is_alive: F) -> usize
where
F: FnMut(u32, &Path) -> bool,
{
let lock_path = repo_dir.join("arks-ref-gate.lock");
if let Some(pid) = parse_lockfile_pid(&lock_path) {
if !is_alive(pid, &lock_path) && fs::remove_file(&lock_path).is_ok() {
return 1;
}
}
0
}
pub(crate) fn sweep_stale_temps(git_dir: &Path, multi_repo_root: bool) -> usize {
let mut removed =
sweep_stale_temps_in_dir_with(&git_dir.join("arks-forge"), is_other_pid_alive);
removed += sweep_stale_ref_gate_lock(git_dir, is_other_pid_alive);
if multi_repo_root {
if let Ok(entries) = fs::read_dir(git_dir) {
for entry in entries.flatten() {
let p = entry.path();
if p.is_dir() {
removed +=
sweep_stale_temps_in_dir_with(&p.join("arks-forge"), is_other_pid_alive);
removed += sweep_stale_ref_gate_lock(&p, is_other_pid_alive);
}
}
}
}
removed
}
fn sweep_stale_temps_once(git_dir: &Path) {
use std::collections::HashSet;
use std::sync::{Mutex, OnceLock};
static SWEPT: OnceLock<Mutex<HashSet<PathBuf>>> = OnceLock::new();
let set = SWEPT.get_or_init(|| Mutex::new(HashSet::new()));
let forge_dir = git_dir.join("arks-forge");
let first_time = {
let mut g = set.lock().unwrap_or_else(|e| e.into_inner());
g.insert(forge_dir.clone())
};
if first_time {
let _ = sweep_stale_temps_in_dir_with(&forge_dir, is_other_pid_alive);
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct FileStamp {
len: u64,
mtime: Option<std::time::SystemTime>,
}
fn file_stamp(path: &Path) -> Option<FileStamp> {
let meta = fs::metadata(path).ok()?;
Some(FileStamp {
len: meta.len(),
mtime: meta.modified().ok(),
})
}
type StoreCacheMap = std::collections::HashMap<PathBuf, (FileStamp, Arc<ForgeStore>)>;
fn store_cache() -> &'static std::sync::RwLock<StoreCacheMap> {
use std::collections::HashMap;
use std::sync::{OnceLock, RwLock};
static CACHE: OnceLock<RwLock<StoreCacheMap>> = OnceLock::new();
CACHE.get_or_init(|| RwLock::new(HashMap::new()))
}
impl ForgeStore {
pub fn is_private(&self) -> bool {
self.visibility == "private"
}
pub fn load_shared(git_dir: &Path) -> Arc<Self> {
sweep_stale_temps_once(git_dir);
let path = store_path(git_dir);
if let Some(stamp) = file_stamp(&path) {
let cache = store_cache().read().unwrap_or_else(|e| e.into_inner());
if let Some((cached_stamp, cached_store)) = cache.get(&path) {
if *cached_stamp == stamp {
return Arc::clone(cached_store);
}
}
}
Self::load_shared_unlocked(git_dir)
}
#[cfg(test)]
pub fn load(git_dir: &Path) -> Self {
(*Self::load_shared(git_dir)).clone()
}
pub fn lock_mut(git_dir: &Path) -> ForgeStoreTx {
sweep_stale_temps_once(git_dir);
let in_proc = acquire_in_process_store_lock(git_dir);
let (file_lock, lock_err) = match acquire_store_file_lock_with(
&store_lock_path(git_dir),
std::time::Duration::from_secs(STORE_LOCK_STALE_SECS),
std::time::Duration::from_secs(STORE_LOCK_TIMEOUT_SECS),
) {
Ok(fl) => (Some(fl), None),
Err(e) => (None, Some(e.to_string())),
};
let store = (*Self::load_shared_unlocked(git_dir)).clone();
ForgeStoreTx {
git_dir: git_dir.to_path_buf(),
store,
lock_err,
_file_lock: file_lock,
_in_proc: in_proc,
}
}
fn load_shared_unlocked(git_dir: &Path) -> Arc<Self> {
let path = store_path(git_dir);
let stamp = file_stamp(&path);
if let Some(st) = stamp {
let cache = store_cache().read().unwrap_or_else(|e| e.into_inner());
if let Some((cached_stamp, cached_store)) = cache.get(&path) {
if *cached_stamp == st {
return Arc::clone(cached_store);
}
}
}
let raw = match fs::read_to_string(&path) {
Ok(content) => content,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Arc::new(Self {
schema_version: CURRENT_SCHEMA_VERSION,
next_id: 1,
next_card_id: 1,
next_run_id: 1,
..Self::default()
});
}
Err(_) => {
let mut cache = store_cache().write().unwrap_or_else(|e| e.into_inner());
cache.remove(&path);
return Arc::new(Self {
corrupt: true,
..Self::default()
});
}
};
let mut s: Self = match serde_json::from_str(&raw) {
Ok(parsed) => parsed,
Err(_) => {
let mut cache = store_cache().write().unwrap_or_else(|e| e.into_inner());
cache.remove(&path);
return Arc::new(Self {
corrupt: true,
..Self::default()
});
}
};
if s.schema_version > CURRENT_SCHEMA_VERSION {
eprintln!(
"arks serve: store {} has schema_version {} > supported {} (fail-closed)",
path.display(),
s.schema_version,
CURRENT_SCHEMA_VERSION
);
let mut cache = store_cache().write().unwrap_or_else(|e| e.into_inner());
cache.remove(&path);
return Arc::new(Self {
schema_version: s.schema_version,
corrupt: true,
..Self::default()
});
}
if s.schema_version < CURRENT_SCHEMA_VERSION {
let from = s.schema_version;
let bak = path.with_extension(format!("json.pre-migrate-v{from}.bak"));
if !bak.exists() {
let _ = atomic_write_file(&bak, raw.as_bytes());
}
while s.schema_version < CURRENT_SCHEMA_VERSION {
match s.schema_version {
0 => {
if s.next_id == 0 {
s.next_id = s.issues.iter().map(|i| i.id).max().unwrap_or(0) + 1;
}
if s.next_card_id == 0 {
s.next_card_id =
s.project_cards.iter().map(|c| c.id).max().unwrap_or(0) + 1;
}
if s.next_run_id == 0 {
s.next_run_id =
s.workflow_runs.iter().map(|r| r.id).max().unwrap_or(0) + 1;
}
s.schema_version = 1;
}
_ => break,
}
}
}
if s.next_id == 0 {
s.next_id = s.issues.iter().map(|i| i.id).max().unwrap_or(0) + 1;
}
if s.next_card_id == 0 {
s.next_card_id = s.project_cards.iter().map(|c| c.id).max().unwrap_or(0) + 1;
}
if s.next_run_id == 0 {
s.next_run_id = s.workflow_runs.iter().map(|r| r.id).max().unwrap_or(0) + 1;
}
let arc = Arc::new(s);
if let Some(st) = stamp {
let mut cache = store_cache().write().unwrap_or_else(|e| e.into_inner());
cache.insert(path, (st, Arc::clone(&arc)));
}
arc
}
fn save_owned_unlocked(mut self, git_dir: &Path) -> std::io::Result<()> {
if self.corrupt {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"refusing to overwrite corrupted forge store.json (fail-closed)",
));
}
if self.schema_version > CURRENT_SCHEMA_VERSION {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"refusing to overwrite future store schema_version {} (supported {})",
self.schema_version, CURRENT_SCHEMA_VERSION
),
));
}
self.schema_version = CURRENT_SCHEMA_VERSION;
let path = store_path(git_dir);
let data = serde_json::to_vec_pretty(&self)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
atomic_write_file(&path, &data)?;
let mut cache = store_cache().write().unwrap_or_else(|e| e.into_inner());
if let Some(st) = file_stamp(&path) {
cache.insert(path, (st, Arc::new(self)));
} else {
cache.remove(&path);
}
Ok(())
}
pub fn update<R>(git_dir: &Path, f: impl FnOnce(&mut Self) -> R) -> std::io::Result<R> {
let mut tx = Self::lock_mut(git_dir);
if tx.corrupt {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"refusing to mutate corrupted forge store.json (fail-closed)",
));
}
let out = f(&mut tx);
tx.commit()?;
Ok(out)
}
#[cfg(test)]
pub fn save(&self, git_dir: &Path) -> std::io::Result<()> {
let _in_proc = acquire_in_process_store_lock(git_dir);
let _file_lock = acquire_store_file_lock_with(
&store_lock_path(git_dir),
std::time::Duration::from_secs(STORE_LOCK_STALE_SECS),
std::time::Duration::from_secs(STORE_LOCK_TIMEOUT_SECS),
)?;
self.clone().save_owned_unlocked(git_dir)
}
pub fn create_issue(
&mut self,
title: String,
body: String,
author: String,
labels: Vec<String>,
assignee: Option<String>,
) -> u64 {
let id = self.next_id.max(1);
self.next_id = id + 1;
self.issues.push(ForgeIssue {
id,
title,
body,
state: "open".into(),
author,
created_at: now_unix(),
labels,
assignee,
comments: Vec::new(),
reactions: BTreeMap::new(),
});
id
}
pub fn update_issue_meta(
&mut self,
id: u64,
labels: Vec<String>,
assignee: Option<String>,
) -> bool {
let Some(issue) = self.issues.iter_mut().find(|i| i.id == id) else {
return false;
};
issue.labels = labels;
issue.assignee = assignee;
true
}
pub fn add_issue_comment(&mut self, id: u64, author: String, body: String) -> bool {
let Some(issue) = self.issues.iter_mut().find(|i| i.id == id) else {
return false;
};
issue.comments.push(ForgeComment {
author,
body,
created_at: now_unix(),
});
true
}
pub fn toggle_issue_state(&mut self, id: u64) -> Option<&str> {
let issue = self.issues.iter_mut().find(|i| i.id == id)?;
issue.state = if issue.state == "open" {
"closed".into()
} else {
"open".into()
};
Some(issue.state.as_str())
}
pub fn add_pr_comment(&mut self, branch: String, author: String, body: String) {
self.pr_comments.push(PrComment {
branch,
author,
body,
created_at: now_unix(),
});
}
pub fn create_card(
&mut self,
title: String,
column: String,
issue_id: Option<u64>,
assignee: Option<String>,
) -> u64 {
let id = self.next_card_id.max(1);
self.next_card_id = id + 1;
let col = if is_valid_project_column(&column) {
column
} else {
"backlog".to_string()
};
self.project_cards.push(ProjectCard {
id,
title,
column: col,
issue_id,
assignee,
created_at: now_unix(),
});
id
}
pub fn move_card(&mut self, id: u64, column: &str) -> bool {
if !is_valid_project_column(column) {
return false;
}
let Some(card) = self.project_cards.iter_mut().find(|c| c.id == id) else {
return false;
};
card.column = column.to_string();
true
}
pub fn delete_card(&mut self, id: u64) -> bool {
let before = self.project_cards.len();
self.project_cards.retain(|c| c.id != id);
self.project_cards.len() < before
}
pub fn upsert_wiki_page(
&mut self,
slug: String,
title: String,
body: String,
author: String,
) -> String {
let clean_slug = sanitize_slug(if slug.is_empty() { &title } else { &slug });
let final_slug = if clean_slug.is_empty() {
"home".to_string()
} else {
clean_slug
};
let now = now_unix();
if let Some(existing) = self.wiki_pages.iter_mut().find(|p| p.slug == final_slug) {
existing.title = title;
existing.body = body;
existing.author = author;
existing.updated_at = now;
} else {
self.wiki_pages.push(WikiPage {
slug: final_slug.clone(),
title,
body,
author,
updated_at: now,
});
}
final_slug
}
pub fn delete_wiki_page(&mut self, slug: &str) -> bool {
let before = self.wiki_pages.len();
self.wiki_pages.retain(|p| p.slug != slug);
self.wiki_pages.len() < before
}
#[allow(dead_code)]
pub fn record_workflow_run(
&mut self,
workflow: String,
status: String,
exit_code: i32,
log: String,
started_at: i64,
finished_at: i64,
) -> u64 {
let id = self.next_run_id.max(1);
self.next_run_id = id + 1;
self.workflow_runs.push(WorkflowRun {
id,
workflow,
status,
exit_code,
log,
started_at,
finished_at,
});
id
}
}
pub fn parse_form_urlencoded(body: &[u8]) -> BTreeMap<String, String> {
let text = String::from_utf8_lossy(body);
let mut map = BTreeMap::new();
for pair in text.split('&') {
if let Some((k, v)) = pair.split_once('=') {
map.insert(percent_decode(k), percent_decode(v));
}
}
map
}
fn percent_decode(input: &str) -> String {
let mut bytes = Vec::with_capacity(input.len());
let raw = input.as_bytes();
let mut i = 0;
while i < raw.len() {
if raw[i] == b'+' {
bytes.push(b' ');
i += 1;
} else if raw[i] == b'%' && i + 2 < raw.len() {
if let Ok(val) = u8::from_str_radix(&input[i + 1..i + 3], 16) {
bytes.push(val);
i += 3;
continue;
}
bytes.push(b'%');
i += 1;
} else {
bytes.push(raw[i]);
i += 1;
}
}
String::from_utf8_lossy(&bytes).into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn corrupt_store_json_fails_closed_and_refuses_overwrite() {
let dir = TempDir::new().unwrap();
let path = store_path(dir.path());
fs::create_dir_all(path.parent().unwrap()).unwrap();
let corrupt_payload = b"{not valid json!!!";
fs::write(&path, corrupt_payload).unwrap();
let loaded = ForgeStore::load_shared(dir.path());
assert!(loaded.corrupt, "corrupt JSON must mark ForgeStore::corrupt");
let tx = ForgeStore::lock_mut(dir.path());
assert!(tx.corrupt);
let commit_err = tx.commit().unwrap_err();
assert_eq!(commit_err.kind(), std::io::ErrorKind::InvalidData);
let update_err = ForgeStore::update(dir.path(), |s| {
s.create_issue("nope".into(), "".into(), "alice".into(), vec![], None);
})
.unwrap_err();
assert_eq!(update_err.kind(), std::io::ErrorKind::InvalidData);
assert_eq!(fs::read(&path).unwrap(), corrupt_payload);
}
#[test]
fn store_tx_holds_and_releases_sibling_lockfile_and_reclaims_stale() {
let dir = TempDir::new().unwrap();
let lock_path = store_lock_path(dir.path());
{
let mut tx = ForgeStore::lock_mut(dir.path());
assert!(
lock_path.is_file(),
"store.json.lock must exist while ForgeStoreTx is held"
);
tx.create_issue("locked".into(), "".into(), "alice".into(), vec![], None);
tx.commit().unwrap();
}
assert!(
!lock_path.exists(),
"store.json.lock must be removed after ForgeStoreTx commit"
);
fs::create_dir_all(lock_path.parent().unwrap()).unwrap();
fs::write(&lock_path, b"pid=999999\n").unwrap();
std::thread::sleep(std::time::Duration::from_millis(15));
let fl = acquire_store_file_lock_with(
&lock_path,
std::time::Duration::from_millis(5),
std::time::Duration::from_secs(2),
)
.expect("stale lockfile must be reclaimed");
assert!(lock_path.is_file());
drop(fl);
assert!(!lock_path.exists());
}
#[test]
fn store_tx_startup_gc_sweeps_dead_pid_lockfile_and_preserves_live_pid() {
let dir = TempDir::new().unwrap();
let forge_dir = dir.path().join("arks-forge");
fs::create_dir_all(&forge_dir).unwrap();
let lock_path = forge_dir.join("store.json.lock");
fs::write(&lock_path, format!("pid={}\n", 424_242)).unwrap();
assert_eq!(
sweep_stale_temps_in_dir_with(&forge_dir, |pid, _| pid == 424_242),
0
);
assert!(lock_path.is_file());
fs::write(&lock_path, b"pid=999999999\n").unwrap();
assert_eq!(
sweep_stale_temps_in_dir_with(&forge_dir, |pid, _| pid == 424_242),
1
);
assert!(!lock_path.exists());
#[cfg(target_os = "linux")]
{
fs::write(&lock_path, b"pid=999999999\n").unwrap();
let fl = acquire_store_file_lock_with(
&lock_path,
std::time::Duration::from_secs(300),
std::time::Duration::from_secs(2),
)
.expect("dead-PID store.json.lock must be reclaimed immediately");
drop(fl);
assert!(!lock_path.exists());
}
}
#[test]
fn schema_version_migrates_v0_and_fails_closed_on_future_version() {
let dir = tempfile::TempDir::new().unwrap();
let forge_dir = dir.path().join("arks-forge");
fs::create_dir_all(&forge_dir).unwrap();
let path = forge_dir.join("store.json");
fs::write(&path, r#"{"next_id":0,"issues":[]}"#).unwrap();
let loaded = ForgeStore::load_shared(dir.path());
assert!(!loaded.corrupt);
assert_eq!(loaded.schema_version, CURRENT_SCHEMA_VERSION);
assert_eq!(loaded.next_id, 1);
let bak = forge_dir.join("store.json.pre-migrate-v0.bak");
assert!(bak.is_file(), "pre-migration backup must be written");
ForgeStore::update(dir.path(), |s| {
s.create_issue(
"Migrated".into(),
"ok".into(),
"alice".into(),
Vec::new(),
None,
);
})
.unwrap();
let saved_raw = fs::read_to_string(&path).unwrap();
assert!(saved_raw.contains(&format!("\"schema_version\": {CURRENT_SCHEMA_VERSION}")));
let future_json = format!(
r#"{{"schema_version":{},"next_id":1,"issues":[]}}"#,
CURRENT_SCHEMA_VERSION + 99
);
let dir2 = tempfile::TempDir::new().unwrap();
let forge_dir2 = dir2.path().join("arks-forge");
fs::create_dir_all(&forge_dir2).unwrap();
let path2 = forge_dir2.join("store.json");
fs::write(&path2, &future_json).unwrap();
let future_loaded = ForgeStore::load_shared(dir2.path());
assert!(
future_loaded.corrupt,
"future schema_version must fail closed"
);
let err = ForgeStore::update(dir2.path(), |s| {
s.create_issue(
"Should fail".into(),
"".into(),
"bob".into(),
Vec::new(),
None,
);
})
.unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert_eq!(
fs::read_to_string(&path2).unwrap(),
future_json,
"fail-closed must not overwrite future store.json"
);
}
}