sockudo-adapter 4.5.0

Connection adapters and horizontal scaling for Sockudo
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use crate::handler::ConnectionHandler;
use sockudo_core::annotations::{
    Annotation, AnnotationAction, AnnotationEventLookupRequest, AnnotationEventsRequest,
    AnnotationId, AnnotationProjectionOptions, AnnotationSerial, AnnotationSummary, AnnotationType,
    StoredAnnotationEvent, StoredAnnotationProjection,
};
use sockudo_core::app::App;
use sockudo_core::error::{Error, Result};
use sockudo_core::history::now_ms;
use sockudo_core::versioned_messages::MessageSerial;
use sockudo_protocol::messages::{
    ANNOTATION_EVENT_NAME, AnnotationEventAction, AnnotationEventData, AnnotationSummaryEnvelope,
    MESSAGE_SUMMARY_EVENT_NAME, MessageData, MessageExtras, MessageSummaryData, PusherMessage,
};
use sonic_rs::Value;
use std::collections::BTreeMap;
use std::time::Instant;

pub struct PublishAnnotationRuntimeRequest {
    pub app: App,
    pub channel: String,
    pub message_serial: MessageSerial,
    pub annotation_type: AnnotationType,
    pub name: Option<String>,
    pub client_id: Option<String>,
    pub count: Option<u64>,
    pub data: Option<Value>,
    pub encoding: Option<String>,
}

pub struct PublishAnnotationRuntimeResult {
    pub annotation_serial: AnnotationSerial,
    pub projection: StoredAnnotationProjection,
}

pub struct DeleteAnnotationRuntimeRequest {
    pub app: App,
    pub channel: String,
    pub message_serial: MessageSerial,
    pub target_serial: AnnotationSerial,
}

pub struct DeleteAnnotationRuntimeResult {
    pub annotation_serial: AnnotationSerial,
    pub deleted_annotation_serial: AnnotationSerial,
    pub projection: Option<StoredAnnotationProjection>,
}

impl ConnectionHandler {
    pub async fn publish_annotation_runtime(
        &self,
        request: PublishAnnotationRuntimeRequest,
    ) -> Result<PublishAnnotationRuntimeResult> {
        if self
            .version_store()
            .get_latest(&request.app.id, &request.channel, &request.message_serial)
            .await?
            .is_none()
        {
            return Err(Error::Channel(format!(
                "Message '{}' was not found in channel '{}'",
                request.message_serial.as_str(),
                request.channel
            )));
        }

        let serial = AnnotationSerial::new(self.next_version_serial())?;
        let annotation = Annotation {
            id: AnnotationId::new(uuid::Uuid::new_v4().to_string())?,
            action: AnnotationAction::Create,
            serial: serial.clone(),
            message_serial: request.message_serial.clone(),
            annotation_type: request.annotation_type.clone(),
            name: request.name,
            client_id: request.client_id,
            count: request.count,
            data: request.data,
            encoding: request.encoding,
            timestamp: now_ms(),
        };
        annotation.validate()?;

        let projection = self
            .annotation_store()
            .append_event(StoredAnnotationEvent {
                app_id: request.app.id.clone(),
                channel_id: request.channel.clone(),
                annotation: annotation.clone(),
                stored_at_ms: now_ms(),
            })
            .await?;
        if let Some(metrics) = self.metrics() {
            metrics.mark_annotation_published(&request.channel, request.annotation_type.as_str());
        }
        let projection = self
            .projection_fitting_payload(&request.app, &request.channel, projection)
            .await?;

        self.deliver_annotation_change(
            &request.app,
            &request.channel,
            &annotation,
            &request.message_serial,
            &request.annotation_type,
            &projection.summary,
        )
        .await?;

        Ok(PublishAnnotationRuntimeResult {
            annotation_serial: serial,
            projection,
        })
    }

    pub async fn delete_annotation_runtime(
        &self,
        request: DeleteAnnotationRuntimeRequest,
    ) -> Result<DeleteAnnotationRuntimeResult> {
        let target = self
            .annotation_store()
            .get_event_by_serial(AnnotationEventLookupRequest {
                app_id: request.app.id.clone(),
                channel_id: request.channel.clone(),
                annotation_serial: request.target_serial.clone(),
            })
            .await?
            .ok_or_else(|| {
                Error::Channel(format!(
                    "Annotation '{}' was not found in channel '{}'",
                    request.target_serial.as_str(),
                    request.channel
                ))
            })?;

        if target.message_serial() != &request.message_serial {
            return Err(Error::Channel(format!(
                "Annotation '{}' does not target message '{}'",
                request.target_serial.as_str(),
                request.message_serial.as_str()
            )));
        }
        if target.annotation.action != AnnotationAction::Create {
            return Err(Error::InvalidMessageFormat(
                "Only annotation.create events can be deleted".to_string(),
            ));
        }

        let existing = self
            .annotation_store()
            .get_events(AnnotationEventsRequest {
                app_id: request.app.id.clone(),
                channel_id: request.channel.clone(),
                message_serial: request.message_serial.clone(),
                annotation_type: target.annotation.annotation_type.clone(),
            })
            .await?;
        if existing.iter().any(|record| {
            record.annotation.action == AnnotationAction::Delete
                && record.annotation.id == target.annotation.id
        }) {
            return Ok(DeleteAnnotationRuntimeResult {
                annotation_serial: request.target_serial.clone(),
                deleted_annotation_serial: request.target_serial,
                projection: None,
            });
        }

        let delete_serial = AnnotationSerial::new(self.next_version_serial())?;
        let annotation = Annotation {
            id: target.annotation.id.clone(),
            action: AnnotationAction::Delete,
            serial: delete_serial.clone(),
            message_serial: request.message_serial.clone(),
            annotation_type: target.annotation.annotation_type.clone(),
            name: target.annotation.name.clone(),
            client_id: target.annotation.client_id.clone(),
            count: target.annotation.count,
            data: None,
            encoding: None,
            timestamp: now_ms(),
        };
        annotation.validate()?;

        let projection = self
            .annotation_store()
            .append_event(StoredAnnotationEvent {
                app_id: request.app.id.clone(),
                channel_id: request.channel.clone(),
                annotation: annotation.clone(),
                stored_at_ms: now_ms(),
            })
            .await?;
        if let Some(metrics) = self.metrics() {
            metrics.mark_annotation_deleted(
                &request.channel,
                target.annotation.annotation_type.as_str(),
            );
        }
        let projection = self
            .projection_fitting_payload(&request.app, &request.channel, projection)
            .await?;

        self.deliver_annotation_change(
            &request.app,
            &request.channel,
            &annotation,
            &request.message_serial,
            &target.annotation.annotation_type,
            &projection.summary,
        )
        .await?;

        Ok(DeleteAnnotationRuntimeResult {
            annotation_serial: delete_serial,
            deleted_annotation_serial: request.target_serial,
            projection: Some(projection),
        })
    }

    async fn projection_fitting_payload(
        &self,
        app: &App,
        channel: &str,
        projection: StoredAnnotationProjection,
    ) -> Result<StoredAnnotationProjection> {
        let max_payload = app
            .event_payload_limit_kb()
            .map(|kb| kb as usize * 1024)
            .unwrap_or(self.server_options().websocket_max_payload_kb as usize * 1024);
        if max_payload == 0 {
            return Ok(projection);
        }

        let mut limit = None;
        let mut candidate = projection;
        loop {
            let message = annotation_summary_message(
                channel,
                &candidate.message_serial,
                &candidate.annotation_type,
                &candidate.summary,
            )?;
            if sonic_rs::to_vec(&message)?.len() <= max_payload {
                return Ok(candidate);
            }

            limit = Some(match limit {
                None => 64,
                Some(0) => return Ok(candidate),
                Some(previous) => previous / 2,
            });

            let projection_key = candidate.projection_key();
            let annotation_count = self
                .annotation_store()
                .get_events(AnnotationEventsRequest {
                    app_id: app.id.clone(),
                    channel_id: channel.to_string(),
                    message_serial: projection_key.message_serial.clone(),
                    annotation_type: projection_key.annotation_type.clone(),
                })
                .await
                .map(|events| events.len())
                .unwrap_or(0);

            tracing::warn!(
                channel = %channel,
                message_serial = %projection_key.message_serial.as_str(),
                annotation_type = %projection_key.annotation_type.as_str(),
                annotation_count,
                client_id_limit = limit.unwrap_or_default(),
                "annotation projection rebuild triggered on hot channel"
            );

            if let Some(metrics) = self.metrics() {
                metrics.mark_annotation_projection_rebuild(channel);
            }
            let rebuild_started = Instant::now();
            let rebuilt = self
                .annotation_store()
                .rebuild_projection_with_options(
                    projection_key,
                    AnnotationProjectionOptions {
                        client_id_limit: limit,
                    },
                )
                .await;
            if let Some(metrics) = self.metrics() {
                metrics.track_annotation_projection_rebuild_duration(
                    channel,
                    rebuild_started.elapsed().as_secs_f64(),
                );
            }
            candidate = rebuilt?;
        }
    }

    fn observe_clipped_summary(
        &self,
        channel: &str,
        message_serial: &MessageSerial,
        annotation_type: &AnnotationType,
        summary: &AnnotationSummary,
    ) {
        let Some(contributor_count) = clipped_contributor_count(summary) else {
            return;
        };

        tracing::warn!(
            channel = %channel,
            message_serial = %message_serial.as_str(),
            annotation_type = %annotation_type.as_str(),
            contributor_count,
            "annotation summary clipped"
        );

        if let Some(metrics) = self.metrics() {
            metrics.mark_annotation_summary_clipped(channel, annotation_type.as_str());
        }
    }

    async fn deliver_annotation_change(
        &self,
        app: &App,
        channel: &str,
        annotation: &Annotation,
        message_serial: &MessageSerial,
        annotation_type: &AnnotationType,
        summary: &AnnotationSummary,
    ) -> Result<()> {
        self.observe_clipped_summary(channel, message_serial, annotation_type, summary);

        let summary_message =
            annotation_summary_message(channel, message_serial, annotation_type, summary)?;
        if let Err(err) = self
            .broadcast_to_channel_force_full(app, channel, summary_message, None, None)
            .await
        {
            tracing::error!(
                channel = %channel,
                message_serial = %message_serial.as_str(),
                annotation_type = %annotation_type.as_str(),
                error = %err,
                "annotation summary failed to fan out through cluster broadcast"
            );
            return Err(err);
        }
        if let Some(metrics) = self.metrics() {
            metrics.mark_annotation_summary_delivery(channel);
        }

        let raw_message = annotation_event_message(channel, annotation)?;
        if let Err(err) = self
            .broadcast_to_channel_force_full(app, channel, raw_message, None, None)
            .await
        {
            tracing::error!(
                channel = %channel,
                message_serial = %message_serial.as_str(),
                annotation_type = %annotation_type.as_str(),
                annotation_serial = %annotation.serial.as_str(),
                error = %err,
                "annotation event failed to fan out through cluster broadcast"
            );
            return Err(err);
        }

        Ok(())
    }
}

pub(crate) fn clipped_contributor_count(summary: &AnnotationSummary) -> Option<u64> {
    match summary {
        AnnotationSummary::Total(_) => None,
        AnnotationSummary::Flag(summary) => summary.clipped.then_some(summary.total),
        AnnotationSummary::Distinct(names) | AnnotationSummary::Unique(names) => {
            let total = names
                .values()
                .filter(|summary| summary.clipped)
                .map(|summary| summary.total)
                .sum::<u64>();
            (total > 0).then_some(total)
        }
        AnnotationSummary::Multiple(names) => {
            let total = names
                .values()
                .filter(|summary| summary.clipped)
                .map(|summary| summary.total_client_ids)
                .sum::<u64>();
            (total > 0).then_some(total)
        }
    }
}

fn annotation_wire_event(annotation: &Annotation) -> AnnotationEventData {
    AnnotationEventData {
        action: match annotation.action {
            AnnotationAction::Create => AnnotationEventAction::Create,
            AnnotationAction::Delete => AnnotationEventAction::Delete,
        },
        id: matches!(annotation.action, AnnotationAction::Create)
            .then(|| annotation.id.as_str().to_string()),
        serial: annotation.serial.as_str().to_string(),
        message_serial: annotation.message_serial.as_str().to_string(),
        annotation_type: annotation.annotation_type.as_str().to_string(),
        name: annotation.name.clone(),
        client_id: annotation.client_id.clone(),
        count: annotation.count,
        data: annotation.data.clone(),
        encoding: annotation.encoding.clone(),
        timestamp: annotation.timestamp,
    }
}

fn annotation_event_message(channel: &str, annotation: &Annotation) -> Result<PusherMessage> {
    Ok(PusherMessage {
        event: Some(ANNOTATION_EVENT_NAME.to_string()),
        channel: Some(channel.to_string()),
        data: Some(MessageData::Json(sonic_rs::to_value(
            &annotation_wire_event(annotation),
        )?)),
        name: None,
        user_id: None,
        tags: None,
        sequence: None,
        conflation_key: None,
        message_id: None,
        stream_id: None,
        serial: None,
        idempotency_key: None,
        extras: None,
        delta_sequence: None,
        delta_conflation_key: None,
    })
}

fn annotation_summary_message(
    channel: &str,
    message_serial: &MessageSerial,
    annotation_type: &AnnotationType,
    summary: &AnnotationSummary,
) -> Result<PusherMessage> {
    let mut summary_by_type = BTreeMap::new();
    summary_by_type.insert(
        annotation_type.as_str().to_string(),
        sonic_rs::to_value(summary)?,
    );

    Ok(PusherMessage {
        event: Some(MESSAGE_SUMMARY_EVENT_NAME.to_string()),
        channel: Some(channel.to_string()),
        data: Some(MessageData::Json(sonic_rs::to_value(
            &MessageSummaryData {
                action: "message.summary".to_string(),
                serial: message_serial.as_str().to_string(),
                annotations: AnnotationSummaryEnvelope {
                    summary: summary_by_type,
                },
            },
        )?)),
        name: None,
        user_id: None,
        tags: None,
        sequence: None,
        conflation_key: None,
        message_id: None,
        stream_id: None,
        serial: None,
        idempotency_key: None,
        extras: Some(MessageExtras {
            ephemeral: Some(true),
            ..Default::default()
        }),
        delta_sequence: None,
        delta_conflation_key: None,
    })
}