withone 0.2.1

Typed Rust client for the One API: the client, webhooks and the action type every withone-<platform> crate builds on.
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! Receiving-side webhook support: verify a delivery, dispatch it to typed
//! handlers, and register the listener with One idempotently.
//!
//! The event catalog and the per-event handler methods are generated at build
//! time from the committed SDK spec, so a new server event reaches this API by
//! regenerating rather than by a hand edit.

use crate::{
    client::{CallResponse, Error, One, PATH_SEGMENT},
    transport::types::WebhookSubscriptionView
};
use chrono::{DateTime, Utc};
use hmac::{Hmac, KeyInit, Mac};
use percent_encoding::utf8_percent_encode;
use secrecy::{ExposeSecret, SecretString};
use serde::de::DeserializeOwned;
use serde_json::{Value, from_value, json};
use sha2::Sha256;
use std::{collections::HashMap, error::Error as StdError, future::ready, pin::Pin, time::Duration};
use uuid::Uuid;

type HmacSha256 = Hmac<Sha256>;

/// A handler's returned work, boxed so handlers of different concrete future
/// types share one registry.
pub type HandlerFuture = Pin<Box<dyn Future<Output = Result<(), WebhookError>> + Send>>;

type Handler = Box<dyn Fn(Delivery) -> HandlerFuture + Send + Sync>;

/// A webhook handler's completion value.
///
/// Returning `()` acknowledges successful processing. Returning a fallible
/// result propagates its error from [`Webhooks::handle`] so the receiver can
/// answer non-2xx and request a retry.
pub trait WebhookHandlerOutput {
    #[doc(hidden)]
    fn into_webhook_result(self) -> Result<(), Box<dyn StdError + Send + Sync>>;
}

impl WebhookHandlerOutput for () {
    fn into_webhook_result(self) -> Result<(), Box<dyn StdError + Send + Sync>> {
        Ok(())
    }
}

impl<E> WebhookHandlerOutput for Result<(), E>
where
    E: StdError + Send + Sync + 'static
{
    fn into_webhook_result(self) -> Result<(), Box<dyn StdError + Send + Sync>> {
        self.map_err(|error| Box::new(error) as Box<dyn StdError + Send + Sync>)
    }
}

const SIGNATURE_PREFIX: &str = "sha256=";
const SUBSCRIPTIONS_BY_KEY_PATH: &str = "/v1/webhooks/subscriptions/by-key/";
const TEST_METADATA_FIELD: &str = "test";

/// Failures from verifying, parsing, or registering a webhook.
///
/// `#[non_exhaustive]`: new variants may be added in future releases, so
/// downstream `match` statements must include a `_ =>` arm.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum WebhookError {
    /// The signature header was absent, or not a `sha256=<hex>` value.
    #[error("webhook signature header is missing or malformed")]
    MalformedSignature,
    /// The signature did not match the body under the configured secret.
    #[error("webhook signature verification failed")]
    InvalidSignature,
    /// The event is older than the configured maximum age. Only returned when
    /// [`Webhooks::max_event_age`] is set.
    #[error("webhook event is older than the configured {max_age_secs}s maximum age")]
    Expired { max_age_secs: u64 },
    /// The body verified but was not a well-formed delivery, or its payload did
    /// not match the type its event declares.
    #[error("failed to parse webhook payload: {0}")]
    Parse(#[from] serde_json::Error),
    /// A registered handler failed while processing the delivery.
    #[error("webhook handler failed: {0}")]
    Handler(#[source] Box<dyn StdError + Send + Sync>),
    /// Registering the listener with One failed.
    #[error(transparent)]
    Api(#[from] Error)
}

/// A verified delivery, with the payload still typed as raw JSON.
///
/// Typed handlers receive [`Delivery`] with the payload already decoded into
/// the event's own type; [`Webhooks::on_any`] and [`Webhooks::verify`] hand
/// back this untyped form because the event is only known at runtime.
#[derive(Clone, Debug)]
pub struct Delivery<P = Value> {
    event:     String,
    id:        Uuid,
    timestamp: DateTime<Utc>,
    payload:   P,
    metadata:  Option<Value>
}

impl<P> Delivery<P> {
    /// The event type as a known variant, or `None` for an event this SDK
    /// build does not recognize - a subscription edited outside the SDK can
    /// carry one.
    pub fn event_type(&self) -> Option<WebhookEventType> {
        WebhookEventType::parse(&self.event)
    }

    /// The raw on-the-wire event string, present even for unknown types.
    pub fn event(&self) -> &str {
        &self.event
    }

    /// Stable delivery id, identical on every retry. Deduplicate on this:
    /// delivery is at-least-once.
    pub fn id(&self) -> Uuid {
        self.id
    }

    /// When One emitted the event.
    pub fn timestamp(&self) -> DateTime<Utc> {
        self.timestamp
    }

    /// The event-specific payload.
    pub fn payload(&self) -> &P {
        &self.payload
    }

    /// Metadata recorded on the event when it was captured, if any. This is the
    /// event's own metadata - a subscription's `metadata` field is not echoed
    /// back on delivery.
    pub fn metadata(&self) -> Option<&Value> {
        self.metadata.as_ref()
    }
}

impl Delivery {
    /// The connection key this delivery concerns, for the events that carry
    /// one. `None` for account-level events (`project.*`, `organization.*`,
    /// `member.*`) and for an `oauth.failed` that fired before the connection
    /// existed. Every known event is decoded first, so a payload that does not
    /// match its declared type returns a decode error even when it has no
    /// connection key.
    pub fn connection_key(&self) -> Result<Option<String>, serde_json::Error> {
        if self.is_test() {
            return Ok(None);
        }
        match self.event_type() {
            Some(event) => event.connection_key_of(&self.payload),
            None => Ok(None)
        }
    }

    /// Whether this is a test delivery from the dashboard's "send test" action.
    ///
    /// A test delivery reuses a real event name but carries a synthetic
    /// payload, so it cannot decode into that event's type. Typed handlers are
    /// skipped for it and only [`Webhooks::on_any`] runs - otherwise every test
    /// send would fail to decode and be retried forever.
    pub fn is_test(&self) -> bool {
        self.metadata
            .as_ref()
            .and_then(|metadata| metadata.get(TEST_METADATA_FIELD))
            .and_then(Value::as_bool)
            .unwrap_or(false)
    }

    /// Re-decodes the payload into the event's own type.
    fn retype<P: DeserializeOwned>(&self) -> Result<Delivery<P>, serde_json::Error> {
        Ok(Delivery {
            event:     self.event.clone(),
            id:        self.id,
            timestamp: self.timestamp,
            payload:   from_value(self.payload.clone())?,
            metadata:  self.metadata.clone()
        })
    }
}

/// What the server puts on the wire, mapped into [`Delivery`].
#[derive(Deserialize)]
struct RawDelivery {
    event:     String,
    event_id:  Uuid,
    timestamp: DateTime<Utc>,
    payload:   Value,
    metadata:  Option<Value>
}

/// A handler plus the connection it was scoped to, if any.
struct Registered {
    connection: Option<String>,
    run:        Handler
}

impl Registered {
    /// Whether this handler should see `delivery`. An unscoped handler sees
    /// everything; a scoped one only deliveries carrying its connection key.
    fn accepts(&self, delivery: &Delivery) -> Result<bool, WebhookError> {
        match &self.connection {
            None => Ok(true),
            Some(key) => Ok(delivery.connection_key()?.as_deref() == Some(key.as_str()))
        }
    }

    /// Runs this handler when its connection scope accepts the delivery.
    async fn run_if_accepted(&self, delivery: &Delivery) -> Result<(), WebhookError> {
        if self.accepts(delivery)? {
            (self.run)(delivery.clone()).await?;
        }
        Ok(())
    }
}

/// A registry of typed webhook handlers plus the listener registration that
/// makes One send them.
///
/// Built fluently; every per-event method is generated from the SDK spec's
/// event catalog.
pub struct Webhooks {
    client:    One,
    secret:    SecretString,
    tolerance: Option<Duration>,
    handlers:  HashMap<WebhookEventType, Vec<Registered>>,
    any:       Vec<Registered>
}

impl Webhooks {
    pub(crate) fn new(client: One, secret: SecretString) -> Self {
        Self {
            client,
            secret,
            tolerance: None,
            handlers: HashMap::new(),
            any: Vec::new()
        }
    }

    /// Rejects deliveries whose event is older than `max_age`.
    ///
    /// **Off by default, and not replay protection.** The signed timestamp is
    /// when the *event* occurred, not when this attempt was sent: the server
    /// retries on a `30 * (2^n - 1)` second backoff over five attempts, and a
    /// backed-up delivery queue can push an authentic first attempt arbitrarily
    /// far past the event. Any window therefore rejects genuine deliveries once
    /// the server is behind, which is exactly when you least want to drop them.
    ///
    /// Deduplicate on [`Delivery::id`] instead - it is stable across retries.
    /// Real replay protection needs a per-attempt signed timestamp, which is a
    /// server-side signing change.
    pub fn max_event_age(mut self, max_age: Duration) -> Self {
        self.tolerance = Some(max_age);
        self
    }

    /// Registers handlers scoped to one connection: they fire only for
    /// deliveries carrying that connection's key.
    ///
    /// The block form keeps the scope lexical, so a reader never has to scan
    /// backwards to work out which connection a handler belongs to, and only
    /// the connection-carrying events are offered inside it.
    pub fn connection<F>(mut self, key: impl Into<String>, block: F) -> Self
    where
        F: FnOnce(ConnectionWebhooks) -> ConnectionWebhooks
    {
        let scope = block(ConnectionWebhooks {
            key:      key.into(),
            handlers: HashMap::new(),
            any:      Vec::new()
        });
        for (event, handlers) in scope.handlers {
            self.handlers.entry(event).or_default().extend(handlers);
        }
        self.any.extend(scope.any);
        self
    }

    /// Registers a handler fired for every verified delivery, whatever its
    /// event type. Runs after event-specific handlers.
    ///
    /// "Every" means every event in this SDK build's catalog, which is what
    /// [`Webhooks::listen`] subscribes to. An event the server adds after this
    /// build was released is not in that list and will not be delivered, so
    /// regenerate the SDK to pick up new events. A delivery for an unrecognized
    /// type still verifies and reaches this handler with
    /// [`Delivery::event_type`] as `None` - that path exists for a subscription
    /// edited outside the SDK, not as forward compatibility.
    pub fn on_any<F, Fut, Output>(mut self, handler: F) -> Self
    where
        F: Fn(Delivery) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Output> + Send + 'static,
        Output: WebhookHandlerOutput + Send + 'static
    {
        self.any.push(Registered {
            connection: None,
            run:        Box::new(move |delivery| {
                let work = handler(delivery);
                Box::pin(async move { work.await.into_webhook_result().map_err(WebhookError::Handler) })
            })
        });
        self
    }

    /// Registers a typed handler for `event`. The generated per-event methods
    /// are thin wrappers over this.
    pub(crate) fn register<P, F, Fut, Output>(
        mut self,
        event: WebhookEventType,
        connection: Option<String>,
        handler: F
    ) -> Self
    where
        P: DeserializeOwned + Send + 'static,
        F: Fn(Delivery<P>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Output> + Send + 'static,
        Output: WebhookHandlerOutput + Send + 'static
    {
        self.handlers
            .entry(event)
            .or_default()
            .push(typed_handler(connection, handler));
        self
    }

    /// The event types [`Webhooks::listen`] subscribes to.
    ///
    /// An unscoped catch-all subscribes to this build's whole catalog. The
    /// server matches exact event strings, so an event added after this build
    /// was released is not covered - see [`Webhooks::on_any`].
    ///
    /// A catch-all scoped to a connection adds only the connection-carrying
    /// events. The server cannot filter by connection, so subscribing to
    /// account-level events would just ship deliveries `accepts` discards.
    pub fn events(&self) -> Vec<WebhookEventType> {
        if self.any.iter().any(|handler| handler.connection.is_none()) {
            return WebhookEventType::ALL.to_vec();
        }

        let mut events: Vec<WebhookEventType> = self.handlers.keys().copied().collect();
        if !self.any.is_empty() {
            events.extend(WebhookEventType::CONNECTION_SCOPED);
        }
        events.sort();
        events.dedup();
        events
    }

    /// Verifies the signature and parses the body without dispatching. Use it
    /// when you want to route deliveries yourself.
    pub fn verify(&self, raw_body: &[u8], signature: &str) -> Result<Delivery, WebhookError> {
        Self::verify_with(&self.secret, self.tolerance, raw_body, signature)
    }

    /// Verifies a delivery without a registry, for callers that hold only the
    /// signing secret. The language bindings route through this so signature
    /// checking, the replay window, and its default all have exactly one
    /// implementation.
    ///
    /// `tolerance` of `None` performs no age check, which is the default - see
    /// [`Webhooks::max_event_age`] for why.
    pub fn verify_with(
        secret: &SecretString,
        tolerance: Option<Duration>,
        raw_body: &[u8],
        signature: &str
    ) -> Result<Delivery, WebhookError> {
        let hex_sig = signature
            .strip_prefix(SIGNATURE_PREFIX)
            .ok_or(WebhookError::MalformedSignature)?;
        let expected = hex::decode(hex_sig).map_err(|_| WebhookError::MalformedSignature)?;

        let mut mac = HmacSha256::new_from_slice(secret.expose_secret().as_bytes())
            .map_err(|_| WebhookError::InvalidSignature)?;
        mac.update(raw_body);
        mac.verify_slice(&expected)
            .map_err(|_| WebhookError::InvalidSignature)?;

        let raw: RawDelivery = serde_json::from_slice(raw_body)?;
        if let Some(max_age) = tolerance {
            let age = Utc::now().signed_duration_since(raw.timestamp).abs();
            if age.to_std().is_ok_and(|age| age > max_age) {
                return Err(WebhookError::Expired {
                    max_age_secs: max_age.as_secs()
                });
            }
        }

        Ok(Delivery {
            event:     raw.event,
            id:        raw.event_id,
            timestamp: raw.timestamp,
            payload:   raw.payload,
            metadata:  raw.metadata
        })
    }

    /// Verifies, parses, and dispatches a delivery to every handler registered
    /// for its event type, then to the catch-all handlers.
    ///
    /// Handlers run sequentially, so one that panics or hangs blocks the rest.
    /// Returns the delivery so callers can log it after dispatch.
    pub async fn handle(&self, raw_body: &[u8], signature: &str) -> Result<Delivery, WebhookError> {
        let delivery = self.verify(raw_body, signature)?;

        let mut failure = None;

        if !delivery.is_test()
            && let Some(event) = delivery.event_type()
            && let Some(handlers) = self.handlers.get(&event)
        {
            for handler in handlers {
                if let Err(error) = handler.run_if_accepted(&delivery).await {
                    failure.get_or_insert(error);
                }
            }
        }
        for handler in &self.any {
            if let Err(error) = handler.run_if_accepted(&delivery).await {
                failure.get_or_insert(error);
            }
        }

        match failure {
            Some(error) => Err(error),
            None => Ok(delivery)
        }
    }

    /// Registers this listener with One under the stable name `key`, pointing
    /// at `url` and subscribing to exactly the events handlers were attached
    /// for.
    ///
    /// Idempotent: calling it on every boot reconciles the one listener named
    /// `key` rather than accumulating duplicates, so `url` and the event set
    /// can change freely between runs.
    pub async fn listen(
        &self,
        key: impl AsRef<str>,
        url: impl AsRef<str>
    ) -> Result<WebhookSubscriptionView, WebhookError> {
        let events: Vec<&str> = self.events().iter().map(|event| event.as_str()).collect();
        let response = Self::register_listener(&self.client, key.as_ref(), url.as_ref(), &events, &self.secret).await?;
        Ok(response.output()?)
    }

    /// Performs the listener upsert against the API.
    ///
    /// The route, the request shape, and the percent-encoding of `key` live
    /// here only - the language bindings call this rather than rebuilding the
    /// request, so there is one definition of what registering a listener
    /// means. The raw response metadata is retained for language bindings.
    pub async fn register_listener(
        client: &One,
        key: &str,
        url: &str,
        events: &[&str],
        secret: &SecretString
    ) -> Result<CallResponse<WebhookSubscriptionView>, WebhookError> {
        let path = format!("{SUBSCRIPTIONS_BY_KEY_PATH}{}", utf8_percent_encode(key, PATH_SEGMENT));
        let body = json!({ "url": url, "events": events, "secret": secret.expose_secret() });
        Ok(client.put_json_response(&path, &body).await?)
    }
}

/// Handlers scoped to a single connection. Only the events that carry a
/// connection are offered here, so a scoped handler can never be one that could
/// not fire.
pub struct ConnectionWebhooks {
    key:      String,
    handlers: HashMap<WebhookEventType, Vec<Registered>>,
    any:      Vec<Registered>
}

impl ConnectionWebhooks {
    /// Registers a handler for every event concerning this connection.
    pub fn on_any<F, Fut, Output>(mut self, handler: F) -> Self
    where
        F: Fn(Delivery) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Output> + Send + 'static,
        Output: WebhookHandlerOutput + Send + 'static
    {
        self.any.push(Registered {
            connection: Some(self.key.clone()),
            run:        Box::new(move |delivery| {
                let work = handler(delivery);
                Box::pin(async move { work.await.into_webhook_result().map_err(WebhookError::Handler) })
            })
        });
        self
    }

    /// Registers a typed handler scoped to this connection. The generated
    /// per-event methods are thin wrappers over this.
    pub(crate) fn register<P, F, Fut, Output>(mut self, event: WebhookEventType, handler: F) -> Self
    where
        P: DeserializeOwned + Send + 'static,
        F: Fn(Delivery<P>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Output> + Send + 'static,
        Output: WebhookHandlerOutput + Send + 'static
    {
        let connection = Some(self.key.clone());
        self.handlers
            .entry(event)
            .or_default()
            .push(typed_handler(connection, handler));
        self
    }
}

/// Wraps a typed handler into the registry's untyped shape, decoding the
/// payload on the way in.
///
/// A payload that does not match the type its event declares surfaces as
/// [`WebhookError::Parse`] rather than being skipped: that is what lets the
/// caller answer non-2xx, so the server retries instead of the delivery being
/// silently lost.
fn typed_handler<P, F, Fut, Output>(connection: Option<String>, handler: F) -> Registered
where
    P: DeserializeOwned + Send + 'static,
    F: Fn(Delivery<P>) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Output> + Send + 'static,
    Output: WebhookHandlerOutput + Send + 'static
{
    Registered {
        connection,
        run: Box::new(move |delivery| match delivery.retype::<P>() {
            Ok(typed) => {
                let work = handler(typed);
                Box::pin(async move { work.await.into_webhook_result().map_err(WebhookError::Handler) })
            }
            Err(error) => Box::pin(ready(Err(WebhookError::Parse(error))))
        })
    }
}

include!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/generated/webhooks_generated.rs"));

#[cfg(test)]
mod tests {
    use std::{
        future::ready,
        io::Error as IoError,
        sync::{
            Arc,
            atomic::{AtomicBool, Ordering}
        }
    };

    use chrono::Utc;
    use hmac::{KeyInit, Mac};
    use secrecy::SecretString;
    use serde_json::json;
    use uuid::Uuid;

    use super::{Delivery, HmacSha256, Registered, WebhookError, Webhooks};
    use crate::One;

    #[tokio::test]
    async fn test_webhooks_handle_propagates_first_handler_failure_after_dispatching_all_handlers() {
        let secret = "handler-secret";
        let raw_body = serde_json::to_vec(&json!({
            "event": "future.event",
            "event_id": Uuid::nil(),
            "timestamp": Utc::now(),
            "payload": {},
            "metadata": null
        }))
        .expect("delivery serializes");
        let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC accepts the secret");
        mac.update(&raw_body);
        let signature = format!("sha256={}", hex::encode(mac.finalize().into_bytes()));
        let second_ran = Arc::new(AtomicBool::new(false));
        let second_handler = Arc::clone(&second_ran);
        let webhooks = Webhooks::new(
            One::builder().secret("api-secret").build().expect("client builds"),
            SecretString::from(secret.to_string())
        )
        .on_any(|_| async { Err::<(), _>(IoError::other("first failure")) })
        .on_any(move |_| {
            let second_handler = Arc::clone(&second_handler);
            async move {
                second_handler.store(true, Ordering::SeqCst);
            }
        });

        let error = webhooks
            .handle(&raw_body, &signature)
            .await
            .expect_err("handler failure propagates");

        assert!(second_ran.load(Ordering::SeqCst));
        match error {
            WebhookError::Handler(source) => assert_eq!(source.to_string(), "first failure"),
            other => panic!("unexpected webhook error: {other}")
        }
    }

    #[test]
    fn test_webhooks_scoped_handler_preserves_connection_decode_errors() {
        let delivery = Delivery {
            event:     "connection.created".to_string(),
            id:        Uuid::nil(),
            timestamp: Utc::now(),
            payload:   json!({ "key": 42 }),
            metadata:  None
        };
        let handler = Registered {
            connection: Some("primary".to_string()),
            run:        Box::new(|_| Box::pin(ready(Ok(()))))
        };

        assert!(matches!(handler.accepts(&delivery), Err(WebhookError::Parse(_))));
    }

    #[test]
    fn test_webhooks_test_delivery_skips_connection_payload_decode() {
        let delivery = Delivery {
            event:     "connection.created".to_string(),
            id:        Uuid::nil(),
            timestamp: Utc::now(),
            payload:   json!({ "test": true }),
            metadata:  Some(json!({ "test": true }))
        };

        assert_eq!(delivery.connection_key().expect("test delivery is accepted"), None);
    }
}