Something went wrong. Try again.
contributor fork of @ptr.pet hydrant forked from ptr.pet/hydrant
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253use bytes::Bytes;use jacquard_common::types::cid::IpldCid;use jacquard_common::types::nsid::Nsid;use jacquard_common::types::string::{Did, Rkey};use jacquard_common::types::tid::Tid;use jacquard_common::{CowStr, types::string::Handle};use serde::{Deserialize, Serialize, Serializer};use serde_json::value::RawValue;use std::fmt::Debug;
use crate::db::types::{DbAction, DbRkey, DbTid, TrimmedDid};
#[derive(Debug, Serialize, Clone)]pub enum EventType { Record, Identity, Account,}
impl AsRef<str> for EventType { fn as_ref(&self) -> &str { match self { Self::Record => "record", Self::Identity => "identity", Self::Account => "account", } }}
fn event_type_ser_str<S: Serializer>(v: &EventType, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(v.as_ref())}
#[derive(Debug, Serialize, Clone)]pub struct MarshallableEvt<'i> { pub id: u64, #[serde(rename = "type")] #[serde(serialize_with = "event_type_ser_str")] pub kind: EventType, #[serde(borrow)] #[serde(skip_serializing_if = "Option::is_none")] pub record: Option<RecordEvt<'i>>, #[serde(skip_serializing_if = "Option::is_none")] pub identity: Option<IdentityEvt>, #[serde(borrow)] #[serde(skip_serializing_if = "Option::is_none")] pub account: Option<AccountEvt<'i>>,}
#[derive(Debug, Serialize, Clone)]pub struct RecordEvt<'i> { pub live: bool, pub did: Did, pub rev: Tid, pub collection: Nsid, pub rkey: Rkey, pub action: CowStr<'i>, #[serde(skip_serializing_if = "Option::is_none")] pub record: Option<std::sync::Arc<RawValue>>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(serialize_with = "crate::util::opt_cid_serialize_str")] pub cid: Option<IpldCid>,}
#[derive(Debug, Serialize, Clone)]pub struct IdentityEvt { pub did: Did, #[serde(skip_serializing_if = "Option::is_none")] pub handle: Option<Handle>,}
#[derive(Debug, Serialize, Clone)]pub struct AccountEvt<'i> { pub did: Did, pub active: bool, #[serde(skip_serializing_if = "Option::is_none")] pub status: Option<CowStr<'i>>,}
#[derive(Serialize, Deserialize, Clone, Default)]pub(crate) enum StoredData { #[default] Nothing, Ptr(IpldCid), /// Ephemeral create/update body. The event is its sole durable owner, so /// event TTL removes the identity and bytes together. #[serde(with = "jacquard_common::serde_bytes_helper")] Block(Bytes),}
impl StoredData { pub fn is_nothing(&self) -> bool { matches!(self, StoredData::Nothing) }}
impl Debug for StoredData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Nothing => f.write_str("nothing"), Self::Ptr(cid) => write!(f, "{cid}"), Self::Block(_) => f.write_str("<block>"), } }}
#[derive(Debug, Serialize, Deserialize, Clone)]#[serde(bound(deserialize = "'i: 'de"))]pub(crate) struct StoredEvent<'i> { #[serde(default)] pub live: bool, #[serde(borrow)] pub did: TrimmedDid<'i>, pub rev: DbTid, #[serde(borrow)] pub collection: CowStr<'i>, pub rkey: DbRkey, pub action: DbAction, #[serde(default)] #[serde(skip_serializing_if = "StoredData::is_nothing")] pub data: StoredData,}
/// a durable record event that is also emitted on the in-memory stream after commit.////// `inline_block` is only used for live tailing to avoid resolving the durable/// record body again. cursor replay continues to read from the database.#[derive(Debug, Clone)]pub(crate) struct LiveRecordEvent { pub id: u64, pub stored: StoredEvent<'static>, pub inline_block: Option<Bytes>,}
#[cfg(test)]mod tests { use super::*;
#[test] fn stream_event_json_envelopes_cover_every_variant() { let did = Did::new_static("did:web:example.com").unwrap(); let cid = jacquard_repo::mst::util::compute_cid(b"body").unwrap(); let record = MarshallableEvt { id: 1, kind: EventType::Record, record: Some(RecordEvt { live: false, did: did.clone(), rev: Tid::new("3jzfcijpj2z2a").unwrap(), collection: Nsid::new_static("app.bsky.feed.post").unwrap(), rkey: Rkey::new_static("stinkpot").unwrap(), action: CowStr::Borrowed("create"), record: None, cid: Some(cid), }), identity: None, account: None, }; assert_eq!( serde_json::to_value(&record).unwrap(), serde_json::json!({ "id": 1, "type": "record", "record": { "live": false, "did": "did:web:example.com", "rev": "3jzfcijpj2z2a", "collection": "app.bsky.feed.post", "rkey": "stinkpot", "action": "create", "cid": cid.to_string(), }, }) );
let identity = MarshallableEvt { id: 2, kind: EventType::Identity, record: None, identity: Some(IdentityEvt { did: did.clone(), handle: None, }), account: None, }; assert_eq!( serde_json::to_value(&identity).unwrap(), serde_json::json!({ "id": 2, "type": "identity", "identity": {"did": "did:web:example.com"}, }) );
let account = MarshallableEvt { id: 3, kind: EventType::Account, record: None, identity: None, account: Some(AccountEvt { did, active: true, status: None, }), }; assert_eq!( serde_json::to_value(&account).unwrap(), serde_json::json!({ "id": 3, "type": "account", "account": { "did": "did:web:example.com", "active": true, }, }) ); }
#[test] fn stored_data_persisted_golden_fixtures() { let cid = jacquard_repo::mst::util::compute_cid(b"body").unwrap(); let variants = [ StoredData::Nothing, StoredData::Ptr(cid), StoredData::Block(Bytes::from_static(b"stinkpot")), ]; let encoded = variants .iter() .map(|value| rmp_serde::to_vec(value).unwrap()) .collect::<Vec<_>>(); assert_eq!( encoded.iter().map(hex::encode).collect::<Vec<_>>(), [ "a74e6f7468696e67", "81a3507472c42401711220230d8358dc8e8890b4c58deeb62912ee2f20357ae92a5cc861b98e68fe31acb5", "81a5426c6f636bc4087374696e6b706f74", ] ); assert!(matches!( rmp_serde::from_slice::<StoredData>(&encoded[0]).unwrap(), StoredData::Nothing )); assert!(matches!( rmp_serde::from_slice::<StoredData>(&encoded[1]).unwrap(), StoredData::Ptr(decoded) if decoded == cid )); assert!(matches!( rmp_serde::from_slice::<StoredData>(&encoded[2]).unwrap(), StoredData::Block(decoded) if decoded.as_ref() == b"stinkpot" )); }}