ctb_io_csc/journal/
stream.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//! Streaming serialization and output sinks for journal entries and metadata.
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, session_context,
32};
33use ctb_formats_checksum::Sha256Stream;
34use ctb_formats_dcdata::dc;
35use ctb_formats_dcstring::{DcMixedEncode, DcMstring, SharedValueContext};
36use ctb_io::file::{Extent, FileEntity, FileEntityKind, PayloadSource};
37use std::io::{Read, Seek, SeekFrom, Write};
38
39pub const ARCHIVE_MAGIC_V1: &[u8; 8] = b"CTBCSCA\x01";
40pub const ARCHIVE_MAGIC_V2: &[u8; 8] = b"CTBCSCA\x02";
41pub const ARCHIVE_MAGIC: &[u8; 8] = ARCHIVE_MAGIC_V2;
42
43pub(crate) fn ensure_clean_metadata(entity: &FileEntity) -> Result<()> {
44    entity.check_ok()?;
45    ensure!(
46        entity.metadata.warnings.is_empty(),
47        "Archive member has semantic metadata warnings: {}",
48        entity.metadata.warnings.join("; ")
49    );
50    for stream in &entity.streams {
51        ensure_clean_metadata(&stream.entity)?;
52    }
53    Ok(())
54}
55
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum JournalMagic {
58    /// Journal v5 (`DcMixed2`) header magic.
59    JournalV5,
60    /// Archive v2 (`DcMixed2`) header magic.
61    ArchiveV2,
62}
63
64pub struct JournalWriter<W: Write> {
65    writer: W,
66    sequence: u64,
67    context: SharedValueContext,
68    failed: bool,
69    source_failed: bool,
70    sink_failed: bool,
71    completed: bool,
72}
73
74impl<W: Write> JournalWriter<W> {
75    pub fn new(
76        mut writer: W,
77        session: &JournalSessionRecord,
78        magic: JournalMagic,
79    ) -> Result<Self> {
80        let mut header = DcMstring::new();
81        header.push_system_graph_most_recent()?;
82        session.encode_dc_mixed(&mut header)?;
83        ctb_formats_dcstring::validate_dc_mixed_strict(&header)?;
84        writer.write_all(match magic {
85            JournalMagic::JournalV5 => super::JOURNAL_MAGIC_V5,
86            JournalMagic::ArchiveV2 => ARCHIVE_MAGIC_V2,
87        })?;
88        writer.write_all(header.as_bytes())?;
89        Self::resume_output(writer, session, 0, false)
90    }
91
92    pub(crate) fn resume_output(
93        writer: W,
94        session: &JournalSessionRecord,
95        sequence: u64,
96        completed: bool,
97    ) -> Result<Self> {
98        Ok(Self {
99            writer,
100            sequence,
101            context: session_context(session)?,
102            failed: false,
103            source_failed: false,
104            sink_failed: false,
105            completed,
106        })
107    }
108
109    pub fn output_mut(&mut self) -> &mut W {
110        &mut self.writer
111    }
112
113    pub fn into_output(self) -> W {
114        self.writer
115    }
116
117    pub(crate) fn sequence(&self) -> u64 {
118        self.sequence
119    }
120
121    #[cfg(test)]
122    pub(crate) fn context(&self) -> &SharedValueContext {
123        &self.context
124    }
125
126    #[cfg(test)]
127    pub(crate) fn sink_failed(&self) -> bool {
128        self.sink_failed
129    }
130
131    #[cfg(test)]
132    pub(crate) fn source_failed(&self) -> bool {
133        self.source_failed
134    }
135
136    pub(crate) fn ensure_ready(&self) -> Result<()> {
137        ensure!(
138            !self.failed,
139            "Record writer has an uncommitted failed record"
140        );
141        ensure!(!self.completed, "Record writer is already completed");
142        Ok(())
143    }
144
145    pub(crate) fn transaction<T>(
146        &mut self,
147        encode: impl FnOnce(&mut W, &SharedValueContext) -> Result<T>,
148        durable: impl FnOnce(&mut W) -> Result<()>,
149    ) -> Result<T> {
150        self.ensure_ready()?;
151        self.failed = true;
152        self.source_failed = false;
153        let value = encode(&mut self.writer, &self.context)?;
154        durable(&mut self.writer)?;
155        self.failed = false;
156        Ok(value)
157    }
158
159    pub(crate) fn write_batch(
160        &mut self,
161        entities: &[FileEntity],
162        durable: impl FnOnce(&mut W) -> Result<()>,
163    ) -> Result<()> {
164        self.ensure_ready()?;
165        self.write_record_durable(
166            |writer, context| {
167                for entity in entities {
168                    if let Some(read_time) = entity.metadata.read_time {
169                        read_time
170                            .duration_since(std::time::UNIX_EPOCH)
171                            .context(
172                                "Read time timestamp is before Unix epoch",
173                            )?;
174                    }
175                    entity.encode_record_to_writer_with_policy(
176                        writer,
177                        None,
178                        ctb_io::file::encoding::BodyPolicy::Omit,
179                        context,
180                    )?;
181                }
182                Ok(())
183            },
184            durable,
185        )
186    }
187
188    pub fn write_entity(
189        &mut self,
190        entity: &FileEntity,
191        payload: Option<&mut dyn PayloadSource>,
192    ) -> Result<()> {
193        self.write_entity_checked(
194            entity,
195            payload,
196            ctb_io::file::encoding::BodyPolicy::Include,
197            || Ok(()),
198        )
199    }
200
201    pub fn write_entity_checked(
202        &mut self,
203        entity: &FileEntity,
204        payload: Option<&mut dyn PayloadSource>,
205        bodies: ctb_io::file::encoding::BodyPolicy,
206        precommit: impl FnOnce() -> Result<()>,
207    ) -> Result<()> {
208        self.ensure_ready()?;
209        if let FileEntityKind::Regular { size, .. } = &entity.kind {
210            if let Some(source) = payload.as_ref() {
211                ensure!(
212                    source.total_size() == *size,
213                    "Source size differs from record metadata"
214                );
215            }
216        } else {
217            ensure!(
218                payload.is_none(),
219                "Non-regular record cannot contain primary data"
220            );
221        }
222        let mut source_failed = false;
223        let result = self.write_record(|mut writer, context| {
224            if let (
225                FileEntityKind::Regular { size, sha256, .. },
226                Some(source),
227            ) = (&entity.kind, payload)
228            {
229                let mut source = VerifiedSource {
230                    source,
231                    digest: Sha256Stream::new(),
232                    bytes: 0,
233                    size: *size,
234                    failed: &mut source_failed,
235                };
236                entity.encode_record_to_writer_with_policy(
237                    &mut writer,
238                    Some(&mut source),
239                    bodies,
240                    context,
241                )?;
242                if source.bytes != *size
243                    || source.digest.clone().finalize() != *sha256
244                {
245                    *source.failed = true;
246                    bail!("Source contents changed while encoding");
247                }
248                let warnings = source.finish()?;
249                if !warnings.is_empty() {
250                    *source.failed = true;
251                    bail!("Source fidelity warnings: {}", warnings.join("; "));
252                }
253            } else {
254                entity.encode_record_to_writer_with_policy(
255                    &mut writer,
256                    None,
257                    bodies,
258                    context,
259                )?;
260            }
261            if let Err(error) = precommit() {
262                source_failed = true;
263                return Err(error);
264            }
265            Ok(())
266        });
267        self.source_failed = result.as_ref().err().is_some_and(|error| {
268            source_failed
269                || error.is::<ctb_formats_dcstring::DcBinarySourceError>()
270        });
271        result
272    }
273
274    pub fn record_error(&mut self, error: &JournalErrorRecord) -> Result<()> {
275        self.record_error_durable(error, |_| Ok(()))
276    }
277
278    pub(crate) fn record_error_durable(
279        &mut self,
280        error: &JournalErrorRecord,
281        durable: impl FnOnce(&mut W) -> Result<()>,
282    ) -> Result<()> {
283        self.write_diagnostic(
284            |writer, _| {
285                let mut record = DcMstring::new();
286                JournalErrorRecordPayload::from_record(error)?
287                    .encode_dc_mixed(&mut record)?;
288                ctb_formats_dcstring::validate_dc_mixed_strict(&record)?;
289                writer.write_all(record.payload_bytes())?;
290                Ok(())
291            },
292            durable,
293        )
294    }
295
296    pub fn record_warning(
297        &mut self,
298        warning: &JournalWarningRecord,
299    ) -> Result<()> {
300        self.record_warning_durable(warning, |_| Ok(()))
301    }
302
303    pub(crate) fn record_warning_durable(
304        &mut self,
305        warning: &JournalWarningRecord,
306        durable: impl FnOnce(&mut W) -> Result<()>,
307    ) -> Result<()> {
308        self.write_diagnostic(
309            |writer, _| {
310                let mut record = DcMstring::new();
311                JournalWarningRecordPayload::from_record(warning)
312                    .encode_dc_mixed(&mut record)?;
313                ctb_formats_dcstring::validate_dc_mixed_strict(&record)?;
314                writer.write_all(record.payload_bytes())?;
315                Ok(())
316            },
317            durable,
318        )
319    }
320
321    fn write_diagnostic(
322        &mut self,
323        encode: impl FnOnce(&mut dyn Write, &SharedValueContext) -> Result<()>,
324        durable: impl FnOnce(&mut W) -> Result<()>,
325    ) -> Result<()> {
326        self.transaction(|writer, context| encode(writer, context), durable)
327    }
328
329    pub(crate) fn write_record(
330        &mut self,
331        encode: impl FnOnce(&mut dyn Write, &SharedValueContext) -> Result<()>,
332    ) -> Result<()> {
333        self.write_record_durable(encode, |_| Ok(()))
334    }
335
336    fn write_record_durable(
337        &mut self,
338        encode: impl FnOnce(&mut dyn Write, &SharedValueContext) -> Result<()>,
339        durable: impl FnOnce(&mut W) -> Result<()>,
340    ) -> Result<()> {
341        self.ensure_ready()?;
342        self.failed = true;
343        self.source_failed = false;
344        let next = self
345            .sequence
346            .checked_add(1)
347            .context("Record sequence overflow")?;
348        let mut writer = ObservedSink {
349            writer: &mut self.writer,
350            failed: &mut self.sink_failed,
351        };
352        crate::section::write_section(&mut writer, next, |mut writer| {
353            encode(&mut writer, &self.context)
354        })?;
355        durable(&mut self.writer)?;
356        self.failed = false;
357        self.sequence = next;
358        Ok(())
359    }
360
361    pub(crate) fn is_failed(&self) -> bool {
362        self.failed
363    }
364
365    /// Reports whether only an observed member source failure needs rollback.
366    pub(crate) fn can_rollback_source_failure(&self) -> bool {
367        self.failed && self.source_failed && !self.sink_failed
368    }
369
370    /// The caller must discard the failed section and restore the output position.
371    /// A failed callback permanently disables this writer, even if retried.
372    pub(crate) fn rollback_source_failure(
373        &mut self,
374        rollback: impl FnOnce(&mut W) -> Result<()>,
375    ) -> Result<()> {
376        ensure!(
377            self.can_rollback_source_failure(),
378            "Record failure is not source-only"
379        );
380        self.sink_failed = true;
381        rollback(&mut self.writer)?;
382        self.failed = false;
383        self.source_failed = false;
384        self.sink_failed = false;
385        Ok(())
386    }
387
388    pub(crate) fn complete(
389        &mut self,
390        durable: impl FnOnce(&mut W) -> Result<()>,
391    ) -> Result<()> {
392        self.ensure_ready()?;
393        self.failed = true;
394        let mut completion = DcMstring::new();
395        completion.push_char(dc::DC_OPERATION_COMPLETED);
396        let mut writer = ObservedSink {
397            writer: &mut self.writer,
398            failed: &mut self.sink_failed,
399        };
400        writer.write_all(completion.payload_bytes())?;
401        writer.flush()?;
402        durable(&mut self.writer)?;
403        self.completed = true;
404        self.failed = false;
405        Ok(())
406    }
407
408    pub fn finish(mut self) -> Result<W> {
409        self.complete(|_| Ok(()))?;
410        Ok(self.into_output())
411    }
412
413    #[cfg(test)]
414    pub(crate) fn map_output<T: Write>(
415        self,
416        map: impl FnOnce(W) -> T,
417    ) -> JournalWriter<T> {
418        JournalWriter {
419            writer: map(self.writer),
420            sequence: self.sequence,
421            context: self.context,
422            failed: self.failed,
423            source_failed: self.source_failed,
424            sink_failed: self.sink_failed,
425            completed: self.completed,
426        }
427    }
428}
429
430pub(crate) struct ObservedSink<'writer, W> {
431    pub(crate) writer: &'writer mut W,
432    pub(crate) failed: &'writer mut bool,
433}
434
435impl<W: Write> Write for ObservedSink<'_, W> {
436    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
437        match self.writer.write(bytes) {
438            Ok(0) if !bytes.is_empty() => {
439                *self.failed = true;
440                Err(std::io::Error::new(
441                    std::io::ErrorKind::WriteZero,
442                    "Record sink accepted no bytes",
443                ))
444            }
445            Ok(count) if count > bytes.len() => {
446                *self.failed = true;
447                Err(std::io::Error::other("Invalid record sink write count"))
448            }
449            Err(error) => {
450                if error.kind() != std::io::ErrorKind::Interrupted {
451                    *self.failed = true;
452                }
453                Err(error)
454            }
455            result => result,
456        }
457    }
458
459    fn flush(&mut self) -> std::io::Result<()> {
460        let result = self.writer.flush();
461        if result.is_err() {
462            *self.failed = true;
463        }
464        result
465    }
466}
467
468pub(crate) struct VerifiedSource<'source> {
469    pub(crate) source: &'source mut dyn PayloadSource,
470    pub(crate) digest: Sha256Stream,
471    pub(crate) bytes: u64,
472    pub(crate) size: u64,
473    pub(crate) failed: &'source mut bool,
474}
475
476impl Read for VerifiedSource<'_> {
477    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
478        let count = match self.source.read(buffer) {
479            Ok(0) if !buffer.is_empty() && self.bytes < self.size => {
480                *self.failed = true;
481                return Err(std::io::Error::new(
482                    std::io::ErrorKind::UnexpectedEof,
483                    "Record source ended before its declared size",
484                ));
485            }
486            Ok(count) if count > buffer.len() => {
487                return Err(std::io::Error::other("Invalid source read count"));
488            }
489            Ok(count) => count,
490            Err(error) => {
491                *self.failed = true;
492                return Err(error);
493            }
494        };
495        self.digest.update(buffer.get(..count).ok_or_else(|| {
496            std::io::Error::other("Invalid source read count")
497        })?);
498        self.bytes = self
499            .bytes
500            .checked_add(u64::try_from(count).map_err(std::io::Error::other)?)
501            .ok_or_else(|| {
502                std::io::Error::other("Source byte count overflow")
503            })?;
504        Ok(count)
505    }
506}
507
508impl Seek for VerifiedSource<'_> {
509    fn seek(&mut self, position: SeekFrom) -> std::io::Result<u64> {
510        if self.bytes != 0 {
511            return Err(std::io::Error::other(
512                "Cannot seek after hashing source data",
513            ));
514        }
515        let result = self.source.seek(position);
516        if result.is_err() {
517            *self.failed = true;
518        }
519        result
520    }
521}
522
523impl PayloadSource for VerifiedSource<'_> {
524    fn total_size(&self) -> u64 {
525        self.size
526    }
527    fn extents(&self) -> &[Extent] {
528        self.source.extents()
529    }
530    fn finish(&mut self) -> Result<Vec<String>> {
531        let result = self.source.finish();
532        if result.is_err() {
533            *self.failed = true;
534        }
535        result
536    }
537}
538
539#[cfg(test)]
540#[allow(
541    clippy::panic,
542    clippy::expect_used,
543    clippy::unwrap_used,
544    clippy::unwrap_in_result,
545    clippy::panic_in_result_fn,
546    clippy::indexing_slicing,
547    clippy::arithmetic_side_effects,
548    reason = "Standard repository test boilerplate"
549)]
550mod tests {
551    use super::*;
552    use ctb_io::file::MemoryPayloadSource;
553
554    struct ShortOutput(Vec<u8>);
555
556    impl Write for ShortOutput {
557        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
558            let accepted = bytes
559                .get(..bytes.len().min(3))
560                .context("Invalid test slice")
561                .map_err(std::io::Error::other)?;
562            self.0.extend_from_slice(accepted);
563            Ok(accepted.len())
564        }
565
566        fn flush(&mut self) -> std::io::Result<()> {
567            Ok(())
568        }
569    }
570
571    fn session() -> JournalSessionRecord {
572        JournalSessionRecord {
573            sources: vec!["source".into()],
574            destination: "destination".into(),
575            origin_platform: 1,
576            environment: Some(std::sync::Arc::new(
577                ctb_io_environment::EnvDescription::default(),
578            )),
579        }
580    }
581
582    fn reference_section(
583        output: &mut Vec<u8>,
584        sequence: u64,
585        bytes: &[u8],
586    ) -> Result<()> {
587        let mut section = DcMstring::new();
588        section.push_char(dc::DC_BEGIN_CHECKSUMMED_SECTION);
589        let mut body = DcMstring::new();
590        body.push_char(dc::DC_SEQUENCE_IDENTIFIER);
591        sequence.encode_dc_mixed(&mut body)?;
592        let mut body = body.payload_bytes().to_vec();
593        body.extend_from_slice(bytes);
594        output.extend_from_slice(section.payload_bytes());
595        output.extend_from_slice(&body);
596        let mut footer = DcMstring::new();
597        footer.push_char(dc::DC_END_CHECKSUMMED_SECTION);
598        footer.push_char(dc::DC_SECTION_DIGEST);
599        footer.push_checksum(
600            ctb_utilities::format_id::DC_SHA256,
601            &ctb_formats_checksum::sha256(&body),
602        )?;
603        output.extend_from_slice(footer.payload_bytes());
604        Ok(())
605    }
606
607    #[crate::ctb_test]
608    fn magic_does_not_select_record_grammar() -> Result<()> {
609        let session = session();
610        let entity = FileEntity::from_vec(b"body".to_vec());
611        let error = JournalErrorRecord::from_error(
612            std::path::Path::new("source"),
613            super::super::JournalErrorStage::PayloadRead,
614            &anyhow::anyhow!("capture failure"),
615        );
616        let mut encodings = Vec::new();
617        for magic in [JournalMagic::JournalV5, JournalMagic::ArchiveV2] {
618            let mut writer = JournalWriter::new(Vec::new(), &session, magic)?;
619            writer.write_batch(std::slice::from_ref(&entity), |_| Ok(()))?;
620            let mut payload = MemoryPayloadSource::new(b"body".to_vec())?;
621            writer.write_entity(&entity, Some(&mut payload))?;
622            writer.write_entity(&entity, None)?;
623            writer.record_error(&error)?;
624            let bytes = writer.finish()?;
625            encodings
626                .push(bytes.get(8..).context("Missing format magic")?.to_vec());
627        }
628        ensure!(
629            encodings.first() == encodings.get(1),
630            "Magic changed the record grammar"
631        );
632        Ok(())
633    }
634
635    #[crate::ctb_test]
636    fn either_magic_uses_journal_layout_with_short_output() -> Result<()> {
637        let session = session();
638        let context = session_context(&session)?;
639        let entities = [
640            FileEntity::from_vec(b"first".to_vec()),
641            FileEntity::from_vec(Vec::new()),
642        ];
643        let error = JournalErrorRecord {
644            path: "source".into(),
645            raw_path: b"source".to_vec(),
646            stage: super::super::JournalErrorStage::PayloadRead,
647            error_message: "read failed".into(),
648            os_error: Some(5),
649            timestamp_sec: 12,
650        };
651        let warning = JournalWarningRecord {
652            code: "capture".into(),
653            message: "warning".into(),
654            timestamp_sec: 13,
655        };
656        for profile in [JournalMagic::JournalV5, JournalMagic::ArchiveV2] {
657            let mut writer =
658                JournalWriter::new(ShortOutput(Vec::new()), &session, profile)?;
659            let mut header = DcMstring::new();
660            header.push_system_graph_most_recent()?;
661            session.encode_dc_mixed(&mut header)?;
662            let mut expected = match profile {
663                JournalMagic::JournalV5 => {
664                    super::super::JOURNAL_MAGIC_V5.to_vec()
665                }
666                JournalMagic::ArchiveV2 => ARCHIVE_MAGIC_V2.to_vec(),
667            };
668            expected.extend_from_slice(header.as_bytes());
669            let mut body = DcMstring::new();
670            for entity in &entities {
671                entity.encode_dc_mixed_with_context(&mut body, &context)?;
672            }
673            reference_section(&mut expected, 1, body.payload_bytes())?;
674            writer.write_batch(&entities, |_| Ok(()))?;
675            for (index, entity) in entities.iter().enumerate() {
676                let data = if index == 0 {
677                    b"first".to_vec()
678                } else {
679                    Vec::new()
680                };
681                let mut source = MemoryPayloadSource::new(data.clone())?;
682                let mut body = Vec::new();
683                entity.encode_record_to_writer_with_payload_and_context(
684                    &mut body,
685                    &mut source,
686                    &context,
687                )?;
688                reference_section(
689                    &mut expected,
690                    u64::try_from(index)?
691                        .checked_add(2)
692                        .context("Test sequence overflow")?,
693                    &body,
694                )?;
695                let mut source = MemoryPayloadSource::new(data)?;
696                writer.write_entity(entity, Some(&mut source))?;
697            }
698            let mut diagnostic = DcMstring::new();
699            JournalErrorRecordPayload::from_record(&error)?
700                .encode_dc_mixed(&mut diagnostic)?;
701            expected.extend_from_slice(diagnostic.payload_bytes());
702            writer.record_error(&error)?;
703            let mut diagnostic = DcMstring::new();
704            JournalWarningRecordPayload::from_record(&warning)
705                .encode_dc_mixed(&mut diagnostic)?;
706            expected.extend_from_slice(diagnostic.payload_bytes());
707            writer.record_warning(&warning)?;
708            let mut completion = DcMstring::new();
709            completion.push_char(dc::DC_OPERATION_COMPLETED);
710            expected.extend_from_slice(completion.payload_bytes());
711            ensure!(
712                writer.finish()?.0 == expected,
713                "Magic {profile:?} changed the journal record layout"
714            );
715            let mstr = ctb_formats_dcstring::DcMstr::from_bytes(&expected[8..])?;
716            let Some(ctb_formats_dcstring::DcMixedChunk::Text(first_text)) =
717                mstr.chunks().next()
718            else {
719                bail!("Expected leading text chunk in journal/archive DcMixed2 stream");
720            };
721            let mut chars = first_text.chars();
722            ensure!(
723                chars.next()
724                    == Some(dc::DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID),
725                "Expected leading Dc 641 most_recent in {profile:?} stream"
726            );
727            let expected_wm =
728                ctb_formats_dcdata::seed_graph::current_system_block_most_recent_node_id()?;
729            ensure!(
730                chars.next()
731                    == Some(ctb_formats_dcstring::DcChar::from_u128(expected_wm)),
732                "Expected leading System-block most_recent node ID l{expected_wm} in {profile:?} stream"
733            );
734            ensure!(
735                chars.next() == Some(dc::DC_BEGIN_OPERATION_SESSION),
736                "Expected Dc 547 (Begin operation session) immediately after Dc 641 most_recent"
737            );
738        }
739        Ok(())
740    }
741
742    #[crate::ctb_test]
743    fn durable_failure_keeps_sequence_and_refuses_retry() -> Result<()> {
744        let mut writer = JournalWriter::new(
745            Vec::new(),
746            &session(),
747            JournalMagic::JournalV5,
748        )?;
749        let entity = FileEntity::from_vec(b"payload".to_vec());
750        ensure!(
751            writer
752                .write_batch(std::slice::from_ref(&entity), |_| bail!(
753                    "injected sync failure"
754                ))
755                .is_err()
756        );
757        ensure!(
758            writer.sequence() == 0
759                && writer.is_failed()
760                && !writer.can_rollback_source_failure()
761        );
762        let before = writer.output_mut().clone();
763        let mut called = false;
764        ensure!(
765            writer
766                .write_batch(&[entity], |_| {
767                    called = true;
768                    Ok(())
769                })
770                .is_err()
771        );
772        ensure!(
773            writer
774                .complete(|_| {
775                    called = true;
776                    Ok(())
777                })
778                .is_err()
779        );
780        ensure!(!called, "Refused operation invoked durability");
781        ensure!(*writer.output_mut() == before);
782        Ok(())
783    }
784
785    #[crate::ctb_test]
786    fn capture_metadata_precommit_failure_has_no_footer_and_can_rollback()
787    -> Result<()> {
788        let mut writer = JournalWriter::new(
789            Vec::new(),
790            &session(),
791            JournalMagic::ArchiveV2,
792        )?;
793        let checkpoint = writer.output_mut().len();
794        let mut entity = FileEntity::from_vec(Vec::new());
795        entity.kind = FileEntityKind::Directory;
796        ensure!(
797            writer
798                .write_entity_checked(
799                    &entity,
800                    None,
801                    ctb_io::file::encoding::BodyPolicy::Include,
802                    || bail!("injected source change after encode")
803                )
804                .is_err()
805        );
806        ensure!(
807            writer.sequence() == 0
808                && writer.source_failed()
809                && !writer.sink_failed()
810        );
811        ensure!(writer.can_rollback_source_failure());
812        let bytes = writer.output_mut();
813        let mut footer = DcMstring::new();
814        footer.push_char(dc::DC_END_CHECKSUMMED_SECTION);
815        ensure!(!bytes.ends_with(footer.payload_bytes()));
816        writer.rollback_source_failure(|output| {
817            output.truncate(checkpoint);
818            Ok(())
819        })?;
820        writer.write_entity_checked(
821            &entity,
822            None,
823            ctb_io::file::encoding::BodyPolicy::Include,
824            || Ok(()),
825        )?;
826        ensure!(writer.sequence() == 1);
827        Ok(())
828    }
829
830    #[crate::ctb_test]
831    fn journal_completion_durability_failure_poisoned() -> Result<()> {
832        let mut writer = JournalWriter::new(
833            Vec::new(),
834            &session(),
835            JournalMagic::JournalV5,
836        )?;
837        let result =
838            writer.complete(|_| bail!("injected completion sync failure"));
839        ensure!(result.is_err() && writer.is_failed());
840        ensure!(!writer.completed && !writer.can_rollback_source_failure());
841        let bytes = writer.output_mut().clone();
842        let mut called = false;
843        ensure!(
844            writer
845                .complete(|_| {
846                    called = true;
847                    Ok(())
848                })
849                .is_err()
850        );
851        ensure!(
852            writer
853                .write_batch(&[], |_| {
854                    called = true;
855                    Ok(())
856                })
857                .is_err()
858        );
859        ensure!(
860            writer
861                .transaction(
862                    |_, _| {
863                        called = true;
864                        Ok(())
865                    },
866                    |_| Ok(())
867                )
868                .is_err()
869        );
870        ensure!(
871            !called && *writer.output_mut() == bytes && writer.sequence() == 0
872        );
873        Ok(())
874    }
875
876    #[crate::ctb_test]
877    fn completed_profiles_refuse_all_writes_and_duplicate_completion()
878    -> Result<()> {
879        for profile in [JournalMagic::JournalV5, JournalMagic::ArchiveV2] {
880            let mut writer =
881                JournalWriter::new(Vec::new(), &session(), profile)?;
882            writer.complete(|_| Ok(()))?;
883            let before = writer.output_mut().clone();
884            let mut called = false;
885            ensure!(
886                writer
887                    .complete(|_| {
888                        called = true;
889                        Ok(())
890                    })
891                    .is_err()
892            );
893            ensure!(
894                writer
895                    .write_batch(&[], |_| {
896                        called = true;
897                        Ok(())
898                    })
899                    .is_err()
900            );
901            ensure!(
902                writer
903                    .write_entity(&FileEntity::from_vec(Vec::new()), None)
904                    .is_err()
905            );
906            ensure!(
907                writer
908                    .record_warning(&JournalWarningRecord {
909                        code: "late".into(),
910                        message: "late".into(),
911                        timestamp_sec: 0
912                    })
913                    .is_err()
914            );
915            ensure!(!called, "Completed writer invoked durability");
916            ensure!(*writer.output_mut() == before);
917        }
918        Ok(())
919    }
920}