Skip to main content

qualia_core_db/sensing/local_custody/
publish.rs

1use super::{
2    entry_size, filename, validate_root, CustodyAuthority, CustodyError, SidecarReceipt,
3    HEADER_BYTES, MAGIC, SIDECAR_BYTES, SIDECAR_RECEIPT_BYTES,
4};
5use std::{
6    fs::{self, OpenOptions},
7    io::Write,
8    path::Path,
9};
10
11/// Atomic bundle publication was attempted and the target link was created.
12/// Directory synchronization and chain-head publication are not established.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub struct PublishedBundle {
15    pub checkpoint: [u8; 32],
16    pub bytes: usize,
17}
18
19/// Publish a single receipt-addressed bundle without replacing an existing
20/// destination. Other links or writers may still modify the underlying file.
21/// Host must hold an
22/// exclusive lease and enforce local-root/aggregate-budget policy throughout.
23/// A same-filesystem hard-link create is used; no replacement is attempted.
24/// Temporary cleanup is best effort and crash cleanup is external.
25pub fn publish_bundle(
26    root: &Path,
27    sidecar: &[u8; SIDECAR_BYTES],
28    payload: &[u8],
29    receipt: &SidecarReceipt,
30    byte_budget: usize,
31    authority: &mut impl CustodyAuthority,
32) -> Result<PublishedBundle, CustodyError> {
33    validate_root(root)?;
34    let total = entry_size(payload.len(), byte_budget)?;
35    let payload_len = u64::try_from(payload.len()).map_err(|_| CustodyError::TooLarge)?;
36    receipt
37        .verify_with_authority(sidecar, payload, payload.len(), authority)
38        .map_err(CustodyError::Receipt)?;
39    if !authority.permit_publish(root, receipt, sidecar, payload, total) {
40        return Err(CustodyError::PermissionDenied);
41    }
42    let temp = tempfile::Builder::new()
43        .prefix("qualia-sensing-")
44        .tempdir_in(root)?;
45    let temporary_file = temp.path().join("bundle");
46    let mut options = OpenOptions::new();
47    options.write(true).create_new(true);
48    #[cfg(unix)]
49    {
50        use std::os::unix::fs::OpenOptionsExt;
51        options.mode(0o600);
52    }
53    let mut file = options.open(&temporary_file)?;
54    let mut header = [0u8; HEADER_BYTES];
55    header[..4].copy_from_slice(MAGIC);
56    header[4..6].copy_from_slice(&1u16.to_le_bytes());
57    header[6..8].copy_from_slice(&(HEADER_BYTES as u16).to_le_bytes());
58    header[8..16].copy_from_slice(&payload_len.to_le_bytes());
59    let mut receipt_bytes = [0u8; SIDECAR_RECEIPT_BYTES];
60    receipt
61        .encode(&mut receipt_bytes)
62        .map_err(CustodyError::Receipt)?;
63    file.write_all(&header)?;
64    file.write_all(sidecar)?;
65    file.write_all(&receipt_bytes)?;
66    file.write_all(payload)?;
67    file.sync_all()?;
68    drop(file);
69    // Recheck current policy and lease immediately before publication.
70    receipt
71        .verify_with_authority(sidecar, payload, payload.len(), authority)
72        .map_err(CustodyError::Receipt)?;
73    if !authority.permit_publish(root, receipt, sidecar, payload, total) {
74        return Err(CustodyError::PermissionDenied);
75    }
76    let checkpoint = receipt.checkpoint();
77    let name = filename(&checkpoint);
78    let target = root.join(std::str::from_utf8(&name).map_err(|_| CustodyError::InvalidEncoding)?);
79    fs::hard_link(&temporary_file, &target)?;
80    Ok(PublishedBundle {
81        checkpoint,
82        bytes: total,
83    })
84}