|
| 1 | +# -------------------------------------------------------------------------- |
| 2 | +# Architecture-preset layout strategy for interactive project generation. |
| 3 | +# |
| 4 | +# Maps each architecture preset (issue #44) to the actual generation |
| 5 | +# decisions interactive ``init`` makes: |
| 6 | +# |
| 7 | +# - which template ships as the base scaffold, |
| 8 | +# - whether the dynamic ``main.py`` overlay should overwrite the shipped one, |
| 9 | +# - where database / auth config files should land so they sit next to the |
| 10 | +# template's existing structure rather than in a parallel ``src/config``, |
| 11 | +# - and which feature combinations need a "you must wire this up manually" |
| 12 | +# warning because the dynamic ``main.py`` overlay isn't applied. |
| 13 | +# |
| 14 | +# Keeping every preset's layout knowledge in one place lets the CLI flow stay |
| 15 | +# linear ("ask the strategist where to write the file") instead of growing a |
| 16 | +# branching maze of preset-specific if/else blocks. |
| 17 | +# |
| 18 | +# @author bnbong bbbong9@gmail.com |
| 19 | +# -------------------------------------------------------------------------- |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +from dataclasses import dataclass, field |
| 23 | +from pathlib import Path |
| 24 | +from typing import Any, Dict, List, Tuple |
| 25 | + |
| 26 | +# Canonical preset id used when a caller doesn't supply one. Picked to |
| 27 | +# preserve pre-#45 behaviour: interactive ``init`` historically deployed |
| 28 | +# ``fastapi-empty`` and regenerated ``src/main.py`` from feature flags. |
| 29 | +_FALLBACK_PRESET_ID: str = "minimal" |
| 30 | + |
| 31 | + |
| 32 | +@dataclass(frozen=True) |
| 33 | +class PresetProfile: |
| 34 | + """Per-preset generation decisions. Treat as a value object.""" |
| 35 | + |
| 36 | + preset_id: str |
| 37 | + base_template: str |
| 38 | + regenerate_main: bool |
| 39 | + main_py_relpath: str |
| 40 | + db_config_relpath: str |
| 41 | + auth_config_relpath: str |
| 42 | + # Hint shown when ``regenerate_main`` is False and the user picked a |
| 43 | + # feature whose dynamic main.py overlay won't run. Empty string means |
| 44 | + # "no special note for this preset". |
| 45 | + manual_wiring_note: str = "" |
| 46 | + extra_warning_targets: Tuple[str, ...] = field(default_factory=tuple) |
| 47 | + |
| 48 | + |
| 49 | +_PRESET_PROFILES: Dict[str, PresetProfile] = { |
| 50 | + "minimal": PresetProfile( |
| 51 | + preset_id="minimal", |
| 52 | + base_template="fastapi-empty", |
| 53 | + regenerate_main=True, |
| 54 | + main_py_relpath="src/main.py", |
| 55 | + db_config_relpath="src/config/database.py", |
| 56 | + auth_config_relpath="src/config/auth.py", |
| 57 | + ), |
| 58 | + "single-module": PresetProfile( |
| 59 | + preset_id="single-module", |
| 60 | + base_template="fastapi-single-module", |
| 61 | + regenerate_main=True, |
| 62 | + main_py_relpath="src/main.py", |
| 63 | + db_config_relpath="src/config/database.py", |
| 64 | + auth_config_relpath="src/config/auth.py", |
| 65 | + ), |
| 66 | + "classic-layered": PresetProfile( |
| 67 | + preset_id="classic-layered", |
| 68 | + base_template="fastapi-default", |
| 69 | + regenerate_main=False, |
| 70 | + main_py_relpath="src/main.py", |
| 71 | + db_config_relpath="src/core/database.py", |
| 72 | + auth_config_relpath="src/core/auth.py", |
| 73 | + # CORS is intentionally NOT in this list: fastapi-default's shipped |
| 74 | + # main.py already imports CORSMiddleware and adds it conditionally |
| 75 | + # on settings.all_cors_origins, so the user only has to populate |
| 76 | + # BACKEND_CORS_ORIGINS in .env — no code edits needed. |
| 77 | + manual_wiring_note=( |
| 78 | + "fastapi-default's shipped src/main.py is preserved. The " |
| 79 | + "selections below need manual wiring there (CORS is already " |
| 80 | + "wired — set BACKEND_CORS_ORIGINS in .env to activate it)." |
| 81 | + ), |
| 82 | + extra_warning_targets=("Rate-Limiting", "Prometheus"), |
| 83 | + ), |
| 84 | + "domain-starter": PresetProfile( |
| 85 | + preset_id="domain-starter", |
| 86 | + base_template="fastapi-domain-starter", |
| 87 | + regenerate_main=False, |
| 88 | + main_py_relpath="src/app/main.py", |
| 89 | + db_config_relpath="src/app/core/database.py", |
| 90 | + auth_config_relpath="src/app/core/auth.py", |
| 91 | + manual_wiring_note=( |
| 92 | + "fastapi-domain-starter's shipped src/app/main.py is preserved. " |
| 93 | + "The selections below need manual wiring there (CORS is already " |
| 94 | + "wired — set BACKEND_CORS_ORIGINS in .env to activate it)." |
| 95 | + ), |
| 96 | + extra_warning_targets=("Rate-Limiting", "Prometheus"), |
| 97 | + ), |
| 98 | +} |
| 99 | + |
| 100 | + |
| 101 | +class PresetLayoutStrategist: |
| 102 | + """Single source of truth for preset → generation-layout decisions.""" |
| 103 | + |
| 104 | + def __init__(self, preset_id: str | None) -> None: |
| 105 | + # Empty / None / unknown ids fall back to ``minimal`` so older callers |
| 106 | + # that pre-date the architecture-preset prompt keep working. |
| 107 | + canonical = (preset_id or _FALLBACK_PRESET_ID).strip() |
| 108 | + self.profile: PresetProfile = _PRESET_PROFILES.get( |
| 109 | + canonical, _PRESET_PROFILES[_FALLBACK_PRESET_ID] |
| 110 | + ) |
| 111 | + |
| 112 | + @classmethod |
| 113 | + def supported_presets(cls) -> List[str]: |
| 114 | + """Return the ordered list of preset ids the strategist understands.""" |
| 115 | + return list(_PRESET_PROFILES.keys()) |
| 116 | + |
| 117 | + @property |
| 118 | + def preset_id(self) -> str: |
| 119 | + return self.profile.preset_id |
| 120 | + |
| 121 | + @property |
| 122 | + def base_template(self) -> str: |
| 123 | + return self.profile.base_template |
| 124 | + |
| 125 | + @property |
| 126 | + def should_regenerate_main(self) -> bool: |
| 127 | + return self.profile.regenerate_main |
| 128 | + |
| 129 | + def main_py_target(self, project_dir: str) -> Path: |
| 130 | + """Absolute path where the dynamic main.py overlay should land.""" |
| 131 | + return Path(project_dir) / self.profile.main_py_relpath |
| 132 | + |
| 133 | + @property |
| 134 | + def app_module(self) -> str: |
| 135 | + """Return the ``module:attr`` string uvicorn / Docker should target. |
| 136 | +
|
| 137 | + Derived from ``main_py_relpath`` so docker generation, runserver, |
| 138 | + and any future container-orchestration code all agree on the |
| 139 | + entrypoint a given preset produces. |
| 140 | + """ |
| 141 | + # Strip the trailing ``.py`` and convert path separators to dots. |
| 142 | + relpath = self.profile.main_py_relpath |
| 143 | + if relpath.endswith(".py"): |
| 144 | + relpath = relpath[: -len(".py")] |
| 145 | + module_part = relpath.replace("/", ".").replace("\\", ".") |
| 146 | + return f"{module_part}:app" |
| 147 | + |
| 148 | + def db_config_target(self, project_dir: str) -> Path: |
| 149 | + """Absolute path for the generated database config module.""" |
| 150 | + return Path(project_dir) / self.profile.db_config_relpath |
| 151 | + |
| 152 | + def auth_config_target(self, project_dir: str) -> Path: |
| 153 | + """Absolute path for the generated authentication config module.""" |
| 154 | + return Path(project_dir) / self.profile.auth_config_relpath |
| 155 | + |
| 156 | + def compatibility_warnings(self, config: Dict[str, Any]) -> List[str]: |
| 157 | + """Return user-facing warnings for unsupported preset/feature mixes. |
| 158 | +
|
| 159 | + The dynamic ``main.py`` overlay (CORS middleware wiring, Prometheus |
| 160 | + instrumentation, rate-limit hookup) only runs for presets that |
| 161 | + regenerate ``main.py``. For the other presets we keep the |
| 162 | + template-shipped ``main.py`` intact and surface a single warning |
| 163 | + listing the affected features so users know to wire them up |
| 164 | + themselves rather than assuming the package install was enough. |
| 165 | + """ |
| 166 | + if self.profile.regenerate_main: |
| 167 | + return [] |
| 168 | + |
| 169 | + affected = self._affected_overlay_targets(config) |
| 170 | + if not affected: |
| 171 | + return [] |
| 172 | + |
| 173 | + warnings: List[str] = [] |
| 174 | + if self.profile.manual_wiring_note: |
| 175 | + warnings.append(self.profile.manual_wiring_note) |
| 176 | + warnings.append( |
| 177 | + "Affected selections (packages installed, but no dynamic main.py " |
| 178 | + "edits applied for the '" |
| 179 | + + self.profile.preset_id |
| 180 | + + "' preset): " |
| 181 | + + ", ".join(affected) |
| 182 | + ) |
| 183 | + return warnings |
| 184 | + |
| 185 | + def _affected_overlay_targets(self, config: Dict[str, Any]) -> List[str]: |
| 186 | + """Detect which of the user's selections rely on main.py overlay.""" |
| 187 | + triggered: List[str] = [] |
| 188 | + utilities = set(config.get("utilities") or []) |
| 189 | + |
| 190 | + for target in self.profile.extra_warning_targets: |
| 191 | + if target in {"CORS", "Rate-Limiting"}: |
| 192 | + if target in utilities: |
| 193 | + triggered.append(target) |
| 194 | + elif target == "Prometheus": |
| 195 | + if config.get("monitoring") == "Prometheus": |
| 196 | + triggered.append(target) |
| 197 | + return triggered |
| 198 | + |
| 199 | + |
| 200 | +__all__ = [ |
| 201 | + "PresetLayoutStrategist", |
| 202 | + "PresetProfile", |
| 203 | +] |
0 commit comments