Skip to main content

qualia_core_db/medical/dicom_source/
ingest.rs

1use super::association::associate;
2use super::storage::{preserve, read_source};
3use super::{DicomSourceArtifact, DicomSourceBudget};
4use crate::dicom::{split_dicom_payload, DicomSplitPayload};
5use crate::dicom_ingest::{self, DicomBlobStore, DicomIngestError, DicomSeriesRecord};
6use crate::wal::WriteAheadLog;
7use crate::{q_hash, NQuin};
8use std::path::Path;
9
10/// Additive result; the existing public series-record layout stays unchanged.
11#[derive(Debug, Clone)]
12pub struct DicomIngestWithSource {
13    pub record: DicomSeriesRecord,
14    pub source: DicomSourceArtifact,
15}
16
17/// Ingest admitted original bytes unchanged, preserving full source custody before
18/// reporting success. Pixel bytes retain the existing append-only representation.
19/// Metadata/encapsulated payloads are not decoded, deidentified or reserialized.
20/// On later pixel/WAL/registry failure an admitted immutable source may remain;
21/// this is not a transaction or aggregate retention/garbage-collection policy.
22pub fn split_ingest_sync_with_source(
23    storage_root: &Path,
24    source_path: &Path,
25    patient_did_hash: u64,
26    budget: DicomSourceBudget,
27) -> Result<DicomIngestWithSource, DicomIngestError> {
28    let map_source = |e: super::DicomSourceError| DicomIngestError::Io(e.to_string());
29    let file_bytes = read_source(source_path, budget).map_err(map_source)?;
30    let DicomSplitPayload { meta, pixels } =
31        split_dicom_payload(&file_bytes).map_err(|e| DicomIngestError::Parse(e.to_string()))?;
32    let pixel_end = pixels
33        .offset
34        .checked_add(pixels.length)
35        .ok_or_else(|| DicomIngestError::Parse("pixel extent overflow".into()))?;
36    let pixel_bytes = file_bytes
37        .get(pixels.offset..pixel_end)
38        .ok_or_else(|| DicomIngestError::Parse("pixel extent outside original".into()))?;
39    let blob_length = u32::try_from(pixels.length)
40        .map_err(|_| DicomIngestError::Parse("pixel length exceeds blob record".into()))?;
41    let source = preserve(storage_root, &file_bytes, budget).map_err(map_source)?;
42    let mut store = DicomBlobStore::open(&dicom_ingest::blob_path(storage_root))
43        .map_err(|e| DicomIngestError::Io(e.to_string()))?;
44    let blob_offset = store
45        .append_pixels(pixel_bytes)
46        .map_err(|e| DicomIngestError::Io(e.to_string()))?;
47    let series_hash = dicom_ingest::hash_series_uid(&meta.series_instance_uid);
48    let patient = if patient_did_hash != 0 {
49        patient_did_hash
50    } else if !meta.patient_id.is_empty() {
51        q_hash(&meta.patient_id)
52    } else {
53        q_hash("q42:anonymousPatient")
54    };
55    let mut quins = [NQuin::default(); 6];
56    let quin_count = dicom_ingest::compile_semantic_quins(
57        &meta,
58        patient,
59        series_hash,
60        blob_offset,
61        blob_length,
62        &mut quins,
63    );
64    // Preserve existing best-effort WAL semantics; source publication does not
65    // assert WAL durability or repair the preexisting multi-store transaction gap.
66    if let Ok(mut wal) = WriteAheadLog::open(&dicom_ingest::wal_path(storage_root)) {
67        for quin in &quins[..quin_count] {
68            let _ = wal.append_mutation(quin);
69        }
70    }
71    let record = DicomSeriesRecord {
72        patient_did_hash: patient,
73        series_hash,
74        blob_offset,
75        blob_length,
76        rows: meta.rows,
77        cols: meta.columns,
78        organ_hash: dicom_ingest::infer_organ_hash(&meta),
79        pixel_pointer_quin_parity: quins[quin_count.saturating_sub(1)].parity,
80    };
81    associate(storage_root, &record, &source).map_err(map_source)?;
82    dicom_ingest::publish_series_record(record)?;
83    Ok(DicomIngestWithSource { record, source })
84}