sockudo-core 4.6.0

Core traits, types, error handling, and configuration for Sockudo
Documentation
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use super::types::*;
use crate::error::Result;
use crate::history::now_ms;
use crate::versioned_messages::MessageSerial;
use async_trait::async_trait;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use tokio::sync::RwLock;

#[derive(Clone, Default)]
pub struct MemoryAnnotationStore {
    pub(super) state: Arc<RwLock<MemoryAnnotationState>>,
}

#[derive(Default)]
pub(super) struct MemoryAnnotationState {
    pub(super) events_by_projection:
        BTreeMap<String, BTreeMap<AnnotationSerial, StoredAnnotationEvent>>,
    pub(super) raw_by_channel: BTreeMap<String, BTreeMap<AnnotationSerial, StoredAnnotationEvent>>,
    pub(super) projections: BTreeMap<String, StoredAnnotationProjection>,
}

impl MemoryAnnotationStore {
    pub fn new() -> Self {
        Self::default()
    }

    pub(super) fn channel_key(app_id: &str, channel_id: &str) -> String {
        format!("{app_id}\0{channel_id}")
    }

    fn projection_key(
        app_id: &str,
        channel_id: &str,
        message_serial: &MessageSerial,
        annotation_type: &AnnotationType,
    ) -> String {
        format!(
            "{}\0{}\0{}",
            Self::channel_key(app_id, channel_id),
            message_serial.as_str(),
            annotation_type.as_str()
        )
    }

    fn request_projection_key(request: &AnnotationProjectionRequest) -> String {
        Self::projection_key(
            &request.app_id,
            &request.channel_id,
            &request.message_serial,
            &request.annotation_type,
        )
    }

    pub(super) fn event_projection_key(record: &StoredAnnotationEvent) -> String {
        Self::projection_key(
            &record.app_id,
            &record.channel_id,
            record.message_serial(),
            record.annotation_type(),
        )
    }

    fn projection_max_serial(
        state: &MemoryAnnotationState,
        projection_key: &str,
    ) -> Option<AnnotationSerial> {
        state
            .events_by_projection
            .get(projection_key)
            .and_then(|events| events.keys().next_back().cloned())
    }

    fn projection_events(
        state: &MemoryAnnotationState,
        projection_key: &str,
    ) -> Vec<StoredAnnotationEvent> {
        state
            .events_by_projection
            .get(projection_key)
            .map(|events| events.values().cloned().collect())
            .unwrap_or_default()
    }

    fn build_projection(
        request: &AnnotationProjectionRequest,
        events: Vec<StoredAnnotationEvent>,
        options: AnnotationProjectionOptions,
    ) -> Result<StoredAnnotationProjection> {
        let projection = AnnotationProjection::rebuild_with_options(
            request.channel_id.clone(),
            request.message_serial.clone(),
            request.annotation_type.clone(),
            events.into_iter().map(|record| record.annotation),
            options,
        )?;
        Ok(StoredAnnotationProjection::from_projection(
            request.app_id.clone(),
            projection,
        ))
    }

    fn rebuild_projection_from_state(
        state: &mut MemoryAnnotationState,
        request: AnnotationProjectionRequest,
        options: AnnotationProjectionOptions,
    ) -> Result<StoredAnnotationProjection> {
        let projection_key = Self::request_projection_key(&request);
        let events = Self::projection_events(state, &projection_key);
        let stored = Self::build_projection(&request, events, options)?;
        state.projections.insert(projection_key, stored.clone());
        Ok(stored)
    }

    async fn rebuild_projection_optimistic(
        &self,
        request: AnnotationProjectionRequest,
        options: AnnotationProjectionOptions,
    ) -> Result<StoredAnnotationProjection> {
        request.validate()?;
        let projection_key = Self::request_projection_key(&request);

        loop {
            let (events, expected_last_serial) = {
                let state = self.state.read().await;
                (
                    Self::projection_events(&state, &projection_key),
                    Self::projection_max_serial(&state, &projection_key),
                )
            };

            let projection = Self::build_projection(&request, events, options)?;
            let mut state = self.state.write().await;
            let current_last_serial = Self::projection_max_serial(&state, &projection_key);
            if current_last_serial == expected_last_serial {
                state
                    .projections
                    .insert(projection_key.clone(), projection.clone());
                return Ok(projection);
            }
        }
    }
}

#[async_trait]
impl AnnotationStore for MemoryAnnotationStore {
    async fn append_event(
        &self,
        mut record: StoredAnnotationEvent,
    ) -> Result<StoredAnnotationProjection> {
        record.validate()?;
        if record.stored_at_ms == 0 {
            record.stored_at_ms = now_ms();
        }

        let projection_request = AnnotationProjectionRequest {
            app_id: record.app_id.clone(),
            channel_id: record.channel_id.clone(),
            message_serial: record.message_serial().clone(),
            annotation_type: record.annotation_type().clone(),
        };
        let projection_key = Self::event_projection_key(&record);
        let channel_key = Self::channel_key(&record.app_id, &record.channel_id);

        {
            let mut state = self.state.write().await;
            let events = state
                .events_by_projection
                .entry(projection_key)
                .or_default();
            events
                .entry(record.annotation_serial().clone())
                .or_insert_with(|| record.clone());
            state
                .raw_by_channel
                .entry(channel_key)
                .or_default()
                .entry(record.annotation_serial().clone())
                .or_insert(record);
        }

        self.rebuild_projection_optimistic(
            projection_request,
            AnnotationProjectionOptions::default(),
        )
        .await
    }

    async fn get_events(
        &self,
        request: AnnotationEventsRequest,
    ) -> Result<Vec<StoredAnnotationEvent>> {
        request.validate()?;
        let key = Self::projection_key(
            &request.app_id,
            &request.channel_id,
            &request.message_serial,
            &request.annotation_type,
        );
        let state = self.state.read().await;
        Ok(state
            .events_by_projection
            .get(&key)
            .map(|events| events.values().cloned().collect())
            .unwrap_or_default())
    }

    async fn replay_raw(
        &self,
        request: RawAnnotationReplayRequest,
    ) -> Result<Vec<StoredAnnotationEvent>> {
        request.validate()?;
        let key = Self::channel_key(&request.app_id, &request.channel_id);
        let state = self.state.read().await;
        let Some(events) = state.raw_by_channel.get(&key) else {
            return Ok(Vec::new());
        };

        let items = events
            .iter()
            .filter(|(serial, _)| {
                request
                    .after_annotation_serial
                    .as_ref()
                    .is_none_or(|after| *serial > after)
            })
            .map(|(_, record)| record.clone())
            .take(request.limit)
            .collect();
        Ok(items)
    }

    async fn get_event_by_serial(
        &self,
        request: AnnotationEventLookupRequest,
    ) -> Result<Option<StoredAnnotationEvent>> {
        request.validate()?;
        let key = Self::channel_key(&request.app_id, &request.channel_id);
        let state = self.state.read().await;
        Ok(state
            .raw_by_channel
            .get(&key)
            .and_then(|events| events.get(&request.annotation_serial).cloned()))
    }

    async fn get_projection(
        &self,
        request: AnnotationProjectionRequest,
    ) -> Result<Option<StoredAnnotationProjection>> {
        request.validate()?;
        let key = Self::request_projection_key(&request);
        let state = self.state.read().await;
        let projection = state.projections.get(&key).cloned();
        let max_serial = Self::projection_max_serial(&state, &key);
        if projection
            .as_ref()
            .is_some_and(|projection| projection.last_annotation_serial == max_serial)
        {
            return Ok(projection);
        }
        if projection.is_none() && max_serial.is_none() {
            return Ok(None);
        }
        drop(state);

        self.rebuild_projection_optimistic(request, AnnotationProjectionOptions::default())
            .await
            .map(Some)
    }

    async fn list_projections_for_channel(
        &self,
        request: AnnotationProjectionsForChannelRequest,
    ) -> Result<Vec<StoredAnnotationProjection>> {
        let (projections, _) = self
            .list_projections_for_channel_with_rebuild_count(request)
            .await?;
        Ok(projections)
    }

    async fn list_projections_for_channel_with_rebuild_count(
        &self,
        request: AnnotationProjectionsForChannelRequest,
    ) -> Result<(Vec<StoredAnnotationProjection>, usize)> {
        request.validate()?;
        let requests = {
            let state = self.state.read().await;
            let mut requests = BTreeMap::new();
            for events in state.events_by_projection.values() {
                let Some(record) = events.values().next() else {
                    continue;
                };
                if record.app_id == request.app_id && record.channel_id == request.channel_id {
                    let projection_request = AnnotationProjectionRequest {
                        app_id: record.app_id.clone(),
                        channel_id: record.channel_id.clone(),
                        message_serial: record.message_serial().clone(),
                        annotation_type: record.annotation_type().clone(),
                    };
                    requests.insert(
                        Self::request_projection_key(&projection_request),
                        projection_request,
                    );
                }
            }
            for projection in state.projections.values() {
                if projection.app_id == request.app_id
                    && projection.channel_id == request.channel_id
                {
                    let projection_request = projection.projection_key();
                    requests.insert(
                        Self::request_projection_key(&projection_request),
                        projection_request,
                    );
                }
            }
            requests.into_values().collect::<Vec<_>>()
        };

        let mut projections = Vec::new();
        let mut rebuild_count = 0;
        for projection_request in requests {
            let should_rebuild = {
                let state = self.state.read().await;
                let key = Self::request_projection_key(&projection_request);
                let projection = state.projections.get(&key);
                let max_serial = Self::projection_max_serial(&state, &key);
                match (projection, max_serial) {
                    (None, Some(_)) => true,
                    (Some(projection), max_serial) => {
                        projection.last_annotation_serial != max_serial
                    }
                    _ => false,
                }
            };
            if let Some(projection) = self.get_projection(projection_request).await? {
                if should_rebuild {
                    rebuild_count += 1;
                }
                projections.push(projection);
            }
        }
        projections.sort_by(|left, right| {
            left.message_serial
                .cmp(&right.message_serial)
                .then_with(|| left.annotation_type.cmp(&right.annotation_type))
        });
        Ok((projections, rebuild_count))
    }

    async fn rebuild_projection(
        &self,
        request: AnnotationProjectionRequest,
    ) -> Result<StoredAnnotationProjection> {
        self.rebuild_projection_optimistic(request, AnnotationProjectionOptions::default())
            .await
    }

    async fn rebuild_projection_with_options(
        &self,
        request: AnnotationProjectionRequest,
        options: AnnotationProjectionOptions,
    ) -> Result<StoredAnnotationProjection> {
        self.rebuild_projection_optimistic(request, options).await
    }

    async fn purge_before(&self, before_ms: i64, batch_size: usize) -> Result<(u64, bool)> {
        if batch_size == 0 {
            return Ok((0, false));
        }

        let mut state = self.state.write().await;
        let mut deleted = 0_u64;
        let mut has_more = false;
        let mut affected_projection_keys = BTreeSet::new();
        let mut raw_removals = Vec::new();

        for (projection_key, events) in state.events_by_projection.iter_mut() {
            let remaining = batch_size.saturating_sub(deleted as usize);
            if remaining == 0 {
                has_more = true;
                break;
            }

            let to_remove = events
                .iter()
                .filter(|(_, record)| record.stored_at_ms < before_ms)
                .map(|(serial, _)| serial.clone())
                .take(remaining)
                .collect::<Vec<_>>();

            for serial in to_remove {
                if let Some(record) = events.remove(&serial) {
                    deleted += 1;
                    affected_projection_keys.insert(projection_key.clone());
                    raw_removals.push((
                        Self::channel_key(&record.app_id, &record.channel_id),
                        serial,
                    ));
                }
            }
        }

        for (channel_key, serial) in raw_removals {
            if let Some(raw) = state.raw_by_channel.get_mut(&channel_key) {
                raw.remove(&serial);
            }
        }

        state
            .events_by_projection
            .retain(|_, events| !events.is_empty());
        state.raw_by_channel.retain(|_, events| !events.is_empty());

        let affected_projection_keys = affected_projection_keys.into_iter().collect::<Vec<_>>();
        let requests = affected_projection_keys
            .iter()
            .filter_map(|key| {
                state
                    .events_by_projection
                    .get(key)
                    .and_then(|events| events.values().next())
                    .map(|record| AnnotationProjectionRequest {
                        app_id: record.app_id.clone(),
                        channel_id: record.channel_id.clone(),
                        message_serial: record.message_serial().clone(),
                        annotation_type: record.annotation_type().clone(),
                    })
            })
            .collect::<Vec<_>>();

        for request in requests {
            Self::rebuild_projection_from_state(
                &mut state,
                request,
                AnnotationProjectionOptions::default(),
            )?;
        }
        for key in affected_projection_keys {
            if !state.events_by_projection.contains_key(&key) {
                state.projections.remove(&key);
            }
        }

        if !has_more
            && state.events_by_projection.values().any(|events| {
                events
                    .values()
                    .any(|record| record.stored_at_ms < before_ms)
            })
        {
            has_more = true;
        }

        Ok((deleted, has_more))
    }
}