rushls_common/hooks/
envelope.rs1use bytes::Bytes;
12use serde::Serialize;
13use time::{OffsetDateTime, format_description::well_known::Rfc3339};
14use uuid::Uuid;
15
16use crate::hooks::{Occurrence, Subject};
17
18pub const CONTENT_TYPE: &str = "application/cloudevents+json";
20
21const SPEC_VERSION: &str = "1.0";
22const JSON: &str = "application/json";
23
24#[derive(Clone, Debug, Eq, PartialEq)]
26pub struct Envelope<S, K> {
27 pub id: String,
29 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#[derive(Debug)]
50pub struct Renderer<E> {
51 source: String,
52 schema_version: u32,
53 event: std::marker::PhantomData<fn(&E)>,
54}
55
56impl<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 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);