Audit rows older than 365 days are swept in batches
Browse files at this commit68aaef69902544f45b403e13266a8b61227fd22aParent: 5e60f59- fix
- audit rows older than 365 days are swept in batches
4 changed files +89 -3
- crates/in-core/src/store/audit.rs +70 -0
- crates/in-web/src/sweeper.rs +14 -0
- docs/architecture.md +4 -2
- docs/conventions.md +1 -1
crates/in-core/src/store/audit.rsmodified+70 -0
| @@ -13,6 +13,13 @@ use crate::time::now_stamp; | |||
| 13 | /// Column list for [`map_audit`]. Keep the two in step. | 13 | /// Column list for [`map_audit`]. Keep the two in step. |
| 14 | const AUDIT_COLS: &str = "id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data"; | 14 | const AUDIT_COLS: &str = "id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data"; |
| 15 | 15 | ||
| 16 | +/// Days an audit entry is kept. The sweeper removes older rows; nothing else deletes them. | ||
| 17 | +pub const AUDIT_RETENTION_DAYS: u64 = 365; | ||
| 18 | + | ||
| 19 | +/// Rows one purge statement removes. Each batch is its own statement, so the writer lock is released between | ||
| 20 | +/// batches and other writes are not held up by a large purge. | ||
| 21 | +pub const AUDIT_PURGE_BATCH: u64 = 1000; | ||
| 22 | + | ||
| 16 | /// One entry to append. | 23 | /// One entry to append. |
| 17 | #[derive(Debug, Clone, PartialEq, Eq)] | 24 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 18 | pub struct NewAudit { | 25 | pub struct NewAudit { |
| @@ -149,6 +156,29 @@ impl Store { | |||
| 149 | .await | 156 | .await |
| 150 | } | 157 | } |
| 151 | 158 | ||
| 159 | + /// Removes entries stamped before `cutoff`, oldest first, in batches of [`AUDIT_PURGE_BATCH`]. The writer | ||
| 160 | + /// lock is taken per batch. Returns the number of rows removed. | ||
| 161 | + pub async fn purge_audit_before(&self, cutoff: &str) -> Result<u64> { | ||
| 162 | + let batch = i64::try_from(AUDIT_PURGE_BATCH).unwrap_or(i64::MAX); | ||
| 163 | + let mut total = 0; | ||
| 164 | + loop { | ||
| 165 | + let removed = { | ||
| 166 | + let conn = self.inner.conn.lock().await; | ||
| 167 | + conn.execute( | ||
| 168 | + "DELETE FROM audit_log WHERE id IN \ | ||
| 169 | + (SELECT id FROM audit_log WHERE at < ?1 ORDER BY at LIMIT ?2)", | ||
| 170 | + (cutoff.to_string(), batch), | ||
| 171 | + ) | ||
| 172 | + .await | ||
| 173 | + .map_err(db_err)? | ||
| 174 | + }; | ||
| 175 | + total += removed; | ||
| 176 | + if removed < AUDIT_PURGE_BATCH { | ||
| 177 | + return Ok(total); | ||
| 178 | + } | ||
| 179 | + } | ||
| 180 | + } | ||
| 181 | + | ||
| 152 | /// The id of the newest entry, or `None` for an empty log. The live page uses it as its fingerprint. | 182 | /// The id of the newest entry, or `None` for an empty log. The live page uses it as its fingerprint. |
| 153 | pub async fn latest_audit_id(&self) -> Result<Option<String>> { | 183 | pub async fn latest_audit_id(&self) -> Result<Option<String>> { |
| 154 | let conn = self.read_conn().await; | 184 | let conn = self.read_conn().await; |
| @@ -162,3 +192,43 @@ impl Store { | |||
| 162 | Ok(rows.into_iter().next()) | 192 | Ok(rows.into_iter().next()) |
| 163 | } | 193 | } |
| 164 | } | 194 | } |
| 195 | + | ||
| 196 | +#[cfg(test)] | ||
| 197 | +mod tests { | ||
| 198 | + use super::*; | ||
| 199 | + use crate::store::test_support::store_with_member; | ||
| 200 | + use crate::time::{stamp_after, stamp_before}; | ||
| 201 | + use std::time::Duration; | ||
| 202 | + | ||
| 203 | + #[tokio::test] | ||
| 204 | + async fn purge_removes_only_rows_before_the_cutoff() { | ||
| 205 | + let (_dir, store) = store_with_member("ann").await; | ||
| 206 | + store | ||
| 207 | + .insert_audit(NewAudit { | ||
| 208 | + actor_id: Some("ann".into()), | ||
| 209 | + actor_kind: "member", | ||
| 210 | + action: "quota.set".into(), | ||
| 211 | + target_kind: "member".into(), | ||
| 212 | + target_id: Some("ann".into()), | ||
| 213 | + ip: None, | ||
| 214 | + data: "{}".into(), | ||
| 215 | + }) | ||
| 216 | + .await | ||
| 217 | + .unwrap(); | ||
| 218 | + assert_eq!( | ||
| 219 | + store | ||
| 220 | + .purge_audit_before(&stamp_before(Duration::from_secs(3600))) | ||
| 221 | + .await | ||
| 222 | + .unwrap(), | ||
| 223 | + 0 | ||
| 224 | + ); | ||
| 225 | + assert_eq!( | ||
| 226 | + store | ||
| 227 | + .purge_audit_before(&stamp_after(Duration::from_secs(3600))) | ||
| 228 | + .await | ||
| 229 | + .unwrap(), | ||
| 230 | + 1 | ||
| 231 | + ); | ||
| 232 | + assert!(store.latest_audit_id().await.unwrap().is_none()); | ||
| 233 | + } | ||
| 234 | +} | ||
crates/in-web/src/sweeper.rsmodified+14 -0
| @@ -7,6 +7,7 @@ | |||
| 7 | //! This is what retries a removal that failed earlier: the expiry step has already deleted the row; | 7 | //! This is what retries a removal that failed earlier: the expiry step has already deleted the row; |
| 8 | //! the directory is the only record left; | 8 | //! the directory is the only record left; |
| 9 | //! - trash older than `purge_after_days` (a setting, 30 by default), with its bytes; | 9 | //! - trash older than `purge_after_days` (a setting, 30 by default), with its bytes; |
| 10 | +//! - audit rows older than `AUDIT_RETENTION_DAYS` (365), in batches of `AUDIT_PURGE_BATCH`; | ||
| 10 | //! - blobs under `files/`, `thumbs/` and `objects/` that no row names and that are at least 24 hours old; | 11 | //! - blobs under `files/`, `thumbs/` and `objects/` that no row names and that are at least 24 hours old; |
| 11 | //! - leftover files in `data_dir/tmp` at least 24 hours old; | 12 | //! - leftover files in `data_dir/tmp` at least 24 hours old; |
| 12 | //! - once a day, the quota check: every member's `used_bytes` is recomputed from their files, and any | 13 | //! - 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}; | |||
| 22 | 23 | ||
| 23 | use in_core::error::Result; | 24 | use in_core::error::Result; |
| 24 | use in_core::staging::{TMP_DIR, UPLOADS_DIR, remove_upload_dir, upload_dir}; | 25 | use in_core::staging::{TMP_DIR, UPLOADS_DIR, remove_upload_dir, upload_dir}; |
| 26 | +use in_core::store::audit::AUDIT_RETENTION_DAYS; | ||
| 25 | use in_core::time::{now_stamp, stamp_before}; | 27 | use in_core::time::{now_stamp, stamp_before}; |
| 26 | use tokio::sync::watch; | 28 | use tokio::sync::watch; |
| 27 | 29 | ||
| @@ -78,6 +80,7 @@ pub async fn sweep(state: &AppState) -> Result<()> { | |||
| 78 | sweep_upload_dirs(state, SystemTime::now()).await, | 80 | sweep_upload_dirs(state, SystemTime::now()).await, |
| 79 | ); | 81 | ); |
| 80 | log_step("trash", purge_trash(state).await); | 82 | log_step("trash", purge_trash(state).await); |
| 83 | + log_step("audit", purge_audit(state).await); | ||
| 81 | log_step("blobs", sweep_blobs(state, SystemTime::now()).await); | 84 | log_step("blobs", sweep_blobs(state, SystemTime::now()).await); |
| 82 | log_step( | 85 | log_step( |
| 83 | "tmp", | 86 | "tmp", |
| @@ -124,6 +127,17 @@ async fn purge_trash(state: &AppState) -> Result<usize> { | |||
| 124 | Ok(count) | 127 | Ok(count) |
| 125 | } | 128 | } |
| 126 | 129 | ||
| 130 | +/// Removes audit rows older than [`AUDIT_RETENTION_DAYS`]. The store deletes them in batches, so a large backlog | ||
| 131 | +/// is cleared over several statements and the writer lock is free between them. | ||
| 132 | +async fn purge_audit(state: &AppState) -> Result<u64> { | ||
| 133 | + let cutoff = stamp_before(Duration::from_secs(AUDIT_RETENTION_DAYS * 24 * 60 * 60)); | ||
| 134 | + let removed = state.store.purge_audit_before(&cutoff).await?; | ||
| 135 | + if removed > 0 { | ||
| 136 | + tracing::info!(audit_rows = removed, "sweeper: audit rows purged"); | ||
| 137 | + } | ||
| 138 | + Ok(removed) | ||
| 139 | +} | ||
| 140 | + | ||
| 127 | /// True when `modified` is at least [`ORPHAN_GRACE`] before `now`. A timestamp in the future counts as young. | 141 | /// True when `modified` is at least [`ORPHAN_GRACE`] before `now`. A timestamp in the future counts as young. |
| 128 | fn is_old(modified: SystemTime, now: SystemTime) -> bool { | 142 | fn is_old(modified: SystemTime, now: SystemTime) -> bool { |
| 129 | now.duration_since(modified) | 143 | now.duration_since(modified) |
docs/architecture.mdmodified+4 -2
| @@ -110,7 +110,9 @@ again), `target_kind`, `target_id`, `owner`, `can_download`, `password_hash` NUL | |||
| 110 | **objects**: `service` FK services, `external_id`, `size`, `sha256`, `content_type`, `name` NULL, `blob_key` | 110 | **objects**: `service` FK services, `external_id`, `size`, `sha256`, `content_type`, `name` NULL, `blob_key` |
| 111 | (`objects/<service>/<sha256 of the content>`, shared by objects of one service with equal bytes; removed when the last one goes), `created_at`, `updated_at`; PK (service, external_id). | 111 | (`objects/<service>/<sha256 of the content>`, shared by objects of one service with equal bytes; removed when the last one goes), `created_at`, `updated_at`; PK (service, external_id). |
| 112 | 112 | ||
| 113 | -**audit_log**, **settings**: per conventions. | 113 | +**audit_log**, **settings**: per conventions. The audit log is kept for `AUDIT_RETENTION_DAYS` (365 days, |
| 114 | +`in-core/src/store/audit.rs`); the sweeper deletes older rows in batches of `AUDIT_PURGE_BATCH` (1000), each | ||
| 115 | +batch its own statement, so no purge holds the writer lock for long. | ||
| 114 | 116 | ||
| 115 | Quota rule (one place, `quota.rs`): `used_bytes` = sum of `size` of the person's files, live and trashed, kept | 117 | Quota rule (one place, `quota.rs`): `used_bytes` = sum of `size` of the person's files, live and trashed, kept |
| 116 | up to date inside the same transaction as every insert, replace, purge; headroom for a new upload = quota − | 118 | 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. | |||
| 222 | 10 s limit per decode, marks ready/failed. A decode that outlives its limit keeps its slot until it returns. | 224 | 10 s limit per decode, marks ready/failed. A decode that outlives its limit keeps its slot until it returns. |
| 223 | - **sweeper** (hourly): expired sessions, expired uploads, staging directories that no open upload names (24 h old, | 225 | - **sweeper** (hourly): expired sessions, expired uploads, staging directories that no open upload names (24 h old, |
| 224 | which retries failed removals), seen JTIs, trash past | 226 | which retries failed removals), seen JTIs, trash past |
| 225 | - `purge_after_days`, unreferenced blobs older than 24 h, quota drift check (nightly). | 227 | + `purge_after_days`, audit rows past 365 days, unreferenced blobs older than 24 h, quota drift check (nightly). |
| 226 | - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from | 228 | - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from |
| 227 | `in.key`, checked before a restore parses anything), keep N, dead-man pings. | 229 | `in.key`, checked before a restore parses anything), keep N, dead-man pings. |
| 228 | 230 | ||
docs/conventions.mdmodified+1 -1
| @@ -132,7 +132,7 @@ unit-tested as a truth table. | |||
| 132 | 132 | ||
| 133 | Append-only `audit_log` (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written | 133 | Append-only `audit_log` (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written |
| 134 | after the change commits; a failed audit write is logged and never fails the request. Never store secrets in | 134 | after the change commits; a failed audit write is logged and never fails the request. Never store secrets in |
| 135 | -`data`. Admin page with filters and keyset paging. Purge only through `admin audit-purge --older-than-days N`. | 135 | +`data`. Admin page with filters and keyset paging. Rows older than the retention window are removed by the sweeper; nothing else deletes them. |
| 136 | 136 | ||
| 137 | ## 11. i18n | 137 | ## 11. i18n |
| 138 | 138 | ||