rostra_client_db/tables/event.rs
1//! Event-related database record types.
2//!
3//! Events in Rostra form a DAG (Directed Acyclic Graph) where each event
4//! references parent events. The event "envelope" (metadata + signature) is
5//! stored separately from the event "content" (payload) to allow content
6//! pruning while maintaining DAG integrity.
7
8use std::borrow::Cow;
9
10use bincode::{Decode, Encode};
11use rostra_core::event::{EventContentRaw, EventContentUnsized, EventExt, SignedEvent};
12use rostra_core::{ExternalEventId, ShortEventId, Timestamp};
13use serde::Serialize;
14
15/// Record for the main `events` table.
16///
17/// Contains the signed event envelope (metadata + signature). The actual
18/// content is stored separately in `content_store`.
19#[derive(Debug, Encode, Decode, Clone, Serialize)]
20pub struct EventRecord {
21 /// The signed event (includes event metadata and cryptographic signature)
22 pub signed: SignedEvent,
23}
24
25impl EventExt for EventRecord {
26 fn event(&self) -> &rostra_core::event::Event {
27 self.signed.event()
28 }
29}
30
31/// Record for the `events_missing` table.
32///
33/// When we receive an event that references a parent we don't have, we create
34/// a "missing" record for that parent. This drives sync to fetch the missing
35/// event.
36#[derive(Decode, Encode, Debug)]
37pub struct EventsMissingRecord {
38 /// If set, a content deletion event was received before the actual event.
39 ///
40 /// When the missing event is finally received, its content should be
41 /// marked as deleted immediately rather than processed normally.
42 ///
43 /// Multiple direct deleters are merged by maximum
44 /// `(event.timestamp, ShortEventId)`. An ordinary child cannot erase
45 /// existing deletion attribution.
46 pub deleted_by: Option<ShortEventId>,
47}
48
49/// Marker record for the `events_heads` table.
50///
51/// The key `(author, event_id)` identifies the head; this empty struct just
52/// marks its existence. A "head" is an event with no known children - the
53/// current tip of the DAG for that author.
54#[derive(Decode, Encode, Debug)]
55pub struct EventsHeadsTableRecord;
56
57/// Authoritative value retained for a social-vote singleton winner.
58#[derive(Debug, Encode, Decode, Clone, Copy, PartialEq, Eq, Serialize)]
59pub enum SocialVoteValue {
60 /// A vote against the target.
61 Down,
62 /// No vote for or against the target.
63 Neutral,
64 /// A vote for the target.
65 Up,
66}
67
68impl SocialVoteValue {
69 /// Return the vote's contribution to the target's aggregate.
70 pub fn score(self) -> i64 {
71 match self {
72 Self::Down => -1,
73 Self::Neutral => 0,
74 Self::Up => 1,
75 }
76 }
77
78 /// Return the public optional-boolean representation.
79 pub fn as_upvote(self) -> Option<bool> {
80 match self {
81 Self::Down => Some(false),
82 Self::Neutral => None,
83 Self::Up => Some(true),
84 }
85 }
86}
87
88impl From<Option<bool>> for SocialVoteValue {
89 fn from(upvote: Option<bool>) -> Self {
90 match upvote {
91 Some(false) => Self::Down,
92 None => Self::Neutral,
93 Some(true) => Self::Up,
94 }
95 }
96}
97
98/// Authoritative current projection retained for a social-vote winner.
99#[derive(Debug, Encode, Decode, Clone, Copy, PartialEq, Eq, Serialize)]
100pub struct SocialVoteProjection {
101 /// Full post identity needed to disambiguate equal shortened event IDs.
102 pub target: ExternalEventId,
103 /// Winner's contribution to the target aggregate.
104 pub value: SocialVoteValue,
105}
106
107/// Record for singleton event tables (`events_singletons`,
108/// `events_singletons_new`).
109///
110/// All singleton records retain their source ID for deterministic ordering and
111/// attribution. Social-vote records also retain their authoritative current
112/// full-target/value projection so incremental updates do not depend on
113/// GC-eligible source content.
114#[derive(Debug, Encode, Decode, Clone, Serialize)]
115pub struct EventSingletonRecord {
116 /// The event ID of the latest singleton event.
117 pub event_id: ShortEventId,
118 /// Current vote projection for a well-shaped vote; absent for other kinds.
119 ///
120 /// Every retained `SOCIAL_VOTE` winner must contain `Some`, and every other
121 /// singleton kind must contain `None`; either opposite is corruption. A
122 /// retained target's shortened event ID must also equal its row auxiliary
123 /// key.
124 pub social_vote: Option<SocialVoteProjection>,
125}
126
127impl super::LatestEventValue for EventSingletonRecord {
128 fn event_id(&self) -> ShortEventId {
129 self.event_id
130 }
131}
132
133// ============================================================================
134// Content Deduplication Types (V1)
135//
136// These types support storing content by hash for deduplication across events.
137// ============================================================================
138
139/// Content stored in the `content_store` table, keyed by ContentHash.
140///
141/// This enables content deduplication - identical content (e.g., the same
142/// image posted by multiple users) is stored only once.
143#[derive(Debug, Encode, Decode, Clone, Serialize)]
144pub struct ContentStoreRecord<'a>(pub Cow<'a, EventContentUnsized>);
145
146/// Owned record for the `content_store` table.
147pub type ContentStoreRecordOwned = ContentStoreRecord<'static>;
148
149/// Per-event content processing state stored in `events_content_state` table.
150///
151/// This enum tracks the content processing lifecycle for each event:
152///
153/// ## State Transitions
154///
155/// ```text
156/// Event inserted ──► Missing ──► (no entry) ──► Deleted/Pruned
157/// │ │
158/// │ └─ Content processed successfully
159/// │ (side effects applied)
160/// │
161/// ├─ Can also go directly to Deleted/Pruned
162/// │
163/// └─► Invalid ──► Deleted
164/// ```
165///
166/// Note: Events with `content_len == 0` skip the `Missing` state entirely. They
167/// go straight to "no entry" (processed) unless they start in `Deleted`.
168///
169/// ## Interpretation
170///
171/// - **No entry in table**: Content has been processed for this event. This is
172/// the normal state after successful content processing. Side effects (reply
173/// counts, follow updates, etc.) have been applied. Also the state for events
174/// with no content (`content_len == 0`) unless they start in `Deleted`.
175///
176/// - **`Missing`**: Event was inserted but content hasn't been received or
177/// processed yet. The event's content side effects have NOT been applied.
178///
179/// - **`Invalid`**: Content was received but failed validation (e.g. CBOR
180/// deserialization). RC has been decremented. Content bytes are discarded.
181///
182/// - **`Deleted` / `Pruned`**: Content is unwanted. RC has been decremented. An
183/// eligible Deleted social-post edit may still contribute immutable
184/// replacement metadata without ordinary content processing.
185///
186/// ## Idempotency Guarantee
187///
188/// The `Missing` state ensures content processing is idempotent:
189/// - `process_event_content_tx` checks for `Missing` before processing
190/// - If `Missing` → process content, then remove the marker
191/// - If no entry → skip (already processed)
192/// - If `Deleted`/`Pruned`/`Invalid` → skip ordinary processing; the narrow
193/// Deleted social-post lineage exception remains idempotent table insertion
194///
195/// This prevents duplicate side effects (e.g., incrementing reply_count twice)
196/// when the same content is received multiple times for the same event.
197#[derive(Debug, Encode, Decode, Clone, Copy, Serialize, PartialEq, Eq)]
198pub enum EventContentState {
199 /// Content has not been received/processed yet for this event.
200 ///
201 /// This state is set when an event with `content_len > 0` is inserted
202 /// (in `insert_event_tx`). Events with `content_len == 0` skip this state,
203 /// going directly to processed or `Deleted`.
204 ///
205 /// When `process_event_content_tx` runs and sees this state:
206 /// 1. It processes the content (applies side effects)
207 /// 2. Stores content in `content_store` if not already there
208 /// 3. Removes this `Missing` marker (deletes entry from table)
209 ///
210 /// After processing, the event will have NO entry in
211 /// `events_content_state`, indicating content was successfully
212 /// processed.
213 ///
214 /// When the event has a current `events_content_missing` row, the
215 /// `next_fetch_attempt` field mirrors the `Timestamp` component of that
216 /// canonical at-most-one `(Timestamp, ShortEventId)` key, enabling removal
217 /// from the table (which requires the full composite key).
218 Missing {
219 /// When we last attempted to fetch this content from peers.
220 last_fetch_attempt: Option<Timestamp>,
221 /// Number of times we've attempted to fetch this content.
222 fetch_attempt_count: u16,
223 /// Scheduled time for next fetch attempt.
224 next_fetch_attempt: Timestamp,
225 },
226
227 /// Content was deleted by the author via a deletion event.
228 ///
229 /// When a deletion event targets this event's content:
230 /// - This state is set with a reference to the deleting event
231 /// - RC is decremented in `content_rc`
232 /// - Content may be garbage collected if RC reaches 0
233 Deleted {
234 /// Canonical direct deleter: maximum
235 /// `(event.timestamp, ShortEventId)`.
236 deleted_by: ShortEventId,
237 },
238
239 /// Content was pruned locally (e.g., too large to store).
240 ///
241 /// Unlike `Deleted`, this is a local decision, not an author request.
242 /// Used when content exceeds size limits or for storage management.
243 Pruned,
244
245 /// Content was received but failed validation.
246 ///
247 /// The content bytes could not be deserialized for the event's kind.
248 /// RC has been decremented and content bytes are not stored.
249 /// A later author deletion can supersede this with `Deleted` without
250 /// another RC decrement.
251 Invalid,
252}
253
254/// Result of looking up event content.
255///
256/// This is returned by `get_event_content_full_tx` and combines the per-event
257/// state with the actual content from the content store.
258#[derive(Debug, Clone)]
259pub enum EventContentResult {
260 /// Content is present and valid
261 Present(EventContentRaw),
262 /// Content was received but failed validation
263 Invalid,
264 /// Content was deleted by the author
265 Deleted {
266 /// The event that requested this content be deleted
267 deleted_by: ShortEventId,
268 },
269 /// Content was pruned locally
270 Pruned,
271 /// Content is not in the store (check events_content_missing)
272 Missing,
273}
274
275impl EventContentResult {
276 /// Returns the content if present and valid.
277 pub fn content(&self) -> Option<&EventContentRaw> {
278 match self {
279 EventContentResult::Present(c) => Some(c),
280 _ => None,
281 }
282 }
283
284 /// Returns true if content is present and valid.
285 pub fn is_present(&self) -> bool {
286 matches!(self, EventContentResult::Present(_))
287 }
288
289 /// Returns true if content was deleted.
290 pub fn is_deleted(&self) -> bool {
291 matches!(self, EventContentResult::Deleted { .. })
292 }
293}
294
295// ============================================================================
296// Event Reception Tracking (V6)
297//
298// These types track when and how we received each event.
299// ============================================================================
300
301use rostra_core::event::IrohNodeId;
302use rostra_core::id::RostraId;
303
304/// How we acquired an event.
305///
306/// Tracks the source and method by which we received an event, useful for
307/// debugging sync issues, understanding network propagation, and analytics.
308#[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, Serialize)]
309pub enum EventReceivedSource {
310 /// Event was backfilled during a database migration.
311 ///
312 /// For events that existed before we started tracking reception info.
313 Migration,
314
315 /// Event was pushed to us by a peer.
316 Pushed {
317 /// The identity that sent us this event (if known).
318 from_id: Option<RostraId>,
319 /// The iroh node that sent us this event (if known).
320 from_node: Option<IrohNodeId>,
321 },
322
323 /// We actively pulled/requested this event.
324 Pulled {
325 /// The identity we pulled from (if known).
326 from_id: Option<RostraId>,
327 /// The iroh node we pulled from (if known).
328 from_node: Option<IrohNodeId>,
329 /// Description of the task/query that triggered this pull.
330 task: Option<String>,
331 },
332
333 /// Event was created locally by this node.
334 Local,
335}
336
337/// Information about when and how we received an event.
338///
339/// Stored in the `events_received_at` table, keyed by `(Timestamp,
340/// reception_order)`.
341///
342/// The key `(Timestamp, u64)` is allocated durably from the database-local
343/// reception sequence. Insertion fails without replacement if the key is
344/// occupied. The event ID is stored in the value for lookup.
345#[derive(Debug, Encode, Decode, Clone, Serialize)]
346pub struct EventReceivedRecord {
347 /// The event that was received.
348 pub event_id: ShortEventId,
349 /// How we acquired this event.
350 pub source: EventReceivedSource,
351}