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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
use crate::error::ObixFault;
use es_entity::errlanes::Laned;
use tokio::sync::{broadcast, mpsc, oneshot};
use std::sync::Arc;
use super::event::{EphemeralEventType, EphemeralOutboxEvent, RawPayload};
use crate::{
handle::{OwnedTaskHandle, spawn_supervised},
out::pg_notify::NotifyMessage,
};
pub(super) type CachedEvent = Arc<EphemeralOutboxEvent<RawPayload>>;
pub(super) type CachedEvents = im::HashMap<EphemeralEventType, CachedEvent>;
pub struct CacheHandle {
ephemeral_event_receiver: Option<broadcast::Receiver<CachedEvent>>,
backfill_request: mpsc::UnboundedSender<oneshot::Sender<CachedEvents>>,
}
impl CacheHandle {
pub fn ephemeral_event_stream(&mut self) -> broadcast::Receiver<CachedEvent> {
self.ephemeral_event_receiver
.take()
.expect("receiver already taken")
}
pub fn request_current_ephemeral_events(&self) -> oneshot::Receiver<CachedEvents> {
let (tx, rx) = oneshot::channel();
let _ = self.backfill_request.send(tx);
rx
}
}
#[derive(Debug)]
pub struct EphemeralOutboxEventCache<Tables> {
ephemeral_event_sender: broadcast::Sender<CachedEvent>,
backfill_request_send: mpsc::UnboundedSender<oneshot::Sender<CachedEvents>>,
cache_fill_sender: broadcast::Sender<CachedEvent>,
_cache_loop_handle: OwnedTaskHandle,
_phantom: std::marker::PhantomData<Tables>,
}
impl<Tables> EphemeralOutboxEventCache<Tables>
where
Tables: crate::tables::MailboxTables,
{
pub fn handle(&self) -> CacheHandle {
CacheHandle {
ephemeral_event_receiver: Some(self.ephemeral_event_sender.subscribe()),
backfill_request: self.backfill_request_send.clone(),
}
}
pub fn cache_fill_sender(&self) -> &broadcast::Sender<CachedEvent> {
&self.cache_fill_sender
}
pub async fn init(
pool: &sqlx::PgPool,
event_buffer_size: usize,
ephemeral_notification_rx: mpsc::Receiver<NotifyMessage>,
) -> Result<Self, sqlx::Error> {
let (backfill_send, backfill_recv) = mpsc::unbounded_channel();
let (cache_fill_send, cache_fill_recv) = broadcast::channel(event_buffer_size);
let (ephemeral_event_sender, _) = broadcast::channel(event_buffer_size);
let cache_loop_handle = Self::spawn_cache_loop(
pool,
ephemeral_event_sender.clone(),
backfill_recv,
cache_fill_recv,
cache_fill_send.clone(),
ephemeral_notification_rx,
)
.await?;
let ret = Self {
backfill_request_send: backfill_send,
ephemeral_event_sender,
cache_fill_sender: cache_fill_send,
_cache_loop_handle: cache_loop_handle,
_phantom: std::marker::PhantomData,
};
Ok(ret)
}
fn insert_into_cache_and_broadcast(
cache: CachedEvents,
event: CachedEvent,
ephemeral_event_sender: &broadcast::Sender<CachedEvent>,
) -> CachedEvents {
// Last-write-wins by recorded_at: notification-triggered fetches for
// the same event type can complete out of order — a strictly older
// event must never overwrite (or be broadcast after) a newer one.
if let Some(cached) = cache.get(&event.event_type)
&& cached.recorded_at > event.recorded_at
{
return cache;
}
let event_type = event.event_type.clone();
let cache = cache.update(event_type, event.clone());
let _ = ephemeral_event_sender.send(event);
cache
}
async fn fetch_event_by_type(
pool: sqlx::PgPool,
event_type: EphemeralEventType,
cache_fill_sender: broadcast::Sender<CachedEvent>,
) {
if let Ok(events) =
Tables::load_ephemeral_events::<RawPayload>(&pool, Some(event_type)).await
{
for event in events {
let _ = cache_fill_sender.send(Arc::new(event));
}
}
}
/// Handle a `{event_type, recorded_at}` notification hint.
///
/// The payload is NEVER taken from the notification body. PostgreSQL
/// performs no authorization on LISTEN/NOTIFY channels — any role able
/// to connect to this database can signal any channel — so a
/// notification is only ever a hint that something changed; the event
/// itself is always (re-)fetched from the table with this process's own
/// credentials. `recorded_at` bounds that fetch: when the in-process
/// cache already holds an event at least as recent (the publisher's
/// post-commit broadcast beat the NOTIFY), the hint is a no-op.
fn handle_notification(payload: &str, cache: &CachedEvents) -> Option<EphemeralEventType> {
#[derive(serde::Deserialize)]
struct NotificationHeader {
event_type: EphemeralEventType,
recorded_at: chrono::DateTime<chrono::Utc>,
}
let header: NotificationHeader = match serde_json::from_str(payload) {
Ok(header) => header,
Err(error) => {
record_notification_undecodable(&error);
return None;
}
};
let cache_is_current = cache
.get(&header.event_type)
.is_some_and(|cached| cached.recorded_at >= header.recorded_at);
if cache_is_current {
None
} else {
Some(header.event_type)
}
}
fn process_notification(
notification: sqlx::postgres::PgNotification,
cache: &CachedEvents,
) -> Option<EphemeralEventType> {
if notification.channel() == Tables::ephemeral_outbox_events_channel() {
Self::handle_notification(notification.payload(), cache)
} else {
None
}
}
async fn spawn_cache_loop(
pool: &sqlx::PgPool,
ephemeral_event_sender: broadcast::Sender<CachedEvent>,
mut backfill_request: mpsc::UnboundedReceiver<oneshot::Sender<CachedEvents>>,
mut cache_fill_receiver: broadcast::Receiver<CachedEvent>,
cache_fill_sender: broadcast::Sender<CachedEvent>,
mut ephemeral_notification_rx: mpsc::Receiver<NotifyMessage>,
) -> Result<OwnedTaskHandle, sqlx::Error> {
let pool = pool.clone();
let handle = spawn_supervised("obix::ephemeral_cache_loop", async move {
let mut ephemeral_cache: CachedEvents = im::HashMap::new();
loop {
tokio::select! {
biased;
result = backfill_request.recv() => {
match result {
Some(sender) => {
let _ = sender.send(ephemeral_cache.clone());
}
None => {
record_backfill_channel_closed();
break;
}
}
continue;
}
result = cache_fill_receiver.recv() => {
match result {
Ok(event) => {
ephemeral_cache = Self::insert_into_cache_and_broadcast(
ephemeral_cache,
event,
&ephemeral_event_sender,
);
while let Ok(event) = cache_fill_receiver.try_recv() {
ephemeral_cache = Self::insert_into_cache_and_broadcast(
ephemeral_cache,
event,
&ephemeral_event_sender,
);
}
}
Err(broadcast::error::RecvError::Lagged(n)) => {
record_cache_fill_lagged(n);
continue;
}
Err(broadcast::error::RecvError::Closed) => {
record_cache_fill_closed();
break;
}
}
}
result = ephemeral_notification_rx.recv() => {
match result {
Some(message) => {
let mut resync_needed = false;
let mut messages = vec![message];
// Process any additional buffered notifications
while let Ok(message) = ephemeral_notification_rx.try_recv() {
messages.push(message);
}
// Collect the unique event types that need a
// fetch. A burst of N notifications for the
// same type is drained against one cache
// snapshot (fetches are async, the cache is
// unchanged during the drain), so deduping
// here collapses them into a single fetch
// rather than N redundant broadcasts of the
// same latest event.
let mut types_to_fetch =
std::collections::HashSet::<EphemeralEventType>::new();
for message in messages {
match message {
NotifyMessage::Notification(notification) => {
if let Some(event_type) =
Self::process_notification(
notification,
&ephemeral_cache,
)
{
types_to_fetch.insert(event_type);
}
}
NotifyMessage::Resync => {
resync_needed = true;
}
}
}
for event_type in types_to_fetch {
tokio::spawn(Self::fetch_event_by_type(
pool.clone(),
event_type,
cache_fill_sender.clone(),
));
}
if resync_needed {
match Tables::load_ephemeral_events::<RawPayload>(&pool, None).await {
Ok(events) => {
for event in events {
let stale = ephemeral_cache
.get(&event.event_type)
.is_some_and(|cached| {
cached.recorded_at >= event.recorded_at
});
if !stale {
ephemeral_cache =
Self::insert_into_cache_and_broadcast(
ephemeral_cache,
Arc::new(event),
&ephemeral_event_sender,
);
}
}
}
Err(e) => {
record_resync_failed(e)
}
}
}
}
None => {
record_notification_channel_closed();
break;
}
}
}
}
}
});
Ok(OwnedTaskHandle::new(handle))
}
}
#[tracing::instrument(
name = "obix.ephemeral_cache.backfill_channel_closed",
level = "error",
fields(otel.status_code = "ERROR"),
)]
fn record_backfill_channel_closed() {}
#[tracing::instrument(
name = "obix.ephemeral_cache.cache_fill_lagged",
level = "error",
fields(otel.status_code = "ERROR"),
)]
fn record_cache_fill_lagged(dropped: u64) {}
#[tracing::instrument(
name = "obix.ephemeral_cache.cache_fill_closed",
level = "error",
fields(otel.status_code = "ERROR"),
)]
fn record_cache_fill_closed() {}
#[tracing::instrument(
name = "obix.ephemeral_cache.notification_channel_closed",
level = "error",
fields(otel.status_code = "ERROR"),
)]
fn record_notification_channel_closed() {}
#[tracing::instrument(
name = "obix.ephemeral_cache.resync_failed",
level = "error",
skip_all,
fields(
otel.status_code = "ERROR",
error = tracing::field::Empty,
error.lane = tracing::field::Empty,
error.code = tracing::field::Empty,
error.level = tracing::field::Empty,
exception.message = tracing::field::Empty,
exception.type = tracing::field::Empty,
),
)]
fn record_resync_failed(fault: impl Into<ObixFault>) {
fault.into().record(&tracing::Span::current());
}
#[tracing::instrument(
name = "obix.ephemeral_cache.notification_undecodable",
level = "warn",
skip_all,
fields(error = %error),
)]
fn record_notification_undecodable(error: &serde_json::Error) {}