|
| 1 | +//! Dropping the payloads of statements once their retention ends. |
| 2 | +
|
| 3 | +use std::collections::HashSet; |
| 4 | +use std::time::SystemTime; |
| 5 | + |
| 6 | +use origin_platform::Platform; |
| 7 | +use origin_shared::{ObjectId, RecordId}; |
| 8 | + |
| 9 | +use super::Annotations; |
| 10 | +use crate::index::Index; |
| 11 | +use crate::policy::Retention; |
| 12 | +use crate::store::StoreError; |
| 13 | + |
| 14 | +/// What garbage collection dropped. |
| 15 | +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 16 | +pub struct Dropped { |
| 17 | + /// The payloads deleted. |
| 18 | + pub payloads: usize, |
| 19 | + /// The bytes that freed on disk. |
| 20 | + pub bytes: u64, |
| 21 | +} |
| 22 | + |
| 23 | +impl<P: Platform> Annotations<'_, P> { |
| 24 | + /// Deletes the payloads whose retention ended by `now`, counted from |
| 25 | + /// when this node stored their statement. A payload stays while any |
| 26 | + /// statement still keeps it, or a revision or a tree refers to the same |
| 27 | + /// blob, such as an empty file and an empty payload. Statements stay. |
| 28 | + /// It waits for the writers [holding objects](crate::store::Store::hold_objects), |
| 29 | + /// which landings on `policy` are too, then reads the rules from |
| 30 | + /// `retention` and the index again, so a writer never refers to a |
| 31 | + /// payload deleted under it, and a policy landed meanwhile applies. |
| 32 | + /// Without rules, it neither waits nor reads anything: a policy landed |
| 33 | + /// meanwhile could only have dropped payloads that this run keeps. |
| 34 | + /// |
| 35 | + /// # Errors |
| 36 | + /// |
| 37 | + /// Fails if `retention` does, a record cannot be read or a payload |
| 38 | + /// deleted. |
| 39 | + pub fn drop_expired_payloads<E: From<StoreError>>( |
| 40 | + &mut self, |
| 41 | + retention: impl Fn() -> Result<Retention, E>, |
| 42 | + now: SystemTime, |
| 43 | + ) -> Result<Dropped, E> { |
| 44 | + if retention()?.is_empty() { |
| 45 | + return Ok(Dropped::default()); |
| 46 | + } |
| 47 | + let _collecting = self.store.lock_for_collection()?; |
| 48 | + let retention = retention()?; |
| 49 | + if retention.is_empty() { |
| 50 | + return Ok(Dropped::default()); |
| 51 | + } |
| 52 | + self.index = Index::open(self.store)?; |
| 53 | + let mut expired = HashSet::new(); |
| 54 | + let mut live: HashSet<ObjectId> = HashSet::new(); |
| 55 | + let mut roots = Vec::new(); |
| 56 | + for &record in self.index.arrivals() { |
| 57 | + match record { |
| 58 | + RecordId::Revision(id) => { |
| 59 | + let revision = self.store.get(id)?; |
| 60 | + roots.push(revision.snapshot); |
| 61 | + live.insert(revision.description.into()); |
| 62 | + } |
| 63 | + RecordId::Acceptance(id) => roots.push(self.store.get(id)?.body().state), |
| 64 | + RecordId::Statement(id) => { |
| 65 | + let statement = self.store.get(id)?; |
| 66 | + if let RecordId::Snapshot(tree) = statement.subject { |
| 67 | + roots.push(tree); |
| 68 | + } |
| 69 | + let Some(payload) = statement.payload else { |
| 70 | + continue; |
| 71 | + }; |
| 72 | + let ended = match retention.period(&statement.kind) { |
| 73 | + Some(period) => { |
| 74 | + let stored = self.store.stored_at(id.into())?; |
| 75 | + now.duration_since(stored).is_ok_and(|age| age >= period) |
| 76 | + } |
| 77 | + None => false, |
| 78 | + }; |
| 79 | + if ended { |
| 80 | + expired.insert(payload.into()); |
| 81 | + } else { |
| 82 | + live.insert(payload.into()); |
| 83 | + } |
| 84 | + } |
| 85 | + RecordId::Snapshot(_) => {} |
| 86 | + } |
| 87 | + } |
| 88 | + if expired.is_empty() { |
| 89 | + return Ok(Dropped::default()); |
| 90 | + } |
| 91 | + self.store.reach(roots, &mut live)?; |
| 92 | + let mut doomed = Vec::new(); |
| 93 | + for &id in expired.difference(&live) { |
| 94 | + if self.store.contains(id)? { |
| 95 | + doomed.push(id); |
| 96 | + } |
| 97 | + } |
| 98 | + Ok(Dropped { |
| 99 | + payloads: doomed.len(), |
| 100 | + bytes: self.store.remove(&doomed)?, |
| 101 | + }) |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +#[cfg(test)] |
| 106 | +mod tests { |
| 107 | + use std::thread; |
| 108 | + use std::time::Duration; |
| 109 | + |
| 110 | + use origin_platform::Native; |
| 111 | + use origin_shared::{EncodedObject, Verdict}; |
| 112 | + |
| 113 | + use super::*; |
| 114 | + use crate::annotations::tests::{FILES, check, issue, revision, store}; |
| 115 | + use crate::store::Store; |
| 116 | + |
| 117 | + #[test] |
| 118 | + fn retention_drops_payloads_and_keeps_statements() { |
| 119 | + let (_dir, store) = store(); |
| 120 | + let first = revision(&store, 1, &[], &[("empty", "")]); |
| 121 | + let with_payload = |kind: &str, payload: &[u8]| { |
| 122 | + let payload = EncodedObject::blob(payload); |
| 123 | + let mut statement = check(first, kind, Verdict::Pass, "node:ci", None); |
| 124 | + statement.payload = Some(payload.id().into()); |
| 125 | + let annotations = Annotations::open(&store).unwrap(); |
| 126 | + let id = annotations |
| 127 | + .issue(&statement, Some(payload.clone())) |
| 128 | + .unwrap(); |
| 129 | + (id, payload.id()) |
| 130 | + }; |
| 131 | + let (log_statement, log) = with_payload("ci.test", b"a long log"); |
| 132 | + // The same blob as the empty file, which must stay. |
| 133 | + let (_, empty) = with_payload("ci.lint", b""); |
| 134 | + let (_, review) = with_payload("review", b"looks good"); |
| 135 | + let (_, shared) = with_payload("ci.bench", b"shared"); |
| 136 | + // Also the payload of a statement whose retention hasn't ended. |
| 137 | + let mut kept = check(first, "keep", Verdict::Pass, "node:ci", None); |
| 138 | + kept.payload = Some(shared.into()); |
| 139 | + issue(&store, &kept); |
| 140 | + |
| 141 | + let retention: Retention = toml::from_str::<crate::policy::Policy>( |
| 142 | + "[retention]\n\"ci.*\" = \"1d\"\n\"keep\" = \"1000d\"\n", |
| 143 | + ) |
| 144 | + .unwrap() |
| 145 | + .retention; |
| 146 | + let mut annotations = Annotations::open(&store).unwrap(); |
| 147 | + let now = SystemTime::now(); |
| 148 | + assert_eq!( |
| 149 | + annotations |
| 150 | + .drop_expired_payloads(|| Ok::<_, StoreError>(retention.clone()), now) |
| 151 | + .unwrap(), |
| 152 | + Dropped::default(), |
| 153 | + "not a day old yet" |
| 154 | + ); |
| 155 | + let later = now + Duration::from_hours(48); |
| 156 | + let dropped = annotations |
| 157 | + .drop_expired_payloads(|| Ok::<_, StoreError>(retention.clone()), later) |
| 158 | + .unwrap(); |
| 159 | + assert_eq!(dropped.payloads, 1); |
| 160 | + assert!(!store.contains(log).unwrap()); |
| 161 | + for stays in [empty, review, shared] { |
| 162 | + assert!(store.contains(stays).unwrap(), "{stays}"); |
| 163 | + } |
| 164 | + assert!(store.get(log_statement).is_ok(), "statements are permanent"); |
| 165 | + } |
| 166 | + |
| 167 | + #[test] |
| 168 | + fn without_rules_collection_waits_for_no_writer() { |
| 169 | + let (_dir, store) = store(); |
| 170 | + let held = store.hold_objects().unwrap(); |
| 171 | + let (done, collected) = std::sync::mpsc::channel(); |
| 172 | + thread::scope(|scope| { |
| 173 | + scope.spawn(|| { |
| 174 | + let none = || Ok::<_, StoreError>(Retention::default()); |
| 175 | + let dropped = Annotations::open(&store) |
| 176 | + .unwrap() |
| 177 | + .drop_expired_payloads(none, SystemTime::now()) |
| 178 | + .unwrap(); |
| 179 | + done.send(dropped).unwrap(); |
| 180 | + }); |
| 181 | + let finished = collected.recv_timeout(Duration::from_secs(2)); |
| 182 | + drop(held); |
| 183 | + assert_eq!(finished, Ok(Dropped::default()), "it waited for the writer"); |
| 184 | + }); |
| 185 | + } |
| 186 | + |
| 187 | + #[test] |
| 188 | + fn collection_waits_for_writers_holding_objects() { |
| 189 | + let (_dir, store) = store(); |
| 190 | + let first = revision(&store, 1, &[], FILES); |
| 191 | + let payload = EncodedObject::blob(b"a log, and a file"); |
| 192 | + let mut statement = check(first, "ci.test", Verdict::Pass, "node:ci", None); |
| 193 | + statement.payload = Some(payload.id().into()); |
| 194 | + Annotations::open(&store) |
| 195 | + .unwrap() |
| 196 | + .issue(&statement, Some(payload.clone())) |
| 197 | + .unwrap(); |
| 198 | + let retention = toml::from_str::<crate::policy::Policy>("[retention]\n\"ci.*\" = \"1s\"\n") |
| 199 | + .unwrap() |
| 200 | + .retention; |
| 201 | + |
| 202 | + // A writer finds the expired payload stored as a file it snapshots, |
| 203 | + // so it doesn't write it, then writes the revision referring to it. |
| 204 | + let held = store.hold_objects().unwrap(); |
| 205 | + assert_eq!(store.write_all(std::slice::from_ref(&payload)).unwrap(), 0); |
| 206 | + let (done, collected) = std::sync::mpsc::channel(); |
| 207 | + thread::scope(|scope| { |
| 208 | + scope.spawn(|| { |
| 209 | + let later = SystemTime::now() + Duration::from_hours(1); |
| 210 | + let dropped = Annotations::open(&store) |
| 211 | + .unwrap() |
| 212 | + .drop_expired_payloads(|| Ok::<_, StoreError>(retention.clone()), later) |
| 213 | + .unwrap(); |
| 214 | + done.send(dropped).unwrap(); |
| 215 | + }); |
| 216 | + thread::sleep(Duration::from_millis(100)); |
| 217 | + assert!(collected.try_recv().is_err(), "collection waits"); |
| 218 | + revision(&store, 2, &[], &[("log", "a log, and a file")]); |
| 219 | + drop(held); |
| 220 | + assert_eq!(collected.recv().unwrap(), Dropped::default()); |
| 221 | + }); |
| 222 | + assert!(store.contains(payload.id()).unwrap()); |
| 223 | + } |
| 224 | + |
| 225 | + #[test] |
| 226 | + fn promotions_and_collection_exclude_each_other() { |
| 227 | + let (_dir, store) = store(); |
| 228 | + let first = revision(&store, 1, &[], FILES); |
| 229 | + let payload = EncodedObject::blob(b"a log to promote"); |
| 230 | + let inputs = Some((&["src"][..], false)); |
| 231 | + let mut result = check(first, "ci.test", Verdict::Pass, "node:ci", inputs); |
| 232 | + result.payload = Some(payload.id().into()); |
| 233 | + Annotations::open(&store) |
| 234 | + .unwrap() |
| 235 | + .issue(&result, Some(payload.clone())) |
| 236 | + .unwrap(); |
| 237 | + let second = RecordId::Revision(revision(&store, 2, &[], FILES)); |
| 238 | + |
| 239 | + // A promotion refers to the payload without writing it: it waits |
| 240 | + // for a collection under way, which then reads it. |
| 241 | + let collecting = store.lock_for_collection().unwrap(); |
| 242 | + let (done, promoted) = std::sync::mpsc::channel(); |
| 243 | + thread::scope(|scope| { |
| 244 | + scope.spawn(|| { |
| 245 | + let issuer = "node:queue".parse().unwrap(); |
| 246 | + let promotions = Annotations::open(&store) |
| 247 | + .unwrap() |
| 248 | + .promote(second, &issuer) |
| 249 | + .unwrap(); |
| 250 | + done.send(promotions.len()).unwrap(); |
| 251 | + }); |
| 252 | + thread::sleep(Duration::from_millis(100)); |
| 253 | + assert!(promoted.try_recv().is_err(), "promotion waits"); |
| 254 | + drop(collecting); |
| 255 | + assert_eq!(promoted.recv().unwrap(), 1); |
| 256 | + }); |
| 257 | + assert!(store.contains(payload.id()).unwrap()); |
| 258 | + } |
| 259 | + |
| 260 | + #[test] |
| 261 | + fn writers_never_trust_a_pack_collection_rewrote() { |
| 262 | + let (dir, store) = store(); |
| 263 | + let first = revision(&store, 1, &[], FILES); |
| 264 | + let payload = EncodedObject::blob(b"expired, then needed again"); |
| 265 | + let mut statement = check(first, "ci.test", Verdict::Pass, "node:ci", None); |
| 266 | + statement.payload = Some(payload.id().into()); |
| 267 | + Annotations::open(&store) |
| 268 | + .unwrap() |
| 269 | + .issue(&statement, Some(payload.clone())) |
| 270 | + .unwrap(); |
| 271 | + store.compact().unwrap(); |
| 272 | + // Another process, which loaded the pack holding the payload. |
| 273 | + let writer = Store::new(dir.path().join(".origin"), Native::default()); |
| 274 | + assert!(writer.contains(payload.id()).unwrap()); |
| 275 | + |
| 276 | + let retention = toml::from_str::<crate::policy::Policy>("[retention]\n\"ci.*\" = \"1s\"\n") |
| 277 | + .unwrap() |
| 278 | + .retention; |
| 279 | + let later = SystemTime::now() + Duration::from_hours(1); |
| 280 | + let dropped = Annotations::open(&store) |
| 281 | + .unwrap() |
| 282 | + .drop_expired_payloads(|| Ok::<_, StoreError>(retention.clone()), later) |
| 283 | + .unwrap(); |
| 284 | + assert_eq!(dropped.payloads, 1, "its pack is rewritten without it"); |
| 285 | + let _held = writer.hold_objects().unwrap(); |
| 286 | + assert_eq!( |
| 287 | + writer.write_all(std::slice::from_ref(&payload)).unwrap(), |
| 288 | + 1, |
| 289 | + "so the writer writes it again" |
| 290 | + ); |
| 291 | + assert!(store.contains(payload.id()).unwrap()); |
| 292 | + } |
| 293 | +} |
0 commit comments