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
use crate::generators::layout::{self, Layer};
use std::{fs, path::Path};

use serde::Serialize;

use crate::generators::naming::{
    crud_use_case, is_crud_entity, pascal_to_snake, to_pascal_case, write_file,
};
use crate::generators::render::render;

#[derive(Serialize, Clone)]
struct BootstrapUseCase {
    action: String,
    uc_pascal: String,
    /// Unit-of-work entities only: which ports the use case is built with.
    repository: bool,
    uow: bool,
    /// A use case of a `fichero` field (Fase 38): built with the file store too.
    almacen: bool,
}

#[derive(Serialize)]
struct BootstrapEntity {
    pascal: String,
    snake: String,
    db: bool,
    /// Its writes go through a `Pg{Entity}UnitOfWorkFactory` (ADR-0018 § 2).
    uow: bool,
    /// Some use case is built with the repository / the unit of work factory.
    needs_repository: bool,
    needs_uow: bool,
    use_cases: Vec<BootstrapUseCase>,
    /// The fields of `Api{Entity}`: every use case but its transitions'.
    api_use_cases: Vec<BootstrapUseCase>,
    /// Its transitions' use cases (27.12), each on its own `Api{UseCase}`.
    transitions: Vec<BootstrapUseCase>,
    /// The use cases of its `fichero` fields (Fase 38), built by `construir_ficheros` and routed by
    /// `ApiFicheros{Entity}`.
    files: Vec<BootstrapUseCase>,
}

/// Whether an entity's writes go through a unit of work: a CRUD entity of an `events` project.
pub fn uses_unit_of_work(entity: &crate::puerto_toml::Entity, events: bool) -> bool {
    events && entity.db && is_crud_entity(&pascal_to_snake(&entity.name), &entity.use_cases)
}

/// What the wiring templates know of each entity.
fn bootstrap_entities(
    entities: &[crate::puerto_toml::Entity],
    project: &crate::puerto_toml::Project,
) -> Vec<BootstrapEntity> {
    let events = project.has_events();
    entities
        .iter()
        .map(|entity| {
            let snake = pascal_to_snake(&entity.name);
            let uow = uses_unit_of_work(entity, events);
            // With a unit of work, `create` only writes; `get` and `list` only read; the rest
            // (update, delete and every custom use case) read, then write. Without one, every use
            // case holds the repository.
            let create = crud_use_case("create", &snake);
            let reads = [
                crud_use_case("get", &snake),
                crud_use_case("list", &snake),
                crate::generators::naming::mine_use_case(&snake),
            ];
            let use_cases: Vec<BootstrapUseCase> = entity
                .use_cases
                .iter()
                .map(|uc| BootstrapUseCase {
                    action: uc.clone(),
                    uc_pascal: to_pascal_case(uc),
                    repository: !uow || *uc != create,
                    uow: uow && !reads.contains(uc),
                    almacen: false,
                })
                .collect();
            // Fase 38: uploading and removing write; downloading only reads.
            let files: Vec<BootstrapUseCase> =
                crate::generators::types::file_ctxs(&snake, &entity.fields)
                    .into_iter()
                    .flat_map(|f| {
                        [
                            (f.subir, f.subir_pascal, true),
                            (f.descargar, f.descargar_pascal, false),
                            (f.quitar, f.quitar_pascal, true),
                        ]
                    })
                    .map(|(action, uc_pascal, writes)| BootstrapUseCase {
                        action,
                        uc_pascal,
                        repository: true,
                        uow: uow && writes,
                        almacen: true,
                    })
                    .collect();
            let routed = entity.routed_transition_use_cases();
            let own = entity.api_use_cases();
            let pick = |names: &[String]| -> Vec<BootstrapUseCase> {
                use_cases
                    .iter()
                    .filter(|uc| names.contains(&uc.action))
                    .cloned()
                    .collect()
            };
            let (transitions, api_use_cases) = (pick(&routed), pick(&own));
            BootstrapEntity {
                pascal: entity.name.clone(),
                api_use_cases,
                transitions,
                files,
                db: entity.db,
                uow,
                needs_repository: use_cases.iter().any(|uc| uc.repository),
                needs_uow: use_cases.iter().any(|uc| uc.uow),
                use_cases,
                snake,
            }
        })
        .collect()
}

fn build_context(
    entities: &[crate::puerto_toml::Entity],
    project: &crate::puerto_toml::Project,
) -> tera::Context {
    let mut ctx = tera::Context::new();
    ctx.insert("entities", &bootstrap_entities(entities, project));
    let auth = project.has_auth();
    // An auth project's users live in Postgres whenever the project has a database.
    let user_db = auth && project.db;
    // The live stream listens on the pool: an events project opens it before its first Postgres
    // entity too.
    ctx.insert(
        "has_db",
        &(entities.iter().any(|e| e.db) || user_db || project.has_events()),
    );
    ctx.insert("web", &project.web);
    ctx.insert("auth", &auth);
    ctx.insert("user_db", &user_db);
    let local = project.auth.as_deref() == Some("local");
    ctx.insert("local", &local);
    // Fase 39: whether the local account cycle is wired; `regenerate_bootstrap` knows from disk.
    ctx.insert("cuenta", &local);
    // Fase 41 (ADR-0037): the live stream comes with the events, whose outbox notifies it.
    let en_vivo = project.has_events();
    ctx.insert("en_vivo", &en_vivo);
    ctx.insert("notificaciones", &project.notificaciones);
    ctx.insert(
        "apis",
        &api_expression(entities, auth, local, en_vivo, project.notificaciones),
    );
    ctx.insert("any_db", &entities.iter().any(|e| e.db));
    ctx.insert(
        "any_files",
        &entities
            .iter()
            .any(|e| !crate::generators::file_fields(&e.fields).is_empty()),
    );
    // The spec export test wraps a mock per use case in an `Arc`.
    ctx.insert(
        "wraps_mocks",
        &(auth || entities.iter().any(|e| !e.use_cases.is_empty())),
    );
    ctx
}

/// What `OpenApiService` serves: `()` with no API, the one `api_{snake}`, or a tuple of them —
/// `(api_me, api_usuario)` last in an auth project, then `api_auth` in a local one, then
/// `api_en_vivo` in one with events — `(api_en_vivo, api_notificaciones)` with the inbox.
fn api_expression(
    entities: &[crate::puerto_toml::Entity],
    auth: bool,
    local: bool,
    en_vivo: bool,
    notificaciones: bool,
) -> String {
    // An entity and its transitions' APIs are one element: a tuple holds at most 16.
    let mut apis: Vec<String> = entities
        .iter()
        .map(|e| {
            let snake = pascal_to_snake(&e.name);
            let own = format!("api_{snake}");
            let mut rest: Vec<String> = e
                .routed_transition_use_cases()
                .iter()
                .map(|uc| format!("api_{uc}"))
                .collect();
            // Fase 38: the routes of its files, on their own `Api`.
            if !crate::generators::file_fields(&e.fields).is_empty() {
                rest.push(format!("api_ficheros_{snake}"));
            }
            if rest.is_empty() {
                own
            } else {
                format!("({own}, {})", rest.join(", "))
            }
        })
        .collect();
    if auth {
        // One element: a tuple holds at most 16.
        apis.push("(api_me, api_usuario)".into());
    }
    if local {
        apis.push("api_auth".into());
    }
    if notificaciones {
        // One element: a tuple holds at most 16.
        apis.push("(api_en_vivo, api_notificaciones)".into());
    } else if en_vivo {
        apis.push("api_en_vivo".into());
    }
    match apis.as_slice() {
        [single] => single.clone(),
        _ => format!("({})", apis.join(", ")),
    }
}

/// `web`: the project has a frontend, so `bootstrap.rs` also carries the test that exports the
/// OpenAPI spec to `docs/api/openapi.json` (ADR-0013).
#[cfg(test)]
pub fn generate_bootstrap_content(
    entities: &[crate::puerto_toml::Entity],
    web: bool,
) -> Result<String, crate::generators::render::RenderError> {
    let project = crate::puerto_toml::Project {
        web,
        ..Default::default()
    };
    generate_bootstrap_for(entities, &project)
}

/// `project`: whether it has a frontend (the spec export test), domain events (its CRUD entities
/// are wired with a unit of work), auth (the authenticator, `GET /me`) and a database.
#[cfg(test)]
pub fn generate_bootstrap_for(
    entities: &[crate::puerto_toml::Entity],
    project: &crate::puerto_toml::Project,
) -> Result<String, crate::generators::render::RenderError> {
    let ctx = build_context(entities, project);
    render("bootstrap/bootstrap.tera", &ctx)
}

/// `puerto generar bootstrap` — refuses when the manifest describes code that is not on disk.
///
/// The write itself is unconditional in `regenerate_bootstrap()` (scaffold calls it right after
/// writing the very files in question). The refusal belongs to the standalone command, which is
/// the one a user runs against a manifest they hand-edited.
pub fn run_bootstrap_command(
    base: &Path,
    allow_missing: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    if !allow_missing {
        let config = crate::puerto_toml::read(base)?;
        let mut lines = crate::generators::consistency::drift_lines(
            &crate::generators::consistency::missing_entity_files(base, &config),
        );
        lines.extend(crate::generators::consistency::missing_consumer_files(
            base, &config,
        ));
        lines.extend(crate::generators::consistency::missing_scheduled_task_files(base, &config));
        lines.extend(crate::generators::consistency::missing_mail_files(
            base, &config,
        ));
        if !lines.is_empty() {
            return Err(format!(
                "no se escribe un cableado generado que no compilaría:\n  {}\n\nPasa \
                 --permitir-faltantes para escribirlo igualmente.",
                lines.join("\n  ")
            )
            .into());
        }
    }
    regenerate_bootstrap(base)?;
    println!("✓ bootstrap.rs regenerado.");
    if crate::puerto_toml::read(base).is_ok_and(|c| c.project.web) {
        println!("✓ web/src/generado/ regenerado.");
    }
    Ok(())
}

/// Read puerto.toml and overwrite the generated wiring: `presentacion/cableado` (its `Cargo.toml`
/// too), `presentacion/api/src/generado/bootstrap.rs` and, in a web project,
/// `web/src/generado/*`. The `api` crate gains the REST crate of every context.
///
/// Warns — rather than refuses — on manifest/filesystem drift: this runs inside `scaffold`, where
/// the entity being generated is fine and it is some *other* declared entity that is missing.
pub fn regenerate_bootstrap(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;

    for line in crate::generators::consistency::drift_lines(
        &crate::generators::consistency::missing_entity_files(base, &config),
    )
    .into_iter()
    .chain(crate::generators::consistency::missing_consumer_files(
        base, &config,
    ))
    .chain(crate::generators::consistency::missing_scheduled_task_files(base, &config))
    .chain(crate::generators::consistency::missing_mail_files(
        base, &config,
    )) {
        eprintln!("⚠ {line}");
    }

    let mut ctx = build_context(&config.entity, &config.project);
    // A local project from before Fase 39 has no account cycle (ADR-0035): wiring it would name use
    // cases it lacks. It is wired once `solicitar_restablecimiento` is there.
    let cycle = layout::crate_file(
        layout::USER_CONTEXT,
        layout::Layer::Application,
        "solicitar_restablecimiento",
    );
    ctx.insert(
        "cuenta",
        &(config.project.auth.as_deref() == Some("local") && base.join(cycle).exists()),
    );
    write_file(
        &base.join(layout::CABLEADO_MANIFEST),
        &render("bootstrap/cableado_cargo.tera", &ctx)?,
    )?;
    write_file(
        &base.join(layout::CABLEADO_LIB),
        &render("bootstrap/cableado.tera", &ctx)?,
    )?;
    write_file(
        &base.join(layout::BOOTSTRAP_RS),
        &render("bootstrap/bootstrap.tera", &ctx)?,
    )?;
    if config
        .entity
        .iter()
        .any(|e| !crate::generators::file_fields(&e.fields).is_empty())
    {
        add_files_to_project(base)?;
    }
    for entity in &config.entity {
        let snake = pascal_to_snake(&entity.name);
        add_crate_dependency(
            base,
            layout::API_MANIFEST,
            "dependencies",
            &layout::crate_name(&snake, Layer::Rest),
            "{ workspace = true }",
        )?;
        if !entity.use_cases.is_empty() {
            // The spec export test builds every API from the use cases' doubles.
            add_crate_dependency(
                base,
                layout::API_MANIFEST,
                "dev-dependencies",
                &layout::crate_name(&snake, Layer::Application),
                "{ workspace = true, features = [\"pruebas\"] }",
            )?;
        }
    }

    write_use_case_builders(base, &config)?;

    crate::generators::crates::sync_workspace_dependencies(base)?;
    crate::generators::events::regenerate_events(base, &config)?;
    crate::generators::worker::regenerate_registry(base, &config)?;
    crate::generators::web::regenerate_web(base, &config)?;

    Ok(())
}

/// `presentacion/cableado/src/<c>/casos.rs`, how each use case of a context is built (Fase 33.2,
/// ADR-0029): the user's. Written whole when missing; otherwise only the function of a use case
/// it lacks (no `fn <use case>(`) is appended. Never rewritten.
fn write_use_case_builders(
    base: &Path,
    config: &crate::puerto_toml::PuertoConfig,
) -> Result<(), Box<dyn std::error::Error>> {
    for entity in bootstrap_entities(&config.entity, &config.project) {
        if entity.use_cases.is_empty() {
            continue;
        }
        let path = base.join(layout::cableado_use_cases(&entity.snake));
        let existing = fs::read_to_string(&path).ok();
        let missing: Vec<&BootstrapUseCase> = entity
            .use_cases
            .iter()
            .chain(&entity.files)
            .filter(|uc| {
                existing
                    .as_deref()
                    .is_none_or(|src| !src.contains(&format!("fn {}(", uc.action)))
            })
            .collect();
        if missing.is_empty() {
            continue;
        }
        let mut ctx = tera::Context::new();
        ctx.insert("entity", &entity);
        ctx.insert("use_cases", &missing);
        ctx.insert("header", &existing.is_none());
        let functions = render("bootstrap/cableado_casos.tera", &ctx)?;
        let content = match existing {
            Some(src) => format!("{}\n{functions}", src.trim_end()),
            None => functions,
        };
        write_file(&path, &content)?;
    }
    Ok(())
}

/// What the first `fichero` field brings to a project (Fase 38): `puerto-ficheros` in the `api`
/// binary (with `s3`, so `FICHEROS_URL=s3://…` needs no rebuild), `FICHEROS_URL` in `.env` and
/// `.env.example`, and the local store's directory in `.gitignore`. Each only once.
fn add_files_to_project(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    add_crate_dependency(
        base,
        layout::API_MANIFEST,
        "dependencies",
        "puerto-ficheros",
        "{ workspace = true, features = [\"s3\"] }",
    )?;
    let vars = "\n# Ficheros (ADR-0034 de Puerto): dónde van sus bytes. En producción, s3://<bucket> con las\n\
                # AWS_* (AWS_ENDPOINT para R2 o MinIO). FICHEROS_TAMANO_MAXIMO, en bytes (10 MiB por defecto).\n\
                FICHEROS_URL=file://./ficheros\n";
    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("FICHEROS_URL") {
            continue;
        }
        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(vars);
        fs::write(&path, content)?;
    }
    let gitignore = base.join(".gitignore");
    let mut ignored = fs::read_to_string(&gitignore).unwrap_or_default();
    if !ignored.lines().any(|l| l == "/ficheros") {
        if !ignored.is_empty() && !ignored.ends_with('\n') {
            ignored.push('\n');
        }
        ignored.push_str("/ficheros\n");
        fs::write(&gitignore, ignored)?;
    }
    Ok(())
}

/// Adds `name = value` to the `[section]` of the crate manifest `manifest` (a path under `base`)
/// unless it is there: at the end of the section, which is created at the end of the file when
/// missing. How a binary gains a crate of the project (ADR-0023 § 7).
pub fn add_crate_dependency(
    base: &Path,
    manifest: &str,
    section: &str,
    name: &str,
    value: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join(manifest);
    let src = fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
    let header = format!("[{section}]\n");
    let line = format!("{name} = {value}\n");
    let out = match src.find(&header) {
        Some(at) => {
            let body = at + header.len();
            let end = src[body..].find("\n[").map_or(src.len(), |i| body + i + 1);
            if src[body..end]
                .lines()
                .any(|l| l.starts_with(&format!("{name} = ")))
            {
                return Ok(());
            }
            let end = body + src[body..end].trim_end().len();
            let sep = if end > body { "\n" } else { "" };
            format!("{}{sep}{}{}", &src[..end], line.trim_end(), &src[end..])
        }
        None => {
            let sep = if src.ends_with('\n') { "\n" } else { "\n\n" };
            format!("{src}{sep}{header}{line}")
        }
    };
    fs::write(&path, out)?;
    Ok(())
}