use std::collections::BTreeMap;
use std::time::Duration;
use serde_json::Value;
use super::book::{BookEntry, BookRecord, RECORD_HEADER_MEMBER};
use super::{Shelf, ShelfError};
use crate::canonical;
use crate::seal::{self, Producer, DEFAULT_DEVELOPER};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SentCapsule {
pub capsule_id: String,
pub capsule: Vec<u8>,
pub envelope: Vec<u8>,
pub payload: Vec<u8>,
}
#[derive(Debug)]
pub struct SealedSent {
pub record: BookRecord,
pub capsule: SentCapsule,
pub error: Option<ShelfError>,
}
impl Shelf {
pub fn seal_sent(
&self,
entry: &BookEntry,
members: &BTreeMap<String, Value>,
action_id: &str,
) -> Result<SealedSent, ShelfError> {
if action_id.is_empty() {
return Err(ShelfError::Invalid(
"a sent record needs an action_id".into(),
));
}
let [payload] = entry.payloads.as_slice() else {
return Err(ShelfError::Invalid(
"a sent record carries exactly one payload, its record".into(),
));
};
if members.contains_key(RECORD_HEADER_MEMBER) {
return Err(ShelfError::Invalid(format!(
"a sent Capsule carries no {RECORD_HEADER_MEMBER}"
)));
}
let decoded: Value = serde_json::from_slice(payload)
.map_err(|e| ShelfError::Invalid(format!("a sent record's payload is JSON: {e}")))?;
if canonical::jcs(&decoded).ok().as_deref() != Some(payload.as_slice()) {
return Err(ShelfError::Invalid(
"a sent record's payload is its canonical JSON (JCS) bytes".into(),
));
}
let journal = self.journal()?;
let core = &journal.0;
let mut state = core.lock();
if state.released {
return Err(ShelfError::Released);
}
let shared = self.shared();
let developer = if shared.developer.is_empty() {
DEFAULT_DEVELOPER
} else {
&shared.developer
};
let at = core.now().truncate(Duration::from_secs(1));
let sealed = seal::seal_payload(
action_id,
&at.rfc3339(),
payload,
members,
&Producer {
operator: &shared.operator,
developer,
signer: shared.signer.as_ref(),
},
)
.map_err(|e| match e {
seal::SealRecordError::Invalid(why) => {
ShelfError::Invalid(format!("seal the sent record: {why}"))
}
other => ShelfError::Seal(other),
})?;
let capsule = SentCapsule {
capsule_id: sealed.capsule_id,
capsule: sealed.capsule,
envelope: sealed.envelope,
payload: payload.clone(),
};
let pending_before = state.pending.as_ref().map(|r| r.record_id.clone());
match core.append_locked(&mut state, entry) {
Ok(record) => Ok(SealedSent {
record,
capsule,
error: None,
}),
Err(e) => match &state.pending {
Some(pending) if Some(&pending.record_id) != pending_before.as_ref() => {
Ok(SealedSent {
record: pending.clone(),
capsule,
error: Some(e),
})
}
_ => Err(e),
},
}
}
}