1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
use std::num::NonZeroUsize;
use bincode::{Decode, Encode};
use redb::ReadableTable as _;
use rostra_core::event::{EventExt as _, EventKind, content_kind};
use rostra_core::{ExternalEventId, ShortEventId, Timestamp};
use serde::{Deserialize, Serialize};
use snafu::OptionExt as _;
use crate::event::ContentStoreRecord;
use crate::{
Database, DbResult, EventContentState, OverflowSnafu, WriteTransactionCtx, content_store,
events, events_content_state, social_post_materializations, social_posts_replaced_by,
};
/// Maximum number of materialization rows resolved by one scan.
pub const SOCIAL_POST_MATERIALIZATION_SCAN_MAX: usize = 4_096;
/// Opaque durable position in one database lineage's SocialPost materialization
/// feed.
///
/// Persist this value only after durably handling every item in its page, then
/// pass it back to resume. A cursor belongs to the database lineage that issued
/// it. A faithful backup carrying the same feed prefix retains its meaning;
/// divergent copies and unrelated databases do not. Restoring a database older
/// than the cursor fails as out of range.
#[derive(
Clone, Copy, Debug, Decode, Deserialize, Encode, Eq, Ord, PartialEq, PartialOrd, Serialize,
)]
#[serde(transparent)]
pub struct SocialPostMaterializationCursor(u64);
/// Current high-level state of one logged ordinary SocialPost materialization.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SocialPostMaterialization {
/// The materialized post remains current and its validated content is
/// available.
Present {
/// Immutable author and event identity.
post_id: ExternalEventId,
/// Author-provided creation timestamp.
authored_at: Timestamp,
/// Currently available validated post content.
content: Box<content_kind::SocialPost>,
},
/// The post was later deleted, pruned, or replaced.
Removed {
/// Immutable author and event identity of the original occurrence.
post_id: ExternalEventId,
},
}
/// One bounded snapshot page from the ordinary SocialPost materialization feed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SocialPostMaterializationPage {
/// Occurrences resolved against current state in the page's read snapshot.
pub items: Vec<SocialPostMaterialization>,
/// Position acknowledging every occurrence before this cursor.
pub scanned_through: SocialPostMaterializationCursor,
/// Whether the same read snapshot contained no later occurrence.
pub exhausted: bool,
}
impl Database {
pub(crate) fn append_social_post_materialization_tx(
event_id: ShortEventId,
tx: &WriteTransactionCtx,
) -> DbResult<()> {
if !tx.materialization_emission_enabled() {
return Ok(());
}
let mut table = tx.open_table(&social_post_materializations::TABLE)?;
let next = {
let last = table.as_raw().last()?;
Self::social_post_materialization_next_sequence(
last.as_ref().map(|entry| entry.0.value()),
)?
};
if next == u64::MAX {
return OverflowSnafu.fail();
}
table.insert(&next, &event_id)?;
Ok(())
}
/// Gets a cursor at the current tip of the SocialPost materialization feed.
///
/// The cursor denotes the next sequence in one read snapshot. Establishing
/// that snapshot is the consumer-enablement linearization point: every
/// occurrence visible before the tip is acknowledged by the cursor, while
/// an occurrence committed after the snapshot has a sequence at or after
/// the cursor and remains discoverable by a later scan. A commit concurrent
/// with this call may fall on either side of that boundary.
///
/// This reads only the feed's last key; it does not enumerate or resolve
/// feed rows. An empty feed returns the sequence-zero cursor.
///
/// # Errors
///
/// Returns an error on storage, key decode, or sequence overflow.
pub async fn get_social_post_materialization_tip(
&self,
) -> DbResult<SocialPostMaterializationCursor> {
self.read_with(|tx| {
let feed = tx.open_table(&social_post_materializations::TABLE)?;
let last = feed.as_raw().last()?;
let next = Self::social_post_materialization_next_sequence(
last.as_ref().map(|entry| entry.0.value()),
)?;
Ok(SocialPostMaterializationCursor(next))
})
.await
}
/// Scans ordinary SocialPost materializations in commit order.
///
/// `after` is an opaque position acknowledging every earlier occurrence.
/// `None` starts at this database lineage's cutover position zero. The
/// schema upgrade does not backfill posts materialized by older code.
///
/// Each logged identity is resolved against one current-state read
/// snapshot. Later deletion, pruning, or replacement yields
/// [`SocialPostMaterialization::Removed`]; a currently available post
/// yields [`SocialPostMaterialization::Present`]. Log rows remain
/// append-only either way. `limit` bounds rows resolved, and the
/// implementation performs at most one additional key lookahead to
/// determine snapshot-relative exhaustion.
///
/// A replaced post is still required to have a coherent lifecycle. If that
/// lifecycle claims the content remains processed, retained bytes must be
/// present and decodable. Corruption takes precedence over `Removed`.
///
/// # Errors
///
/// Returns no page or acknowledgment on storage, decode, cursor, density,
/// or current-state invariant errors.
pub async fn scan_social_post_materializations(
&self,
after: Option<SocialPostMaterializationCursor>,
limit: NonZeroUsize,
) -> DbResult<SocialPostMaterializationPage> {
if SOCIAL_POST_MATERIALIZATION_SCAN_MAX < limit.get() {
return Err(crate::DbError::SocialPostMaterializationScanLimitTooHigh {
requested: limit.get(),
maximum: SOCIAL_POST_MATERIALIZATION_SCAN_MAX,
});
}
self.read_with(|tx| {
let feed = tx.open_table(&social_post_materializations::TABLE)?;
let last = feed.as_raw().last()?;
let durable_next = Self::social_post_materialization_next_sequence(
last.as_ref().map(|entry| entry.0.value()),
)?;
let mut expected = after.map_or(0, |cursor| cursor.0);
if durable_next < expected {
return crate::SocialPostMaterializationCursorOutOfRangeSnafu {
position: expected,
durable_next,
}
.fail();
}
let events_table = tx.open_table(&events::TABLE)?;
let states = tx.open_table(&events_content_state::TABLE)?;
let content = tx.open_table(&content_store::TABLE)?;
let replacements = tx.open_table(&social_posts_replaced_by::TABLE)?;
let mut range = feed.range(expected..)?;
let mut items = Vec::with_capacity(limit.get());
for _ in 0..limit.get() {
let Some(entry) = range.next() else {
return Ok(SocialPostMaterializationPage {
items,
scanned_through: SocialPostMaterializationCursor(expected),
exhausted: true,
});
};
let (sequence, event_id) = entry?;
let actual = sequence.value_try()?;
if actual != expected {
return crate::SocialPostMaterializationLogGapSnafu { expected, actual }.fail();
}
let event_id = event_id.value_try()?;
items.push(Self::resolve_social_post_materialization_tx(
event_id,
&events_table,
&states,
&content,
&replacements,
)?);
expected = expected.checked_add(1).context(OverflowSnafu)?;
}
let exhausted = match range.next().transpose()? {
None => true,
Some((sequence, _)) => {
let actual = sequence.value_try()?;
if actual != expected {
return crate::SocialPostMaterializationLogGapSnafu { expected, actual }
.fail();
}
false
}
};
Ok(SocialPostMaterializationPage {
items,
scanned_through: SocialPostMaterializationCursor(expected),
exhausted,
})
})
.await
}
fn social_post_materialization_next_sequence(last_key: Option<&[u8]>) -> DbResult<u64> {
let Some(last_key) = last_key else {
return Ok(0);
};
let (last, consumed) =
bincode::decode_from_slice::<u64, _>(last_key, redb_bincode::BINCODE_CONFIG)?;
if consumed != last_key.len() {
return Err(
bincode::error::DecodeError::Other("Trailing bytes after encoded value").into(),
);
}
last.checked_add(1).context(OverflowSnafu)
}
fn resolve_social_post_materialization_tx(
event_id: ShortEventId,
events_table: &impl events::ReadableTable,
states: &impl events_content_state::ReadableTable,
content: &impl content_store::ReadableTable,
replacements: &impl social_posts_replaced_by::ReadableTable,
) -> DbResult<SocialPostMaterialization> {
let event = events_table
.get(&event_id)?
.map(|entry| entry.value_try())
.transpose()?
.context(crate::MissingSocialPostMaterializationEventSnafu { event_id })?;
if event.kind() != EventKind::SOCIAL_POST {
return crate::InvalidSocialPostMaterializationKindSnafu {
event_id,
kind: event.kind(),
}
.fail();
}
let post_id = ExternalEventId::new(event.author(), event_id);
match Self::get_event_content_state_tx(event_id, states)? {
Some(EventContentState::Deleted { .. } | EventContentState::Pruned) => {
return Ok(SocialPostMaterialization::Removed { post_id });
}
Some(EventContentState::Missing { .. }) => {
return crate::MissingSocialPostMaterializationStateSnafu { event_id }.fail();
}
Some(EventContentState::Invalid) => {
return crate::InvalidSocialPostMaterializationStateSnafu { event_id }.fail();
}
None => {}
}
let ContentStoreRecord(raw) = content
.get(&event.content_hash())?
.map(|entry| entry.value_try())
.transpose()?
.context(crate::MissingSocialPostMaterializationContentSnafu { event_id })?;
let content = raw
.deserialize_cbor::<content_kind::SocialPost>()
.map_err(
|source| crate::DbError::InvalidSocialPostMaterializationContent {
event_id,
source: Box::new(source),
},
)?;
if Self::is_social_post_replaced_tx(event.author(), event_id, replacements)? {
return Ok(SocialPostMaterialization::Removed { post_id });
}
Ok(SocialPostMaterialization::Present {
post_id,
authored_at: event.timestamp(),
content: Box::new(content),
})
}
}