use anyhow::{Context, Result, bail}; use crate::{atproto::blob_cid, db::PlcSequencedOp}; pub struct Bundle { pub dag_cbor: Vec, pub cid: String, pub seq_start: u64, pub seq_end: u64, pub count: usize, } pub fn encode_bundle(ops: &[PlcSequencedOp]) -> Result { let (first, last) = match (ops.first(), ops.last()) { (Some(f), Some(l)) => (f, l), _ => bail!("encode_bundle called with no ops"), }; let entries: Vec<(u64, &str, &str, serde_json::Value)> = ops .iter() .map(|op| { let operation: serde_json::Value = serde_json::from_str(&op.operation) .with_context(|| format!("parsing operation JSON for seq {}", op.seq))?; Ok((op.seq, op.did.as_str(), op.created_at.as_str(), operation)) }) .collect::>()?; let dag_cbor = serde_ipld_dagcbor::to_vec(&entries).context("encoding DAG-CBOR")?; let cid = blob_cid(&dag_cbor).to_string(); Ok(Bundle { dag_cbor, cid, seq_start: first.seq, seq_end: last.seq, count: ops.len(), }) } pub fn decode_bundle(dag_cbor: &[u8]) -> Result> { let entries: Vec<(u64, String, String, serde_json::Value)> = serde_ipld_dagcbor::from_slice(dag_cbor).context("decoding bundle DAG-CBOR")?; Ok(entries .into_iter() .map(|(seq, did, created_at, operation)| PlcSequencedOp { seq, did, created_at, operation: operation.to_string(), }) .collect()) }