a3s-boot-macros 0.1.2

Attribute macros for a3s-boot
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::{Attribute, Ident, ImplItem, ImplItemFn, ItemImpl, LitStr, Meta, Result, Token};

use crate::controller::attrs::{
    take_controller_metadata_attrs, take_controller_pipeline_attrs, take_route_metadata_attrs,
    take_route_pipeline_attrs, MetadataSpec, PipelineSpec,
};
use crate::controller::{MethodArg, ProtocolExtractor, ProtocolPayloadExtractor, RouteMethodInput};
use crate::decorators::expand_apply_decorators_attrs;
use crate::is_type_ident;
use crate::protocol::json_payload_binding_tokens;
use crate::validation::{
    take_controller_validation_attrs, take_route_validation_attrs,
    AttrOptions as ValidationAttrOptions,
};
use crate::{push_error, set_once};

pub(crate) struct WebSocketGatewayArgs {
    path: LitStr,
    namespace: Option<LitStr>,
}

impl Parse for WebSocketGatewayArgs {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let path = input.parse::<LitStr>()?;
        let mut namespace = None;

        while input.peek(Token![,]) {
            input.parse::<Token![,]>()?;
            if input.is_empty() {
                break;
            }

            let name = input.parse::<Ident>()?;
            input.parse::<Token![=]>()?;
            match name.to_string().as_str() {
                "namespace" => set_once(&mut namespace, input.parse::<LitStr>()?, name)?,
                _ => {
                    return Err(syn::Error::new_spanned(
                        name,
                        "unsupported websocket_gateway option",
                    ));
                }
            }
        }

        Ok(Self { path, namespace })
    }
}

pub(crate) fn expand_websocket_gateway(
    args: WebSocketGatewayArgs,
    mut item_impl: ItemImpl,
) -> Result<proc_macro2::TokenStream> {
    if item_impl.trait_.is_some() {
        return Err(syn::Error::new_spanned(
            &item_impl,
            "#[websocket_gateway] can only be used on inherent impl blocks",
        ));
    }

    let self_ty = item_impl.self_ty.clone();
    let path = args.path;
    let namespace = args.namespace.as_ref().map(
        |namespace| quote!(__a3s_boot_gateway = __a3s_boot_gateway.with_namespace(#namespace)?;),
    );
    let mut subscriptions = Vec::new();
    let mut lifecycle_hooks = Vec::new();
    let mut errors: Option<syn::Error> = None;
    let (impl_attrs, impl_decorator_errors) = expand_apply_decorators_attrs(&item_impl.attrs);
    for error in impl_decorator_errors {
        push_error(&mut errors, error);
    }
    let (clean_impl_attrs, gateway_validation, gateway_validation_errors) =
        take_controller_validation_attrs(&impl_attrs);
    let (clean_impl_attrs, gateway_pipeline, gateway_pipeline_errors) =
        take_controller_pipeline_attrs(&clean_impl_attrs);
    let (clean_impl_attrs, gateway_metadata, gateway_metadata_errors) =
        take_controller_metadata_attrs(&clean_impl_attrs);
    item_impl.attrs = clean_impl_attrs;
    for error in gateway_validation_errors {
        push_error(&mut errors, error);
    }
    for error in gateway_pipeline_errors {
        push_error(&mut errors, error);
    }
    for error in gateway_metadata_errors {
        push_error(&mut errors, error);
    }
    let gateway_pipeline = gateway_pipeline.tokens();
    let gateway_metadata = gateway_metadata.tokens();

    for item in &mut item_impl.items {
        let ImplItem::Fn(method) = item else {
            continue;
        };

        let (method_attrs, decorator_errors) = expand_apply_decorators_attrs(&method.attrs);
        for error in decorator_errors {
            push_error(&mut errors, error);
        }
        let (clean_attrs, events, event_errors) = take_subscribe_message_attrs(&method_attrs);
        let (clean_attrs, lifecycle_kinds, lifecycle_errors) =
            take_websocket_lifecycle_attrs(&clean_attrs);
        let (clean_attrs, route_validation, validation_errors) =
            take_route_validation_attrs(&clean_attrs);
        let (clean_attrs, metadata_specs, metadata_errors) =
            take_route_metadata_attrs(&clean_attrs);
        let (clean_attrs, pipeline_specs, pipeline_errors) =
            take_route_pipeline_attrs(&clean_attrs);
        method.attrs = clean_attrs;
        for error in event_errors {
            push_error(&mut errors, error);
        }
        for error in lifecycle_errors {
            push_error(&mut errors, error);
        }
        for error in validation_errors {
            push_error(&mut errors, error);
        }
        for error in metadata_errors {
            push_error(&mut errors, error);
        }
        for error in pipeline_errors {
            push_error(&mut errors, error);
        }
        if events.is_empty() && !metadata_specs.is_empty() {
            push_error(
                &mut errors,
                syn::Error::new_spanned(
                    &method.sig.ident,
                    "metadata attributes must be used on websocket message handlers",
                ),
            );
        }
        if events.is_empty() && route_validation.is_present() {
            push_error(
                &mut errors,
                syn::Error::new_spanned(
                    &method.sig.ident,
                    "validation attributes must be used on websocket message handlers",
                ),
            );
        }
        if events.is_empty() && !pipeline_specs.is_empty() {
            push_error(
                &mut errors,
                syn::Error::new_spanned(
                    &method.sig.ident,
                    "pipeline attributes must be used on websocket message handlers",
                ),
            );
        }
        if events.is_empty() && lifecycle_kinds.is_empty() {
            continue;
        }

        let input = match RouteMethodInput::from_method(method) {
            Ok(input) => input,
            Err(error) => {
                push_error(&mut errors, error);
                continue;
            }
        };

        if method.sig.asyncness.is_none() {
            push_error(
                &mut errors,
                syn::Error::new_spanned(
                    method.sig.fn_token,
                    "websocket gateway message handlers and lifecycle hooks must be async",
                ),
            );
            continue;
        }

        for event in events {
            let validation_options = route_validation.enabled_options(gateway_validation);
            match websocket_subscription(
                method,
                input.clone(),
                event,
                validation_options,
                &metadata_specs,
                &pipeline_specs,
            ) {
                Ok(subscription) => subscriptions.push(subscription),
                Err(error) => push_error(&mut errors, error),
            }
        }
        for kind in lifecycle_kinds {
            match websocket_lifecycle_hook(method, input.clone(), kind) {
                Ok(hook) => lifecycle_hooks.push(hook),
                Err(error) => push_error(&mut errors, error),
            }
        }
    }

    if let Some(error) = errors {
        return Err(error);
    }

    Ok(quote! {
        #item_impl

        impl #self_ty {
            pub fn gateway(
                self: ::std::sync::Arc<Self>,
            ) -> ::a3s_boot::Result<::a3s_boot::WebSocketGatewayDefinition> {
                let mut __a3s_boot_gateway =
                    ::a3s_boot::WebSocketGatewayDefinition::new(#path)?;
                #namespace
                #(
                    __a3s_boot_gateway = __a3s_boot_gateway.#gateway_metadata?;
                )*
                #(
                    __a3s_boot_gateway = __a3s_boot_gateway.#gateway_pipeline;
                )*
                #(
                    __a3s_boot_gateway = #subscriptions;
                )*
                #(
                    __a3s_boot_gateway = #lifecycle_hooks;
                )*
                Ok(__a3s_boot_gateway)
            }
        }
    })
}

fn take_subscribe_message_attrs(
    attrs: &[Attribute],
) -> (Vec<Attribute>, Vec<LitStr>, Vec<syn::Error>) {
    let mut clean_attrs = Vec::new();
    let mut events = Vec::new();
    let mut errors = Vec::new();

    for attr in attrs {
        let Some(ident) = attr.path().segments.last().map(|segment| &segment.ident) else {
            clean_attrs.push(attr.clone());
            continue;
        };

        if ident != "subscribe_message" {
            clean_attrs.push(attr.clone());
            continue;
        }

        match attr.parse_args::<LitStr>() {
            Ok(event) => events.push(event),
            Err(error) => errors.push(error),
        }
    }

    (clean_attrs, events, errors)
}

#[derive(Clone, Copy)]
enum WebSocketLifecycleHookKind {
    Init,
    Connection,
    Disconnect,
}

impl WebSocketLifecycleHookKind {
    fn from_attribute(attr: &Attribute) -> Option<Self> {
        let ident = attr.path().segments.last().map(|segment| &segment.ident)?;
        if ident == "on_gateway_init" {
            Some(Self::Init)
        } else if ident == "on_gateway_connection" {
            Some(Self::Connection)
        } else if ident == "on_gateway_disconnect" {
            Some(Self::Disconnect)
        } else {
            None
        }
    }

    fn attribute_name(self) -> &'static str {
        match self {
            Self::Init => "on_gateway_init",
            Self::Connection => "on_gateway_connection",
            Self::Disconnect => "on_gateway_disconnect",
        }
    }
}

fn take_websocket_lifecycle_attrs(
    attrs: &[Attribute],
) -> (
    Vec<Attribute>,
    Vec<WebSocketLifecycleHookKind>,
    Vec<syn::Error>,
) {
    let mut clean_attrs = Vec::new();
    let mut hooks = Vec::new();
    let mut errors = Vec::new();

    for attr in attrs {
        let Some(kind) = WebSocketLifecycleHookKind::from_attribute(attr) else {
            clean_attrs.push(attr.clone());
            continue;
        };

        match &attr.meta {
            Meta::Path(_) => hooks.push(kind),
            _ => errors.push(syn::Error::new_spanned(
                attr,
                format!("#[{}] does not accept arguments", kind.attribute_name()),
            )),
        }
    }

    (clean_attrs, hooks, errors)
}

fn websocket_subscription(
    method: &ImplItemFn,
    input: RouteMethodInput,
    event: LitStr,
    validation_options: Option<ValidationAttrOptions>,
    metadata_specs: &[MetadataSpec],
    pipeline_specs: &[PipelineSpec],
) -> Result<proc_macro2::TokenStream> {
    let method_ident = &method.sig.ident;
    let controller_name = format_ident!("__a3s_boot_ws_{}", method_ident);
    let args = websocket_subscription_args(input)?;
    let handler = websocket_subscription_handler(method_ident, &controller_name, &args);
    let pipeline_specs = pipeline_specs.iter().map(PipelineSpec::token);
    let subscription = websocket_subscription_metadata_definition(
        quote! {
            ::a3s_boot::WebSocketSubscriptionDefinition::new_with_connection(#handler)
        },
        metadata_specs,
    );
    let subscription = websocket_validation_subscription(subscription, &args, validation_options)?;
    Ok(quote! {
        __a3s_boot_gateway.subscribe_definition(
            #event,
            (#subscription)
                #(.#pipeline_specs)*
        )?
    })
}

#[derive(Clone)]
struct WebSocketSubscriptionArgs {
    args: Vec<WebSocketSubscriptionArg>,
}

impl WebSocketSubscriptionArgs {
    fn whole_payload_arg(&self) -> Option<&MethodArg> {
        self.args.iter().find_map(|arg| match &arg.kind {
            WebSocketSubscriptionArgKind::Payload(ProtocolPayloadExtractor::Whole) => {
                Some(&arg.arg)
            }
            WebSocketSubscriptionArgKind::Payload(ProtocolPayloadExtractor::Field(_))
            | WebSocketSubscriptionArgKind::Connection
            | WebSocketSubscriptionArgKind::Server
            | WebSocketSubscriptionArgKind::Message => None,
        })
    }

    fn message_arg(&self) -> Option<&MethodArg> {
        self.args.iter().find_map(|arg| match &arg.kind {
            WebSocketSubscriptionArgKind::Message => Some(&arg.arg),
            WebSocketSubscriptionArgKind::Connection
            | WebSocketSubscriptionArgKind::Server
            | WebSocketSubscriptionArgKind::Payload(_) => None,
        })
    }
}

#[derive(Clone)]
struct WebSocketSubscriptionArg {
    arg: MethodArg,
    kind: WebSocketSubscriptionArgKind,
}

#[derive(Clone)]
enum WebSocketSubscriptionArgKind {
    Connection,
    Server,
    Message,
    Payload(ProtocolPayloadExtractor),
}

fn websocket_subscription_args(input: RouteMethodInput) -> Result<WebSocketSubscriptionArgs> {
    if input.has_extractors() {
        return Err(syn::Error::new_spanned(
            input
                .args
                .iter()
                .find(|arg| arg.extractor.is_some())
                .map(|arg| arg.ident.clone())
                .unwrap_or_else(|| format_ident!("argument")),
            "websocket subscription methods do not support route extractor attributes",
        ));
    }

    let has_protocol_extractors = input.has_protocol_extractors();
    let mut has_connection = false;
    let mut has_server = false;
    let mut has_message_arg = false;
    let mut whole_payload_arg = None;
    let mut field_payload_arg = None;
    let mut args = Vec::new();

    for arg in input.args {
        let kind = if is_type_ident(&arg.ty, "WebSocketGatewayConnection") {
            if arg.protocol_extractor.is_some() {
                return Err(syn::Error::new_spanned(
                    arg.ident,
                    "WebSocketGatewayConnection arguments do not use protocol payload extractor attributes",
                ));
            }
            if has_connection {
                return Err(syn::Error::new_spanned(
                    arg.ident,
                    "websocket subscription methods can accept at most one WebSocketGatewayConnection argument",
                ));
            }
            has_connection = true;
            WebSocketSubscriptionArgKind::Connection
        } else if is_type_ident(&arg.ty, "WebSocketGatewayServer") {
            if arg.protocol_extractor.is_some() {
                return Err(syn::Error::new_spanned(
                    arg.ident,
                    "WebSocketGatewayServer arguments do not use protocol payload extractor attributes",
                ));
            }
            if has_server {
                return Err(syn::Error::new_spanned(
                    arg.ident,
                    "websocket subscription methods can accept at most one WebSocketGatewayServer argument",
                ));
            }
            has_server = true;
            WebSocketSubscriptionArgKind::Server
        } else if !has_protocol_extractors {
            if is_type_ident(&arg.ty, "WebSocketMessage") {
                if has_message_arg || whole_payload_arg.is_some() {
                    return Err(syn::Error::new_spanned(
                        arg.ident,
                        "websocket subscription methods can accept at most one message body argument",
                    ));
                }
                has_message_arg = true;
                WebSocketSubscriptionArgKind::Message
            } else {
                if has_message_arg || whole_payload_arg.is_some() {
                    return Err(syn::Error::new_spanned(
                        arg.ident,
                        "websocket subscription methods can accept at most one message body argument",
                    ));
                }
                whole_payload_arg = Some(arg.ident.clone());
                WebSocketSubscriptionArgKind::Payload(ProtocolPayloadExtractor::Whole)
            }
        } else {
            let Some(extractor) = arg.protocol_extractor.clone() else {
                return Err(syn::Error::new_spanned(
                    arg.ident,
                    "websocket subscription methods must use #[message_body] on every payload argument when any protocol payload extractor is used",
                ));
            };

            let payload = match extractor {
                ProtocolExtractor::MessageBody(payload) => payload,
                ProtocolExtractor::Payload(_) => {
                    return Err(syn::Error::new_spanned(
                        arg.ident,
                        "websocket subscription methods support #[message_body], not #[payload]",
                    ));
                }
            };

            if is_type_ident(&arg.ty, "WebSocketMessage") {
                return Err(syn::Error::new_spanned(
                    arg.ident,
                    "whole #[message_body] arguments must be DTOs; use an undecorated WebSocketMessage argument for raw access",
                ));
            }

            match &payload {
                ProtocolPayloadExtractor::Whole => {
                    if let Some(existing) = whole_payload_arg {
                        return Err(syn::Error::new_spanned(
                            existing,
                            "websocket subscription methods can accept at most one whole #[message_body] argument",
                        ));
                    }
                    if let Some(existing) = &field_payload_arg {
                        return Err(syn::Error::new_spanned(
                            existing,
                            "websocket subscription methods cannot combine whole #[message_body] arguments with #[message_body(\"field\")] arguments",
                        ));
                    }
                    whole_payload_arg = Some(arg.ident.clone());
                }
                ProtocolPayloadExtractor::Field(_) => {
                    if let Some(existing) = &whole_payload_arg {
                        return Err(syn::Error::new_spanned(
                            existing,
                            "websocket subscription methods cannot combine whole #[message_body] arguments with #[message_body(\"field\")] arguments",
                        ));
                    }
                    field_payload_arg.get_or_insert_with(|| arg.ident.clone());
                }
            }

            WebSocketSubscriptionArgKind::Payload(payload)
        };
        args.push(WebSocketSubscriptionArg { arg, kind });
    }

    Ok(WebSocketSubscriptionArgs { args })
}

fn websocket_subscription_handler(
    method_ident: &Ident,
    controller_name: &Ident,
    args: &WebSocketSubscriptionArgs,
) -> proc_macro2::TokenStream {
    let bindings = args.args.iter().map(|arg| {
        let MethodArg { ident, ty, .. } = &arg.arg;
        match &arg.kind {
            WebSocketSubscriptionArgKind::Connection => quote! {
                let #ident: #ty = __a3s_boot_connection.clone();
            },
            WebSocketSubscriptionArgKind::Server => quote! {
                let #ident: #ty = __a3s_boot_connection.server();
            },
            WebSocketSubscriptionArgKind::Message => quote! {
                let #ident: #ty = __a3s_boot_message.clone();
            },
            WebSocketSubscriptionArgKind::Payload(extractor) => json_payload_binding_tokens(
                ident.clone(),
                ty.clone(),
                extractor.clone(),
                |value_ty| quote!(__a3s_boot_message.data_as::<#value_ty>()),
                |value_ty, name| quote!(__a3s_boot_message.data_field_as::<#value_ty>(#name)),
                |value_ty, name| {
                    quote!(__a3s_boot_message.optional_data_field_as::<#value_ty>(#name))
                },
                |name| quote!(__a3s_boot_message.data_field_string(#name)),
                |name| quote!(__a3s_boot_message.optional_data_field_string(#name)),
            ),
        }
    });
    let call_args = args.args.iter().map(|arg| &arg.arg.ident);

    quote! {
        {
            let #controller_name = ::std::sync::Arc::clone(&self);
            move |
                __a3s_boot_connection: ::a3s_boot::WebSocketGatewayConnection,
                __a3s_boot_message: ::a3s_boot::WebSocketMessage,
            | {
                let #controller_name = ::std::sync::Arc::clone(&#controller_name);
                async move {
                    #(#bindings)*
                    #controller_name.#method_ident(#(#call_args),*).await
                }
            }
        }
    }
}

fn websocket_validation_subscription(
    subscription: proc_macro2::TokenStream,
    args: &WebSocketSubscriptionArgs,
    validation_options: Option<ValidationAttrOptions>,
) -> Result<proc_macro2::TokenStream> {
    let Some(options) = validation_options else {
        return Ok(subscription);
    };

    if let Some(arg) = args.message_arg() {
        return Err(syn::Error::new_spanned(
            arg.ident.clone(),
            "websocket validation requires a DTO message body argument, not WebSocketMessage",
        ));
    }

    let Some(arg) = args.whole_payload_arg() else {
        return Err(syn::Error::new(
            proc_macro2::Span::call_site(),
            "websocket validation requires one whole typed message body argument",
        ));
    };

    let ty = &arg.ty;
    if options.is_empty() {
        Ok(quote! {
            (#subscription).with_payload_validation::<#ty>()
        })
    } else {
        let options = options.token();
        Ok(quote! {
            (#subscription).with_payload_validation_options::<#ty>(#options)
        })
    }
}

fn websocket_subscription_metadata_definition(
    mut subscription: proc_macro2::TokenStream,
    metadata_specs: &[MetadataSpec],
) -> proc_macro2::TokenStream {
    for spec in metadata_specs {
        let key = &spec.key;
        let value = &spec.value;
        subscription = quote! {
            (#subscription).with_metadata(#key, #value)?
        };
    }
    subscription
}

fn websocket_lifecycle_hook(
    method: &ImplItemFn,
    input: RouteMethodInput,
    kind: WebSocketLifecycleHookKind,
) -> Result<proc_macro2::TokenStream> {
    let method_ident = &method.sig.ident;
    let gateway_name = format_ident!("__a3s_boot_ws_{}", method_ident);
    let (builder, context_ty) = match kind {
        WebSocketLifecycleHookKind::Init => (
            quote!(with_after_init),
            quote!(::a3s_boot::WebSocketGatewayInitContext),
        ),
        WebSocketLifecycleHookKind::Connection => (
            quote!(with_connection_hook),
            quote!(::a3s_boot::WebSocketGatewayConnection),
        ),
        WebSocketLifecycleHookKind::Disconnect => (
            quote!(with_disconnect_hook),
            quote!(::a3s_boot::WebSocketGatewayConnection),
        ),
    };
    let args = websocket_lifecycle_args(input, kind)?;
    let bindings = args.bindings();
    let call_args = args.call_args();
    let handler = quote! {
        {
            let #gateway_name = ::std::sync::Arc::clone(&self);
            move |__a3s_boot_context: #context_ty| {
                let #gateway_name = ::std::sync::Arc::clone(&#gateway_name);
                async move {
                    #(#bindings)*
                    #gateway_name.#method_ident(#(#call_args),*).await
                }
            }
        }
    };

    Ok(quote! {
        __a3s_boot_gateway.#builder(#handler)
    })
}

#[derive(Clone)]
struct WebSocketLifecycleArgs {
    args: Vec<WebSocketLifecycleArg>,
}

impl WebSocketLifecycleArgs {
    fn bindings(&self) -> Vec<proc_macro2::TokenStream> {
        self.args
            .iter()
            .map(|arg| {
                let MethodArg { ident, ty, .. } = &arg.arg;
                match arg.kind {
                    WebSocketLifecycleArgKind::Context => quote! {
                        let #ident: #ty = __a3s_boot_context.clone();
                    },
                    WebSocketLifecycleArgKind::Server => quote! {
                        let #ident: #ty = __a3s_boot_context.server();
                    },
                }
            })
            .collect()
    }

    fn call_args(&self) -> Vec<Ident> {
        self.args.iter().map(|arg| arg.arg.ident.clone()).collect()
    }
}

#[derive(Clone)]
struct WebSocketLifecycleArg {
    arg: MethodArg,
    kind: WebSocketLifecycleArgKind,
}

#[derive(Clone, Copy)]
enum WebSocketLifecycleArgKind {
    Context,
    Server,
}

fn websocket_lifecycle_args(
    input: RouteMethodInput,
    kind: WebSocketLifecycleHookKind,
) -> Result<WebSocketLifecycleArgs> {
    if input.has_extractors() || input.has_protocol_extractors() {
        return Err(syn::Error::new_spanned(
            input
                .args
                .iter()
                .find(|arg| arg.extractor.is_some() || arg.protocol_extractor.is_some())
                .map(|arg| arg.ident.clone())
                .unwrap_or_else(|| format_ident!("argument")),
            "websocket lifecycle hook methods do not support extractor attributes",
        ));
    }

    let context_type = match kind {
        WebSocketLifecycleHookKind::Init => "WebSocketGatewayInitContext",
        WebSocketLifecycleHookKind::Connection | WebSocketLifecycleHookKind::Disconnect => {
            "WebSocketGatewayConnection"
        }
    };
    let mut has_context = false;
    let mut has_server = false;
    let mut args = Vec::new();

    for arg in input.args {
        let kind = if is_type_ident(&arg.ty, "WebSocketGatewayServer") {
            if has_server {
                return Err(syn::Error::new_spanned(
                    arg.ident,
                    "websocket lifecycle hook methods can accept at most one WebSocketGatewayServer argument",
                ));
            }
            has_server = true;
            WebSocketLifecycleArgKind::Server
        } else if is_type_ident(&arg.ty, context_type) {
            if has_context {
                return Err(syn::Error::new_spanned(
                    arg.ident,
                    format!(
                        "websocket lifecycle hook methods can accept at most one {context_type} argument"
                    ),
                ));
            }
            has_context = true;
            WebSocketLifecycleArgKind::Context
        } else {
            return Err(syn::Error::new_spanned(
                arg.ident,
                format!(
                    "websocket lifecycle hook methods can only accept {context_type} and WebSocketGatewayServer arguments"
                ),
            ));
        };

        args.push(WebSocketLifecycleArg { arg, kind });
    }

    Ok(WebSocketLifecycleArgs { args })
}