protoc-gen-rust-temporal 0.1.1

protoc plugin that emits a typed Rust Temporal client from temporal.v1.* annotated services
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! `ServiceModel` -> Rust source emission.
//!
//! Output shape (`<package>_<service>_temporal` module):
//!
//! * One `<RPC>_WORKFLOW_NAME` constant per workflow.
//! * One `<Service>Client` struct holding a `temporal_runtime::TemporalClient`,
//!   plus one `<rpc>(input, opts) -> <Workflow>Handle` start method and one
//!   `<rpc>_handle(workflow_id)` attach method per workflow.
//! * One `<Workflow>StartOptions` per workflow.
//! * One `<Workflow>Handle` per workflow, exposing only the signals, queries,
//!   and updates wired in via `WorkflowOptions.{signal,query,update}`.
//! * One `<signal>_with_start` / `<update>_with_start` free function per
//!   start-flagged ref.
//!
//! Generated code refers to runtime helpers via `crate::temporal_runtime::*`
//! — the consumer crate provides that module. This mirrors the PoC's wiring
//! and lets the plugin stay agnostic to whichever Temporal SDK shape the
//! consumer pins.

use std::fmt::Write;

use heck::{ToShoutySnakeCase, ToSnakeCase};

use crate::model::{
    IdTemplateSegment, QueryModel, ServiceModel, SignalModel, UpdateModel, WorkflowModel,
};

/// Render the `<package>_<service>_temporal.rs` source for one service.
pub fn render(svc: &ServiceModel) -> String {
    let mut out = String::new();
    let mod_name = mod_name(svc);
    let proto_mod = proto_module_path(&svc.package);
    let client_struct = format!("{}Client", svc.service);

    let _ = writeln!(
        out,
        "// Code generated by protoc-gen-rust-temporal. DO NOT EDIT."
    );
    let _ = writeln!(out, "// source: {}", svc.source_file);
    let _ = writeln!(out);
    let _ = writeln!(out, "#[allow(clippy::all, unused_imports, dead_code)]");
    let _ = writeln!(out, "pub mod {mod_name} {{");
    let _ = writeln!(out, "    use anyhow::Result;");
    let _ = writeln!(out, "    use std::time::Duration;");
    let _ = writeln!(out, "    use crate::temporal_runtime;");
    let _ = writeln!(out, "    use {proto_mod}::*;");
    let _ = writeln!(out);

    render_message_type_impls(&mut out, svc);
    render_constants(&mut out, svc);
    render_id_fns(&mut out, svc);
    render_client_struct(&mut out, svc, &client_struct);
    for wf in &svc.workflows {
        render_start_options(&mut out, wf);
        render_handle(&mut out, svc, wf);
    }
    render_with_start_functions(&mut out, svc);

    let _ = writeln!(out, "}}");
    out
}

/// Emit one `impl temporal_runtime::TemporalProtoMessage for <Ty>` per
/// distinct prost message type referenced by this service. The runtime
/// facade re-exports the trait from `temporal-proto-runtime`, so this is
/// what lets `start_workflow_proto::<I>` / `signal_proto::<I>` etc. resolve
/// at the call site. `google.protobuf.Empty` types are skipped — the
/// `_empty` runtime variants take no payload generic.
fn render_message_type_impls(out: &mut String, svc: &ServiceModel) {
    use std::collections::BTreeMap;

    let mut by_rust_name: BTreeMap<String, String> = BTreeMap::new();
    let mut record = |pt: &crate::model::ProtoType| {
        if pt.is_empty {
            return;
        }
        by_rust_name
            .entry(pt.rust_name().to_string())
            .or_insert_with(|| pt.full_name.clone());
    };

    for wf in &svc.workflows {
        record(&wf.input_type);
        record(&wf.output_type);
    }
    for s in &svc.signals {
        record(&s.input_type);
        record(&s.output_type);
    }
    for q in &svc.queries {
        record(&q.input_type);
        record(&q.output_type);
    }
    for u in &svc.updates {
        record(&u.input_type);
        record(&u.output_type);
    }
    // Activities are validate-only — their message types are not used by the
    // emitted client surface, so they do not need impls.

    if by_rust_name.is_empty() {
        return;
    }

    for (rust_name, full_name) in &by_rust_name {
        let _ = writeln!(
            out,
            "    impl temporal_runtime::TemporalProtoMessage for {rust_name} {{"
        );
        let _ = writeln!(
            out,
            "        const MESSAGE_TYPE: &'static str = \"{full_name}\";"
        );
        let _ = writeln!(out, "    }}");
    }
    let _ = writeln!(out);
}

fn render_constants(out: &mut String, svc: &ServiceModel) {
    for wf in &svc.workflows {
        let const_name = format!("{}_WORKFLOW_NAME", wf.rpc_method.to_shouty_snake_case());
        let _ = writeln!(
            out,
            "    pub const {const_name}: &str = \"{}\";",
            wf.registered_name
        );
        if let Some(tq) = effective_task_queue(svc, wf) {
            let tq_const = format!("{}_TASK_QUEUE", wf.rpc_method.to_shouty_snake_case());
            let _ = writeln!(out, "    pub const {tq_const}: &str = \"{tq}\";");
        }
    }
    if !svc.workflows.is_empty() {
        let _ = writeln!(out);
    }
}

/// Emit one private `<wf>_id` function per workflow that has an `id`
/// template, materialising the template into a `format!` against the
/// input message's fields at codegen time. The start path (and the
/// `<signal>_with_start` / `<update>_with_start` free functions) call
/// this instead of a generic runtime template helper — there's no
/// runtime template engine to maintain and the field lookups are
/// statically type-checked.
fn render_id_fns(out: &mut String, svc: &ServiceModel) {
    let mut emitted_any = false;
    for wf in &svc.workflows {
        let Some(segments) = wf.id_expression.as_ref() else {
            continue;
        };
        emitted_any = true;
        let fn_name = format!("{}_id", wf.rpc_method.to_snake_case());
        let (fmt, args) = compile_id_template(segments);

        if wf.input_type.is_empty {
            // Validation in parse.rs guarantees a Field segment cannot
            // refer to a field on Empty, so `args` is empty here. The fn
            // takes no input.
            let _ = writeln!(out, "    fn {fn_name}() -> String {{");
            if fmt.is_empty() {
                let _ = writeln!(out, "        String::new()");
            } else {
                let _ = writeln!(out, "        \"{fmt}\".to_string()");
            }
            let _ = writeln!(out, "    }}");
            let _ = writeln!(out);
            continue;
        }

        let input_ty = wf.input_type.rust_name();
        let _ = writeln!(out, "    fn {fn_name}(input: &{input_ty}) -> String {{");
        if args.is_empty() {
            let _ = writeln!(out, "        let _ = input;");
            let _ = writeln!(out, "        \"{fmt}\".to_string()");
        } else {
            let _ = writeln!(out, "        format!(\"{fmt}\", {})", args.join(", "));
        }
        let _ = writeln!(out, "    }}");
        let _ = writeln!(out);
    }
    if emitted_any {
        // No trailing blank — `render_client_struct` adds its own.
    }
}

/// Pick the call site that produces a workflow id when the caller did
/// not supply one. With a proto-declared `id` template we route through
/// the codegen-emitted `<wf>_id(...)` function; without one we fall
/// back to `temporal_runtime::random_workflow_id()`.
///
/// `in_self_method` is true inside `<Service>Client::<rpc>` (where the
/// workflow input is named `input`) and false inside the
/// `<signal>_with_start` / `<update>_with_start` free functions (where
/// the workflow input is named `workflow_input`).
fn id_fallback_call(wf: &WorkflowModel, in_self_method: bool) -> String {
    if wf.id_expression.is_none() {
        return "temporal_runtime::random_workflow_id()".to_string();
    }
    let fn_name = format!("{}_id", wf.rpc_method.to_snake_case());
    if wf.input_type.is_empty {
        // Validated in parse.rs: an Empty workflow input cannot host a
        // Field segment, so the id fn takes no arguments.
        return format!("{fn_name}()");
    }
    if in_self_method {
        format!("{fn_name}(&input)")
    } else {
        format!("{fn_name}(&workflow_input)")
    }
}

/// Walk template segments into a `format!` string + arg list. Literal `{`
/// and `}` characters in the template are doubled so they survive the
/// `format!` parse.
fn compile_id_template(segments: &[IdTemplateSegment]) -> (String, Vec<String>) {
    let mut fmt = String::new();
    let mut args = Vec::new();
    for seg in segments {
        match seg {
            IdTemplateSegment::Literal(s) => {
                fmt.push_str(&s.replace('{', "{{").replace('}', "}}"));
            }
            IdTemplateSegment::Field(rust_name) => {
                fmt.push_str("{}");
                args.push(format!("input.{rust_name}"));
            }
        }
    }
    (fmt, args)
}

fn render_client_struct(out: &mut String, svc: &ServiceModel, client_struct: &str) {
    let _ = writeln!(out, "    pub struct {client_struct} {{");
    let _ = writeln!(out, "        client: temporal_runtime::TemporalClient,");
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out);

    let _ = writeln!(out, "    impl {client_struct} {{");
    let _ = writeln!(
        out,
        "        pub fn new(client: temporal_runtime::TemporalClient) -> Self {{"
    );
    let _ = writeln!(out, "            Self {{ client }}");
    let _ = writeln!(out, "        }}");
    let _ = writeln!(out);
    let _ = writeln!(
        out,
        "        pub fn inner(&self) -> &temporal_runtime::TemporalClient {{"
    );
    let _ = writeln!(out, "            &self.client");
    let _ = writeln!(out, "        }}");
    let _ = writeln!(out);

    for wf in &svc.workflows {
        render_client_workflow_methods(out, svc, wf);
    }

    let _ = writeln!(out, "    }}");
    let _ = writeln!(out);
}

fn render_client_workflow_methods(out: &mut String, svc: &ServiceModel, wf: &WorkflowModel) {
    let method_snake = wf.rpc_method.to_snake_case();
    let handle_struct = format!("{}Handle", wf.rpc_method);
    let opts_struct = format!("{}StartOptions", wf.rpc_method);
    let const_name = format!("{}_WORKFLOW_NAME", wf.rpc_method.to_shouty_snake_case());

    let _ = writeln!(
        out,
        "        /// Start a new `{}` workflow.",
        wf.registered_name
    );
    let _ = writeln!(out, "        pub async fn {method_snake}(");
    let _ = writeln!(out, "            &self,");
    if !wf.input_type.is_empty {
        let _ = writeln!(out, "            input: {},", wf.input_type.rust_name());
    }
    let _ = writeln!(out, "            opts: {opts_struct},");
    let _ = writeln!(out, "        ) -> Result<{handle_struct}> {{");
    render_start_body(
        out,
        svc,
        wf,
        &const_name,
        /* leading_indent: */ "            ",
    );
    let _ = writeln!(out, "            Ok({handle_struct} {{ inner }})");
    let _ = writeln!(out, "        }}");
    let _ = writeln!(out);

    let _ = writeln!(
        out,
        "        /// Attach to a running `{}` workflow by id.",
        wf.registered_name
    );
    let _ = writeln!(
        out,
        "        pub fn {method_snake}_handle(&self, workflow_id: impl Into<String>) -> {handle_struct} {{"
    );
    let _ = writeln!(out, "            {handle_struct} {{");
    let _ = writeln!(
        out,
        "                inner: temporal_runtime::attach_handle(&self.client, workflow_id.into()),"
    );
    let _ = writeln!(out, "            }}");
    let _ = writeln!(out, "        }}");
    let _ = writeln!(out);
}

/// Emit the body of the regular start method: resolves workflow_id +
/// task_queue and dispatches `start_workflow_proto`. `leading_indent` is the
/// whitespace prefix applied to each emitted line (12 spaces inside an
/// `impl` method, 8 spaces inside a free function).
fn render_start_body(
    out: &mut String,
    svc: &ServiceModel,
    wf: &WorkflowModel,
    const_name: &str,
    leading_indent: &str,
) {
    let ind = leading_indent;
    let _ = writeln!(
        out,
        "{ind}let workflow_id = opts.workflow_id.unwrap_or_else(|| {{"
    );
    let _ = writeln!(
        out,
        "{ind}    {}",
        id_fallback_call(wf, /* in_self_method: */ true)
    );
    let _ = writeln!(out, "{ind}}});");

    if let Some(tq) = effective_task_queue(svc, wf) {
        let _ = writeln!(
            out,
            "{ind}let task_queue = opts.task_queue.unwrap_or_else(|| \"{tq}\".to_string());"
        );
    } else {
        let _ = writeln!(
            out,
            "{ind}let task_queue = opts.task_queue.expect(\"workflow has no proto-level task_queue; opts.task_queue is required\");"
        );
    }

    if wf.input_type.is_empty {
        // Empty workflow input — route to a separate runtime function that
        // skips the payload arg. Avoids `&()` not impl'ing
        // TemporalProtoMessage at the call site.
        let _ = writeln!(
            out,
            "{ind}let inner = temporal_runtime::start_workflow_proto_empty("
        );
        let _ = writeln!(out, "{ind}    &self.client,");
        let _ = writeln!(out, "{ind}    {const_name},");
        let _ = writeln!(out, "{ind}    &workflow_id,");
        let _ = writeln!(out, "{ind}    &task_queue,");
    } else {
        let _ = writeln!(
            out,
            "{ind}let inner = temporal_runtime::start_workflow_proto("
        );
        let _ = writeln!(out, "{ind}    &self.client,");
        let _ = writeln!(out, "{ind}    {const_name},");
        let _ = writeln!(out, "{ind}    &workflow_id,");
        let _ = writeln!(out, "{ind}    &task_queue,");
        let _ = writeln!(out, "{ind}    &input,");
    }
    let _ = writeln!(out, "{ind}    opts.id_reuse_policy,");
    let _ = writeln!(out, "{ind}    opts.execution_timeout,");
    let _ = writeln!(out, "{ind}    opts.run_timeout,");
    let _ = writeln!(out, "{ind}    opts.task_timeout,");
    let _ = writeln!(out, "{ind}).await?;");
}

fn render_start_options(out: &mut String, wf: &WorkflowModel) {
    let opts_struct = format!("{}StartOptions", wf.rpc_method);
    let _ = writeln!(out, "    #[derive(Debug, Default, Clone)]");
    let _ = writeln!(out, "    pub struct {opts_struct} {{");
    let _ = writeln!(out, "        pub workflow_id: Option<String>,");
    let _ = writeln!(out, "        pub task_queue: Option<String>,");
    let _ = writeln!(
        out,
        "        pub id_reuse_policy: Option<temporal_runtime::WorkflowIdReusePolicy>,"
    );
    let _ = writeln!(out, "        pub execution_timeout: Option<Duration>,");
    let _ = writeln!(out, "        pub run_timeout: Option<Duration>,");
    let _ = writeln!(out, "        pub task_timeout: Option<Duration>,");
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out);

    let mut defaults: Vec<(&'static str, String, &'static str)> = Vec::new();
    if let Some(p) = wf.id_reuse_policy {
        defaults.push((
            "default_id_reuse_policy",
            format!(
                "temporal_runtime::WorkflowIdReusePolicy::{}",
                p.rust_variant()
            ),
            "temporal_runtime::WorkflowIdReusePolicy",
        ));
    }
    if let Some(d) = wf.execution_timeout {
        defaults.push(("default_execution_timeout", duration_literal(d), "Duration"));
    }
    if let Some(d) = wf.run_timeout {
        defaults.push(("default_run_timeout", duration_literal(d), "Duration"));
    }
    if let Some(d) = wf.task_timeout {
        defaults.push(("default_task_timeout", duration_literal(d), "Duration"));
    }
    if !defaults.is_empty() {
        let _ = writeln!(out, "    impl {opts_struct} {{");
        for (name, value, return_ty) in &defaults {
            let _ = writeln!(out, "        pub fn {name}() -> {return_ty} {{");
            let _ = writeln!(out, "            {value}");
            let _ = writeln!(out, "        }}");
        }
        let _ = writeln!(out, "    }}");
        let _ = writeln!(out);
    }
}

fn render_handle(out: &mut String, svc: &ServiceModel, wf: &WorkflowModel) {
    let handle_struct = format!("{}Handle", wf.rpc_method);
    let _ = writeln!(out, "    pub struct {handle_struct} {{");
    let _ = writeln!(out, "        inner: temporal_runtime::WorkflowHandle,");
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out);

    let _ = writeln!(out, "    impl {handle_struct} {{");
    let _ = writeln!(out, "        pub fn workflow_id(&self) -> &str {{");
    let _ = writeln!(out, "            self.inner.workflow_id()");
    let _ = writeln!(out, "        }}");
    let _ = writeln!(out);

    // result()
    let _ = writeln!(
        out,
        "        /// Wait for the workflow to complete and return its output."
    );
    if wf.output_type.is_empty {
        let _ = writeln!(out, "        pub async fn result(&self) -> Result<()> {{");
        let _ = writeln!(
            out,
            "            temporal_runtime::wait_result_unit(&self.inner).await"
        );
        let _ = writeln!(out, "        }}");
    } else {
        let output_ty = wf.output_type.rust_name();
        let _ = writeln!(
            out,
            "        pub async fn result(&self) -> Result<{output_ty}> {{"
        );
        let _ = writeln!(
            out,
            "            temporal_runtime::wait_result_proto::<{output_ty}>(&self.inner).await"
        );
        let _ = writeln!(out, "        }}");
    }
    let _ = writeln!(out);

    for sref in &wf.attached_signals {
        if let Some(sig) = svc.signals.iter().find(|s| s.rpc_method == sref.rpc_method) {
            render_signal_method(out, sig);
        }
    }
    for qref in &wf.attached_queries {
        if let Some(q) = svc
            .queries
            .iter()
            .find(|qq| qq.rpc_method == qref.rpc_method)
        {
            render_query_method(out, q);
        }
    }
    for uref in &wf.attached_updates {
        if let Some(u) = svc
            .updates
            .iter()
            .find(|uu| uu.rpc_method == uref.rpc_method)
        {
            render_update_method(out, u);
        }
    }

    let _ = writeln!(out, "    }}");
    let _ = writeln!(out);
}

fn render_signal_method(out: &mut String, sig: &SignalModel) {
    let method_snake = sig.rpc_method.to_snake_case();
    let _ = writeln!(
        out,
        "        /// Send the `{}` signal.",
        sig.registered_name
    );
    if sig.input_type.is_empty {
        let _ = writeln!(
            out,
            "        pub async fn {method_snake}(&self) -> Result<()> {{"
        );
        let _ = writeln!(
            out,
            "            temporal_runtime::signal_unit(&self.inner, \"{}\").await",
            sig.registered_name
        );
        let _ = writeln!(out, "        }}");
    } else {
        let input_ty = sig.input_type.rust_name();
        let _ = writeln!(
            out,
            "        pub async fn {method_snake}(&self, input: {input_ty}) -> Result<()> {{"
        );
        let _ = writeln!(
            out,
            "            temporal_runtime::signal_proto(&self.inner, \"{}\", &input).await",
            sig.registered_name
        );
        let _ = writeln!(out, "        }}");
    }
    let _ = writeln!(out);
}

fn render_query_method(out: &mut String, q: &QueryModel) {
    let method_snake = q.rpc_method.to_snake_case();
    let out_ty = q.output_type.rust_name();
    let _ = writeln!(out, "        /// Run the `{}` query.", q.registered_name);
    if q.input_type.is_empty {
        let _ = writeln!(
            out,
            "        pub async fn {method_snake}(&self) -> Result<{out_ty}> {{"
        );
        let _ = writeln!(
            out,
            "            temporal_runtime::query_proto_empty::<{out_ty}>(&self.inner, \"{}\").await",
            q.registered_name
        );
        let _ = writeln!(out, "        }}");
    } else {
        let in_ty = q.input_type.rust_name();
        let _ = writeln!(
            out,
            "        pub async fn {method_snake}(&self, input: {in_ty}) -> Result<{out_ty}> {{"
        );
        let _ = writeln!(
            out,
            "            temporal_runtime::query_proto::<{in_ty}, {out_ty}>(&self.inner, \"{}\", &input).await",
            q.registered_name
        );
        let _ = writeln!(out, "        }}");
    }
    let _ = writeln!(out);
}

fn render_update_method(out: &mut String, u: &UpdateModel) {
    let method_snake = u.rpc_method.to_snake_case();
    let out_ty = u.output_type.rust_name();
    let _ = writeln!(out, "        /// Run the `{}` update.", u.registered_name);
    if u.input_type.is_empty {
        let _ = writeln!(
            out,
            "        pub async fn {method_snake}(&self, wait_policy: temporal_runtime::WaitPolicy) -> Result<{out_ty}> {{"
        );
        let _ = writeln!(
            out,
            "            temporal_runtime::update_proto_empty::<{out_ty}>(&self.inner, \"{}\", wait_policy).await",
            u.registered_name
        );
        let _ = writeln!(out, "        }}");
    } else {
        let in_ty = u.input_type.rust_name();
        let _ = writeln!(
            out,
            "        pub async fn {method_snake}(&self, input: {in_ty}, wait_policy: temporal_runtime::WaitPolicy) -> Result<{out_ty}> {{"
        );
        let _ = writeln!(
            out,
            "            temporal_runtime::update_proto::<{in_ty}, {out_ty}>(&self.inner, \"{}\", &input, wait_policy).await",
            u.registered_name
        );
        let _ = writeln!(out, "        }}");
    }
    let _ = writeln!(out);
}

fn render_with_start_functions(out: &mut String, svc: &ServiceModel) {
    for wf in &svc.workflows {
        for sref in &wf.attached_signals {
            if !sref.start {
                continue;
            }
            let Some(sig) = svc.signals.iter().find(|s| s.rpc_method == sref.rpc_method) else {
                continue;
            };
            render_signal_with_start_fn(out, svc, wf, sig);
        }
        for uref in &wf.attached_updates {
            if !uref.start {
                continue;
            }
            let Some(u) = svc
                .updates
                .iter()
                .find(|uu| uu.rpc_method == uref.rpc_method)
            else {
                continue;
            };
            render_update_with_start_fn(out, svc, wf, u);
        }
    }
}

fn render_signal_with_start_fn(
    out: &mut String,
    svc: &ServiceModel,
    wf: &WorkflowModel,
    sig: &SignalModel,
) {
    // Free function lives alongside the client struct so callers can pass a
    // raw `TemporalClient` without constructing the client wrapper.
    let fn_name = format!("{}_with_start", sig.rpc_method.to_snake_case());
    let handle_struct = format!("{}Handle", wf.rpc_method);
    let opts_struct = format!("{}StartOptions", wf.rpc_method);
    let const_name = format!("{}_WORKFLOW_NAME", wf.rpc_method.to_shouty_snake_case());

    let _ = writeln!(
        out,
        "    /// Start `{}` and atomically deliver the `{}` signal.",
        wf.registered_name, sig.registered_name
    );
    let _ = writeln!(out, "    pub async fn {fn_name}(");
    let _ = writeln!(out, "        client: &temporal_runtime::TemporalClient,");
    if !sig.input_type.is_empty {
        let _ = writeln!(out, "        signal_input: {},", sig.input_type.rust_name());
    }
    if !wf.input_type.is_empty {
        let _ = writeln!(
            out,
            "        workflow_input: {},",
            wf.input_type.rust_name()
        );
    }
    let _ = writeln!(out, "        opts: {opts_struct},");
    let _ = writeln!(out, "    ) -> Result<{handle_struct}> {{");

    let signal_input_expr = if sig.input_type.is_empty {
        "&()".to_string()
    } else {
        "&signal_input".to_string()
    };
    let workflow_input_expr = if wf.input_type.is_empty {
        "&()".to_string()
    } else {
        "&workflow_input".to_string()
    };

    let _ = writeln!(
        out,
        "        let workflow_id = opts.workflow_id.clone().unwrap_or_else(|| {{"
    );
    let _ = writeln!(
        out,
        "            {}",
        id_fallback_call(wf, /* in_self_method: */ false)
    );
    let _ = writeln!(out, "        }});");
    if let Some(tq) = effective_task_queue(svc, wf) {
        let _ = writeln!(
            out,
            "        let task_queue = opts.task_queue.unwrap_or_else(|| \"{tq}\".to_string());"
        );
    } else {
        let _ = writeln!(
            out,
            "        let task_queue = opts.task_queue.expect(\"workflow has no proto-level task_queue; opts.task_queue is required\");"
        );
    }
    let _ = writeln!(
        out,
        "        let inner = temporal_runtime::signal_with_start_workflow_proto("
    );
    let _ = writeln!(out, "            client,");
    let _ = writeln!(out, "            {const_name},");
    let _ = writeln!(out, "            &workflow_id,");
    let _ = writeln!(out, "            &task_queue,");
    let _ = writeln!(out, "            {workflow_input_expr},");
    let _ = writeln!(out, "            \"{}\",", sig.registered_name);
    let _ = writeln!(out, "            {signal_input_expr},");
    let _ = writeln!(out, "            opts.id_reuse_policy,");
    let _ = writeln!(out, "            opts.execution_timeout,");
    let _ = writeln!(out, "            opts.run_timeout,");
    let _ = writeln!(out, "            opts.task_timeout,");
    let _ = writeln!(out, "        ).await?;");
    let _ = writeln!(out, "        Ok({handle_struct} {{ inner }})");
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out);
}

fn render_update_with_start_fn(
    out: &mut String,
    svc: &ServiceModel,
    wf: &WorkflowModel,
    u: &UpdateModel,
) {
    let fn_name = format!("{}_with_start", u.rpc_method.to_snake_case());
    let handle_struct = format!("{}Handle", wf.rpc_method);
    let opts_struct = format!("{}StartOptions", wf.rpc_method);
    let const_name = format!("{}_WORKFLOW_NAME", wf.rpc_method.to_shouty_snake_case());

    let _ = writeln!(
        out,
        "    /// Start `{}` and atomically deliver the `{}` update.",
        wf.registered_name, u.registered_name
    );
    let _ = writeln!(out, "    pub async fn {fn_name}(");
    let _ = writeln!(out, "        client: &temporal_runtime::TemporalClient,");
    if !u.input_type.is_empty {
        let _ = writeln!(out, "        update_input: {},", u.input_type.rust_name());
    }
    if !wf.input_type.is_empty {
        let _ = writeln!(
            out,
            "        workflow_input: {},",
            wf.input_type.rust_name()
        );
    }
    let _ = writeln!(out, "        opts: {opts_struct},");
    let _ = writeln!(out, "        wait_policy: temporal_runtime::WaitPolicy,");
    let _ = writeln!(
        out,
        "    ) -> Result<({handle_struct}, {})> {{",
        u.output_type.rust_name()
    );

    let update_input_expr = if u.input_type.is_empty {
        "&()".to_string()
    } else {
        "&update_input".to_string()
    };
    let workflow_input_expr = if wf.input_type.is_empty {
        "&()".to_string()
    } else {
        "&workflow_input".to_string()
    };

    let _ = writeln!(
        out,
        "        let workflow_id = opts.workflow_id.clone().unwrap_or_else(|| {{"
    );
    let _ = writeln!(
        out,
        "            {}",
        id_fallback_call(wf, /* in_self_method: */ false)
    );
    let _ = writeln!(out, "        }});");
    if let Some(tq) = effective_task_queue(svc, wf) {
        let _ = writeln!(
            out,
            "        let task_queue = opts.task_queue.unwrap_or_else(|| \"{tq}\".to_string());"
        );
    } else {
        let _ = writeln!(
            out,
            "        let task_queue = opts.task_queue.expect(\"workflow has no proto-level task_queue; opts.task_queue is required\");"
        );
    }
    // Three explicit generics: workflow input (W), update input (U),
    // update output (O). All three appear in distinct argument positions
    // so they could in principle be inferred, but spelling them out keeps
    // generated code grep-able and immune to inference brittleness.
    let _ = writeln!(
        out,
        "        let (inner, update_result) = temporal_runtime::update_with_start_workflow_proto::<{}, {}, {}>(",
        wf.input_type.rust_name(),
        u.input_type.rust_name(),
        u.output_type.rust_name(),
    );
    let _ = writeln!(out, "            client,");
    let _ = writeln!(out, "            {const_name},");
    let _ = writeln!(out, "            &workflow_id,");
    let _ = writeln!(out, "            &task_queue,");
    let _ = writeln!(out, "            {workflow_input_expr},");
    let _ = writeln!(out, "            \"{}\",", u.registered_name);
    let _ = writeln!(out, "            {update_input_expr},");
    let _ = writeln!(out, "            wait_policy,");
    let _ = writeln!(out, "            opts.id_reuse_policy,");
    let _ = writeln!(out, "            opts.execution_timeout,");
    let _ = writeln!(out, "            opts.run_timeout,");
    let _ = writeln!(out, "            opts.task_timeout,");
    let _ = writeln!(out, "        ).await?;");
    let _ = writeln!(
        out,
        "        Ok(({handle_struct} {{ inner }}, update_result))"
    );
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out);
}

fn effective_task_queue<'a>(svc: &'a ServiceModel, wf: &'a WorkflowModel) -> Option<&'a str> {
    wf.task_queue
        .as_deref()
        .or(svc.default_task_queue.as_deref())
}

fn duration_literal(d: std::time::Duration) -> String {
    let secs = d.as_secs();
    let nanos = d.subsec_nanos();
    if nanos == 0 {
        format!("Duration::from_secs({secs})")
    } else {
        format!("Duration::new({secs}, {nanos})")
    }
}

fn mod_name(svc: &ServiceModel) -> String {
    // jobs.v1 + JobService -> jobs_v1_job_service_temporal
    format!(
        "{}_{}_temporal",
        svc.package.replace('.', "_"),
        svc.service.to_snake_case()
    )
}

fn proto_module_path(package: &str) -> String {
    let mut p = String::from("crate");
    if package.is_empty() {
        return p;
    }
    for seg in package.split('.') {
        p.push_str("::");
        p.push_str(seg);
    }
    p
}

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

    #[test]
    fn mod_name_lowers_dots_and_camel() {
        let svc = make_service("jobs.v1", "JobService");
        assert_eq!(mod_name(&svc), "jobs_v1_job_service_temporal");
    }

    #[test]
    fn proto_module_path_walks_package() {
        assert_eq!(proto_module_path("jobs.v1"), "crate::jobs::v1");
        assert_eq!(proto_module_path(""), "crate");
    }

    fn make_service(package: &str, service: &str) -> ServiceModel {
        ServiceModel {
            package: package.to_string(),
            service: service.to_string(),
            source_file: "test.proto".to_string(),
            default_task_queue: None,
            workflows: vec![],
            signals: vec![],
            queries: vec![],
            updates: vec![],
            activities: vec![],
        }
    }
}