cliver-playbook-app-basic 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. cliver_playbook/app/basic/__init__.py +12 -0
  2. cliver_playbook/app/basic/__main__.py +33 -0
  3. cliver_playbook/app/basic/alembic/__init__.py +57 -0
  4. cliver_playbook/app/basic/alembic/env.py +91 -0
  5. cliver_playbook/app/basic/alembic/script.py.mako +26 -0
  6. cliver_playbook/app/basic/alembic/versions/0001_basic_items.py +54 -0
  7. cliver_playbook/app/basic/alembic/versions/0002_app_settings.py +47 -0
  8. cliver_playbook/app/basic/api/__init__.py +0 -0
  9. cliver_playbook/app/basic/api/items.py +58 -0
  10. cliver_playbook/app/basic/api/meta.py +27 -0
  11. cliver_playbook/app/basic/api/routes.py +20 -0
  12. cliver_playbook/app/basic/app.py +48 -0
  13. cliver_playbook/app/basic/config_yaml.py +220 -0
  14. cliver_playbook/app/basic/db/__init__.py +0 -0
  15. cliver_playbook/app/basic/db/base.py +7 -0
  16. cliver_playbook/app/basic/db/session.py +31 -0
  17. cliver_playbook/app/basic/models/__init__.py +0 -0
  18. cliver_playbook/app/basic/models/entities.py +83 -0
  19. cliver_playbook/app/basic/runtime.py +160 -0
  20. cliver_playbook/app/basic/runtime_settings.py +557 -0
  21. cliver_playbook/app/basic/schemas/__init__.py +0 -0
  22. cliver_playbook/app/basic/schemas/item.py +31 -0
  23. cliver_playbook/app/basic/services/__init__.py +0 -0
  24. cliver_playbook/app/basic/services/items.py +50 -0
  25. cliver_playbook/app/basic/settings.py +162 -0
  26. cliver_playbook_app_basic-0.1.0.dist-info/METADATA +79 -0
  27. cliver_playbook_app_basic-0.1.0.dist-info/RECORD +29 -0
  28. cliver_playbook_app_basic-0.1.0.dist-info/WHEEL +4 -0
  29. cliver_playbook_app_basic-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,220 @@
1
+ """Layered configuration: the YAML + Jinja2 tier underneath env and .env.
2
+
3
+ Precedence (highest first), assembled by ``Settings.settings_customise_sources``
4
+ in settings.py:
5
+
6
+ constructor kwargs > environment variables > .env > app.yaml > field defaults
7
+
8
+ This module owns the bottom-most tier — an optional ``app.yaml`` at the
9
+ application root, rendered as a Jinja2 template before YAML parsing — plus the
10
+ discovery of the application root and its .env. The checked-in file describes
11
+ *structure and non-secret defaults*; anything sensitive stays in the
12
+ environment/.env layer and never in the repository.
13
+
14
+ Application-root discovery: an installed package has no fixed relationship to
15
+ the project consuming it, so nothing here anchors to ``__file__`` (that would
16
+ point into site-packages). The root is the nearest ancestor of the current
17
+ working directory — the CWD itself included — that contains ``app.yaml`` or
18
+ ``.env``; conventionally the two live side by side. Discovery happens per
19
+ Settings instantiation, so a process may be started from anywhere below the
20
+ project root. ``$CLIVER_CONFIG_FILE`` remains a hard override for unusual
21
+ layouts (see ``resolve_config_path``).
22
+
23
+ Why Jinja2 in front of YAML:
24
+
25
+ - values can be composed from environment variables at load time
26
+ (``{{ env("SOME_HOST", "127.0.0.1") }}``) instead of forcing every
27
+ combination into one flat variable;
28
+ - required inputs fail fast at startup with the variable named, instead of
29
+ surfacing later as a confusing runtime error;
30
+ - the helper surface (``JINJA_GLOBALS``) is a deliberate extension point —
31
+ a project can add its own pure functions without touching loading logic.
32
+
33
+ Keys inside the YAML are the *bare Settings field names* (``database_url``),
34
+ NOT the ``CLIVER_``-prefixed env names — the file feeds the Settings model
35
+ directly, mirroring the Spring Boot application.yaml convention.
36
+
37
+ The rendering environment is sandboxed (``SandboxedEnvironment``) with
38
+ ``StrictUndefined`` (a typo'd template variable raises instead of silently
39
+ rendering empty). Literal Jinja syntax inside YAML values must be wrapped in
40
+ ``{% raw %}...{% endraw %}``.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import os
46
+ from collections.abc import Mapping
47
+ from pathlib import Path
48
+ from typing import Any
49
+
50
+ import yaml
51
+ from dotenv import dotenv_values
52
+ from jinja2 import StrictUndefined, TemplateError
53
+ from jinja2.sandbox import SandboxedEnvironment
54
+ from pydantic_settings import YamlConfigSettingsSource
55
+
56
+ DEFAULT_CONFIG_FILENAME = "app.yaml"
57
+ ENV_FILENAME = ".env"
58
+ CONFIG_FILE_ENV_VAR = "CLIVER_CONFIG_FILE"
59
+
60
+
61
+ class ConfigError(RuntimeError):
62
+ """The configuration layer cannot produce a usable Settings object.
63
+
64
+ Deliberately loud and specific: a broken app.yaml takes down uvicorn,
65
+ alembic and pytest collection alike, so every message names the file and
66
+ the underlying cause — a bare ValidationError deep inside startup tells
67
+ an operator nothing about which layer failed.
68
+ """
69
+
70
+
71
+ def resolve_project_root() -> Path | None:
72
+ """Locate the application root by walking up from the current directory.
73
+
74
+ The root is the nearest ancestor (CWD included) containing ``app.yaml``
75
+ or ``.env``. Returns None when neither exists anywhere up the tree — the
76
+ configuration then falls back to the environment layer and field
77
+ defaults alone, a legitimate setup (e.g. a container configured purely
78
+ through env vars).
79
+ """
80
+ cwd = Path.cwd()
81
+ for directory in (cwd, *cwd.parents):
82
+ if (directory / DEFAULT_CONFIG_FILENAME).is_file():
83
+ return directory
84
+ if (directory / ENV_FILENAME).is_file():
85
+ return directory
86
+ return None
87
+
88
+
89
+ def resolve_config_path() -> Path | None:
90
+ """Locate the YAML config file, or None when there legitimately is none.
91
+
92
+ 1. ``$CLIVER_CONFIG_FILE`` — explicit override (tests, unusual layouts).
93
+ Pointing it at a missing file is a hard error: an explicit override
94
+ that silently does nothing is a misconfiguration, not a fallback.
95
+ 2. ``<application root>/app.yaml`` — the conventional checked-in
96
+ location. Absent is fine: the YAML layer is optional and everything
97
+ falls back to env/.env/field defaults.
98
+ """
99
+ override = os.environ.get(CONFIG_FILE_ENV_VAR, "").strip()
100
+ if override:
101
+ path = Path(override)
102
+ if not path.is_file():
103
+ raise ConfigError(
104
+ f"{CONFIG_FILE_ENV_VAR} points at {path}, but that file does not exist."
105
+ )
106
+ return path
107
+ root = resolve_project_root()
108
+ if root is None:
109
+ return None
110
+ default = root / DEFAULT_CONFIG_FILENAME
111
+ return default if default.is_file() else None
112
+
113
+
114
+ def resolve_env_file() -> Path | None:
115
+ """Locate the .env file: ``<application root>/.env`` when it exists.
116
+
117
+ Used by Settings (to point the dotenv layer at it) and by the Jinja
118
+ env() helper (as its snapshot fallback) — one resolution rule, so both
119
+ layers always read the same file.
120
+ """
121
+ root = resolve_project_root()
122
+ if root is None:
123
+ return None
124
+ candidate = root / ENV_FILENAME
125
+ return candidate if candidate.is_file() else None
126
+
127
+
128
+ def _make_env_helper(dotenv: Mapping[str, str | None], source_file: Path, env_file: Path | None):
129
+ """Build the ``env(name, default=None)`` helper exposed to templates.
130
+
131
+ Resolution order mirrors the layering above: process environment first,
132
+ then the resolved .env snapshot, then the template-supplied default.
133
+ Missing without a default raises ConfigError naming the variable — the
134
+ fail-fast path for required inputs that have no sane universal default.
135
+ """
136
+
137
+ def env(name: str, default: Any = None) -> Any:
138
+ value = os.environ.get(name)
139
+ if value is None:
140
+ value = dotenv.get(name)
141
+ if value is None:
142
+ if default is None:
143
+ raise ConfigError(
144
+ f"{source_file}: env({name!r}) has no value - set {name} in the "
145
+ f"environment or in {env_file or 'the project .env'}, "
146
+ "or pass a default in the template."
147
+ )
148
+ return default
149
+ return value
150
+
151
+ return env
152
+
153
+
154
+ # Extension point: everything in this dict becomes a Jinja global available
155
+ # to app.yaml. Keep entries deterministic and side-effect free — rendering
156
+ # happens once per Settings instantiation, at startup.
157
+ JINJA_GLOBALS: dict[str, Any] = {}
158
+
159
+
160
+ class JinjaYamlSource(YamlConfigSettingsSource):
161
+ """YAML settings source that renders the file as a Jinja2 template first.
162
+
163
+ Overrides exactly one seam — ``_read_file(path) -> dict`` — which the
164
+ parent calls for each existing configured file; everything else (file
165
+ discovery, merging, feeding values into the pydantic core) remains stock
166
+ pydantic-settings behavior. Missing files are skipped by the parent
167
+ before ``_read_file`` is ever called, so ``yaml_file=None`` (or a path
168
+ that does not exist at the default location) simply yields no values.
169
+
170
+ ``_read_file`` is a private (underscore) API, which is why pyproject pins
171
+ ``pydantic-settings>=2.16,<3`` and why tests/test_config.py exercises this
172
+ class end to end: if an upgrade ever moves the seam, tests fail loudly
173
+ here instead of the YAML layer silently deactivating.
174
+ """
175
+
176
+ def __init__(self, settings_cls: type, yaml_file: Path | None = None, **kwargs: Any) -> None:
177
+ # Resolve the .env and snapshot its values once per instantiation so
178
+ # the Jinja env() helper sees the same file the dotenv settings source
179
+ # would (without depending on load order between sources). Both must
180
+ # happen before super().__init__, which reads the YAML file during
181
+ # construction. Empty snapshot when there is no .env — passing None to
182
+ # python-dotenv would instead trigger its own search, a second and
183
+ # subtly different discovery rule.
184
+ self._env_file = resolve_env_file()
185
+ self._dotenv_snapshot: Mapping[str, str | None] = (
186
+ dotenv_values(self._env_file) if self._env_file is not None else {}
187
+ )
188
+ super().__init__(settings_cls, yaml_file=yaml_file, **kwargs)
189
+
190
+ def _read_file(self, file_path: Path) -> dict[str, Any]:
191
+ path = Path(file_path)
192
+ try:
193
+ text = path.read_text(encoding="utf-8")
194
+ except OSError as exc:
195
+ raise ConfigError(f"Cannot read config file {path}: {exc}") from exc
196
+
197
+ environment = SandboxedEnvironment(undefined=StrictUndefined)
198
+ environment.globals.update(JINJA_GLOBALS)
199
+ environment.globals["env"] = _make_env_helper(self._dotenv_snapshot, path, self._env_file)
200
+
201
+ try:
202
+ rendered = environment.from_string(text).render()
203
+ except TemplateError as exc:
204
+ raise ConfigError(f"Jinja2 rendering of {path} failed: {exc}") from exc
205
+ # A ConfigError raised by the env() helper is NOT a TemplateError and
206
+ # propagates untouched — it already carries the file and variable.
207
+
208
+ try:
209
+ data = yaml.safe_load(rendered)
210
+ except yaml.YAMLError as exc:
211
+ raise ConfigError(f"YAML parse of {path} failed after Jinja2 rendering: {exc}") from exc
212
+
213
+ if data is None: # empty file, or comments only
214
+ return {}
215
+ if not isinstance(data, dict):
216
+ raise ConfigError(
217
+ f"{path}: top level must be a YAML mapping of Settings field names, "
218
+ f"got {type(data).__name__}."
219
+ )
220
+ return data
File without changes
@@ -0,0 +1,7 @@
1
+ """Declarative base shared by every ORM model and by Alembic autogenerate."""
2
+
3
+ from sqlalchemy.orm import DeclarativeBase
4
+
5
+
6
+ class Base(DeclarativeBase):
7
+ """All entities subclass this base. Alembic's `target_metadata` is `Base.metadata`."""
@@ -0,0 +1,31 @@
1
+ """Request-scoped database sessions.
2
+
3
+ The engine and session factory are created by ``runtime.configure`` — never
4
+ at import time — so importing this module in a process that runs no
5
+ application (a migration script, a CLI, a docs build) costs nothing.
6
+ """
7
+
8
+ from collections.abc import AsyncGenerator
9
+
10
+ from sqlalchemy.ext.asyncio import AsyncSession
11
+
12
+ from cliver_playbook.app.basic import runtime
13
+
14
+
15
+ async def get_db() -> AsyncGenerator[AsyncSession, None]:
16
+ """FastAPI dependency yielding a request-scoped session (closed on exit)."""
17
+ factory = runtime.session_factory()
18
+ async with factory() as session:
19
+ yield session
20
+
21
+
22
+ def open_session() -> AsyncSession:
23
+ """Open a session directly on the process runtime's engine.
24
+
25
+ ``get_db`` covers the request-scoped dependency case; code that owns its
26
+ own transaction boundaries across several round trips (multi-step auth
27
+ flows, background work, migrations helpers) opens sessions from here
28
+ instead. Both paths resolve the same engine ``runtime.configure`` built,
29
+ so a process never ends up with two connection pools.
30
+ """
31
+ return runtime.session_factory()()
File without changes
@@ -0,0 +1,83 @@
1
+ """ORM entities.
2
+
3
+ The scaffold ships one demo entity — `Item` — as the copy-me pattern for
4
+ regular CRUD: identity PK, sensible defaults, timezone-aware timestamps. Real
5
+ projects add their entities alongside and generate follow-up migrations.
6
+
7
+ `AppSetting` is the storage half of the runtime settings framework
8
+ (ADR-0021): one row per module-owned section, holding only the values an
9
+ administrator changed. It is not a demo — do not delete it when removing the
10
+ items slice.
11
+ """
12
+
13
+ from datetime import datetime
14
+ from typing import Any
15
+
16
+ from sqlalchemy import (
17
+ JSON,
18
+ BigInteger,
19
+ DateTime,
20
+ Identity,
21
+ Index,
22
+ Integer,
23
+ String,
24
+ Text,
25
+ func,
26
+ )
27
+ from sqlalchemy.dialects.postgresql import JSONB
28
+ from sqlalchemy.orm import Mapped, mapped_column
29
+
30
+ from cliver_playbook.app.basic.db.base import Base
31
+
32
+
33
+ class Item(Base):
34
+ """Demo CRUD entity — replace with real domain entities as the project grows."""
35
+
36
+ __tablename__ = "items"
37
+ __table_args__ = (Index("ix_items_created_at", "created_at"),)
38
+
39
+ id: Mapped[int] = mapped_column(
40
+ BigInteger, Identity(always=True), primary_key=True, autoincrement=True
41
+ )
42
+ name: Mapped[str] = mapped_column(String(200), nullable=False)
43
+ description: Mapped[str] = mapped_column(Text, nullable=False, default="", server_default="")
44
+ quantity: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default="0")
45
+ created_at: Mapped[datetime] = mapped_column(
46
+ DateTime(timezone=True), server_default=func.now(), nullable=False
47
+ )
48
+ updated_at: Mapped[datetime] = mapped_column(
49
+ DateTime(timezone=True),
50
+ server_default=func.now(),
51
+ onupdate=func.now(),
52
+ nullable=False,
53
+ )
54
+
55
+
56
+ class AppSetting(Base):
57
+ """Persisted runtime overrides for one module-owned settings section.
58
+
59
+ ``values`` is a flat JSON object of field name -> value; only fields the
60
+ administrator explicitly changed are present, so a later default change in
61
+ code still reaches untouched fields. Secrets are never stored here — the
62
+ settings API rejects them and the loader filters them out defensively.
63
+ """
64
+
65
+ __tablename__ = "app_settings"
66
+
67
+ # The section key registered by the owning package (e.g. "rag", "user").
68
+ section: Mapped[str] = mapped_column(String(64), primary_key=True)
69
+ # PostgreSQL JSONB in production; the SQLite variant keeps the RAG test
70
+ # suite (which creates this table from metadata) portable.
71
+ values: Mapped[dict[str, Any]] = mapped_column(
72
+ JSONB().with_variant(JSON, "sqlite"), nullable=False, default=dict
73
+ )
74
+ # The administrator who last wrote the row; nullable so deleting a user
75
+ # does not erase the settings history (there is no FK by design — the
76
+ # basic package cannot depend on the identity package).
77
+ updated_by: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
78
+ updated_at: Mapped[datetime] = mapped_column(
79
+ DateTime(timezone=True),
80
+ server_default=func.now(),
81
+ onupdate=func.now(),
82
+ nullable=False,
83
+ )
@@ -0,0 +1,160 @@
1
+ """Process-wide runtime state: settings binding and the database engine.
2
+
3
+ The design rules this module exists to enforce (ADR-0016):
4
+
5
+ - Importing a package has no side effects. Nothing here reads configuration
6
+ files, creates an engine, or builds an app at import time.
7
+ - ``configure(settings)`` binds the process exactly once, from a package's
8
+ ``create_app``. Afterwards every module-level ``settings`` proxy in the
9
+ process (``LazySettings`` below) and every database accessor
10
+ (``engine``/``session_factory``) answers from that single binding, so a
11
+ composed application cannot end up with two settings worlds or two
12
+ engines.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ from sqlalchemy.ext.asyncio import (
21
+ AsyncEngine,
22
+ AsyncSession,
23
+ async_sessionmaker,
24
+ create_async_engine,
25
+ )
26
+
27
+ if TYPE_CHECKING: # the bound instance may be any package's Settings subclass
28
+ from cliver_playbook.app.basic.settings import Settings
29
+
30
+
31
+ @dataclass
32
+ class _RuntimeState:
33
+ """State created exactly once by ``configure`` (see module docstring)."""
34
+
35
+ settings: Settings
36
+ # Pristine copy taken at configuration time. Runtime settings overrides
37
+ # mutate ``settings`` in place; "reset to defaults" restores fields from
38
+ # this snapshot without rebuilding the process or the engine (ADR-0021).
39
+ settings_baseline: Settings
40
+ engine: AsyncEngine
41
+ session_factory: async_sessionmaker[AsyncSession]
42
+
43
+
44
+ _state: _RuntimeState | None = None
45
+
46
+
47
+ def configure(settings: Settings) -> Settings:
48
+ """Bind the process settings instance and build the database engine.
49
+
50
+ First call wins. Calling again with the SAME instance is a no-op — a
51
+ package's ``create_app`` may delegate to another package's before adding
52
+ its own routers. Calling again with a DIFFERENT instance raises: silently
53
+ rebinding would leave earlier requests, engines and settings proxies
54
+ pointing at two different worlds.
55
+
56
+ Returns the bound instance for convenience.
57
+ """
58
+ global _state
59
+ if _state is not None:
60
+ if settings is not _state.settings:
61
+ raise RuntimeError(
62
+ "The runtime is already configured with a different Settings instance. "
63
+ "Configure exactly once per process — typically by calling create_app()."
64
+ )
65
+ return _state.settings
66
+
67
+ engine = create_async_engine(settings.db_url, future=True, pool_pre_ping=True)
68
+ _state = _RuntimeState(
69
+ settings=settings,
70
+ settings_baseline=settings.model_copy(deep=True),
71
+ engine=engine,
72
+ # expire_on_commit=False keeps attributes readable on instances after
73
+ # commit — the standard choice for request-scoped sessions handed out
74
+ # by FastAPI dependencies.
75
+ session_factory=async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False),
76
+ )
77
+ return settings
78
+
79
+
80
+ def is_configured() -> bool:
81
+ """True once ``configure`` has bound the process."""
82
+ return _state is not None
83
+
84
+
85
+ def configured_settings() -> Settings | None:
86
+ """The bound settings instance, or None before ``configure``."""
87
+ return _state.settings if _state is not None else None
88
+
89
+
90
+ def baseline_settings() -> Settings | None:
91
+ """The pristine settings snapshot taken by ``configure``, or None.
92
+
93
+ Runtime settings overrides are applied by mutating the bound instance;
94
+ this snapshot is what "reset" restores (ADR-0021).
95
+ """
96
+ return _state.settings_baseline if _state is not None else None
97
+
98
+
99
+ def engine() -> AsyncEngine:
100
+ """The process-wide async engine (asyncpg over ``settings.db_url``)."""
101
+ return _require_state().engine
102
+
103
+
104
+ def session_factory() -> async_sessionmaker[AsyncSession]:
105
+ """The process-wide async session factory bound to the runtime engine."""
106
+ return _require_state().session_factory
107
+
108
+
109
+ async def dispose() -> None:
110
+ """Dispose the engine's connection pool; a no-op before ``configure``.
111
+
112
+ Call on application shutdown. Tests call it between cases: asyncpg
113
+ connections are bound to the event loop that created them, and each test
114
+ runs on a fresh one.
115
+ """
116
+ if _state is not None:
117
+ await _state.engine.dispose()
118
+
119
+
120
+ def _require_state() -> _RuntimeState:
121
+ if _state is None:
122
+ raise RuntimeError(
123
+ "The runtime is not configured: call create_app() (or configure(settings)) "
124
+ "before using the database engine or session factory."
125
+ )
126
+ return _state
127
+
128
+
129
+ class LazySettings:
130
+ """Deferred, process-aware settings accessor for one package's Settings class.
131
+
132
+ Attribute access resolves to the process-bound instance when one exists,
133
+ else to an instance of ``settings_cls`` built on first use and cached for
134
+ the process. Construction is deferred so that importing a package's
135
+ ``settings`` module reads no configuration files — the import-safety rule
136
+ from ADR-0016.
137
+ """
138
+
139
+ def __init__(self, settings_cls: type) -> None:
140
+ self._settings_cls = settings_cls
141
+ self._fallback: Any = None
142
+
143
+ def resolve(self) -> Any:
144
+ """The effective settings instance (bound instance, else fallback)."""
145
+ bound = configured_settings()
146
+ if bound is not None:
147
+ return bound
148
+ if self._fallback is None:
149
+ self._fallback = self._settings_cls()
150
+ return self._fallback
151
+
152
+ def __getattr__(self, name: str) -> Any:
153
+ # Reached only for attributes missing on the proxy itself, so the
154
+ # proxy's own internals never recurse through here.
155
+ return getattr(self.resolve(), name)
156
+
157
+
158
+ def lazy_settings(settings_cls: type) -> LazySettings:
159
+ """Create a ``LazySettings`` proxy bound to ``settings_cls``."""
160
+ return LazySettings(settings_cls)