Skip to main content

ggen_core/codegen/
python.rs

1//! Python code generation for FastAPI microservices
2//!
3//! This module generates FastAPI services, Pydantic v2 models, SQLAlchemy 2.0
4//! async repositories, pytest scaffolding, and requirements.txt from specification
5//! data derived from RDF ontologies.
6//!
7//! # WvdA / Armstrong compliance
8//! - All SQLAlchemy queries include `execution_options(timeout=30)` (deadlock prevention)
9//! - FastAPI uses `lifespan` context manager for proper startup/shutdown
10//! - All error handlers use proper HTTP status codes (no silent failures)
11
12use std::fmt::Write;
13
14// ---------------------------------------------------------------------------
15// Domain types
16// ---------------------------------------------------------------------------
17
18/// A single field in a Pydantic model or SQLAlchemy table.
19#[derive(Clone, Debug)]
20pub struct Field {
21    /// Python identifier (snake_case), e.g. `"order_id"`
22    pub name: String,
23    /// Python type annotation, e.g. `"str"`, `"int"`, `"UUID"`, `"datetime"`
24    pub field_type: String,
25    /// Whether the field may be `None` (generates `Optional[T]`)
26    pub optional: bool,
27    /// Optional default value literal, e.g. `"None"`, `"0"`, `"\"pending\""`
28    pub default: Option<String>,
29}
30
31/// An HTTP endpoint specification used when generating pytest scaffolding.
32#[derive(Clone, Debug)]
33pub struct Endpoint {
34    /// HTTP method in upper-case, e.g. `"GET"`, `"POST"`, `"DELETE"`
35    pub method: String,
36    /// URL path, e.g. `"/orders/{order_id}"`
37    pub path: String,
38    /// Python function name for the route handler, e.g. `"get_order"`
39    pub handler: String,
40    /// Expected HTTP success status code, e.g. `200`, `201`, `204`
41    pub status_code: u16,
42}
43
44// ---------------------------------------------------------------------------
45// Generator struct
46// ---------------------------------------------------------------------------
47
48/// Python microservice code generator (FastAPI / Pydantic v2 / SQLAlchemy 2.0)
49pub struct PythonGenerator;
50
51impl PythonGenerator {
52    // -----------------------------------------------------------------------
53    // generate_fastapi_service
54    // -----------------------------------------------------------------------
55
56    /// Generate a complete FastAPI service module.
57    ///
58    /// The service includes:
59    /// - `lifespan` context manager for startup/shutdown (Armstrong let-it-crash)
60    /// - `/health` endpoint returning `{"status": "ok", "service": "<name>"}`
61    /// - Logging setup
62    /// - Router stub for domain routes
63    ///
64    /// # Arguments
65    /// * `service_name` - Human-readable service name, e.g. `"OrderService"`
66    /// * `port`         - Port the service listens on (used in log message only)
67    /// * `description`  - One-line description embedded in the OpenAPI title
68    pub fn generate_fastapi_service(
69        service_name: &str, port: u16, description: &str,
70    ) -> Result<String, String> {
71        let mut out = String::new();
72        let snake = to_snake(service_name);
73
74        writeln!(out, "\"\"\"").map_err(|e| e.to_string())?;
75        writeln!(out, "{} — {}", service_name, description).map_err(|e| e.to_string())?;
76        writeln!(out, "\nAuto-generated by ggen. Edit with care.").map_err(|e| e.to_string())?;
77        writeln!(out, "\"\"\"\n").map_err(|e| e.to_string())?;
78
79        writeln!(out, "from contextlib import asynccontextmanager").map_err(|e| e.to_string())?;
80        writeln!(out, "import logging\n").map_err(|e| e.to_string())?;
81        writeln!(out, "from fastapi import FastAPI, HTTPException, status")
82            .map_err(|e| e.to_string())?;
83        writeln!(out, "from fastapi.responses import JSONResponse").map_err(|e| e.to_string())?;
84        writeln!(out, "from {snake}_router import router as {snake}_router\n")
85            .map_err(|e| e.to_string())?;
86
87        writeln!(out, "logger = logging.getLogger(__name__)\n").map_err(|e| e.to_string())?;
88
89        // lifespan context manager — Armstrong: let-it-crash on startup failure
90        writeln!(out, "\n@asynccontextmanager").map_err(|e| e.to_string())?;
91        writeln!(out, "async def lifespan(app: FastAPI):").map_err(|e| e.to_string())?;
92        writeln!(
93            out,
94            "    logger.info(\"{service_name} starting on port {port}\")"
95        )
96        .map_err(|e| e.to_string())?;
97        writeln!(out, "    # Initialise DB pool, cache, OTEL exporter here")
98            .map_err(|e| e.to_string())?;
99        writeln!(out, "    yield").map_err(|e| e.to_string())?;
100        writeln!(
101            out,
102            "    # Armstrong: cleanup — let downstream errors propagate"
103        )
104        .map_err(|e| e.to_string())?;
105        writeln!(
106            out,
107            "    logger.info(\"{service_name} shutdown complete\")\n"
108        )
109        .map_err(|e| e.to_string())?;
110
111        // FastAPI app
112        writeln!(out, "\napp = FastAPI(").map_err(|e| e.to_string())?;
113        writeln!(out, "    title=\"{service_name}\",").map_err(|e| e.to_string())?;
114        writeln!(out, "    description=\"{description}\",").map_err(|e| e.to_string())?;
115        writeln!(out, "    version=\"1.0.0\",").map_err(|e| e.to_string())?;
116        writeln!(out, "    lifespan=lifespan,").map_err(|e| e.to_string())?;
117        writeln!(out, ")\n").map_err(|e| e.to_string())?;
118
119        // Include domain router
120        writeln!(
121            out,
122            "app.include_router({snake}_router, prefix=\"/api/v1\")\n"
123        )
124        .map_err(|e| e.to_string())?;
125
126        // Health endpoint
127        writeln!(out, "\n@app.get(\"/health\", tags=[\"ops\"])").map_err(|e| e.to_string())?;
128        writeln!(out, "async def health():").map_err(|e| e.to_string())?;
129        writeln!(
130            out,
131            "    \"\"\"Liveness probe — returns 200 when the process is running.\"\"\""
132        )
133        .map_err(|e| e.to_string())?;
134        writeln!(
135            out,
136            "    return {{\"status\": \"ok\", \"service\": \"{service_name}\"}}\n"
137        )
138        .map_err(|e| e.to_string())?;
139
140        // Generic exception handler — no silent failures
141        writeln!(out, "\n@app.exception_handler(Exception)").map_err(|e| e.to_string())?;
142        writeln!(
143            out,
144            "async def unhandled_exception_handler(request, exc: Exception):"
145        )
146        .map_err(|e| e.to_string())?;
147        writeln!(
148            out,
149            "    logger.error(\"Unhandled exception: %s\", exc, exc_info=True)"
150        )
151        .map_err(|e| e.to_string())?;
152        writeln!(
153            out,
154            "    return JSONResponse(\n        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,"
155        )
156        .map_err(|e| e.to_string())?;
157        writeln!(
158            out,
159            "        content={{\"detail\": \"Internal server error\"}},\n    )"
160        )
161        .map_err(|e| e.to_string())?;
162
163        Ok(out)
164    }
165
166    // -----------------------------------------------------------------------
167    // generate_pydantic_model
168    // -----------------------------------------------------------------------
169
170    /// Generate a Pydantic v2 model class.
171    ///
172    /// The generated model:
173    /// - Uses `model_config = {"from_attributes": True}` (ORM mode)
174    /// - Emits `Optional[T]` with `= None` for optional fields
175    /// - Adds a `json_schema_extra` example block
176    /// - Includes a `model_validator` stub for cross-field validation
177    ///
178    /// # Arguments
179    /// * `model_name` - PascalCase class name, e.g. `"Order"`
180    /// * `fields`     - Slice of `Field` descriptors
181    pub fn generate_pydantic_model(model_name: &str, fields: &[Field]) -> Result<String, String> {
182        let mut out = String::new();
183
184        writeln!(out, "\"\"\"").map_err(|e| e.to_string())?;
185        writeln!(out, "Pydantic v2 model for {}.", model_name).map_err(|e| e.to_string())?;
186        writeln!(out, "\nAuto-generated by ggen. Edit with care.").map_err(|e| e.to_string())?;
187        writeln!(out, "\"\"\"\n").map_err(|e| e.to_string())?;
188
189        writeln!(out, "from __future__ import annotations\n").map_err(|e| e.to_string())?;
190        writeln!(out, "from datetime import datetime").map_err(|e| e.to_string())?;
191        writeln!(out, "from typing import Optional").map_err(|e| e.to_string())?;
192        writeln!(out, "from uuid import UUID\n").map_err(|e| e.to_string())?;
193        writeln!(
194            out,
195            "from pydantic import BaseModel, Field, model_validator\n"
196        )
197        .map_err(|e| e.to_string())?;
198
199        writeln!(out, "\nclass {model_name}(BaseModel):").map_err(|e| e.to_string())?;
200        writeln!(out, "    model_config = {{\"from_attributes\": True}}\n")
201            .map_err(|e| e.to_string())?;
202
203        // Emit fields
204        for field in fields {
205            let type_annotation = if field.optional {
206                format!("Optional[{}]", field.field_type)
207            } else {
208                field.field_type.clone()
209            };
210
211            let default_part = if field.optional {
212                let default_val = field.default.as_deref().unwrap_or("None");
213                format!(" = Field(default={default_val})")
214            } else if let Some(ref d) = field.default {
215                format!(" = Field(default={d})")
216            } else {
217                String::new()
218            };
219
220            writeln!(
221                out,
222                "    {}: {}{}",
223                field.name, type_annotation, default_part
224            )
225            .map_err(|e| e.to_string())?;
226        }
227
228        // json_schema_extra example
229        writeln!(out, "\n    model_config = {{").map_err(|e| e.to_string())?;
230        writeln!(out, "        \"from_attributes\": True,").map_err(|e| e.to_string())?;
231        writeln!(out, "        \"json_schema_extra\": {{").map_err(|e| e.to_string())?;
232        writeln!(out, "            \"example\": {{").map_err(|e| e.to_string())?;
233        for field in fields {
234            let example_val = example_value_for_type(&field.field_type, field.optional);
235            writeln!(out, "                \"{}\": {},", field.name, example_val)
236                .map_err(|e| e.to_string())?;
237        }
238        writeln!(out, "            }}").map_err(|e| e.to_string())?;
239        writeln!(out, "        }}").map_err(|e| e.to_string())?;
240        writeln!(out, "    }}\n").map_err(|e| e.to_string())?;
241
242        // Cross-field validator stub
243        writeln!(out, "    @model_validator(mode=\"after\")").map_err(|e| e.to_string())?;
244        writeln!(out, "    def validate_model(self) -> \"{model_name}\":")
245            .map_err(|e| e.to_string())?;
246        writeln!(
247            out,
248            "        \"\"\"Cross-field validation hook — add domain invariants here.\"\"\""
249        )
250        .map_err(|e| e.to_string())?;
251        writeln!(out, "        return self").map_err(|e| e.to_string())?;
252
253        Ok(out)
254    }
255
256    // -----------------------------------------------------------------------
257    // generate_sqlalchemy_repository
258    // -----------------------------------------------------------------------
259
260    /// Generate a SQLAlchemy 2.0 async repository with full CRUD.
261    ///
262    /// WvdA compliance: every query uses `.execution_options(timeout=30)` to
263    /// prevent deadlocks (boundedness guarantee).
264    ///
265    /// # Arguments
266    /// * `model_name` - PascalCase model name, e.g. `"Order"`
267    /// * `fields`     - Slice of `Field` descriptors (used to build the ORM table)
268    pub fn generate_sqlalchemy_repository(
269        model_name: &str, fields: &[Field],
270    ) -> Result<String, String> {
271        let mut out = String::new();
272        let table_name = format!("{}s", to_snake(model_name));
273        let snake_model = to_snake(model_name);
274
275        writeln!(out, "\"\"\"").map_err(|e| e.to_string())?;
276        writeln!(out, "SQLAlchemy 2.0 async repository for {}.", model_name)
277            .map_err(|e| e.to_string())?;
278        writeln!(
279            out,
280            "\nWvdA: all queries use execution_options(timeout=30)."
281        )
282        .map_err(|e| e.to_string())?;
283        writeln!(out, "\nAuto-generated by ggen. Edit with care.").map_err(|e| e.to_string())?;
284        writeln!(out, "\"\"\"\n").map_err(|e| e.to_string())?;
285
286        writeln!(out, "from __future__ import annotations\n").map_err(|e| e.to_string())?;
287        writeln!(out, "from typing import List, Optional").map_err(|e| e.to_string())?;
288        writeln!(out, "from uuid import UUID\n").map_err(|e| e.to_string())?;
289        writeln!(
290            out,
291            "from sqlalchemy import Column, String, Integer, Boolean, DateTime, select, update, delete"
292        )
293        .map_err(|e| e.to_string())?;
294        writeln!(
295            out,
296            "from sqlalchemy.dialects.postgresql import UUID as PG_UUID"
297        )
298        .map_err(|e| e.to_string())?;
299        writeln!(out, "from sqlalchemy.ext.asyncio import AsyncSession")
300            .map_err(|e| e.to_string())?;
301        writeln!(
302            out,
303            "from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column\n"
304        )
305        .map_err(|e| e.to_string())?;
306
307        // Base
308        writeln!(out, "\nclass Base(DeclarativeBase):").map_err(|e| e.to_string())?;
309        writeln!(out, "    pass\n").map_err(|e| e.to_string())?;
310
311        // ORM model
312        writeln!(out, "\nclass {model_name}ORM(Base):").map_err(|e| e.to_string())?;
313        writeln!(
314            out,
315            "    \"\"\"SQLAlchemy ORM mapping for {model_name}.\"\"\""
316        )
317        .map_err(|e| e.to_string())?;
318        writeln!(out, "\n    __tablename__ = \"{table_name}\"\n").map_err(|e| e.to_string())?;
319
320        for field in fields {
321            let sa_type = sqlalchemy_type_for(&field.field_type);
322            let nullable_part = if field.optional {
323                ", nullable=True"
324            } else {
325                ""
326            };
327            writeln!(
328                out,
329                "    {}: Mapped[{}] = mapped_column({}{nullable_part})",
330                field.name, field.field_type, sa_type
331            )
332            .map_err(|e| e.to_string())?;
333        }
334
335        writeln!(out).map_err(|e| e.to_string())?;
336
337        // Repository class
338        writeln!(out, "\nclass {model_name}Repository:").map_err(|e| e.to_string())?;
339        writeln!(
340            out,
341            "    \"\"\"Async CRUD repository for {model_name}.\"\"\"\n"
342        )
343        .map_err(|e| e.to_string())?;
344        writeln!(
345            out,
346            "    def __init__(self, session: AsyncSession) -> None:"
347        )
348        .map_err(|e| e.to_string())?;
349        writeln!(out, "        self._session = session\n").map_err(|e| e.to_string())?;
350
351        // create
352        writeln!(
353            out,
354            "    async def create(self, {snake_model}: {model_name}ORM) -> {model_name}ORM:"
355        )
356        .map_err(|e| e.to_string())?;
357        writeln!(
358            out,
359            "        \"\"\"Persist a new {model_name} and return the managed instance.\"\"\""
360        )
361        .map_err(|e| e.to_string())?;
362        writeln!(out, "        self._session.add({snake_model})").map_err(|e| e.to_string())?;
363        writeln!(out, "        await self._session.flush()").map_err(|e| e.to_string())?;
364        writeln!(out, "        await self._session.refresh({snake_model})")
365            .map_err(|e| e.to_string())?;
366        writeln!(out, "        return {snake_model}\n").map_err(|e| e.to_string())?;
367
368        // get_by_id
369        writeln!(
370            out,
371            "    async def get_by_id(self, record_id: UUID) -> Optional[{model_name}ORM]:"
372        )
373        .map_err(|e| e.to_string())?;
374        writeln!(
375            out,
376            "        \"\"\"Retrieve a {model_name} by primary key. Returns None if not found.\"\"\""
377        )
378        .map_err(|e| e.to_string())?;
379        writeln!(
380            out,
381            "        # WvdA: execution_options(timeout=30) prevents query deadlock"
382        )
383        .map_err(|e| e.to_string())?;
384        writeln!(
385            out,
386            "        stmt = (\n            select({model_name}ORM)\n            .where({model_name}ORM.id == record_id)\n            .execution_options(timeout=30)\n        )"
387        )
388        .map_err(|e| e.to_string())?;
389        writeln!(out, "        result = await self._session.execute(stmt)")
390            .map_err(|e| e.to_string())?;
391        writeln!(out, "        return result.scalars().first()\n").map_err(|e| e.to_string())?;
392
393        // list_all
394        writeln!(
395            out,
396            "    async def list_all(self, limit: int = 100) -> List[{model_name}ORM]:"
397        )
398        .map_err(|e| e.to_string())?;
399        writeln!(
400            out,
401            "        \"\"\"Return up to *limit* records (WvdA boundedness: default 100).\"\"\""
402        )
403        .map_err(|e| e.to_string())?;
404        writeln!(
405            out,
406            "        stmt = (\n            select({model_name}ORM)\n            .limit(limit)\n            .execution_options(timeout=30)\n        )"
407        )
408        .map_err(|e| e.to_string())?;
409        writeln!(out, "        result = await self._session.execute(stmt)")
410            .map_err(|e| e.to_string())?;
411        writeln!(out, "        return list(result.scalars().all())\n")
412            .map_err(|e| e.to_string())?;
413
414        // update
415        writeln!(
416            out,
417            "    async def update(self, record_id: UUID, values: dict) -> Optional[{model_name}ORM]:"
418        )
419        .map_err(|e| e.to_string())?;
420        writeln!(
421            out,
422            "        \"\"\"Update fields on a {model_name} by primary key.\"\"\""
423        )
424        .map_err(|e| e.to_string())?;
425        writeln!(
426            out,
427            "        stmt = (\n            update({model_name}ORM)\n            .where({model_name}ORM.id == record_id)\n            .values(**values)\n            .execution_options(timeout=30)\n        )"
428        )
429        .map_err(|e| e.to_string())?;
430        writeln!(out, "        await self._session.execute(stmt)").map_err(|e| e.to_string())?;
431        writeln!(out, "        return await self.get_by_id(record_id)\n")
432            .map_err(|e| e.to_string())?;
433
434        // delete
435        writeln!(out, "    async def delete(self, record_id: UUID) -> bool:")
436            .map_err(|e| e.to_string())?;
437        writeln!(
438            out,
439            "        \"\"\"Delete a {model_name} by primary key. Returns True if a row was deleted.\"\"\""
440        )
441        .map_err(|e| e.to_string())?;
442        writeln!(
443            out,
444            "        stmt = (\n            delete({model_name}ORM)\n            .where({model_name}ORM.id == record_id)\n            .execution_options(timeout=30)\n        )"
445        )
446        .map_err(|e| e.to_string())?;
447        writeln!(out, "        result = await self._session.execute(stmt)")
448            .map_err(|e| e.to_string())?;
449        writeln!(out, "        return result.rowcount > 0").map_err(|e| e.to_string())?;
450
451        Ok(out)
452    }
453
454    // -----------------------------------------------------------------------
455    // generate_pytest_tests
456    // -----------------------------------------------------------------------
457
458    /// Generate a pytest test suite for a FastAPI service.
459    ///
460    /// Produces:
461    /// - `@pytest.fixture` for `async_client` (httpx AsyncClient)
462    /// - A happy-path test and a 404 error test for each endpoint
463    ///
464    /// # Arguments
465    /// * `service_name` - Name used in test module docstring
466    /// * `endpoints`    - Slice of `Endpoint` descriptors
467    pub fn generate_pytest_tests(
468        service_name: &str, endpoints: &[Endpoint],
469    ) -> Result<String, String> {
470        let mut out = String::new();
471        let snake = to_snake(service_name);
472
473        writeln!(out, "\"\"\"").map_err(|e| e.to_string())?;
474        writeln!(out, "pytest test suite for {service_name}.").map_err(|e| e.to_string())?;
475        writeln!(
476            out,
477            "\nChicago TDD: behaviour verification via real FastAPI TestClient."
478        )
479        .map_err(|e| e.to_string())?;
480        writeln!(out, "\nAuto-generated by ggen. Edit with care.").map_err(|e| e.to_string())?;
481        writeln!(out, "\"\"\"\n").map_err(|e| e.to_string())?;
482
483        writeln!(out, "from __future__ import annotations\n").map_err(|e| e.to_string())?;
484        writeln!(out, "import pytest").map_err(|e| e.to_string())?;
485        writeln!(out, "import pytest_asyncio").map_err(|e| e.to_string())?;
486        writeln!(out, "from httpx import AsyncClient, ASGITransport\n")
487            .map_err(|e| e.to_string())?;
488        writeln!(
489            out,
490            "from {snake}_app import app  # FastAPI application instance\n"
491        )
492        .map_err(|e| e.to_string())?;
493
494        // async_client fixture
495        writeln!(out, "\n@pytest_asyncio.fixture").map_err(|e| e.to_string())?;
496        writeln!(
497            out,
498            "async def async_client() -> AsyncClient:  # type: ignore[override]"
499        )
500        .map_err(|e| e.to_string())?;
501        writeln!(
502            out,
503            "    \"\"\"Fixture — yields an HTTPX async client wired to the FastAPI app.\"\"\""
504        )
505        .map_err(|e| e.to_string())?;
506        writeln!(
507            out,
508            "    async with AsyncClient(\n        transport=ASGITransport(app=app), base_url=\"http://test\"\n    ) as client:"
509        )
510        .map_err(|e| e.to_string())?;
511        writeln!(out, "        yield client\n").map_err(|e| e.to_string())?;
512
513        // health check test (always present)
514        writeln!(out, "\n@pytest.mark.asyncio").map_err(|e| e.to_string())?;
515        writeln!(
516            out,
517            "async def test_health_check(async_client: AsyncClient) -> None:"
518        )
519        .map_err(|e| e.to_string())?;
520        writeln!(
521            out,
522            "    \"\"\"Liveness probe returns 200 with service name.\"\"\""
523        )
524        .map_err(|e| e.to_string())?;
525        writeln!(out, "    response = await async_client.get(\"/health\")")
526            .map_err(|e| e.to_string())?;
527        writeln!(out, "    assert response.status_code == 200").map_err(|e| e.to_string())?;
528        writeln!(out, "    assert response.json()[\"status\"] == \"ok\"")
529            .map_err(|e| e.to_string())?;
530        writeln!(
531            out,
532            "    assert response.json()[\"service\"] == \"{service_name}\"\n"
533        )
534        .map_err(|e| e.to_string())?;
535
536        // Per-endpoint tests
537        for ep in endpoints {
538            let method_lower = ep.method.to_lowercase();
539            let handler_snake = to_snake(&ep.handler);
540            let path_escaped = ep.path.replace('{', "{{").replace('}', "}}");
541
542            // Happy path
543            writeln!(out, "\n@pytest.mark.asyncio").map_err(|e| e.to_string())?;
544            writeln!(
545                out,
546                "async def test_{handler_snake}_happy_path(async_client: AsyncClient) -> None:"
547            )
548            .map_err(|e| e.to_string())?;
549            writeln!(
550                out,
551                "    \"\"\"Happy path: {} {} returns {}.\"\"\"\n    # Provide valid payload / path params",
552                ep.method, ep.path, ep.status_code
553            )
554            .map_err(|e| e.to_string())?;
555            writeln!(
556                out,
557                "    response = await async_client.{method_lower}(\"{path_escaped}\")"
558            )
559            .map_err(|e| e.to_string())?;
560            writeln!(
561                out,
562                "    assert response.status_code == {}\n",
563                ep.status_code
564            )
565            .map_err(|e| e.to_string())?;
566
567            // Error path (only meaningful for endpoints that accept IDs)
568            if ep.path.contains('{') {
569                writeln!(out, "\n@pytest.mark.asyncio").map_err(|e| e.to_string())?;
570                writeln!(
571                    out,
572                    "async def test_{handler_snake}_not_found(async_client: AsyncClient) -> None:"
573                )
574                .map_err(|e| e.to_string())?;
575                writeln!(
576                    out,
577                    "    \"\"\"Error path: non-existent resource returns 404.\"\"\""
578                )
579                .map_err(|e| e.to_string())?;
580                writeln!(
581                    out,
582                    "    response = await async_client.{method_lower}(\"/api/v1/00000000-0000-0000-0000-000000000000\")"
583                )
584                .map_err(|e| e.to_string())?;
585                writeln!(out, "    assert response.status_code == 404\n")
586                    .map_err(|e| e.to_string())?;
587            }
588        }
589
590        Ok(out)
591    }
592
593    // -----------------------------------------------------------------------
594    // generate_requirements_txt
595    // -----------------------------------------------------------------------
596
597    /// Generate a pinned `requirements.txt` for a FastAPI microservice.
598    ///
599    /// Core dependencies are always included; optional feature sets are added
600    /// when the corresponding feature tag appears in `features`.
601    ///
602    /// Recognised feature tags: `"postgres"`, `"redis"`, `"otel"`, `"test"`.
603    ///
604    /// # Arguments
605    /// * `service_name` - Used only in the header comment
606    /// * `features`     - Slice of feature tag strings
607    pub fn generate_requirements_txt(
608        service_name: &str, features: &[&str],
609    ) -> Result<String, String> {
610        let mut out = String::new();
611
612        writeln!(out, "# requirements.txt for {service_name}").map_err(|e| e.to_string())?;
613        writeln!(
614            out,
615            "# Auto-generated by ggen. Pin versions before production deploy."
616        )
617        .map_err(|e| e.to_string())?;
618        writeln!(
619            out,
620            "# WvdA: explicit versions prevent unbounded dependency drift.\n"
621        )
622        .map_err(|e| e.to_string())?;
623
624        // Core
625        writeln!(out, "# Core framework").map_err(|e| e.to_string())?;
626        writeln!(out, "fastapi==0.115.0").map_err(|e| e.to_string())?;
627        writeln!(out, "uvicorn[standard]==0.30.6").map_err(|e| e.to_string())?;
628        writeln!(out, "pydantic==2.9.2").map_err(|e| e.to_string())?;
629        writeln!(out, "pydantic-settings==2.5.2").map_err(|e| e.to_string())?;
630        writeln!(out, "httpx==0.27.2\n").map_err(|e| e.to_string())?;
631
632        // Optional: postgres
633        if features.contains(&"postgres") {
634            writeln!(out, "# PostgreSQL / SQLAlchemy").map_err(|e| e.to_string())?;
635            writeln!(out, "sqlalchemy==2.0.36").map_err(|e| e.to_string())?;
636            writeln!(out, "asyncpg==0.30.0").map_err(|e| e.to_string())?;
637            writeln!(out, "alembic==1.13.3\n").map_err(|e| e.to_string())?;
638        }
639
640        // Optional: redis
641        if features.contains(&"redis") {
642            writeln!(out, "# Redis cache").map_err(|e| e.to_string())?;
643            writeln!(out, "redis==5.2.0").map_err(|e| e.to_string())?;
644            writeln!(out, "hiredis==3.0.0\n").map_err(|e| e.to_string())?;
645        }
646
647        // Optional: otel
648        if features.contains(&"otel") {
649            writeln!(out, "# OpenTelemetry").map_err(|e| e.to_string())?;
650            writeln!(out, "opentelemetry-api==1.27.0").map_err(|e| e.to_string())?;
651            writeln!(out, "opentelemetry-sdk==1.27.0").map_err(|e| e.to_string())?;
652            writeln!(out, "opentelemetry-exporter-otlp==1.27.0").map_err(|e| e.to_string())?;
653            writeln!(out, "opentelemetry-instrumentation-fastapi==0.48b0\n")
654                .map_err(|e| e.to_string())?;
655        }
656
657        // Optional: test
658        if features.contains(&"test") {
659            writeln!(out, "# Testing").map_err(|e| e.to_string())?;
660            writeln!(out, "pytest==8.3.3").map_err(|e| e.to_string())?;
661            writeln!(out, "pytest-asyncio==0.24.0").map_err(|e| e.to_string())?;
662            writeln!(out, "anyio==4.6.2\n").map_err(|e| e.to_string())?;
663        }
664
665        Ok(out)
666    }
667
668    // -----------------------------------------------------------------------
669    // generate_main
670    // -----------------------------------------------------------------------
671
672    /// Generate a `main.py` entry point with uvicorn startup and signal handling.
673    ///
674    /// # Arguments
675    /// * `service_name` - Used for the log prefix
676    /// * `port`         - TCP port uvicorn binds to
677    pub fn generate_main(service_name: &str, port: u16) -> Result<String, String> {
678        let mut out = String::new();
679        let snake = to_snake(service_name);
680
681        writeln!(out, "\"\"\"").map_err(|e| e.to_string())?;
682        writeln!(out, "main.py — entry point for {service_name}.").map_err(|e| e.to_string())?;
683        writeln!(
684            out,
685            "\nArmstrong: lifespan context manager handles startup/shutdown."
686        )
687        .map_err(|e| e.to_string())?;
688        writeln!(out, "Let-it-crash: any startup failure exits with code 1.")
689            .map_err(|e| e.to_string())?;
690        writeln!(out, "\nAuto-generated by ggen. Edit with care.").map_err(|e| e.to_string())?;
691        writeln!(out, "\"\"\"\n").map_err(|e| e.to_string())?;
692
693        writeln!(out, "import logging").map_err(|e| e.to_string())?;
694        writeln!(out, "import signal").map_err(|e| e.to_string())?;
695        writeln!(out, "import sys\n").map_err(|e| e.to_string())?;
696        writeln!(out, "import uvicorn\n").map_err(|e| e.to_string())?;
697        writeln!(out, "from {snake}_app import app  # noqa: F401\n").map_err(|e| e.to_string())?;
698
699        writeln!(
700            out,
701            "logging.basicConfig(\n    level=logging.INFO,\n    format=\"%(asctime)s [%(levelname)s] %(name)s: %(message)s\",\n)\nlogger = logging.getLogger(\"{snake}\")\n"
702        )
703        .map_err(|e| e.to_string())?;
704
705        writeln!(out, "# Armstrong: graceful shutdown on SIGINT / SIGTERM")
706            .map_err(|e| e.to_string())?;
707        writeln!(out, "_server: uvicorn.Server | None = None\n").map_err(|e| e.to_string())?;
708
709        writeln!(out, "\ndef _handle_signal(signum: int, _frame) -> None:")
710            .map_err(|e| e.to_string())?;
711        writeln!(
712            out,
713            "    logger.info(\"{service_name} received signal %d, shutting down\", signum)"
714        )
715        .map_err(|e| e.to_string())?;
716        writeln!(out, "    if _server:").map_err(|e| e.to_string())?;
717        writeln!(out, "        _server.should_exit = True\n").map_err(|e| e.to_string())?;
718
719        writeln!(out, "\ndef main() -> None:").map_err(|e| e.to_string())?;
720        writeln!(out, "    global _server").map_err(|e| e.to_string())?;
721        writeln!(out, "    signal.signal(signal.SIGINT, _handle_signal)")
722            .map_err(|e| e.to_string())?;
723        writeln!(out, "    signal.signal(signal.SIGTERM, _handle_signal)\n")
724            .map_err(|e| e.to_string())?;
725        writeln!(
726            out,
727            "    config = uvicorn.Config(\n        app=\"{snake}_app:app\","
728        )
729        .map_err(|e| e.to_string())?;
730        writeln!(out, "        host=\"0.0.0.0\",").map_err(|e| e.to_string())?;
731        writeln!(out, "        port={port},").map_err(|e| e.to_string())?;
732        writeln!(out, "        log_level=\"info\",").map_err(|e| e.to_string())?;
733        writeln!(out, "        access_log=True,").map_err(|e| e.to_string())?;
734        writeln!(out, "    )").map_err(|e| e.to_string())?;
735        writeln!(out, "    _server = uvicorn.Server(config)").map_err(|e| e.to_string())?;
736        writeln!(
737            out,
738            "    logger.info(\"{service_name} starting on port {port}\")"
739        )
740        .map_err(|e| e.to_string())?;
741        writeln!(out, "    _server.run()").map_err(|e| e.to_string())?;
742        writeln!(out, "    logger.info(\"{service_name} stopped\")\n")
743            .map_err(|e| e.to_string())?;
744
745        writeln!(out, "\nif __name__ == \"__main__\":").map_err(|e| e.to_string())?;
746        writeln!(out, "    main()").map_err(|e| e.to_string())?;
747
748        Ok(out)
749    }
750}
751
752// ---------------------------------------------------------------------------
753// Private helpers
754// ---------------------------------------------------------------------------
755
756/// Convert PascalCase or mixed identifiers to snake_case.
757fn to_snake(s: &str) -> String {
758    let mut out = String::new();
759    let chars: Vec<char> = s.chars().collect();
760    for (i, &c) in chars.iter().enumerate() {
761        if c.is_uppercase() {
762            if i != 0 {
763                out.push('_');
764            }
765            out.push(c.to_ascii_lowercase());
766        } else {
767            out.push(c);
768        }
769    }
770    out
771}
772
773/// Map a Python type name to a SQLAlchemy column type string.
774fn sqlalchemy_type_for(py_type: &str) -> &'static str {
775    match py_type {
776        "str" => "String",
777        "int" => "Integer",
778        "bool" => "Boolean",
779        "float" => "Integer", // use Numeric in real code
780        "datetime" => "DateTime",
781        "UUID" => "PG_UUID(as_uuid=True)",
782        _ => "String",
783    }
784}
785
786/// Return a plausible JSON example literal for a Python type.
787fn example_value_for_type(py_type: &str, optional: bool) -> &'static str {
788    if optional {
789        return "null";
790    }
791    match py_type {
792        "str" => "\"example\"",
793        "int" => "0",
794        "bool" => "true",
795        "float" => "0.0",
796        "datetime" => "\"2024-01-01T00:00:00Z\"",
797        "UUID" => "\"00000000-0000-0000-0000-000000000000\"",
798        _ => "\"example\"",
799    }
800}
801
802// ---------------------------------------------------------------------------
803// Tests (Chicago TDD — Red→Green→Refactor)
804// ---------------------------------------------------------------------------
805
806#[cfg(test)]
807mod tests {
808    use super::*;
809
810    // Shared helpers -----------------------------------------------------------
811
812    fn order_fields() -> Vec<Field> {
813        vec![
814            Field {
815                name: "id".to_string(),
816                field_type: "UUID".to_string(),
817                optional: false,
818                default: None,
819            },
820            Field {
821                name: "customer_id".to_string(),
822                field_type: "UUID".to_string(),
823                optional: false,
824                default: None,
825            },
826            Field {
827                name: "status".to_string(),
828                field_type: "str".to_string(),
829                optional: false,
830                default: Some("\"pending\"".to_string()),
831            },
832            Field {
833                name: "total".to_string(),
834                field_type: "float".to_string(),
835                optional: true,
836                default: None,
837            },
838        ]
839    }
840
841    fn order_endpoints() -> Vec<Endpoint> {
842        vec![
843            Endpoint {
844                method: "GET".to_string(),
845                path: "/api/v1/orders".to_string(),
846                handler: "list_orders".to_string(),
847                status_code: 200,
848            },
849            Endpoint {
850                method: "POST".to_string(),
851                path: "/api/v1/orders".to_string(),
852                handler: "create_order".to_string(),
853                status_code: 201,
854            },
855            Endpoint {
856                method: "GET".to_string(),
857                path: "/api/v1/orders/{order_id}".to_string(),
858                handler: "get_order".to_string(),
859                status_code: 200,
860            },
861            Endpoint {
862                method: "DELETE".to_string(),
863                path: "/api/v1/orders/{order_id}".to_string(),
864                handler: "delete_order".to_string(),
865                status_code: 204,
866            },
867        ]
868    }
869
870    // -------------------------------------------------------------------------
871    // Test 1: FastAPI service contains health endpoint
872    // -------------------------------------------------------------------------
873
874    #[test]
875    fn test_fastapi_service_contains_health_endpoint() {
876        let result =
877            PythonGenerator::generate_fastapi_service("OrderService", 8001, "Manages orders");
878        assert!(result.is_ok(), "generate_fastapi_service should succeed");
879        let code = result.unwrap();
880        assert!(
881            code.contains("@app.get(\"/health\""),
882            "must contain @app.get(\"/health\")"
883        );
884        assert!(
885            code.contains("\"status\": \"ok\""),
886            "health response must include status: ok"
887        );
888        assert!(
889            code.contains("\"service\": \"OrderService\""),
890            "health response must include service name"
891        );
892    }
893
894    // -------------------------------------------------------------------------
895    // Test 2: FastAPI service uses lifespan context manager
896    // -------------------------------------------------------------------------
897
898    #[test]
899    fn test_fastapi_service_uses_lifespan() {
900        let result =
901            PythonGenerator::generate_fastapi_service("OrderService", 8001, "Manages orders");
902        assert!(result.is_ok());
903        let code = result.unwrap();
904        assert!(
905            code.contains("@asynccontextmanager"),
906            "must use @asynccontextmanager"
907        );
908        assert!(
909            code.contains("async def lifespan(app: FastAPI):"),
910            "must define lifespan function"
911        );
912        assert!(
913            code.contains("lifespan=lifespan"),
914            "FastAPI() must receive lifespan="
915        );
916        assert!(code.contains("yield"), "lifespan must yield");
917    }
918
919    // -------------------------------------------------------------------------
920    // Test 3: FastAPI service is non-empty and contains service name
921    // -------------------------------------------------------------------------
922
923    #[test]
924    fn test_fastapi_service_non_empty_with_service_name() {
925        let result =
926            PythonGenerator::generate_fastapi_service("PaymentService", 9001, "Handles payments");
927        assert!(result.is_ok());
928        let code = result.unwrap();
929        assert!(!code.is_empty(), "generated code must not be empty");
930        assert!(
931            code.contains("PaymentService"),
932            "generated code must reference service name"
933        );
934        assert!(
935            code.contains("9001"),
936            "generated code must reference the port"
937        );
938    }
939
940    // -------------------------------------------------------------------------
941    // Test 4: Pydantic model with required and optional fields
942    // -------------------------------------------------------------------------
943
944    #[test]
945    fn test_pydantic_model_required_and_optional_fields() {
946        let fields = order_fields();
947        let result = PythonGenerator::generate_pydantic_model("Order", &fields);
948        assert!(result.is_ok(), "generate_pydantic_model should succeed");
949        let code = result.unwrap();
950
951        // Required fields
952        assert!(code.contains("id: UUID"), "must emit required UUID field");
953        assert!(code.contains("customer_id: UUID"), "must emit customer_id");
954        // Optional field
955        assert!(
956            code.contains("Optional[float]"),
957            "optional float must be Optional[float]"
958        );
959        // Pydantic v2 config
960        assert!(
961            code.contains("from_attributes"),
962            "must include from_attributes ORM mode"
963        );
964        // Validator
965        assert!(
966            code.contains("@model_validator"),
967            "must include @model_validator stub"
968        );
969    }
970
971    // -------------------------------------------------------------------------
972    // Test 5: SQLAlchemy repository has all four CRUD methods
973    // -------------------------------------------------------------------------
974
975    #[test]
976    fn test_sqlalchemy_repository_has_crud_methods() {
977        let fields = order_fields();
978        let result = PythonGenerator::generate_sqlalchemy_repository("Order", &fields);
979        assert!(
980            result.is_ok(),
981            "generate_sqlalchemy_repository should succeed"
982        );
983        let code = result.unwrap();
984
985        assert!(
986            code.contains("async def create("),
987            "must have create method"
988        );
989        assert!(
990            code.contains("async def get_by_id("),
991            "must have get_by_id method"
992        );
993        assert!(
994            code.contains("async def list_all("),
995            "must have list_all method"
996        );
997        assert!(
998            code.contains("async def update("),
999            "must have update method"
1000        );
1001        assert!(
1002            code.contains("async def delete("),
1003            "must have delete method"
1004        );
1005    }
1006
1007    // -------------------------------------------------------------------------
1008    // Test 6: SQLAlchemy repository uses execution_options(timeout=30)
1009    // -------------------------------------------------------------------------
1010
1011    #[test]
1012    fn test_sqlalchemy_repository_uses_execution_timeout() {
1013        let fields = order_fields();
1014        let result = PythonGenerator::generate_sqlalchemy_repository("Order", &fields);
1015        assert!(result.is_ok());
1016        let code = result.unwrap();
1017
1018        // WvdA: count occurrences of the timeout guard
1019        let timeout_count = code.matches("execution_options(timeout=30)").count();
1020        assert!(
1021            timeout_count >= 3,
1022            "at least 3 queries must use execution_options(timeout=30), found {}",
1023            timeout_count
1024        );
1025    }
1026
1027    // -------------------------------------------------------------------------
1028    // Test 7: pytest file contains fixtures and health test
1029    // -------------------------------------------------------------------------
1030
1031    #[test]
1032    fn test_pytest_file_has_fixtures_and_health_test() {
1033        let endpoints = order_endpoints();
1034        let result = PythonGenerator::generate_pytest_tests("OrderService", &endpoints);
1035        assert!(result.is_ok(), "generate_pytest_tests should succeed");
1036        let code = result.unwrap();
1037
1038        assert!(
1039            code.contains("@pytest_asyncio.fixture"),
1040            "must have async_client fixture"
1041        );
1042        assert!(
1043            code.contains("async def async_client("),
1044            "fixture must define async_client"
1045        );
1046        assert!(
1047            code.contains("test_health_check"),
1048            "must include health check test"
1049        );
1050        assert!(
1051            code.contains("@pytest.mark.asyncio"),
1052            "tests must be marked asyncio"
1053        );
1054    }
1055
1056    // -------------------------------------------------------------------------
1057    // Test 8: requirements.txt always contains fastapi and pydantic
1058    // -------------------------------------------------------------------------
1059
1060    #[test]
1061    fn test_requirements_txt_contains_fastapi_and_pydantic() {
1062        let result =
1063            PythonGenerator::generate_requirements_txt("OrderService", &["postgres", "test"]);
1064        assert!(result.is_ok(), "generate_requirements_txt should succeed");
1065        let code = result.unwrap();
1066
1067        assert!(code.contains("fastapi=="), "must pin fastapi");
1068        assert!(code.contains("pydantic=="), "must pin pydantic");
1069        assert!(
1070            code.contains("sqlalchemy=="),
1071            "postgres feature must add sqlalchemy"
1072        );
1073        assert!(code.contains("pytest=="), "test feature must add pytest");
1074    }
1075
1076    // -------------------------------------------------------------------------
1077    // Test 9: requirements.txt without optional features has no postgres deps
1078    // -------------------------------------------------------------------------
1079
1080    #[test]
1081    fn test_requirements_txt_no_optional_features() {
1082        let result = PythonGenerator::generate_requirements_txt("MinimalService", &[]);
1083        assert!(result.is_ok());
1084        let code = result.unwrap();
1085
1086        assert!(code.contains("fastapi=="), "must always contain fastapi");
1087        assert!(code.contains("pydantic=="), "must always contain pydantic");
1088        assert!(
1089            !code.contains("sqlalchemy"),
1090            "sqlalchemy must NOT appear without postgres feature"
1091        );
1092        assert!(
1093            !code.contains("pytest"),
1094            "pytest must NOT appear without test feature"
1095        );
1096    }
1097
1098    // -------------------------------------------------------------------------
1099    // Test 10: main.py has uvicorn startup and signal handling
1100    // -------------------------------------------------------------------------
1101
1102    #[test]
1103    fn test_main_has_uvicorn_and_signal_handling() {
1104        let result = PythonGenerator::generate_main("OrderService", 8001);
1105        assert!(result.is_ok(), "generate_main should succeed");
1106        let code = result.unwrap();
1107
1108        assert!(code.contains("uvicorn"), "must use uvicorn");
1109        assert!(code.contains("signal.SIGINT"), "must handle SIGINT");
1110        assert!(code.contains("signal.SIGTERM"), "must handle SIGTERM");
1111        assert!(code.contains("8001"), "must reference the configured port");
1112        assert!(
1113            code.contains("if __name__ == \"__main__\":"),
1114            "must have __main__ guard"
1115        );
1116    }
1117
1118    // -------------------------------------------------------------------------
1119    // Test 11: pytest test per endpoint, error paths for ID-parameterised routes
1120    // -------------------------------------------------------------------------
1121
1122    #[test]
1123    fn test_pytest_generates_per_endpoint_tests() {
1124        let endpoints = order_endpoints();
1125        let result = PythonGenerator::generate_pytest_tests("OrderService", &endpoints);
1126        assert!(result.is_ok());
1127        let code = result.unwrap();
1128
1129        // Endpoint handlers become test function names
1130        assert!(
1131            code.contains("test_list_orders_happy_path"),
1132            "must have test for list_orders"
1133        );
1134        assert!(
1135            code.contains("test_create_order_happy_path"),
1136            "must have test for create_order"
1137        );
1138        assert!(
1139            code.contains("test_get_order_happy_path"),
1140            "must have test for get_order"
1141        );
1142        // ID-parameterised routes get a not-found test
1143        assert!(
1144            code.contains("test_get_order_not_found"),
1145            "must have not-found test for get_order"
1146        );
1147        assert!(
1148            code.contains("test_delete_order_not_found"),
1149            "must have not-found test for delete_order"
1150        );
1151    }
1152
1153    // -------------------------------------------------------------------------
1154    // Test 12: to_snake helper
1155    // -------------------------------------------------------------------------
1156
1157    #[test]
1158    fn test_to_snake_converts_pascal_case() {
1159        assert_eq!(to_snake("OrderService"), "order_service");
1160        assert_eq!(to_snake("PaymentGateway"), "payment_gateway");
1161        assert_eq!(to_snake("order"), "order");
1162        assert_eq!(to_snake("A"), "a");
1163    }
1164}