event.rs (21606B)
1 //! Canonical event persistence contracts. 2 3 pub use radroots_event::EventId; 4 use radroots_event::{SignedEvent, VerifiedEvent, admission::VisibleEvent}; 5 pub use radroots_transport::BoxFuture; 6 use radroots_transport::{ 7 TransportId, 8 source::{EventProvenance, FetchCursor, ObservedEvent}, 9 target::TargetFingerprint, 10 }; 11 use std::collections::BTreeSet; 12 13 use crate::{Error, status::EventStoreStatus}; 14 15 mod visibility; 16 mod visibility_index; 17 #[doc(hidden)] 18 pub use visibility::VisibilityEventMetadata; 19 #[doc(hidden)] 20 pub use visibility::{VisibilityEvaluation, VisibilityInput, evaluate_visibility}; 21 pub use visibility_index::{VisibilityIndexBounds, VisibilityIndexProgress}; 22 23 /// Maximum events returned by one storage query. 24 pub const EVENT_QUERY_LIMIT_MAX: u16 = 1_000; 25 /// Maximum explicit event identifiers in one storage query. 26 pub const EVENT_QUERY_ID_MAX: usize = 256; 27 /// Opaque identity of one append-only canonical event source. 28 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 29 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 30 pub struct SourceGeneration([u8; 32]); 31 32 impl SourceGeneration { 33 /// Creates a generation from host-provided entropy. 34 pub const fn new(bytes: [u8; 32]) -> Result<Self, Error> { 35 if is_all_zero(&bytes) { 36 return Err(Error::InvalidSourceGeneration); 37 } 38 Ok(Self(bytes)) 39 } 40 41 /// Returns the opaque generation bytes. 42 pub const fn as_bytes(&self) -> &[u8; 32] { 43 &self.0 44 } 45 } 46 47 const fn is_all_zero(bytes: &[u8; 32]) -> bool { 48 let mut index = 0; 49 while index < bytes.len() { 50 if bytes[index] != 0 { 51 return false; 52 } 53 index += 1; 54 } 55 true 56 } 57 58 /// Canonical source identity and its semantic admission epoch. 59 /// 60 /// The epoch advances atomically on insertion or admission eligibility changes, 61 /// including changes that leave the event count unchanged. Duplicate admission 62 /// and provenance-only observations do not advance it. Zero denotes an empty 63 /// source. Tokens belong to their source generation; they are not timestamps. 64 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 65 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 66 pub struct EventSourceToken { 67 generation: SourceGeneration, 68 epoch: u64, 69 } 70 71 impl EventSourceToken { 72 /// Creates a source token from an owning provider's durable state. 73 pub const fn new(generation: SourceGeneration, epoch: u64) -> Self { 74 Self { generation, epoch } 75 } 76 77 /// Returns the source generation. 78 pub const fn generation(self) -> SourceGeneration { 79 self.generation 80 } 81 82 /// Returns the generation-local semantic mutation epoch. 83 pub const fn epoch(self) -> u64 { 84 self.epoch 85 } 86 } 87 88 /// Non-zero sequence within one source generation. 89 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 90 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 91 pub struct EventSequence(u64); 92 93 impl EventSequence { 94 /// Creates a non-zero source-local sequence. 95 pub const fn new(value: u64) -> Result<Self, Error> { 96 if value == 0 { 97 return Err(Error::InvalidEventSequence); 98 } 99 Ok(Self(value)) 100 } 101 102 /// Returns the source-local sequence. 103 pub const fn get(self) -> u64 { 104 self.0 105 } 106 } 107 108 /// Stable location of an event within one source generation. 109 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 110 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 111 pub struct EventPosition { 112 generation: SourceGeneration, 113 sequence: EventSequence, 114 } 115 116 impl EventPosition { 117 /// Creates a source position. 118 pub const fn new(generation: SourceGeneration, sequence: EventSequence) -> Self { 119 Self { 120 generation, 121 sequence, 122 } 123 } 124 125 /// Returns the source generation. 126 pub const fn generation(self) -> SourceGeneration { 127 self.generation 128 } 129 130 /// Returns the generation-local sequence. 131 pub const fn sequence(self) -> EventSequence { 132 self.sequence 133 } 134 } 135 136 /// Cursor after which a query resumes. 137 pub type EventCursor = EventPosition; 138 139 /// Validated bounds for a canonical event query. 140 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 141 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 142 pub struct EventQueryBounds { 143 limit: u16, 144 after: Option<EventCursor>, 145 } 146 147 impl EventQueryBounds { 148 /// Creates bounds for a first-page query. 149 pub const fn first(limit: u16) -> Result<Self, Error> { 150 if limit == 0 || limit > EVENT_QUERY_LIMIT_MAX { 151 return Err(Error::InvalidEventQueryLimit); 152 } 153 Ok(Self { limit, after: None }) 154 } 155 156 /// Resumes strictly after a prior cursor. 157 #[must_use] 158 pub const fn after(mut self, cursor: EventCursor) -> Self { 159 self.after = Some(cursor); 160 self 161 } 162 163 /// Returns the maximum number of records. 164 pub const fn limit(self) -> u16 { 165 self.limit 166 } 167 168 /// Returns the optional exclusive cursor. 169 pub const fn cursor(self) -> Option<EventCursor> { 170 self.after 171 } 172 } 173 174 /// Bounded event selection; an empty identifier set selects every event. 175 #[derive(Clone, Debug, Eq, PartialEq)] 176 pub struct EventQuery { 177 bounds: EventQueryBounds, 178 event_ids: Vec<EventId>, 179 } 180 181 impl EventQuery { 182 /// Selects all events under the supplied bounds. 183 pub const fn all(bounds: EventQueryBounds) -> Self { 184 Self { 185 bounds, 186 event_ids: Vec::new(), 187 } 188 } 189 190 /// Selects a bounded, duplicate-free set of event identifiers. 191 pub fn for_ids(bounds: EventQueryBounds, event_ids: Vec<EventId>) -> Result<Self, Error> { 192 if event_ids.is_empty() { 193 return Err(Error::EmptyEventQueryIds); 194 } 195 if event_ids.len() > EVENT_QUERY_ID_MAX { 196 return Err(Error::TooManyEventQueryIds); 197 } 198 let unique = event_ids.iter().collect::<BTreeSet<_>>(); 199 if unique.len() != event_ids.len() { 200 return Err(Error::DuplicateEventQueryId); 201 } 202 Ok(Self { bounds, event_ids }) 203 } 204 205 /// Returns the query bounds. 206 pub const fn bounds(&self) -> EventQueryBounds { 207 self.bounds 208 } 209 210 /// Returns the selected identifiers; empty means all. 211 pub fn event_ids(&self) -> &[EventId] { 212 self.event_ids.as_slice() 213 } 214 215 /// Reports whether an identifier is selected. 216 pub fn selects(&self, event_id: &EventId) -> bool { 217 self.event_ids.is_empty() || self.event_ids.contains(event_id) 218 } 219 } 220 221 /// Durable event admission stage. 222 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 223 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] 224 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] 225 pub enum AdmissionStage { 226 /// Structurally valid and ID-checked, but not signature verified. 227 Raw, 228 /// Canonical identifier and signature verified. 229 Verified, 230 /// Contract-admitted and visibility-authorized. 231 Visible, 232 } 233 234 /// One canonical event admission with exact transport provenance. 235 #[derive(Clone, Debug, Eq, PartialEq)] 236 pub struct EventAdmission { 237 observed: ObservedEvent, 238 state: AdmissionState, 239 } 240 241 #[derive(Clone, Debug, Eq, PartialEq)] 242 enum AdmissionState { 243 Raw, 244 Verified(VerifiedEvent), 245 Visible(VisibleEvent), 246 } 247 248 impl EventAdmission { 249 /// Retains an observed signed event without claiming signature verification. 250 pub const fn raw(observed: ObservedEvent) -> Self { 251 Self { 252 observed, 253 state: AdmissionState::Raw, 254 } 255 } 256 257 /// Retains a verified event after proving it matches the observed payload. 258 pub fn verified(observed: ObservedEvent, verified: VerifiedEvent) -> Result<Self, Error> { 259 if observed.event().envelope() != verified.event() { 260 return Err(Error::AdmissionEventMismatch); 261 } 262 Ok(Self { 263 observed, 264 state: AdmissionState::Verified(verified), 265 }) 266 } 267 268 /// Retains a visible event after proving it matches the observed payload. 269 pub fn visible(observed: ObservedEvent, visible: VisibleEvent) -> Result<Self, Error> { 270 if observed.event().envelope() != visible.event() { 271 return Err(Error::AdmissionEventMismatch); 272 } 273 Ok(Self { 274 observed, 275 state: AdmissionState::Visible(visible), 276 }) 277 } 278 279 /// Returns the durable stage represented by this admission. 280 pub const fn stage(&self) -> AdmissionStage { 281 match self.state { 282 AdmissionState::Raw => AdmissionStage::Raw, 283 AdmissionState::Verified(_) => AdmissionStage::Verified, 284 AdmissionState::Visible(_) => AdmissionStage::Visible, 285 } 286 } 287 288 /// Returns the exact observed signed event. 289 pub const fn event(&self) -> &SignedEvent { 290 self.observed.event() 291 } 292 293 /// Returns the event identifier. 294 pub fn event_id(&self) -> &EventId { 295 self.event().id() 296 } 297 298 /// Returns the transport observation attached to this admission. 299 pub const fn provenance(&self) -> &EventProvenance { 300 self.observed.provenance() 301 } 302 303 /// Returns the verified event when this admission reached verification. 304 pub const fn verified_event(&self) -> Option<&VerifiedEvent> { 305 match &self.state { 306 AdmissionState::Raw => None, 307 AdmissionState::Verified(event) => Some(event), 308 AdmissionState::Visible(event) => { 309 Some(event.admitted_event().validated_event().verified_event()) 310 } 311 } 312 } 313 314 /// Returns the visible event when visibility was authorized. 315 pub const fn visible_event(&self) -> Option<&VisibleEvent> { 316 match &self.state { 317 AdmissionState::Visible(event) => Some(event), 318 AdmissionState::Raw | AdmissionState::Verified(_) => None, 319 } 320 } 321 } 322 323 /// Persistence result for one idempotent admission. 324 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 325 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] 326 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 327 pub enum AdmissionDisposition { 328 Inserted, 329 Advanced, 330 Duplicate, 331 } 332 333 /// Request-bound durable admission receipt. 334 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 335 #[derive(Clone, Debug, Eq, PartialEq)] 336 pub struct AdmissionReceipt { 337 event_id: EventId, 338 position: EventPosition, 339 stage: AdmissionStage, 340 disposition: AdmissionDisposition, 341 } 342 343 impl AdmissionReceipt { 344 /// Creates a backend receipt from validated durable state. 345 pub const fn new( 346 event_id: EventId, 347 position: EventPosition, 348 stage: AdmissionStage, 349 disposition: AdmissionDisposition, 350 ) -> Self { 351 Self { 352 event_id, 353 position, 354 stage, 355 disposition, 356 } 357 } 358 359 pub const fn event_id(&self) -> &EventId { 360 &self.event_id 361 } 362 363 pub const fn position(&self) -> EventPosition { 364 self.position 365 } 366 367 pub const fn stage(&self) -> AdmissionStage { 368 self.stage 369 } 370 371 pub const fn disposition(&self) -> AdmissionDisposition { 372 self.disposition 373 } 374 } 375 376 /// Raw event returned from canonical storage. 377 #[derive(Clone, Debug, Eq, PartialEq)] 378 pub struct StoredRawEvent { 379 position: EventPosition, 380 event: SignedEvent, 381 stage: AdmissionStage, 382 } 383 384 impl StoredRawEvent { 385 pub const fn new(position: EventPosition, event: SignedEvent, stage: AdmissionStage) -> Self { 386 Self { 387 position, 388 event, 389 stage, 390 } 391 } 392 393 pub const fn position(&self) -> EventPosition { 394 self.position 395 } 396 397 pub const fn event(&self) -> &SignedEvent { 398 &self.event 399 } 400 401 pub const fn stage(&self) -> AdmissionStage { 402 self.stage 403 } 404 } 405 406 /// Canonical event returned with durable signature-verification evidence. 407 /// 408 /// The signed event is returned rather than forging an in-memory verification 409 /// typestate from persisted bytes. [`EventStore`] guarantees that only records 410 /// durably admitted at [`AdmissionStage::Verified`] or later appear here. 411 #[derive(Clone, Debug, Eq, PartialEq)] 412 pub struct StoredVerifiedEvent { 413 position: EventPosition, 414 event: SignedEvent, 415 } 416 417 impl StoredVerifiedEvent { 418 pub const fn new(position: EventPosition, event: SignedEvent) -> Self { 419 Self { position, event } 420 } 421 422 pub const fn position(&self) -> EventPosition { 423 self.position 424 } 425 426 pub const fn event(&self) -> &SignedEvent { 427 &self.event 428 } 429 } 430 431 /// Canonical event returned with durable visibility evidence. 432 /// 433 /// The signed event is returned rather than rerunning a host authorization 434 /// policy during a storage read. [`EventStore`] guarantees that only records 435 /// durably admitted at [`AdmissionStage::Visible`] appear here. 436 #[derive(Clone, Debug, Eq, PartialEq)] 437 pub struct StoredVisibleEvent { 438 position: EventPosition, 439 event: SignedEvent, 440 } 441 442 /// Deterministic digest of one complete visibility rebuild. 443 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 444 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] 445 pub struct VisibilityDigest([u8; 32]); 446 447 impl VisibilityDigest { 448 /// Returns the canonical SHA-256 bytes for the rebuilt visibility state. 449 pub const fn as_bytes(&self) -> &[u8; 32] { 450 &self.0 451 } 452 453 pub(crate) const fn new(bytes: [u8; 32]) -> Self { 454 Self(bytes) 455 } 456 } 457 458 /// Complete deterministic result of rebuilding current event visibility. 459 /// 460 /// Current heads remain listed even when their selected event is suppressed. 461 /// This prevents a deleted head from resurrecting an older revision. 462 #[derive(Clone, Debug, Eq, PartialEq)] 463 pub struct VisibilitySnapshot { 464 generation: SourceGeneration, 465 current_heads: Vec<radroots_event::envelope::event_head::CurrentEventHead>, 466 deletion_request_ids: Vec<EventId>, 467 visible_event_ids: Vec<EventId>, 468 suppressed_event_ids: Vec<EventId>, 469 superseded_event_ids: Vec<EventId>, 470 digest: VisibilityDigest, 471 } 472 473 impl VisibilitySnapshot { 474 pub(crate) const fn new( 475 generation: SourceGeneration, 476 current_heads: Vec<radroots_event::envelope::event_head::CurrentEventHead>, 477 deletion_request_ids: Vec<EventId>, 478 visible_event_ids: Vec<EventId>, 479 suppressed_event_ids: Vec<EventId>, 480 superseded_event_ids: Vec<EventId>, 481 digest: VisibilityDigest, 482 ) -> Self { 483 Self { 484 generation, 485 current_heads, 486 deletion_request_ids, 487 visible_event_ids, 488 suppressed_event_ids, 489 superseded_event_ids, 490 digest, 491 } 492 } 493 494 pub const fn generation(&self) -> SourceGeneration { 495 self.generation 496 } 497 498 pub fn current_heads(&self) -> &[radroots_event::envelope::event_head::CurrentEventHead] { 499 self.current_heads.as_slice() 500 } 501 502 pub fn deletion_request_ids(&self) -> &[EventId] { 503 self.deletion_request_ids.as_slice() 504 } 505 506 pub fn visible_event_ids(&self) -> &[EventId] { 507 self.visible_event_ids.as_slice() 508 } 509 510 pub fn suppressed_event_ids(&self) -> &[EventId] { 511 self.suppressed_event_ids.as_slice() 512 } 513 514 pub fn superseded_event_ids(&self) -> &[EventId] { 515 self.superseded_event_ids.as_slice() 516 } 517 518 pub const fn digest(&self) -> VisibilityDigest { 519 self.digest 520 } 521 } 522 523 impl StoredVisibleEvent { 524 pub const fn new(position: EventPosition, event: SignedEvent) -> Self { 525 Self { position, event } 526 } 527 528 pub const fn position(&self) -> EventPosition { 529 self.position 530 } 531 532 pub const fn event(&self) -> &SignedEvent { 533 &self.event 534 } 535 } 536 537 /// One bounded, generation-consistent page. 538 #[derive(Clone, Debug, Eq, PartialEq)] 539 pub struct EventPage<T> { 540 generation: SourceGeneration, 541 items: Vec<T>, 542 next: Option<EventCursor>, 543 } 544 545 impl<T> EventPage<T> { 546 /// Creates a page and enforces its caller-supplied item bound. 547 pub fn new( 548 generation: SourceGeneration, 549 items: Vec<T>, 550 next: Option<EventCursor>, 551 bounds: EventQueryBounds, 552 ) -> Result<Self, Error> { 553 if items.len() > usize::from(bounds.limit()) { 554 return Err(Error::EventPageLimitExceeded); 555 } 556 if let Some(cursor) = next 557 && cursor.generation() != generation 558 { 559 return Err(Error::CursorGenerationMismatch); 560 } 561 Ok(Self { 562 generation, 563 items, 564 next, 565 }) 566 } 567 568 pub const fn generation(&self) -> SourceGeneration { 569 self.generation 570 } 571 572 pub fn items(&self) -> &[T] { 573 self.items.as_slice() 574 } 575 576 pub const fn next_cursor(&self) -> Option<EventCursor> { 577 self.next 578 } 579 } 580 581 /// Provenance retained for one event observation. 582 #[derive(Clone, Debug, Eq, PartialEq)] 583 pub struct StoredEventProvenance { 584 position: EventPosition, 585 provenance: EventProvenance, 586 } 587 588 impl StoredEventProvenance { 589 pub const fn new(position: EventPosition, provenance: EventProvenance) -> Self { 590 Self { 591 position, 592 provenance, 593 } 594 } 595 596 pub const fn position(&self) -> EventPosition { 597 self.position 598 } 599 600 pub const fn provenance(&self) -> &EventProvenance { 601 &self.provenance 602 } 603 604 /// Reconstructs validated backend-neutral provenance from durable fields. 605 pub fn from_stored_parts( 606 position: EventPosition, 607 transport_id: &str, 608 target_fingerprint: &str, 609 observed_at_unix_ms: u64, 610 cursor: Option<&str>, 611 ) -> Result<Self, Error> { 612 let transport_id = 613 TransportId::parse(transport_id).map_err(|_| Error::CorruptStoredEvent)?; 614 let target = 615 TargetFingerprint::parse(target_fingerprint).map_err(|_| Error::CorruptStoredEvent)?; 616 let mut provenance = EventProvenance::new(transport_id, target, observed_at_unix_ms) 617 .map_err(|_| Error::CorruptStoredEvent)?; 618 if let Some(cursor) = cursor { 619 provenance = provenance 620 .with_cursor(FetchCursor::parse(cursor).map_err(|_| Error::CorruptStoredEvent)?); 621 } 622 Ok(Self::new(position, provenance)) 623 } 624 } 625 626 /// Backend-neutral canonical event storage SPI. 627 /// 628 /// Implementations are dyn-compatible and return native `Send` or browser-local futures. They may not 629 /// expose backend transactions, handles, SQL, or filesystem paths. Admission is 630 /// idempotent for an identical event and provenance observation; a stage may 631 /// advance but never regress. Query cursors are bound to one source generation. 632 pub trait EventStore: radroots_transport::host::HostBound { 633 /// Prepares one bounded, transactionally resumable canonical index chunk. 634 /// 635 /// Completion refers to canonical metadata at the returned source token, 636 /// not to any application projection. It never initiates a hidden task. 637 fn maintain_visibility( 638 &self, 639 _bounds: VisibilityIndexBounds, 640 ) -> BoxFuture<'_, Result<VisibilityIndexProgress, Error>> { 641 Box::pin(async { Err(Error::BackendUnavailable) }) 642 } 643 644 /// Reads the current source token without decoding retained event history. 645 /// 646 /// Providers that cannot supply this fence fail closed. SQLite epochs have 647 /// an `i64::MAX` storage ceiling; the memory provider uses `u64::MAX`. 648 fn source_token(&self) -> BoxFuture<'_, Result<EventSourceToken, Error>> { 649 Box::pin(async { Err(Error::BackendUnavailable) }) 650 } 651 652 /// Returns passive event-store status without initiating maintenance. 653 fn status(&self) -> BoxFuture<'_, Result<EventStoreStatus, Error>>; 654 655 /// Durably admits or advances one canonical event observation. 656 fn admit(&self, admission: EventAdmission) -> BoxFuture<'_, Result<AdmissionReceipt, Error>>; 657 658 /// Queries retained raw events. 659 fn query_raw( 660 &self, 661 query: EventQuery, 662 ) -> BoxFuture<'_, Result<EventPage<StoredRawEvent>, Error>>; 663 664 /// Queries signature-verified events. 665 fn query_verified( 666 &self, 667 query: EventQuery, 668 ) -> BoxFuture<'_, Result<EventPage<StoredVerifiedEvent>, Error>>; 669 670 /// Queries visibility-authorized events. 671 fn query_visible( 672 &self, 673 query: EventQuery, 674 ) -> BoxFuture<'_, Result<EventPage<StoredVisibleEvent>, Error>>; 675 676 /// Queries indexed visibility at exactly the expected canonical source fence. 677 /// 678 /// Compare the fence and hydrate the page in one consistent read. A mismatch 679 /// returns [`Error::SourceEpochChanged`]; unsupported providers fail closed. 680 fn query_visible_at( 681 &self, 682 _query: EventQuery, 683 _expected: EventSourceToken, 684 ) -> BoxFuture<'_, Result<EventPage<StoredVisibleEvent>, Error>> { 685 Box::pin(async { Err(Error::BackendUnavailable) }) 686 } 687 688 /// Rebuilds current visibility from immutable retained event truth. 689 /// 690 /// This explicit full diagnostic is the semantic oracle for indexed reads. 691 fn rebuild_visibility(&self) -> BoxFuture<'_, Result<VisibilitySnapshot, Error>>; 692 693 /// Queries bounded provenance for one event. 694 fn query_provenance( 695 &self, 696 event_id: EventId, 697 bounds: EventQueryBounds, 698 ) -> BoxFuture<'_, Result<EventPage<StoredEventProvenance>, Error>>; 699 }