From 68aaef69902544f45b403e13266a8b61227fd22a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 13:09:32 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=97=83=EF=B8=8F=20fix:=20audit=20rows=20o?= =?UTF-8?q?lder=20than=20365=20days=20are=20swept=20in=20batches?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/in-core/src/store/audit.rs | 70 +++++++++++++++++++++++++++++++ crates/in-web/src/sweeper.rs | 14 +++++++ docs/architecture.md | 6 ++- docs/conventions.md | 2 +- 4 files changed, 89 insertions(+), 3 deletions(-) diff --git a/crates/in-core/src/store/audit.rs b/crates/in-core/src/store/audit.rs index e3d0f36..a4f75ea 100644 --- a/crates/in-core/src/store/audit.rs +++ b/crates/in-core/src/store/audit.rs @@ -13,6 +13,13 @@ use crate::time::now_stamp; /// Column list for [`map_audit`]. Keep the two in step. const AUDIT_COLS: &str = "id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data"; +/// Days an audit entry is kept. The sweeper removes older rows; nothing else deletes them. +pub const AUDIT_RETENTION_DAYS: u64 = 365; + +/// Rows one purge statement removes. Each batch is its own statement, so the writer lock is released between +/// batches and other writes are not held up by a large purge. +pub const AUDIT_PURGE_BATCH: u64 = 1000; + /// One entry to append. #[derive(Debug, Clone, PartialEq, Eq)] pub struct NewAudit { @@ -149,6 +156,29 @@ impl Store { .await } + /// Removes entries stamped before `cutoff`, oldest first, in batches of [`AUDIT_PURGE_BATCH`]. The writer + /// lock is taken per batch. Returns the number of rows removed. + pub async fn purge_audit_before(&self, cutoff: &str) -> Result { + let batch = i64::try_from(AUDIT_PURGE_BATCH).unwrap_or(i64::MAX); + let mut total = 0; + loop { + let removed = { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM audit_log WHERE id IN \ + (SELECT id FROM audit_log WHERE at < ?1 ORDER BY at LIMIT ?2)", + (cutoff.to_string(), batch), + ) + .await + .map_err(db_err)? + }; + total += removed; + if removed < AUDIT_PURGE_BATCH { + return Ok(total); + } + } + } + /// The id of the newest entry, or `None` for an empty log. The live page uses it as its fingerprint. pub async fn latest_audit_id(&self) -> Result> { let conn = self.read_conn().await; @@ -162,3 +192,43 @@ impl Store { Ok(rows.into_iter().next()) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::test_support::store_with_member; + use crate::time::{stamp_after, stamp_before}; + use std::time::Duration; + + #[tokio::test] + async fn purge_removes_only_rows_before_the_cutoff() { + let (_dir, store) = store_with_member("ann").await; + store + .insert_audit(NewAudit { + actor_id: Some("ann".into()), + actor_kind: "member", + action: "quota.set".into(), + target_kind: "member".into(), + target_id: Some("ann".into()), + ip: None, + data: "{}".into(), + }) + .await + .unwrap(); + assert_eq!( + store + .purge_audit_before(&stamp_before(Duration::from_secs(3600))) + .await + .unwrap(), + 0 + ); + assert_eq!( + store + .purge_audit_before(&stamp_after(Duration::from_secs(3600))) + .await + .unwrap(), + 1 + ); + assert!(store.latest_audit_id().await.unwrap().is_none()); + } +} diff --git a/crates/in-web/src/sweeper.rs b/crates/in-web/src/sweeper.rs index 2ae9849..3a8db48 100644 --- a/crates/in-web/src/sweeper.rs +++ b/crates/in-web/src/sweeper.rs @@ -7,6 +7,7 @@ //! This is what retries a removal that failed earlier: the expiry step has already deleted the row; //! the directory is the only record left; //! - trash older than `purge_after_days` (a setting, 30 by default), with its bytes; +//! - audit rows older than `AUDIT_RETENTION_DAYS` (365), in batches of `AUDIT_PURGE_BATCH`; //! - blobs under `files/`, `thumbs/` and `objects/` that no row names and that are at least 24 hours old; //! - leftover files in `data_dir/tmp` at least 24 hours old; //! - once a day, the quota check: every member's `used_bytes` is recomputed from their files, and any @@ -22,6 +23,7 @@ use std::time::{Duration, SystemTime}; use in_core::error::Result; use in_core::staging::{TMP_DIR, UPLOADS_DIR, remove_upload_dir, upload_dir}; +use in_core::store::audit::AUDIT_RETENTION_DAYS; use in_core::time::{now_stamp, stamp_before}; use tokio::sync::watch; @@ -78,6 +80,7 @@ pub async fn sweep(state: &AppState) -> Result<()> { sweep_upload_dirs(state, SystemTime::now()).await, ); log_step("trash", purge_trash(state).await); + log_step("audit", purge_audit(state).await); log_step("blobs", sweep_blobs(state, SystemTime::now()).await); log_step( "tmp", @@ -124,6 +127,17 @@ async fn purge_trash(state: &AppState) -> Result { Ok(count) } +/// Removes audit rows older than [`AUDIT_RETENTION_DAYS`]. The store deletes them in batches, so a large backlog +/// is cleared over several statements and the writer lock is free between them. +async fn purge_audit(state: &AppState) -> Result { + let cutoff = stamp_before(Duration::from_secs(AUDIT_RETENTION_DAYS * 24 * 60 * 60)); + let removed = state.store.purge_audit_before(&cutoff).await?; + if removed > 0 { + tracing::info!(audit_rows = removed, "sweeper: audit rows purged"); + } + Ok(removed) +} + /// True when `modified` is at least [`ORPHAN_GRACE`] before `now`. A timestamp in the future counts as young. fn is_old(modified: SystemTime, now: SystemTime) -> bool { now.duration_since(modified) diff --git a/docs/architecture.md b/docs/architecture.md index dc303cc..79a24f4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -110,7 +110,9 @@ again), `target_kind`, `target_id`, `owner`, `can_download`, `password_hash` NUL **objects**: `service` FK services, `external_id`, `size`, `sha256`, `content_type`, `name` NULL, `blob_key` (`objects//`, shared by objects of one service with equal bytes; removed when the last one goes), `created_at`, `updated_at`; PK (service, external_id). -**audit_log**, **settings**: per conventions. +**audit_log**, **settings**: per conventions. The audit log is kept for `AUDIT_RETENTION_DAYS` (365 days, +`in-core/src/store/audit.rs`); the sweeper deletes older rows in batches of `AUDIT_PURGE_BATCH` (1000), each +batch its own statement, so no purge holds the writer lock for long. Quota rule (one place, `quota.rs`): `used_bytes` = sum of `size` of the person's files, live and trashed, kept up to date inside the same transaction as every insert, replace, purge; headroom for a new upload = quota − @@ -222,7 +224,7 @@ and has no sessions. 10 s limit per decode, marks ready/failed. A decode that outlives its limit keeps its slot until it returns. - **sweeper** (hourly): expired sessions, expired uploads, staging directories that no open upload names (24 h old, which retries failed removals), seen JTIs, trash past - `purge_after_days`, unreferenced blobs older than 24 h, quota drift check (nightly). + `purge_after_days`, audit rows past 365 days, unreferenced blobs older than 24 h, quota drift check (nightly). - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from `in.key`, checked before a restore parses anything), keep N, dead-man pings. diff --git a/docs/conventions.md b/docs/conventions.md index eed1b03..f5869f3 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -132,7 +132,7 @@ unit-tested as a truth table. Append-only `audit_log` (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written after the change commits; a failed audit write is logged and never fails the request. Never store secrets in -`data`. Admin page with filters and keyset paging. Purge only through `admin audit-purge --older-than-days N`. +`data`. Admin page with filters and keyset paging. Rows older than the retention window are removed by the sweeper; nothing else deletes them. ## 11. i18n