ctb_io_csc/journal/
scanner.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Sequential scanning and validation of journal records and stream frames.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use super::{
30    JournalErrorRecord, JournalErrorRecordPayload, JournalSessionRecord,
31    JournalWarningRecord, JournalWarningRecordPayload,
32    JournalWarningRecordStringPayload, session_context,
33};
34use ctb_formats_dcdata::dc;
35use ctb_formats_dcstring::{
36    DcDocumentNavigator, DcFrameHeaderInfo, DcFrameStub, DcProjectionPolicy,
37    DcSyntaxArena, SharedValueContext,
38};
39use ctb_io::file::FileEntityWithPayload;
40use std::fs::File;
41use std::time::UNIX_EPOCH;
42
43/// Whether to require a completed operation or return its committed prefix.
44#[derive(Clone, Copy, PartialEq, Eq)]
45pub enum ReadMode {
46    Complete,
47    Recover,
48}
49
50pub(crate) struct ScanResult {
51    pub session: JournalSessionRecord,
52    pub members: Vec<FileEntityWithPayload>,
53    pub errors: Vec<JournalErrorRecord>,
54    pub warnings: Vec<JournalWarningRecord>,
55    pub sequence: u64,
56    pub completed: bool,
57    pub valid_length: u64,
58    pub is_v1: bool,
59}
60
61fn retain_recovery_diagnostics(
62    arena: &DcSyntaxArena<'_>,
63    policy: &DcProjectionPolicy,
64    warnings: &mut Vec<JournalWarningRecord>,
65) {
66    if policy.is_strict() {
67        return;
68    }
69    for diagnostic in arena.diagnostics() {
70        if !diagnostic
71            .message
72            .starts_with("Deprecated Document Character")
73        {
74            warnings.push(JournalWarningRecord {
75                code: "journal-decode-diagnostic".to_owned(),
76                message: diagnostic.message.clone(),
77                timestamp_sec: 0,
78            });
79        }
80    }
81}
82
83fn warning<'source>(
84    navigator: &mut DcDocumentNavigator<'source>,
85    stub: &DcFrameStub,
86    arena: &mut DcSyntaxArena<'source>,
87    context: &SharedValueContext,
88    policy: &DcProjectionPolicy,
89) -> Result<JournalWarningRecord> {
90    arena.clear();
91    let payload = match navigator
92        .decode_frame_with_arena::<JournalWarningRecordPayload>(
93            stub,
94            arena,
95            Some(context),
96            policy,
97        ) {
98        Ok(payload) => payload,
99        Err(timestamped_error) => {
100            arena.clear();
101            let payload: JournalWarningRecordStringPayload = navigator.decode_frame_with_arena(
102                stub, arena, Some(context), policy)
103                .with_context(|| format!("Invalid journal warning (timestamped form: {timestamped_error:#})"))?;
104            JournalWarningRecordPayload {
105                message: payload.message,
106                timestamp: UNIX_EPOCH,
107            }
108        }
109    };
110    Ok(payload.to_record())
111}
112
113pub(crate) fn scan(
114    file: File,
115    mode: ReadMode,
116    policy: &DcProjectionPolicy,
117) -> Result<ScanResult> {
118    let mut navigator = DcDocumentNavigator::from_dcmm_file(file, 8)?;
119    let is_v1 = navigator.is_v1_encoding();
120    let quiet = DcProjectionPolicy::forgiving_quiet();
121    let scan_policy = if mode == ReadMode::Recover {
122        &quiet
123    } else {
124        policy
125    };
126    let mut arena = DcSyntaxArena::new();
127    let mut initial_warnings = Vec::new();
128    let first_stub = navigator
129        .next_sibling_stub(scan_policy)?
130        .context("Session header is incomplete")?;
131    let session_stub = if first_stub.head_dc
132        == dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID
133    {
134        ensure!(
135            !first_stub.is_unclosed(),
136            "System graph most_recent header is incomplete"
137        );
138        navigator.expand_frame(&first_stub, &mut arena, policy)?;
139        retain_recovery_diagnostics(&arena, policy, &mut initial_warnings);
140        arena.clear();
141        navigator
142            .next_sibling_stub(scan_policy)?
143            .context("Session header is incomplete")?
144    } else {
145        first_stub
146    };
147    ensure!(
148        session_stub.head_dc == dc::DC_BEGIN_OPERATION_SESSION
149            && !session_stub.is_unclosed(),
150        "Session header is incomplete"
151    );
152    let session: JournalSessionRecord = navigator.decode_frame_with_arena(
153        &session_stub,
154        &mut arena,
155        None,
156        policy,
157    )?;
158    if policy.is_strict() {
159        u8::try_from(session.origin_platform)
160            .context("Invalid origin platform code in session header")?;
161    }
162    let context = session_context(&session)?;
163    let mut result = ScanResult {
164        session,
165        members: Vec::new(),
166        errors: Vec::new(),
167        warnings: initial_warnings,
168        sequence: 0,
169        completed: false,
170        valid_length: session_stub.outer_span.end,
171        is_v1,
172    };
173    retain_recovery_diagnostics(&arena, policy, &mut result.warnings);
174    loop {
175        let stub = match navigator.next_sibling_stub(scan_policy) {
176            Ok(Some(stub)) => stub,
177            Ok(None) => break,
178            Err(error)
179                if mode == ReadMode::Recover
180                    && error.downcast_ref::<std::io::Error>().is_some_and(
181                        |error| {
182                            error.kind() == std::io::ErrorKind::UnexpectedEof
183                        },
184                    ) =>
185            {
186                result.completed = false;
187                break;
188            }
189            Err(error) => {
190                return Err(error).context("Invalid journal record structure");
191            }
192        };
193        if stub.is_unclosed() {
194            ensure!(
195                mode == ReadMode::Recover
196                    && stub.outer_span.end == navigator.active_span().end,
197                "Incomplete journal record"
198            );
199            result.completed = false;
200            break;
201        }
202        match stub.head_dc {
203            head if head == dc::DC_BEGIN_CHECKSUMMED_SECTION => {
204                let (sequence, digest_valid) = match stub.header_info {
205                    DcFrameHeaderInfo::ChecksummedSection {
206                        sequence_id: Some(sequence),
207                        digest_valid,
208                        ..
209                    } => (sequence, digest_valid),
210                    _ => bail!(
211                        "Missing sequence identifier in closed checksummed section"
212                    ),
213                };
214                if !digest_valid {
215                    if policy.is_strict() {
216                        bail!("Digest mismatch in journal batch {sequence}");
217                    }
218                    let message = format!(
219                        "Journal batch {sequence} was salvaged despite an invalid section digest; its integrity is not verified"
220                    );
221                    policy.handle(policy.syntax_error, &message)?;
222                    result.warnings.push(JournalWarningRecord {
223                        code: "journal-digest-mismatch".to_owned(),
224                        message,
225                        timestamp_sec: 0,
226                    });
227                }
228                navigator.enter_frame(&stub)?;
229                let identifier = navigator
230                    .next_sibling_stub(scan_policy)?
231                    .context("Missing sequence identifier")?;
232                ensure!(
233                    identifier.head_dc == dc::DC_SEQUENCE_IDENTIFIER,
234                    "Invalid sequence identifier"
235                );
236                let mut members = Vec::new();
237                while let Some(child) =
238                    navigator.next_sibling_stub(scan_policy)?
239                {
240                    ensure!(
241                        child.head_dc
242                            == ctb_formats_dcstring::DcChar::from_short(317),
243                        "Unsupported journal batch record {}",
244                        child.head_dc
245                    );
246                    arena.clear();
247                    members.push(navigator.decode_frame_with_arena::<FileEntityWithPayload>(
248                        &child, &mut arena, Some(&context), policy)
249                        .with_context(|| format!("Failed to decode FileEntity in batch {sequence}"))?);
250                    retain_recovery_diagnostics(
251                        &arena,
252                        policy,
253                        &mut result.warnings,
254                    );
255                }
256                navigator.exit_frame()?;
257                result.members.extend(members);
258                result.sequence = sequence;
259                result.completed = false;
260            }
261            head if head == dc::DC_OPERATION_COMPLETED => {
262                ensure!(
263                    stub.outer_span.len()
264                        == navigator
265                            .char_encoded_len(dc::DC_OPERATION_COMPLETED),
266                    "Invalid completion marker"
267                );
268                result.completed = true;
269            }
270            head if head == dc::DC_BEGIN_ERROR_RECORD => {
271                arena.clear();
272                let payload: JournalErrorRecordPayload = navigator
273                    .decode_frame_with_arena(
274                        &stub,
275                        &mut arena,
276                        Some(&context),
277                        policy,
278                    )
279                    .context("Invalid journal error record")?;
280                retain_recovery_diagnostics(
281                    &arena,
282                    policy,
283                    &mut result.warnings,
284                );
285                result.errors.push(payload.to_record(policy)?);
286            }
287            head if head == dc::DC_BEGIN_WARNING_RECORD => {
288                let w = warning(
289                    &mut navigator,
290                    &stub,
291                    &mut arena,
292                    &context,
293                    policy,
294                )?;
295                retain_recovery_diagnostics(
296                    &arena,
297                    policy,
298                    &mut result.warnings,
299                );
300                result.warnings.push(w);
301            }
302            head => bail!(
303                "Unsupported journal record {head} at offset {}",
304                stub.outer_span.start
305            ),
306        }
307        result.valid_length = stub.outer_span.end;
308    }
309    if result.valid_length != navigator.active_span().end {
310        result.completed = false;
311    }
312    ensure!(
313        mode == ReadMode::Recover || result.completed,
314        "Journal is incomplete (missing completion marker)"
315    );
316    Ok(result)
317}
318
319#[cfg(test)]
320#[allow(
321    clippy::panic,
322    clippy::expect_used,
323    clippy::unwrap_used,
324    clippy::unwrap_in_result,
325    clippy::panic_in_result_fn,
326    clippy::indexing_slicing,
327    clippy::arithmetic_side_effects,
328    reason = "Standard repository test boilerplate"
329)]
330mod tests {
331    use super::*;
332    use crate::journal::stream::{JournalMagic, JournalWriter};
333    use ctb_formats_dcstring::DcMstring;
334    use ctb_io::file::{FileEntity, MemoryPayloadSource};
335    use std::io::Write;
336
337    fn fixture(magic: JournalMagic) -> Result<Vec<u8>> {
338        let session = JournalSessionRecord {
339            sources: Vec::new(),
340            destination: "output".into(),
341            origin_platform: 1,
342            environment: None,
343        };
344        let mut writer = JournalWriter::new(Vec::new(), &session, magic)?;
345        let mut entity = FileEntity::from_vec(b"contents".to_vec());
346        entity.metadata.environment = None;
347        writer.write_batch(&[], |_| Ok(()))?;
348        writer.write_batch(&[entity.clone(), entity.clone()], |_| Ok(()))?;
349        let mut payload = MemoryPayloadSource::new(b"contents".to_vec())?;
350        writer.write_entity(&entity, Some(&mut payload))?;
351        writer.write_record(|mut output, context| {
352            for _ in 0..2 {
353                let mut payload =
354                    MemoryPayloadSource::new(b"contents".to_vec())?;
355                entity.encode_record_to_writer_with_payload_and_context(
356                    &mut output,
357                    &mut payload,
358                    context,
359                )?;
360            }
361            Ok(())
362        })?;
363        writer.record_warning(&JournalWarningRecord {
364            code: "capture".into(),
365            message: "test diagnostic".into(),
366            timestamp_sec: 0,
367        })?;
368        writer.finish()
369    }
370
371    fn read(bytes: &[u8], mode: ReadMode) -> Result<ScanResult> {
372        let mut file = tempfile::tempfile()?;
373        file.write_all(bytes)?;
374        scan(file, mode, &DcProjectionPolicy::strict())
375    }
376
377    #[crate::ctb_test]
378    fn either_magic_accepts_batches_optional_bodies_and_diagnostics()
379    -> Result<()> {
380        let journal = fixture(JournalMagic::JournalV5)?;
381        let archive = fixture(JournalMagic::ArchiveV2)?;
382        ensure!(journal.get(8..) == archive.get(8..));
383        for bytes in [&journal, &archive] {
384            let scanned = read(bytes, ReadMode::Complete)?;
385            ensure!(
386                scanned.members.len() == 5
387                    && scanned.warnings.len() == 1
388                    && scanned.completed
389            );
390            ensure!(
391                scanned
392                    .members
393                    .iter()
394                    .filter(|member| member.payload.is_some())
395                    .count()
396                    == 3
397            );
398        }
399        Ok(())
400    }
401
402    #[crate::ctb_test]
403    fn closed_corruption_is_not_an_incomplete_tail() -> Result<()> {
404        for magic in [JournalMagic::JournalV5, JournalMagic::ArchiveV2] {
405            let session = JournalSessionRecord {
406                sources: Vec::new(),
407                destination: "output".into(),
408                origin_platform: 1,
409                environment: None,
410            };
411            let mut entity = FileEntity::from_vec(Vec::new());
412            entity.identity.relative_path = Some("original".into());
413            let mut writer = JournalWriter::new(Vec::new(), &session, magic)?;
414            writer.write_entity(&entity, None)?;
415            let mut bytes = writer.into_output();
416            let position = bytes
417                .windows(b"original".len())
418                .position(|part| part == b"original")
419                .context("Missing fixture filename")?;
420            *bytes.get_mut(position).context("Missing corruption byte")? = b'X';
421            ensure!(
422                read(&bytes, ReadMode::Recover).is_err(),
423                "Recovery discarded a closed corrupt section"
424            );
425            let mut file = tempfile::tempfile()?;
426            file.write_all(&bytes)?;
427            let salvaged = scan(
428                file,
429                ReadMode::Recover,
430                &DcProjectionPolicy::forgiving_quiet(),
431            )?;
432            ensure!(salvaged.members.len() == 1 && !salvaged.completed);
433            ensure!(
434                salvaged
435                    .warnings
436                    .iter()
437                    .any(|warning| warning.code == "journal-digest-mismatch")
438            );
439        }
440        Ok(())
441    }
442
443    #[crate::ctb_test]
444    fn journal_sequence_and_completion_rules_apply_to_either_magic()
445    -> Result<()> {
446        for magic in [JournalMagic::JournalV5, JournalMagic::ArchiveV2] {
447            let session = JournalSessionRecord {
448                sources: Vec::new(),
449                destination: "output".into(),
450                origin_platform: 1,
451                environment: None,
452            };
453            let mut writer = JournalWriter::new(Vec::new(), &session, magic)?;
454            for sequence in [0, 2, 2, 1] {
455                crate::section::write_section(
456                    writer.output_mut(),
457                    sequence,
458                    |output| {
459                        let mut record = DcMstring::new();
460                        ctb_formats_dcstring::DcMixedEncode::encode_dc_mixed(
461                            &FileEntity::from_vec(Vec::new()),
462                            &mut record,
463                        )?;
464                        output.write_all(record.payload_bytes())?;
465                        Ok(())
466                    },
467                )?;
468            }
469            let mut bytes = writer.finish()?;
470            let mut warning = DcMstring::new();
471            ctb_formats_dcstring::DcMixedEncode::encode_dc_mixed(
472                &JournalWarningRecordPayload::from_record(
473                    &JournalWarningRecord {
474                        code: "retained".into(),
475                        message: "after completion".into(),
476                        timestamp_sec: 0,
477                    },
478                ),
479                &mut warning,
480            )?;
481            bytes.extend_from_slice(warning.payload_bytes());
482            let read = read(&bytes, ReadMode::Complete)?;
483            ensure!(
484                read.completed
485                    && read.sequence == 1
486                    && read.members.len() == 4
487                    && read.warnings.len() == 1
488            );
489        }
490        Ok(())
491    }
492
493    #[crate::ctb_test]
494    fn recovery_and_completion_policy_are_independent_of_magic() -> Result<()> {
495        for magic in [JournalMagic::JournalV5, JournalMagic::ArchiveV2] {
496            let bytes = fixture(magic)?;
497            let mut file = tempfile::tempfile()?;
498            file.write_all(&bytes)?;
499            for length in (8..bytes.len()).rev() {
500                file.set_len(u64::try_from(length)?)?;
501                ensure!(
502                    scan(
503                        file.try_clone()?,
504                        ReadMode::Complete,
505                        &DcProjectionPolicy::strict(),
506                    )
507                    .is_err()
508                );
509                if let Ok(scanned) = scan(
510                    file.try_clone()?,
511                    ReadMode::Recover,
512                    &DcProjectionPolicy::strict(),
513                ) {
514                    ensure!(
515                        !scanned.completed
516                            && scanned.valid_length <= u64::try_from(length)?
517                    );
518                }
519            }
520        }
521        Ok(())
522    }
523}