puerto 0.34.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-framework.
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! The worker (ADR-0018 § 5, ADR-0036): the `presentacion/worker` crate `puerto nuevo --eventos`
//! writes — or the first `puerto generar tarea-programada` of a `--db` project without events —, its
//! `generado/registro.rs` (always regenerated from puerto.toml, on the project's transport) and
//! `puerto generar consumidor`.

use crate::generators::layout::{self, Layer};
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;

use serde::Serialize;

use crate::generators::bootstrap::uses_unit_of_work;
use crate::generators::naming::{
    crud_events, event_variant, pascal_to_snake, to_pascal_case, write_file,
};
use crate::generators::render::render;
use crate::puerto_toml::{Consumer, PuertoConfig};

/// The transport that needs a broker: its registry wires `puerto-kafka`, its outbox migration has
/// no `entregas_eventos` and its `docker-compose.yml` runs Redpanda.
pub const KAFKA_TRANSPORT: &str = "kafka";

/// Names the worker's generated code already uses: a consumer or a scheduled task named after one
/// would not compile.
pub(crate) const RESERVED_CONSUMER_TYPES: &[&str] = &[
    "Arc",
    "SobreEvento",
    "ManejadorEvento",
    "ResultadoManejo",
    "ConfigKafka",
    "PublicadorKafka",
    "SuscripcionKafka",
    "Bucles",
    "DescartadosPostgres",
    "EntregasPostgres",
    "OutboxPostgres",
    "SuscripcionPostgres",
    "ConfigWorker",
    "EjecucionesProgramadasPostgres",
    "Programacion",
];

/// A use case a consumer holds (`generar consumidor --usa`, 27.14), and where `cableado` builds it.
#[derive(Debug, Clone, Serialize)]
pub struct UsedUseCase {
    pub uc: String,
    pub uc_pascal: String,
    pub entity_snake: String,
    /// `cableado::<entity>::construir` takes the pool: the entity is in Postgres.
    pub db: bool,
    /// Its params carry an `actor`: a protected use case of an auth project.
    pub actor: bool,
    /// A CRUD list: `todas_las_paginas` reads it whole.
    pub list: bool,
}

/// The use cases `names` name, each with the entity that declares it; an unknown one is an error.
pub(crate) fn used_use_cases(
    config: &PuertoConfig,
    names: &[String],
) -> Result<Vec<UsedUseCase>, String> {
    let mut used = vec![];
    for name in names {
        let Some(entity) = config.entity.iter().find(|e| e.use_cases.contains(name)) else {
            return Err(format!(
                "--usa: ningún [[entidad]] de puerto.toml declara el caso de uso '{name}'"
            ));
        };
        let snake = pascal_to_snake(&entity.name);
        if used.iter().any(|u: &UsedUseCase| &u.uc == name) {
            continue;
        }
        let list = *name == crate::generators::naming::crud_use_case("list", &snake);
        // 36.2: an owned list gives each caller their rows, and the system owns none.
        if list
            && crate::generators::auth::Access::in_config(config, &entity.name).checks_owner(name)
        {
            return Err(format!(
                "--usa: '{name}' le da a cada uno sus filas y el worker no es dueño de ninguna. \
                 Dale un caso de uso interno (`puerto generar caso-de-uso {} <accion> --interno`), \
                 o haz la lista solo de su rol (`--solo-rol {name}`)",
                entity.name
            ));
        }
        used.push(UsedUseCase {
            uc: name.clone(),
            uc_pascal: to_pascal_case(name),
            db: entity.db,
            actor: config.project.has_auth() && !entity.internal.contains(name),
            list,
            entity_snake: snake,
        });
    }
    Ok(used)
}

/// An event type some entity declares, and where its constant lives.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DeclaredEvent {
    pub event_type: String,
    /// `PRODUCT_CREATED`, exported by the entity's `events.rs`.
    pub constant: String,
    /// `product_created`: a function name in the consumer's tests.
    pub const_lower: String,
    /// The `{Entity}Event` variant: `Created`.
    pub variant: String,
    pub entity_pascal: String,
    pub entity_snake: String,
}

/// Every event type the project's entities record: the CRUD ones of each entity that writes
/// through a unit of work, then its custom ones.
pub fn declared_events(config: &PuertoConfig) -> Vec<DeclaredEvent> {
    config
        .entity
        .iter()
        .filter(|e| uses_unit_of_work(e, config.project.has_events()))
        .flat_map(|entity| {
            let snake = pascal_to_snake(&entity.name);
            crud_events(&snake)
                .into_iter()
                .chain(
                    entity
                        .events
                        .iter()
                        .map(|event| (event_variant(&snake, event), event.clone())),
                )
                .map(|(variant, event_type)| DeclaredEvent {
                    constant: event_type.to_uppercase(),
                    const_lower: event_type.clone(),
                    event_type,
                    variant,
                    entity_pascal: entity.name.clone(),
                    entity_snake: snake.clone(),
                })
                .collect::<Vec<_>>()
        })
        .collect()
}

/// Whether the project at `config` has a `worker/`: every `events` project does, and every one with
/// a `[[tarea_programada]]`.
pub fn has_worker(config: &PuertoConfig) -> bool {
    config.project.events.is_some() || !config.scheduled.is_empty()
}

fn on_kafka(config: &PuertoConfig) -> bool {
    config.project.events.as_deref() == Some(KAFKA_TRANSPORT)
}

/// The declared events `consumer` subscribes to, in its order. Errors on one nobody declares.
pub(crate) fn subscribed(
    consumer: &Consumer,
    declared: &[DeclaredEvent],
) -> Result<Vec<DeclaredEvent>, String> {
    consumer
        .events
        .iter()
        .map(|event| {
            declared
                .iter()
                .find(|d| d.event_type == *event)
                .cloned()
                .ok_or_else(|| undeclared_event(event, declared))
        })
        .collect()
}

fn undeclared_event(event: &str, declared: &[DeclaredEvent]) -> String {
    let known: Vec<&str> = declared.iter().map(|d| d.event_type.as_str()).collect();
    if known.is_empty() {
        format!(
            "ninguna entidad declara el evento '{event}': aún no hay entidades CRUD que registren \
             eventos"
        )
    } else {
        format!(
            "ninguna entidad declara el evento '{event}'. Los declarados: {}",
            known.join(", ")
        )
    }
}

#[derive(Serialize)]
struct RegistryConsumer {
    name: String,
    pascal: String,
    /// The constants it is routed: `PRODUCT_CREATED`.
    events: Vec<String>,
    /// The aggregates whose topics it reads (Kafka): `product`, sorted.
    aggregates: Vec<String>,
    /// The handler, as the registry builds it: `{Consumer}::construir(&pool)` for a `[[consumidor]]`, the
    /// `Send{Mail}Mail { … }` of a mail sent on events.
    handler: String,
}

/// A `[[tarea_programada]]` as the registry wires it.
#[derive(Debug, Serialize)]
struct RegistryTask<'a> {
    name: &'a str,
    pascal: String,
    cron: &'a str,
    zone: Option<&'a str>,
}

/// `presentacion/worker/src/generado/registro.rs`: the relay and every `[[consumidor]]`, on the project's
/// transport, and every `[[tarea_programada]]`. Without events, only the scheduled tasks.
pub fn generate_registry(config: &PuertoConfig) -> Result<String, Box<dyn std::error::Error>> {
    let tasks: Vec<RegistryTask> = config
        .scheduled
        .iter()
        .map(|t| RegistryTask {
            name: &t.name,
            pascal: to_pascal_case(&t.name),
            cron: &t.cron,
            zone: t.zone.as_deref(),
        })
        .collect();
    if !config.project.has_events() {
        let mut ctx = tera::Context::new();
        ctx.insert("events", &false);
        ctx.insert(
            "imports",
            &[
                "puerto_eventos::{Bucles, ConfigWorker, Programacion}",
                "puerto_sqlx::programadas::EjecucionesProgramadasPostgres",
            ],
        );
        ctx.insert("consumers", &Vec::<RegistryConsumer>::new());
        ctx.insert("modules", &Vec::<(&str, &str)>::new());
        ctx.insert("mails", &false);
        ctx.insert("tasks", &tasks);
        return Ok(render("worker/registry.tera", &ctx)?);
    }
    let declared = declared_events(config);
    // entity snake → the constants its consumers name, in declaration order.
    let mut constants: BTreeMap<String, Vec<String>> = BTreeMap::new();
    let mut consumers = vec![];
    for consumer in &config.consumer {
        let events = subscribed(consumer, &declared)
            .map_err(|e| format!("consumer '{}': {e}", consumer.name))?;
        for event in &events {
            let names = constants.entry(event.entity_snake.clone()).or_default();
            if !names.contains(&event.constant) {
                names.push(event.constant.clone());
            }
        }
        let mut aggregates: Vec<String> = events.iter().map(|e| e.entity_snake.clone()).collect();
        aggregates.sort();
        aggregates.dedup();
        let pascal = to_pascal_case(&consumer.name);
        consumers.push(RegistryConsumer {
            name: consumer.name.clone(),
            handler: format!("{pascal}::construir(&pool)"),
            pascal,
            events: events.into_iter().map(|e| e.constant).collect(),
            aggregates,
        });
    }
    // Each mail sent on events is one more consumer, `correo_<name>` (ADR-0020 § 3).
    let mut template_mailers: Vec<String> = vec![];
    for mail in config.mail.iter().filter(|m| !m.on.is_empty()) {
        let consumer = Consumer {
            name: format!("correo_{}", mail.name),
            events: mail.on.clone(),
        };
        let events =
            subscribed(&consumer, &declared).map_err(|e| format!("mail '{}': {e}", mail.name))?;
        for event in &events {
            let names = constants.entry(event.entity_snake.clone()).or_default();
            if !names.contains(&event.constant) {
                names.push(event.constant.clone());
            }
        }
        let mut aggregates: Vec<String> = events.iter().map(|e| e.entity_snake.clone()).collect();
        aggregates.sort();
        aggregates.dedup();
        let mail_pascal = to_pascal_case(&mail.name);
        template_mailers.push(format!(
            "infra_correo::{}::EnviadorCorreo{mail_pascal}Plantilla",
            mail.name
        ));
        let pascal = format!("EnviarCorreo{mail_pascal}");
        consumers.push(RegistryConsumer {
            handler: format!(
                "{pascal} {{ enviador: Arc::new(EnviadorCorreo{mail_pascal}Plantilla::new(enviador.clone())), \
                 correos_enviados: correos_enviados.clone() }}"
            ),
            name: consumer.name,
            pascal,
            events: events.into_iter().map(|e| e.constant).collect(),
            aggregates,
        });
    }
    let mails = !template_mailers.is_empty();

    let mut imports: Vec<String> = constants
        .into_iter()
        .map(|(snake, mut names)| {
            names.sort();
            format!("dominio_{snake}::eventos::{}", braced(&names))
        })
        .collect();
    let kafka = on_kafka(config);
    let adapters: &[&str] = match (kafka, consumers.is_empty()) {
        (false, true) => &["EntregasPostgres", "OutboxPostgres"],
        (false, false) => &[
            "DescartadosPostgres",
            "EntregasPostgres",
            "OutboxPostgres",
            "SuscripcionPostgres",
        ],
        (true, true) => &["OutboxPostgres"],
        (true, false) => &["DescartadosPostgres", "OutboxPostgres"],
    };
    let adapters: Vec<String> = adapters.iter().map(|a| a.to_string()).collect();
    imports.push(format!("puerto_sqlx::eventos::{}", braced(&adapters)));
    if mails {
        imports.push("puerto_sqlx::correo::CorreosEnviadosPostgres".into());
        imports.extend(template_mailers);
    }
    if tasks.is_empty() {
        imports.push("puerto_eventos::{Bucles, ConfigWorker}".into());
    } else {
        imports.push("puerto_eventos::{Bucles, ConfigWorker, Programacion}".into());
        imports.push("puerto_sqlx::programadas::EjecucionesProgramadasPostgres".into());
    }
    if kafka {
        let types = if consumers.is_empty() {
            "{ConfigKafka, PublicadorKafka}"
        } else {
            "{ConfigKafka, PublicadorKafka, SuscripcionKafka}"
        };
        imports.push(format!("puerto_kafka::{types}"));
    }
    if mails {
        imports.push("puerto_correo::{ConfigCorreo, EnviadorCorreoSmtp}".into());
    }

    let mut modules: Vec<(&str, &str)> = consumers
        .iter()
        .map(|c| (c.name.as_str(), c.pascal.as_str()))
        .collect();
    modules.sort_unstable();

    let mut ctx = tera::Context::new();
    ctx.insert("imports", &imports);
    ctx.insert("consumers", &consumers);
    ctx.insert("modules", &modules);
    ctx.insert("mails", &mails);
    ctx.insert("events", &true);
    ctx.insert("tasks", &tasks);
    if !kafka {
        return Ok(render("worker/registry.tera", &ctx)?);
    }
    // Every aggregate that records events gets its topic at startup, subscribed to or not: the
    // relay publishes them all.
    let mut aggregates: Vec<String> = declared.into_iter().map(|e| e.entity_snake).collect();
    aggregates.sort();
    aggregates.dedup();
    ctx.insert("aggregates", &aggregates);
    ctx.insert("project", &config.project.name);
    Ok(render("worker/registry_kafka.tera", &ctx)?)
}

/// `A` or `{A, B}`, as rustfmt writes a `use`.
fn braced(names: &[String]) -> String {
    match names {
        [single] => single.clone(),
        _ => format!("{{{}}}", names.join(", ")),
    }
}

/// `presentacion/worker/src/consumidores/<name>.rs`: a `ManejadorEvento` that matches each subscribed event,
/// decodes its snapshot (dead-lettering what does not decode), logs and acks — with its tests.
pub fn generate_consumer(
    name: &str,
    events: &[DeclaredEvent],
    uses: &[UsedUseCase],
) -> Result<String, Box<dyn std::error::Error>> {
    let Some(first) = events.first() else {
        return Err(format!("el consumidor '{name}' no se suscribe a ningún evento").into());
    };
    let mut by_entity: BTreeMap<&str, (Vec<String>, &str)> = BTreeMap::new();
    for event in events {
        let (names, pascal) = by_entity
            .entry(&event.entity_snake)
            .or_insert((vec![], &event.entity_pascal));
        names.push(event.constant.clone());
        if !names.contains(&format!("Snapshot{pascal}")) {
            names.push(format!("Snapshot{pascal}"));
        }
    }
    let imports: Vec<String> = by_entity
        .into_iter()
        .map(|(snake, (mut names, _))| {
            names.sort();
            format!("dominio_{snake}::eventos::{}", braced(&names))
        })
        .collect();

    let mut ctx = tera::Context::new();
    ctx.insert("name", name);
    ctx.insert("pascal", &to_pascal_case(name));
    ctx.insert("events", events);
    ctx.insert("first", first);
    ctx.insert("imports", &imports);
    ctx.insert("uses", uses);
    // `cableado::<c>::construir` once per context, in the order the use cases name them.
    let mut contexts: Vec<(&str, bool)> = vec![];
    for u in uses {
        if !contexts.iter().any(|(c, _)| *c == u.entity_snake) {
            contexts.push((&u.entity_snake, u.db));
        }
    }
    ctx.insert("contexts", &contexts);
    ctx.insert("actor", &uses.iter().any(|u| u.actor));
    ctx.insert("list", &uses.iter().find(|u| u.list));
    Ok(render("worker/consumer.tera", &ctx)?)
}

/// Rewrites `registry.rs` of a project that has a worker — after `generar bootstrap`, a scaffold
/// and `generar consumidor`, like `bootstrap.rs`.
pub fn regenerate_registry(
    base: &Path,
    config: &PuertoConfig,
) -> Result<(), Box<dyn std::error::Error>> {
    let dir = base.join(layout::WORKER_GENERATED_DIR);
    if !has_worker(config) || !dir.is_dir() {
        return Ok(());
    }
    write_file(&base.join(layout::REGISTRY_RS), &generate_registry(config)?)?;
    add_worker_dependencies(base, config)
}

/// The project crates the worker's code names: the domain of every context whose events a
/// consumer decodes (its Object Mother too, in the consumers' tests), and the `correo` context
/// once a mail is sent on events. Added to `presentacion/worker/Cargo.toml`, never removed.
fn add_worker_dependencies(
    base: &Path,
    config: &PuertoConfig,
) -> Result<(), Box<dyn std::error::Error>> {
    use crate::generators::bootstrap::add_crate_dependency;
    let declared = declared_events(config);
    let mut contexts: Vec<String> = vec![];
    let subscriptions =
        config
            .consumer
            .iter()
            .cloned()
            .chain(
                config
                    .mail
                    .iter()
                    .filter(|m| !m.on.is_empty())
                    .map(|m| Consumer {
                        name: format!("correo_{}", m.name),
                        events: m.on.clone(),
                    }),
            );
    for consumer in subscriptions {
        for event in subscribed(&consumer, &declared)? {
            if !contexts.contains(&event.entity_snake) {
                contexts.push(event.entity_snake);
            }
        }
    }
    contexts.sort();
    for c in &contexts {
        let name = layout::crate_name(c, Layer::Domain);
        add_crate_dependency(
            base,
            layout::WORKER_MANIFEST,
            "dependencies",
            &name,
            "{ workspace = true }",
        )?;
        add_crate_dependency(
            base,
            layout::WORKER_MANIFEST,
            "dev-dependencies",
            &name,
            "{ workspace = true, features = [\"pruebas\"] }",
        )?;
    }
    if config.mail.iter().any(|m| !m.on.is_empty()) {
        let correo = layout::MAIL_CONTEXT;
        for layer in [Layer::Domain, Layer::Infrastructure] {
            add_crate_dependency(
                base,
                layout::WORKER_MANIFEST,
                "dependencies",
                &layout::crate_name(correo, layer),
                "{ workspace = true }",
            )?;
        }
        add_crate_dependency(
            base,
            layout::WORKER_MANIFEST,
            "dev-dependencies",
            &layout::crate_name(correo, Layer::Domain),
            "{ workspace = true, features = [\"pruebas\"] }",
        )?;
    }
    Ok(())
}

/// 36.5: the `eventos_procesados` table `procesar_una_vez` reads and marks, once per project.
pub(crate) fn write_processed_events_migration(
    base: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    let written = fs::read_dir(base.join(layout::MIGRATIONS_DIR)).is_ok_and(|entries| {
        entries.flatten().any(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_eventos_procesados.sql")
        })
    });
    if !written {
        let sql = render("infrastructure/processed_events.sql", &tera::Context::new())?;
        crate::generators::migration::run_migration("eventos_procesados", base, Some(&sql))?;
    }
    Ok(())
}

/// `consumidores/comun.rs` and its `pub mod`, unless they are there: `puerto nuevo --eventos`, and
/// `generar consumidor` in a worker written before them.
fn write_shared_module(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join(layout::consumer(SHARED_CONSUMER_MODULE));
    if !path.exists() {
        write_file(&path, &render("worker/shared.tera", &tera::Context::new())?)?;
    }
    let modules = base.join(layout::CONSUMERS_RS);
    fs::write(
        &modules,
        with_module(&fs::read_to_string(&modules)?, SHARED_CONSUMER_MODULE),
    )?;
    Ok(())
}

/// What a consumer that holds use cases names: `cableado`, and the application crate of each (its
/// doubles in the tests). Added to `presentacion/worker/Cargo.toml`, never removed.
pub(crate) fn add_used_dependencies(
    base: &Path,
    uses: &[UsedUseCase],
) -> Result<(), Box<dyn std::error::Error>> {
    use crate::generators::bootstrap::add_crate_dependency;
    if uses.is_empty() {
        return Ok(());
    }
    let manifest = layout::WORKER_MANIFEST;
    add_crate_dependency(
        base,
        manifest,
        "dependencies",
        "cableado",
        "{ workspace = true }",
    )?;
    // 36.5: `EventosProcesadosEnMemoria`, in the consumer's tests.
    add_crate_dependency(
        base,
        manifest,
        "dev-dependencies",
        "puerto-nucleo",
        "{ workspace = true, features = [\"pruebas\"] }",
    )?;
    for u in uses {
        let name = layout::crate_name(&u.entity_snake, Layer::Application);
        add_crate_dependency(
            base,
            manifest,
            "dependencies",
            &name,
            "{ workspace = true }",
        )?;
        add_crate_dependency(
            base,
            manifest,
            "dev-dependencies",
            &name,
            "{ workspace = true, features = [\"pruebas\"] }",
        )?;
    }
    Ok(())
}

/// `consumers.rs` with `pub mod {name};` among its module declarations, sorted as rustfmt keeps
/// them; every other line stays where it was, ahead of them.
pub(crate) fn with_module(src: &str, name: &str) -> String {
    let declaration = format!("pub mod {name};");
    let (mut modules, other): (Vec<&str>, Vec<&str>) = src
        .lines()
        .partition(|line| line.starts_with("pub mod ") && line.ends_with(';'));
    if !modules.contains(&declaration.as_str()) {
        modules.push(&declaration);
    }
    modules.sort_unstable();
    other
        .into_iter()
        .chain(modules)
        .map(|line| format!("{line}\n"))
        .collect()
}

/// The tasks a project with a worker gets.
const WORKER_TASKS: &str = r#"
  worker:
    desc: "Arranca el worker: hace de relay del outbox y ejecuta los consumidores (health en el WORKER_PORT de .env)"
    deps: [docker-compose:up]
    cmd: cargo run -p worker

  eventos:descartados:
    desc: Lista los 20 eventos descartados más recientes
    deps: [docker-compose:up]
    cmd: >-
      docker compose exec -T postgres psql -U devuser -d @DB@ -c
      "SELECT registrado_en, consumidor, tipo_evento, intentos, motivo, detalle FROM descartados ORDER BY registrado_en DESC LIMIT 20"
"#;

/// `task worker` of a worker without events (ADR-0036): only scheduled tasks.
const WORKER_TASK_WITHOUT_EVENTS: &str = r#"
  worker:
    desc: "Arranca el worker: ejecuta las tareas programadas (health en el WORKER_PORT de .env)"
    deps: [docker-compose:up]
    cmd: cargo run -p worker
"#;

/// The task the first scheduled task adds.
const SCHEDULED_TASKS_TASK: &str = r#"
  programadas:ejecuciones:
    desc: Lista las 20 ejecuciones de tareas programadas más recientes
    deps: [docker-compose:up]
    cmd: >-
      docker compose exec -T postgres psql -U devuser -d @DB@ -c
      "SELECT tarea, programada_para, terminada_en - empezada_en AS duracion, error FROM ejecuciones_programadas ORDER BY programada_para DESC LIMIT 20"
"#;

/// The `worker/` crate of a fresh `events` project, born with the `limpiar_registros` scheduled
/// task (ADR-0036): [`write_worker`], then that task.
pub fn apply_worker_to_new_project(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    write_worker(base)?;
    crate::generators::scheduled::add_cleanup(base)
}

/// The `worker/` crate: the member, its runtime dependencies, the files, `task worker` /
/// `task eventos:descartados` and `WORKER_PORT` — and on the `kafka` transport `puerto-kafka`,
/// Redpanda in `docker-compose.yml` and `KAFKA_BROKERS`. Without events (the first scheduled task of
/// a `--db` project), the same worker without relay or consumers.
pub(crate) fn write_worker(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;
    let events = config.project.has_events();
    let kafka = on_kafka(&config);
    crate::generators::project::add_workspace_dependency(base, "puerto-eventos")?;
    if kafka {
        crate::generators::project::add_workspace_dependency(base, "puerto-kafka")?;
    }

    let mut ctx = tera::Context::new();
    ctx.insert("kafka", &kafka);
    ctx.insert("events", &events);
    let mut files = vec![
        (
            layout::WORKER_MANIFEST.to_string(),
            "worker/cargo_toml.tera",
        ),
        (
            format!("{}/AGENTS.md", layout::WORKER_DIR),
            "worker/agents.tera",
        ),
        (
            format!("{}/main.rs", layout::WORKER_SRC),
            "worker/main.tera",
        ),
        (
            format!("{}/generado.rs", layout::WORKER_SRC),
            "worker/generated.tera",
        ),
    ];
    if events {
        files.push((layout::CONSUMERS_RS.to_string(), "worker/consumers.tera"));
    }
    for (path, template) in files {
        write_file(&base.join(path), &render(template, &ctx)?)?;
    }
    if events {
        write_shared_module(base)?;
    }
    write_file(
        &base.join(layout::REGISTRY_RS),
        &generate_registry(&config)?,
    )?;
    crate::generators::crates::sync_workspace_dependencies(base)?;

    let tasks = if events {
        WORKER_TASKS
    } else {
        WORKER_TASK_WITHOUT_EVENTS
    };
    crate::generators::project::add_tasks(
        base,
        "worker",
        &tasks.replace("@DB@", &database(&config)),
    )?;

    for file in [".env", ".env.example"] {
        let path = base.join(file);
        let mut content = fs::read_to_string(&path).unwrap_or_default();
        if !content.contains("WORKER_PORT") {
            content.push_str("\n# Worker\nWORKER_PORT=8081\n");
        }
        if kafka && !content.contains("KAFKA_BROKERS") {
            // KAFKA_TOPIC_PREFIX defaults to the project name.
            content.push_str(
                "\n# Kafka (Redpanda, en docker-compose.yml)\nKAFKA_BROKERS=localhost:9092\n",
            );
        }
        fs::write(&path, content)?;
    }
    if kafka {
        add_redpanda_to_compose(base, &config.project.name)?;
        crate::generators::project::add_devenv_packages(
            base,
            "--eventos kafka: librdkafka se compila con cmake y las cabeceras de curl",
            &["cmake", "curl", "pkg-config"],
        )?;
    }
    Ok(())
}

/// The development database's name: the project's, with `_` for `-`.
fn database(config: &PuertoConfig) -> String {
    config.project.name.replace('-', "_")
}

/// What every worker with scheduled tasks needs, once: `tareas_programadas.rs` and its `mod` in
/// `main.rs`, `chrono` in its manifest, the `ejecuciones_programadas` migration and
/// `task programadas:ejecuciones`. A worker written before them gets them with its first task.
pub(crate) fn ensure_scheduled_tasks(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let modules = base.join(layout::SCHEDULED_TASKS_RS);
    if !modules.exists() {
        write_file(
            &modules,
            &render("worker/scheduled_tasks.tera", &tera::Context::new())?,
        )?;
    }
    let main = base.join(format!("{}/main.rs", layout::WORKER_SRC));
    let src = fs::read_to_string(&main)?;
    if !src.lines().any(|l| l == "mod tareas_programadas;") {
        fs::write(
            &main,
            src.replacen(
                "mod generado;\n",
                "mod generado;\nmod tareas_programadas;\n",
                1,
            ),
        )?;
    }
    crate::generators::bootstrap::add_crate_dependency(
        base,
        layout::WORKER_MANIFEST,
        "dependencies",
        "chrono",
        "{ workspace = true }",
    )?;
    crate::generators::crates::sync_workspace_dependencies(base)?;

    let written = fs::read_dir(base.join(layout::MIGRATIONS_DIR)).is_ok_and(|entries| {
        entries.flatten().any(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_ejecuciones_programadas.sql")
        })
    });
    if !written {
        let sql = render("infrastructure/scheduled.sql", &tera::Context::new())?;
        crate::generators::migration::run_migration("ejecuciones_programadas", base, Some(&sql))?;
    }
    let config = crate::puerto_toml::read(base)?;
    crate::generators::project::add_tasks(
        base,
        "programadas:ejecuciones",
        &SCHEDULED_TASKS_TASK.replace("@DB@", &database(&config)),
    )
}

/// The Redpanda service the `kafka` transport runs against in development, next to Postgres.
fn redpanda_service(project_name: &str) -> String {
    format!(
        r#"  redpanda:
    image: docker.redpanda.com/redpandadata/redpanda:v24.2.7
    container_name: {project_name}-redpanda
    command:
      - redpanda
      - start
      - --mode
      - dev-container
      - --smp
      - "1"
      - --kafka-addr
      - PLAINTEXT://0.0.0.0:9092
      - --advertise-kafka-addr
      - PLAINTEXT://localhost:${{KAFKA_HOST_PORT:-9092}}
    ports:
      - "${{KAFKA_HOST_PORT:-9092}}:9092"
    volumes:
      - redpanda-data:/var/lib/redpanda/data
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "rpk cluster health | grep -q 'Healthy:.*true'"]
      interval: 5s
      timeout: 5s
      retries: 10
"#
    )
}

/// Adds Redpanda to the `docker-compose.yml` `puerto nuevo --db` wrote: its service after the
/// others, its volume after theirs.
fn add_redpanda_to_compose(
    base: &Path,
    project_name: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join("docker-compose.yml");
    let src = fs::read_to_string(&path)?;
    if src.contains("redpanda:") {
        return Ok(());
    }
    let Some(at) = src.find("\nvolumes:\n") else {
        return Err(format!(
            "{}: no tiene `volumes:` en el nivel superior",
            path.display()
        )
        .into());
    };
    let out = format!(
        "{}{}{}  redpanda-data:\n",
        &src[..=at],
        redpanda_service(project_name),
        &src[at..]
    );
    fs::write(&path, out)?;
    Ok(())
}

/// The module of what several consumers share (27.14): written once, never a consumer.
pub const SHARED_CONSUMER_MODULE: &str = "comun";

#[cfg(test)]
pub fn run_generate_consumer(
    name: &str,
    events: &[String],
    base: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    run_generate_consumer_with(name, events, &[], base)
}

/// `puerto generar consumidor <name> --tras <event_type>[,…] [--usa <use_case>[,…]]`: declares the
/// consumer, writes its handler (holding the `uses` use cases, built from `cableado`), declares its
/// module and regenerates the registry. Refuses an existing name, an event no entity declares, a
/// use case no entity declares, and a file already on disk (it is never overwritten).
pub fn run_generate_consumer_with(
    name: &str,
    events: &[String],
    uses: &[String],
    base: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;
    let (consumer, subscribed) = check_new_consumer(&config, name, events, base)?;
    let uses = used_use_cases(&config, uses)?;
    let content = generate_consumer(name, &subscribed, &uses)?;
    write_new_consumer(base, consumer, &content)?;
    add_used_dependencies(base, &uses)?;
    if !uses.is_empty() {
        write_processed_events_migration(base)?;
    }
    regenerate_registry(base, &crate::puerto_toml::read(base)?)?;

    println!(
        "✓ Consumidor '{name}' añadido, tras: {}",
        subscribed
            .iter()
            .map(|e| e.event_type.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    );
    println!(
        "  presentacion/worker/src/consumidores/{name}.rs es tuyo: hazlo idempotente, puede recibir \
         un evento dos veces."
    );
    println!(
        "  presentacion/worker/src/generado/registro.rs regenerado. Arráncalo con `task worker`."
    );
    Ok(())
}

/// What `generar consumidor` checks before writing anything (also `generar notificacion`, whose
/// consumer it is): a worker, a free name, declared events and no file on disk. The consumer to
/// declare and the events it subscribes to.
pub(crate) fn check_new_consumer(
    config: &PuertoConfig,
    name: &str,
    events: &[String],
    base: &Path,
) -> Result<(Consumer, Vec<DeclaredEvent>), Box<dyn std::error::Error>> {
    if !has_worker(config) {
        return Err(
            "este proyecto no tiene worker: los consumidores necesitan un proyecto creado con \
             `puerto nuevo --db --eventos db|kafka`"
                .into(),
        );
    }
    crate::validation::validate_consumer_name(name)?;
    if name == SHARED_CONSUMER_MODULE {
        return Err(format!(
            "'{name}' es el módulo de lo que comparten los consumidores              (presentacion/worker/src/consumidores/{name}.rs). Elige otro nombre"
        )
        .into());
    }
    let pascal = to_pascal_case(name);
    let taken = RESERVED_CONSUMER_TYPES.contains(&pascal.as_str())
        || config.entity.iter().any(|e| {
            [
                format!("Evento{}", e.name),
                format!("Snapshot{}", e.name),
                format!("Madre{}", e.name),
            ]
            .contains(&pascal)
        });
    if taken {
        return Err(format!(
            "el consumidor '{name}' daría el tipo `{pascal}`, que el worker ya usa"
        )
        .into());
    }
    if config.consumer.iter().any(|c| c.name == name) {
        return Err(format!("el consumidor '{name}' ya está declarado").into());
    }
    if config.scheduled.iter().any(|t| t.name == name) {
        return Err(format!(
            "'{name}' ya es una tarea programada del worker, y los dos serían el tipo `{pascal}` \
             del registro. Elige otro nombre"
        )
        .into());
    }
    if let Some(mail) = name
        .strip_prefix("correo_")
        .filter(|mail| config.mail.iter().any(|m| m.name == *mail))
    {
        return Err(format!(
            "el consumidor '{name}' está reservado: el worker ejecuta el correo '{mail}' como el \
             consumidor 'correo_{mail}'. Elige otro nombre"
        )
        .into());
    }
    if events.is_empty() {
        return Err("un consumidor necesita al menos un evento: --tras <tipo_evento>".into());
    }
    let mut unique: Vec<String> = vec![];
    for event in events {
        if !unique.contains(event) {
            unique.push(event.clone());
        }
    }
    let consumer = Consumer {
        name: name.to_string(),
        events: unique,
    };
    let subscribed = subscribed(&consumer, &declared_events(config))?;

    let path = base.join(layout::consumer(name));
    if path.exists() {
        return Err(format!(
            "{} ya existe, y nunca se sobrescribe. Bórralo o elige otro nombre",
            path.display()
        )
        .into());
    }
    Ok((consumer, subscribed))
}

/// Declares `consumer`, writes its handler and its `pub mod`, and `consumidores/comun.rs` if the
/// worker lacks it.
pub(crate) fn write_new_consumer(
    base: &Path,
    consumer: Consumer,
    content: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join(layout::consumer(&consumer.name));
    let name = consumer.name.clone();
    crate::puerto_toml::add_consumer(base, consumer)?;
    write_file(&path, content)?;
    let modules = base.join(layout::CONSUMERS_RS);
    fs::write(&modules, with_module(&fs::read_to_string(&modules)?, &name))?;
    write_shared_module(base)
}

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

    #[test]
    fn should_sort_only_module_declarations_when_a_consumer_is_added() {
        let src = "pub mod zeta;\npub mod helpers {}\n";

        let out = with_module(src, "alpha");

        assert_eq!(out, "pub mod helpers {}\npub mod alpha;\npub mod zeta;\n");
    }

    #[test]
    fn should_not_declare_a_module_twice() {
        assert_eq!(with_module("pub mod audit;\n", "audit"), "pub mod audit;\n");
    }
}