Skip to main content

rushls_common/hooks/
envelope.rs

1//! Rendering an application's event into the bytes that go on the wire.
2//!
3//! CloudEvents, because it settles `id`, `source`, `type`, and `time` in a way
4//! consumers already have libraries for, without committing anyone to a broker.
5//!
6//! The whole envelope is built at the moment the fact occurs and never touched
7//! again. That is what makes retries safe to deduplicate: the specification
8//! anticipates redelivery under the same `id`, so a consumer keying on
9//! `source` + `id` sees one occurrence however many times it arrives.
10
11use bytes::Bytes;
12use serde::Serialize;
13use time::{OffsetDateTime, format_description::well_known::Rfc3339};
14use uuid::Uuid;
15
16use crate::hooks::{Occurrence, Subject};
17
18/// Structured-mode CloudEvents, as the specification names it.
19pub const CONTENT_TYPE: &str = "application/cloudevents+json";
20
21const SPEC_VERSION: &str = "1.0";
22const JSON: &str = "application/json";
23
24/// One rendered event, immutable from here on.
25#[derive(Clone, Debug, Eq, PartialEq)]
26pub struct Envelope<S, K> {
27    /// Stable across every retry of this occurrence.
28    pub id: String,
29    /// What delivery orders by.
30    pub subject: S,
31    pub kind: K,
32    pub body: Bytes,
33}
34
35#[derive(Serialize)]
36struct CloudEvent<'a> {
37    specversion: &'static str,
38    id: &'a str,
39    source: &'a str,
40    #[serde(rename = "type")]
41    kind: String,
42    time: String,
43    subject: &'a str,
44    datacontenttype: &'static str,
45    data: serde_json::Value,
46}
47
48/// Builds envelopes for one node.
49#[derive(Debug)]
50pub struct Renderer<E> {
51    source: String,
52    schema_version: u32,
53    event: std::marker::PhantomData<fn(&E)>,
54}
55
56// Hand-written because the derive would demand `E: Clone`, which an event type
57// has no reason to be: the marker holds no value.
58impl<E> Clone for Renderer<E> {
59    fn clone(&self) -> Self {
60        Self {
61            source: self.source.clone(),
62            schema_version: self.schema_version,
63            event: std::marker::PhantomData,
64        }
65    }
66}
67
68impl<E: Occurrence> Renderer<E> {
69    pub fn new(source: impl Into<String>, schema_version: u32) -> Self {
70        Self {
71            source: source.into(),
72            schema_version,
73            event: std::marker::PhantomData,
74        }
75    }
76
77    /// Renders now, at the moment the occurrence happened.
78    ///
79    /// `id` and `time` are stamped together and here rather than at send time: a
80    /// queued event describes when it happened, not when delivery got round to
81    /// it, and a retry must not look like a second occurrence.
82    pub fn render(&self, event: &E) -> Result<Envelope<E::Subject, E::Kind>, RenderError> {
83        let id = Uuid::now_v7().to_string();
84        let kind = event.kind();
85        let subject = event.subject();
86        let body = {
87            let cloud_event = CloudEvent {
88                specversion: SPEC_VERSION,
89                id: &id,
90                source: &self.source,
91                kind: format!("{}.{kind}.v{}", E::TYPE_PREFIX, self.schema_version),
92                time: OffsetDateTime::now_utc()
93                    .format(&Rfc3339)
94                    .map_err(|error| RenderError(error.to_string()))?,
95                subject: subject.as_str(),
96                datacontenttype: JSON,
97                data: event.data(),
98            };
99            Bytes::from(
100                serde_json::to_vec(&cloud_event).map_err(|error| RenderError(error.to_string()))?,
101            )
102        };
103
104        Ok(Envelope {
105            id,
106            subject,
107            kind,
108            body,
109        })
110    }
111}
112
113#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
114#[error("a lifecycle event could not be rendered: {0}")]
115pub struct RenderError(String);