1use std::path::Path;
12
13use doublets::data::LinkReference;
14
15use crate::error::LinkError;
16use crate::storage::LinksStorage;
17
18use super::journal_validation::RecoveryJournal;
19use super::log::TransitionLogStore;
20use super::types::{
21 GenericTransition, LogRetentionPolicy, TransitionKind, APPLIED_MARKER_PREFIX,
22 ROLLBACK_MARKER_PREFIX,
23};
24use super::{new_transaction_id, now_unix_ms, GenericTransactionsDecorator, JournalRecord};
25
26impl<T, S, L> GenericTransactionsDecorator<T, S, L>
27where
28 T: LinkReference,
29 S: LinksStorage<T>,
30 L: TransitionLogStore,
31{
32 pub fn apply_transition(&mut self, transition: &GenericTransition<T>) -> Result<(), LinkError> {
36 self.ensure_replay_allowed()?;
37 self.try_apply_transition(transition)
38 }
39
40 pub fn revert_transition(
43 &mut self,
44 transition: &GenericTransition<T>,
45 ) -> Result<(), LinkError> {
46 self.ensure_replay_allowed()?;
47 self.try_revert_transition(transition)
48 }
49
50 pub fn apply_record(&mut self, record: &JournalRecord<T>) -> Result<(), LinkError> {
52 self.ensure_replay_allowed()?;
53 self.validate_record_backend(record)?;
54 self.try_apply_record(record, false)
55 }
56
57 pub fn revert_record(&mut self, record: &JournalRecord<T>) -> Result<(), LinkError> {
59 self.ensure_replay_allowed()?;
60 self.validate_record_backend(record)?;
61 self.try_revert_record(record)
62 }
63
64 fn validate_record_backend(&mut self, record: &JournalRecord<T>) -> Result<(), LinkError> {
65 record.validate()?;
66 if !record.names.is_empty() && self.inner.capture_names()?.is_none() {
67 return Err(LinkError::StorageError(
68 "journal requires a named storage adapter".into(),
69 ));
70 }
71 Ok(())
72 }
73
74 pub(super) fn try_apply_record(
75 &mut self,
76 record: &JournalRecord<T>,
77 record_applied: bool,
78 ) -> Result<(), LinkError> {
79 if !record.name_only {
80 self.try_apply_transition(&record.transition)?;
81 }
82 self.replay_names(record, false)?;
83 if record_applied {
84 self.inner.flush()?;
85 self.mark_applied(record)?;
86 self.log_store.flush_log()?;
87 }
88 Ok(())
89 }
90
91 pub(super) fn try_revert_record(&mut self, record: &JournalRecord<T>) -> Result<(), LinkError> {
92 if !record.name_only {
93 self.try_revert_transition(&record.transition)?;
94 }
95 self.replay_names(record, true)
96 }
97
98 fn ensure_replay_allowed(&self) -> Result<(), LinkError> {
99 if self.has_open_transaction() {
100 return Err(LinkError::Transaction(
101 "Complete the current transaction or its cleanup before unlogged replay.".into(),
102 ));
103 }
104 Ok(())
105 }
106
107 pub(super) fn try_apply_transition(
108 &mut self,
109 transition: &GenericTransition<T>,
110 ) -> Result<(), LinkError> {
111 let zero = T::from_byte(0);
112 let result: Result<(), LinkError> = match transition.kind {
113 TransitionKind::Create => {
114 if transition.after.index != zero {
115 self.inner
116 .ensure_link_created(transition.after.index)
117 .and_then(|_| {
118 self.inner
119 .restore_link(
120 transition.after.index,
121 transition.after.source,
122 transition.after.target,
123 )
124 .map(|_| ())
125 })
126 } else {
127 Ok(())
128 }
129 }
130 TransitionKind::Update => {
131 if transition.after.index != zero && self.inner.link_exists(transition.after.index)
132 {
133 self.inner
134 .restore_link(
135 transition.after.index,
136 transition.after.source,
137 transition.after.target,
138 )
139 .map(|_| ())
140 } else {
141 Ok(())
142 }
143 }
144 TransitionKind::Delete => {
145 if transition.before.index != zero
146 && self.inner.link_exists(transition.before.index)
147 {
148 self.inner.delete_link(transition.before.index).map(|_| ())
149 } else {
150 Ok(())
151 }
152 }
153 };
154 result?;
155 Ok(())
156 }
157
158 pub(super) fn try_revert_transition(
159 &mut self,
160 transition: &GenericTransition<T>,
161 ) -> Result<(), LinkError> {
162 let zero = T::from_byte(0);
163 let result: Result<(), LinkError> = match transition.kind {
164 TransitionKind::Create => {
165 if transition.after.index != zero && self.inner.link_exists(transition.after.index)
166 {
167 self.inner.delete_link(transition.after.index).map(|_| ())
168 } else {
169 Ok(())
170 }
171 }
172 TransitionKind::Update => {
173 if transition.before.index != zero
174 && self.inner.link_exists(transition.before.index)
175 {
176 self.inner
177 .restore_link(
178 transition.before.index,
179 transition.before.source,
180 transition.before.target,
181 )
182 .map(|_| ())
183 } else {
184 Ok(())
185 }
186 }
187 TransitionKind::Delete => {
188 if transition.before.index != zero {
189 self.inner
193 .ensure_link_created(transition.before.index)
194 .and_then(|_| {
195 self.inner
196 .restore_link(
197 transition.before.index,
198 transition.before.source,
199 transition.before.target,
200 )
201 .map(|_| ())
202 })
203 } else {
204 Ok(())
205 }
206 }
207 };
208 result
209 }
210
211 pub(super) fn mark_applied(
212 &mut self,
213 transition: &GenericTransition<T>,
214 ) -> Result<(), LinkError> {
215 if !self.applied.contains(&transition.sequence) {
216 self.write_marker(&format!("{APPLIED_MARKER_PREFIX}{}", transition.sequence))?;
217 self.applied.insert(transition.sequence);
218 if transition.sequence > self.applied_sequence {
219 self.applied_sequence = transition.sequence;
220 }
221 }
222 Ok(())
223 }
224
225 pub(super) fn ensure_recovery_complete(&self) -> Result<(), LinkError> {
228 if self.recovery_pending {
229 return Err(LinkError::Transaction(
230 "Retry recovery before further transaction writes or replay.".into(),
231 ));
232 }
233 Ok(())
234 }
235
236 pub fn recover(&mut self) -> Result<(), LinkError> {
241 if self.current.is_some() || self.version_replay {
242 return Err(LinkError::Transaction(
243 "Cannot recover while a transaction is open.".into(),
244 ));
245 }
246 self.recovery_pending = true;
247 match self.recover_journal() {
248 Ok(()) => {
249 self.recovery_pending = false;
250 Ok(())
251 }
252 Err(error) => {
253 if self.trace {
254 crate::diagnostics::stderr!(
255 "[Transactions] Recovery failed; admission retained: {error}."
256 );
257 }
258 Err(error)
259 }
260 }
261 }
262
263 fn recover_journal(&mut self) -> Result<(), LinkError> {
264 let journal = RecoveryJournal::<T>::parse(self.log_store.read_log_entries()?)?;
265 if let Some(record) = journal.log.iter().find(|record| !record.names.is_empty()) {
268 self.validate_record_backend(record)?;
269 }
270 if journal.images.iter().any(|image| image.names.is_some())
271 && self.inner.capture_names()?.is_none()
272 {
273 return Err(LinkError::StorageError(
274 "undo image requires a named storage adapter".into(),
275 ));
276 }
277 if self.reload_pending {
278 self.inner.reload()?;
279 self.reload_pending = false;
280 }
281 self.log = journal.log;
282 self.committed = journal.committed;
283 self.rolled_back = journal.rolled_back;
284 self.applied = journal.applied;
285 self.sequence_counter = journal.sequence;
286 self.applied_sequence = journal.applied_sequence;
287 self.journal_entries = journal.entry_count;
288 self.last_decision = journal.last_decision;
289
290 let log_snapshot: Vec<JournalRecord<T>> = self.log.clone();
293 let mut replay_from = log_snapshot
294 .iter()
295 .position(|transition| {
296 self.committed.contains(&transition.transaction_id)
297 && !self.applied.contains(&transition.sequence)
298 })
299 .unwrap_or(log_snapshot.len());
300 let pending_images = journal
301 .images
302 .into_iter()
303 .filter(|image| {
304 !self.committed.contains(&image.owner) && !self.rolled_back.contains(&image.owner)
305 })
306 .collect::<Vec<_>>();
307 if let Some(base) = pending_images.iter().map(|image| image.base).min() {
308 replay_from =
309 replay_from.min(log_snapshot.partition_point(|record| record.sequence <= base));
310 }
311 let result = (|| -> Result<Vec<u128>, LinkError> {
312 let mut pending_tx_ids = Vec::new();
313 let mut pending_seen = std::collections::HashSet::new();
314 let imaged = pending_images
315 .iter()
316 .map(|image| image.owner)
317 .collect::<std::collections::HashSet<_>>();
318 if !pending_images.is_empty() {
319 let mut images = pending_images.iter().collect::<Vec<_>>();
323 images.sort_by_key(|image| image.base);
324 let mut records = log_snapshot
325 .iter()
326 .rev()
327 .filter(|record| {
328 !self.committed.contains(&record.transaction_id)
329 && !self.rolled_back.contains(&record.transaction_id)
330 && !imaged.contains(&record.transaction_id)
331 })
332 .collect::<Vec<_>>()
333 .into_iter()
334 .peekable();
335 for image in images.into_iter().rev() {
336 while records
337 .peek()
338 .is_some_and(|record| record.sequence > image.base)
339 {
340 let record = records.next().expect("peeked record");
341 self.try_revert_record(record)?;
342 if pending_seen.insert(record.transaction_id) {
343 pending_tx_ids.push(record.transaction_id);
344 }
345 }
346 self.restore_image(image)?;
347 if pending_seen.insert(image.owner) {
348 pending_tx_ids.push(image.owner);
349 }
350 }
351 for record in records {
352 self.try_revert_record(record)?;
353 if pending_seen.insert(record.transaction_id) {
354 pending_tx_ids.push(record.transaction_id);
355 }
356 }
357 }
358 for transition in &log_snapshot[replay_from..] {
359 if !self.committed.contains(&transition.transaction_id) {
360 continue;
361 }
362 self.try_apply_record(transition, false)?;
363 }
364 for transition in log_snapshot
366 .iter()
367 .rev()
368 .filter(|_| pending_images.is_empty())
369 {
370 if self.committed.contains(&transition.transaction_id) {
371 continue;
372 }
373 if self.rolled_back.contains(&transition.transaction_id) {
374 continue;
375 }
376 self.try_revert_record(transition)?;
377 if pending_seen.insert(transition.transaction_id) {
378 pending_tx_ids.push(transition.transaction_id);
379 }
380 }
381 Ok(pending_tx_ids)
382 })();
383 let pending_tx_ids = result?;
384 self.inner.flush()?;
385 for transition in &log_snapshot[replay_from..] {
388 if self.committed.contains(&transition.transaction_id) {
389 self.mark_applied(transition)?;
390 }
391 }
392 for tx_id in pending_tx_ids {
393 self.rolled_back.insert(tx_id);
394 self.write_marker(&format!("{ROLLBACK_MARKER_PREFIX}{tx_id:032x}"))?;
395 }
396 self.log_store.flush_log()?;
397 Ok(())
398 }
399
400 pub(super) fn enforce_retention(&mut self) -> Result<(), LinkError> {
401 match self.retention_policy.clone() {
402 LogRetentionPolicy::Infinite => Ok(()),
403 LogRetentionPolicy::Sized { max_transitions } => self.enforce_sized(max_transitions),
404 LogRetentionPolicy::Chunked {
405 chunk_size,
406 archive_directory,
407 } => self.enforce_chunked(chunk_size, &archive_directory),
408 }?;
409 self.compact_journal_if_needed()
410 }
411
412 fn enforce_sized(&mut self, max_transitions: u64) -> Result<(), LinkError> {
413 if max_transitions == 0 {
414 return Ok(());
415 }
416 while self.log.len() as u64 > max_transitions {
417 let head = self.log[0].clone();
418 if !self.rolled_back.contains(&head.transaction_id)
419 && !self.applied.contains(&head.sequence)
420 {
421 if !self.committed.contains(&head.transaction_id) {
422 break; }
424 self.try_apply_record(&head, true)?;
425 if !self.applied.contains(&head.sequence) {
426 break; }
428 }
429 self.log.remove(0);
430 if self.trace {
431 crate::diagnostics::stderr!(
432 "[Transactions] Dropped completed transition seq={} per sized retention.",
433 head.sequence
434 );
435 }
436 }
437 Ok(())
438 }
439
440 fn enforce_chunked(
441 &mut self,
442 chunk_size: u64,
443 archive_directory: &Path,
444 ) -> Result<(), LinkError> {
445 if chunk_size == 0 {
446 return Ok(());
447 }
448 if (self.log.len() as u64) < chunk_size {
449 return Ok(());
450 }
451 let chunk: Vec<JournalRecord<T>> =
452 self.log.iter().take(chunk_size as usize).cloned().collect();
453 let archived: Vec<_> = chunk
456 .iter()
457 .filter(|transition| !self.rolled_back.contains(&transition.transaction_id))
458 .cloned()
459 .collect();
460 for transition in &archived {
461 if !self.applied.contains(&transition.sequence) {
462 if !self.committed.contains(&transition.transaction_id) {
463 return Ok(()); }
465 self.try_apply_record(transition, true)?;
466 if !self.applied.contains(&transition.sequence) {
467 return Ok(()); }
469 }
470 }
471 if archived.is_empty() {
472 self.log.drain(0..chunk.len());
473 return Ok(());
474 }
475 std::fs::create_dir_all(archive_directory).map_err(|error| {
476 LinkError::StorageError(format!(
477 "failed to create archive dir {}: {error}",
478 archive_directory.display()
479 ))
480 })?;
481 let timestamp = now_unix_ms();
482 let (mut file, path) = loop {
486 let file_name = format!(
487 "transitions-chunk-{timestamp}-{:032x}.log",
488 new_transaction_id()
489 );
490 let path = archive_directory.join(file_name);
491 match std::fs::OpenOptions::new()
492 .write(true)
493 .create_new(true)
494 .open(&path)
495 {
496 Ok(file) => break (file, path),
497 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
498 if self.trace {
499 crate::diagnostics::stderr!(
500 "[Transactions] Archive entry already owned: {}.",
501 path.display()
502 );
503 }
504 }
505 Err(error) => {
506 return Err(LinkError::StorageError(format!(
507 "failed to create archive file {}: {error}",
508 path.display()
509 )))
510 }
511 }
512 };
513 use std::io::Write;
514 for transition in &archived {
515 writeln!(file, "{}", transition.serialize())?;
516 }
517 file.flush()?;
518 file.sync_all()?;
521 #[cfg(unix)]
522 std::fs::File::open(archive_directory)?.sync_all()?;
523 if self.trace {
524 crate::diagnostics::stderr!(
525 "[Transactions] Archived {} transitions to {}.",
526 archived.len(),
527 path.display()
528 );
529 }
530 self.log.drain(0..chunk.len());
531 Ok(())
532 }
533}