anycms-event-derive 0.1.5

Procedural macros for anycms-event
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
//! Procedural macros for the anycms-event crate.
//!
//! Provides:
//! - `#[derive(Event)]` — auto-implement the `Event` trait
//! - `event_bus! { ... }` — define a typed event bus with compile-time guarantees
//!
//! # `#[derive(Event)]`
//!
//! Generates an `impl Event for YourStruct` block with `event_name()` and `topic()`.
//!
//! ## Attributes
//!
//! - `#[event(name = "user.created")]` — set the event name explicitly
//! - `#[event(topic = "user")]` — set the topic explicitly
//!
//! If `name` is not specified, it is derived from the struct name using CamelCase convention:
//! `UserCreated` -> `"user.created"`, `OrderPlaced` -> `"order.placed"`.
//!
//! If `topic` is not specified, it defaults to the first segment of the event name
//! (e.g., `"user.created"` -> `"user"`).
//!
//! # `event_bus!`
//!
//! Define event structs, a topic enum, and a typed event bus in one declaration.
//!
//! ## Syntax
//!
//! ```ignore
//! event_bus! {
//!     bus AppEventBus {
//!         event UserCreated { user_id: String, username: String }
//!         event UserDeleted { user_id: String, reason: String }
//!
//!         // topic <method_name> => [EventType1, EventType2]
//!         topic user_events => [UserCreated, UserDeleted]
//!     }
//! }
//! ```
//!
//! This generates:
//! - Struct definitions with `#[derive(Debug, Clone, Serialize, Deserialize)]`
//! - `impl Event for ...` blocks
//! - A topic enum `AppEventBusTopicEvent`
//! - A typed `AppEventBus` newtype wrapping `anycms_event::EventBus`
//! - A `subscribe_topic_user_events()` method for the topic group

use proc_macro::TokenStream;
use quote::quote;
use syn::{
    braced, parse, parse_macro_input, Data, DeriveInput, Expr, ExprLit, Ident, Lit,
    Meta, MetaNameValue, Path, Token, Type,
};

// ---------------------------------------------------------------------------
// CamelCase -> snake_case (dotted) conversion
// ---------------------------------------------------------------------------

/// Convert an UpperCamelCase identifier into a dotted lowercase string.
///
/// Rules:
/// - Each uppercase letter starts a new segment (unless it's part of a run
///   like `HTTPServer` -> `http_server` -> `http.server`).
/// - Segments are joined with `"."`.
/// - The entire result is lowercase.
///
/// Examples:
///   `UserCreated`  -> `"user.created"`
///   `OrderPlaced`  -> `"order.placed"`
///   `HTTPServer`   -> `"http.server"`
fn camel_to_dotted(name: &str) -> String {
    let mut result = String::with_capacity(name.len() + 8);
    let mut chars = name.chars().peekable();

    // Track whether the previous char was lowercase (or digit).
    let mut prev_lower = false;

    while let Some(ch) = chars.next() {
        if ch.is_uppercase() {
            // Insert a segment separator if:
            //   - we are not at the start, AND
            //   - the previous char was lowercase OR the next char is lowercase
            //     (handles "HTTPServer" -> "H-T-T-P-Server" with proper splits)
            let next_lower = chars.peek().is_some_and(|c| c.is_lowercase());
            if prev_lower || next_lower {
                if !result.is_empty() {
                    result.push('.');
                }
            } else if !result.is_empty() {
                // We're in an all-uppercase run (e.g., "HTTP").
                // Don't split — just append the lowercase char.
            } else {
                // first char, no separator
            }
            result.push(ch.to_ascii_lowercase());
            prev_lower = false;
        } else {
            // Lowercase or digit.
            if result.is_empty() {
                // first char, just push
            }
            result.push(ch);
            prev_lower = ch.is_lowercase() || ch.is_ascii_digit();
        }
    }

    result
}

// ---------------------------------------------------------------------------
// Attribute parsing helpers
// ---------------------------------------------------------------------------

/// Parsed `#[event(..)]` attributes.
struct EventAttrs {
    /// Explicit event name, e.g. `#[event(name = "user.created")]`.
    name: Option<String>,
    /// Explicit topic, e.g. `#[event(topic = "user")]`.
    topic: Option<String>,
}

/// Parse all `#[event(...)]` attributes on the struct.
fn parse_event_attrs(attrs: &[syn::Attribute]) -> EventAttrs {
    let mut name = None;
    let mut topic = None;

    for attr in attrs {
        if !attr.path().is_ident("event") {
            continue;
        }

        // Parse the contents as a comma-separated list of `key = "value"`.
        let nested = attr.parse_args_with(
            syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated,
        );

        if let Ok(metas) = nested {
            for meta in metas {
                if let Meta::NameValue(MetaNameValue {
                    path,
                    value:
                        Expr::Lit(ExprLit {
                            lit: Lit::Str(lit_str),
                            ..
                        }),
                    ..
                }) = meta
                {
                    if path.is_ident("name") {
                        name = Some(lit_str.value());
                    } else if path.is_ident("topic") {
                        topic = Some(lit_str.value());
                    }
                }
            }
        }
    }

    EventAttrs { name, topic }
}

/// Extract the first dotted segment as the default topic.
///
/// `"user.created"` -> `"user"`
/// `"order.placed"` -> `"order"`
/// `"order"`        -> `"order"`
fn first_segment(name: &str) -> &str {
    name.split('.').next().unwrap_or(name)
}

// ---------------------------------------------------------------------------
// The derive macro
// ---------------------------------------------------------------------------

/// Derive macro for the `Event` trait.
///
/// See the crate-level documentation for usage.
#[proc_macro_derive(Event, attributes(event))]
pub fn derive_event(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    // Only structs are supported.
    match &input.data {
        Data::Struct(_) => {}
        Data::Enum(_) => {
            return syn::Error::new_spanned(
                &input.ident,
                "Event can only be derived for structs, not enums",
            )
            .to_compile_error()
            .into();
        }
        Data::Union(_) => {
            return syn::Error::new_spanned(
                &input.ident,
                "Event can only be derived for structs, not unions",
            )
            .to_compile_error()
            .into();
        }
    }

    let ident = &input.ident;
    let attrs = parse_event_attrs(&input.attrs);

    // Determine event_name.
    let event_name = attrs.name.unwrap_or_else(|| camel_to_dotted(&ident.to_string()));

    // Determine topic.
    let topic = attrs
        .topic
        .unwrap_or_else(|| first_segment(&event_name).to_owned());

    let expanded = quote! {
        impl ::anycms_event::Event for #ident {
            fn event_name() -> &'static str {
                #event_name
            }

            fn topic() -> &'static str {
                #topic
            }

            fn to_json(&self) -> Option<::serde_json::Value> {
                ::serde_json::to_value(self).ok()
            }

            fn from_json(json: &str) -> Option<Self>
            where
                Self: Sized,
            {
                ::serde_json::from_str(json).ok()
            }
        }
    };

    expanded.into()
}

// ---------------------------------------------------------------------------
// event_bus! macro — parser
// ---------------------------------------------------------------------------

/// A single `event Name { fields }` declaration inside the macro.
struct EventDecl {
    name: Ident,
    fields: Vec<(Ident, Type)>,
}

/// A single `topic name => [EventType1, EventType2]` declaration.
struct TopicDecl {
    /// User-specified method name suffix (the identifier after `topic`).
    method_name: Ident,
    event_types: Vec<Ident>,
}

/// The full parsed `event_bus!` input.
struct EventBusDef {
    bus_name: Ident,
    events: Vec<EventDecl>,
    topics: Vec<TopicDecl>,
    /// Whether the `redis` attribute was specified: `bus MyBus(redis) { ... }`
    enable_redis: bool,
}

/// Helper: peek if the next token is a specific identifier (e.g. "bus", "event", "topic").
fn peek_keyword(input: &parse::ParseBuffer, keyword: &str) -> bool {
    input.peek(Ident)
        && input
            .cursor()
            .ident()
            .is_some_and(|(ident, _)| ident == keyword)
}

/// Helper: parse a specific identifier keyword or error.
fn parse_keyword(input: parse::ParseStream, keyword: &str) -> syn::Result<()> {
    let ident: Ident = input.parse()?;
    if ident != keyword {
        return Err(syn::Error::new(ident.span(), format!("expected `{}`", keyword)));
    }
    Ok(())
}

impl parse::Parse for EventBusDef {
    fn parse(input: parse::ParseStream) -> syn::Result<Self> {
        // Expect `bus Ident` or `bus Ident(redis) { ... }`
        parse_keyword(input, "bus")?;
        let bus_name: Ident = input.parse()?;

        // Optional `(redis)` attribute
        let mut enable_redis = false;
        if input.peek(syn::token::Paren) {
            let paren_content;
            syn::parenthesized!(paren_content in input);
            let attr: Ident = paren_content.parse()?;
            if attr != "redis" {
                return Err(syn::Error::new(attr.span(), "expected `redis`"));
            }
            enable_redis = true;
        }

        let content;
        braced!(content in input);

        let mut events = Vec::new();
        let mut topics = Vec::new();

        while !content.is_empty() {
            if peek_keyword(&content, "event") {
                // Parse `event Ident { field: Type, ... }`
                parse_keyword(&content, "event")?;
                let name: Ident = content.parse()?;

                let fields_content;
                braced!(fields_content in content);

                let mut fields = Vec::new();
                while !fields_content.is_empty() {
                    let field_name: Ident = fields_content.parse()?;
                    fields_content.parse::<Token![:]>()?;
                    let field_type: Type = fields_content.parse()?;

                    fields.push((field_name, field_type));

                    // Optional trailing comma
                    if fields_content.peek(Token![,]) {
                        fields_content.parse::<Token![,]>()?;
                    }
                }

                events.push(EventDecl { name, fields });
            } else if peek_keyword(&content, "topic") {
                // Parse `topic name => [EventType1, EventType2]`
                parse_keyword(&content, "topic")?;
                let method_name: Ident = content.parse()?;
                content.parse::<Token![=>]>()?;

                let types_content;
                let _bracket = syn::bracketed!(types_content in content);

                let mut event_types = Vec::new();
                while !types_content.is_empty() {
                    let event_type: Path = types_content.parse()?;
                    // Extract the final ident from the path
                    if let Some(segment) = event_type.segments.last() {
                        event_types.push(segment.ident.clone());
                    }
                    // Optional trailing comma
                    if types_content.peek(Token![,]) {
                        types_content.parse::<Token![,]>()?;
                    }
                }

                topics.push(TopicDecl {
                    method_name,
                    event_types,
                });
            } else {
                return Err(content.error("expected `event` or `topic`"));
            }
        }

        Ok(EventBusDef {
            bus_name,
            events,
            topics,
            enable_redis,
        })
    }
}

// ---------------------------------------------------------------------------
// event_bus! macro — code generation
// ---------------------------------------------------------------------------

/// Define a typed event bus with events and topic groupings.
#[proc_macro]
pub fn event_bus(input: TokenStream) -> TokenStream {
    let def = match syn::parse::<EventBusDef>(input) {
        Ok(d) => d,
        Err(e) => return e.to_compile_error().into(),
    };

    let bus_name = &def.bus_name;
    let enum_name = quote::format_ident!("{}TopicEvent", def.bus_name);

    // ------------------------------------------------------------------
    // 1. Generate event structs + Event impls
    // ------------------------------------------------------------------
    let event_structs: Vec<proc_macro2::TokenStream> = def
        .events
        .iter()
        .map(|event| {
            let name = &event.name;
            let event_name_str = camel_to_dotted(&name.to_string());
            let topic_str = first_segment(&event_name_str).to_owned();

            let fields: Vec<proc_macro2::TokenStream> = event
                .fields
                .iter()
                .map(|(fname, ftype)| {
                    quote! { pub #fname: #ftype }
                })
                .collect();

            quote! {
                #[derive(::std::fmt::Debug, ::std::clone::Clone, ::serde::Serialize, ::serde::Deserialize)]
                pub struct #name {
                    #(#fields),*
                }

                impl ::anycms_event::Event for #name {
                    fn event_name() -> &'static str {
                        #event_name_str
                    }

                    fn topic() -> &'static str {
                        #topic_str
                    }

                    fn to_json(&self) -> Option<::serde_json::Value> {
                        ::serde_json::to_value(self).ok()
                    }

                    fn from_json(json: &str) -> Option<Self>
                    where
                        Self: Sized,
                    {
                        ::serde_json::from_str(json).ok()
                    }
                }
            }
        })
        .collect();

    // ------------------------------------------------------------------
    // 2. Generate the topic enum (only if there are topics)
    // ------------------------------------------------------------------
    let topic_enum = if def.topics.is_empty() {
        quote! {}
    } else {
        let variants: Vec<proc_macro2::TokenStream> = def
            .topics
            .iter()
            .flat_map(|topic| &topic.event_types)
            .map(|event_type| {
                quote! { #event_type(#event_type) }
            })
            .collect();

        // Only generate the enum if we have variants
        if variants.is_empty() {
            quote! {}
        } else {
            quote! {
                #[derive(::std::fmt::Debug, ::std::clone::Clone, ::serde::Serialize, ::serde::Deserialize)]
                #[serde(tag = "event_type")]
                pub enum #enum_name {
                    #(#variants),*
                }
            }
        }
    };

    // ------------------------------------------------------------------
    // 3. Generate per-topic subscribe methods
    // ------------------------------------------------------------------
    let topic_subscribe_methods: Vec<proc_macro2::TokenStream> = if def.topics.is_empty() || def.topics.iter().all(|t| t.event_types.is_empty()) {
        Vec::new()
    } else {
        def.topics
            .iter()
            .map(|topic| {
                let method_name = quote::format_ident!("subscribe_topic_{}", topic.method_name);

                let subscribe_arms: Vec<proc_macro2::TokenStream> = topic
                    .event_types
                    .iter()
                    .map(|event_type| {
                        let variant = event_type;
                        quote! {
                            {
                                let h = handler.clone();
                                self.inner.subscribe::<#variant, _, _>(move |e| {
                                    let h = h.clone();
                                    async move { h(#enum_name::#variant(e)).await }
                                }).await
                            }
                        }
                    })
                    .collect();

                quote! {
                    pub async fn #method_name<F, Fut>(&self, handler: F) -> ::std::vec::Vec<::anycms_event::Result<::anycms_event::bus::Subscription>>
                    where
                        F: Fn(#enum_name) -> Fut + ::std::clone::Clone + ::std::marker::Send + ::std::marker::Sync + 'static,
                        Fut: ::std::future::Future<Output = ::anycms_event::Result<()>> + ::std::marker::Send + 'static,
                    {
                        let mut subs = ::std::vec::Vec::new();
                        #(
                            subs.push(#subscribe_arms);
                        )*
                        subs
                    }
                }
            })
            .collect()
    };

    // ------------------------------------------------------------------
    // 4. Generate redis support (only when `redis` attr is set)
    // ------------------------------------------------------------------
    let forward_calls: Vec<proc_macro2::TokenStream> = def
        .events
        .iter()
        .map(|event| {
            let name = &event.name;
            quote! {
                handles.push(bridged.forward_from_redis::<#name>().await?);
            }
        })
        .collect();

    let redis_impl = if def.enable_redis && !def.events.is_empty() {

        // Generate: bridge() method on the typed bus + Bridged wrapper type
        let bridged_name = quote::format_ident!("Bridged{}", def.bus_name);

        quote! {
            /// A [`::anycms_event_redis::BridgedEventBus`] with all event types
            /// automatically forwarded from Redis to the local bus.
            ///
            /// Created via [`#bus_name::bridge`]. Supports the same `publish` and
            /// `subscribe` operations as a plain bus, with events also sent to/received
            /// from Redis.
            pub struct #bridged_name {
                inner: ::anycms_event_redis::BridgedEventBus,
                _forwarder_handles: ::std::vec::Vec<::anycms_event_redis::ForwarderHandle>,
            }

            impl #bridged_name {
                /// Publish an event to both local subscribers and Redis.
                pub async fn publish<E>(&self, event: E) -> ::anycms_event::Result<()>
                where
                    E: ::anycms_event::Event + ::std::clone::Clone
                        + ::serde::Serialize + ::serde::de::DeserializeOwned,
                {
                    self.inner.publish(event).await
                }

                /// Subscribe to a specific event type on the local bus.
                pub async fn subscribe<E, F, Fut>(&self, handler: F) -> ::anycms_event::Result<::anycms_event::bus::Subscription>
                where
                    E: ::anycms_event::Event,
                    F: Fn(E) -> Fut + ::std::marker::Send + ::std::marker::Sync + 'static,
                    Fut: ::std::future::Future<Output = ::anycms_event::Result<()>> + ::std::marker::Send + 'static,
                {
                    self.inner.subscribe::<E, F, Fut>(handler).await
                }

                /// Access the underlying [`::anycms_event_redis::BridgedEventBus`].
                pub fn inner(&self) -> &::anycms_event_redis::BridgedEventBus {
                    &self.inner
                }
            }

            impl ::std::clone::Clone for #bridged_name {
                fn clone(&self) -> Self {
                    Self {
                        inner: self.inner.clone(),
                        // Forwarder handles are not clonable — the clone shares the
                        // same forwarders from the original instance.
                        _forwarder_handles: ::std::vec::Vec::new(),
                    }
                }
            }
        }
    } else {
        quote! {}
    };

    let redis_bridge_method = if def.enable_redis && !def.events.is_empty() {
        let bridged_name = quote::format_ident!("Bridged{}", def.bus_name);

        quote! {
            /// Bridge this bus with a Redis transport, automatically forwarding all
            /// event types from Redis to the local bus.
            ///
            /// Returns a [`#bridged_name`] that supports `publish` and `subscribe`
            /// with Redis integration. No need to call `forward_from_redis` manually.
            ///
            /// # Example
            ///
            /// ```ignore
            /// let transport = RedisTransport::new("redis://127.0.0.1:6379").await?;
            /// let bus = AppEventBus::new();
            /// let bridged = bus.bridge(&transport).await?;
            ///
            /// bridged.subscribe(|e: UserCreated| async move { Ok(()) }).await?;
            /// bridged.publish(UserCreated { ... }).await?; // local + Redis
            /// ```
            pub async fn bridge(
                &self,
                transport: &::anycms_event_redis::RedisTransport,
            ) -> ::std::result::Result<#bridged_name, ::anycms_event_redis::RedisTransportError> {
                let bridged = transport.bridge(self.inner.clone()).await?;
                let mut handles = ::std::vec::Vec::new();
                #(#forward_calls)*
                Ok(#bridged_name {
                    inner: bridged,
                    _forwarder_handles: handles,
                })
            }
        }
    } else {
        quote! {}
    };

    // ------------------------------------------------------------------
    // 5. Generate the typed EventBus newtype
    // ------------------------------------------------------------------
    let bus_impl = quote! {
        pub struct #bus_name {
            inner: ::anycms_event::EventBus,
        }

        impl #bus_name {
            pub fn new() -> Self {
                Self {
                    inner: ::anycms_event::EventBus::new(),
                }
            }

            /// Get a reference to the underlying [`::anycms_event::EventBus`].
            pub fn inner(&self) -> &::anycms_event::EventBus {
                &self.inner
            }

            /// Consume this typed bus and return the underlying [`::anycms_event::EventBus`].
            pub fn into_inner(self) -> ::anycms_event::EventBus {
                self.inner
            }

            pub async fn publish<E: ::anycms_event::Event>(&self, event: E) -> ::anycms_event::Result<()> {
                self.inner.publish(event).await
            }

            pub async fn subscribe<E, F, Fut>(&self, handler: F) -> ::anycms_event::Result<::anycms_event::bus::Subscription>
            where
                E: ::anycms_event::Event,
                F: Fn(E) -> Fut + ::std::marker::Send + ::std::marker::Sync + 'static,
                Fut: ::std::future::Future<Output = ::anycms_event::Result<()>> + ::std::marker::Send + 'static,
            {
                self.inner.subscribe::<E, F, Fut>(handler).await
            }

            #(#topic_subscribe_methods)*

            #redis_bridge_method
        }

        impl ::std::clone::Clone for #bus_name {
            fn clone(&self) -> Self {
                Self {
                    inner: self.inner.clone(),
                }
            }
        }

        impl ::std::default::Default for #bus_name {
            fn default() -> Self {
                Self::new()
            }
        }
    };

    // ------------------------------------------------------------------
    // Assemble everything
    // ------------------------------------------------------------------
    let expanded = quote! {
        #(#event_structs)*
        #topic_enum
        #bus_impl
        #redis_impl
    };

    expanded.into()
}

// ---------------------------------------------------------------------------
// Tests (run with `cargo test -p anycms-event-derive`)
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_camel_to_dotted_simple() {
        assert_eq!(camel_to_dotted("UserCreated"), "user.created");
    }

    #[test]
    fn test_camel_to_dotted_three_words() {
        assert_eq!(camel_to_dotted("UserProfileUpdated"), "user.profile.updated");
    }

    #[test]
    fn test_camel_to_dotted_single_word() {
        assert_eq!(camel_to_dotted("Order"), "order");
    }

    #[test]
    fn test_camel_to_dotted_acronym() {
        assert_eq!(camel_to_dotted("HTTPServer"), "http.server");
    }

    #[test]
    fn test_camel_to_dotted_order_placed() {
        assert_eq!(camel_to_dotted("OrderPlaced"), "order.placed");
    }

    #[test]
    fn test_first_segment_simple() {
        assert_eq!(first_segment("user.created"), "user");
    }

    #[test]
    fn test_first_segment_single() {
        assert_eq!(first_segment("order"), "order");
    }
}