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,12 @@
1
+ """basic: the foundations package — settings, runtime, and a demo API slice.
2
+
3
+ Public surface only; every name below is a plain import (no settings reads,
4
+ no engine, no app assembly — importing a package must never have side
5
+ effects; see ADR-0015 and ADR-0016).
6
+ """
7
+
8
+ from cliver_playbook.app.basic.api.routes import ROUTERS
9
+ from cliver_playbook.app.basic.app import create_app
10
+ from cliver_playbook.app.basic.settings import Settings, get_settings, settings
11
+
12
+ __all__ = ["ROUTERS", "Settings", "create_app", "get_settings", "settings"]
@@ -0,0 +1,33 @@
1
+ """Standalone entry point: ``python -m cliver_playbook.app.basic``.
2
+
3
+ Runs the package's self-application with uvicorn. The factory string (rather
4
+ than an app instance) keeps ``--reload`` working, which requires uvicorn to
5
+ re-import the application in a subprocess — import safety is what makes that
6
+ cheap.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+
13
+ import uvicorn
14
+
15
+ _FACTORY = "cliver_playbook.app.basic.app:create_app"
16
+
17
+
18
+ def main() -> None:
19
+ parser = argparse.ArgumentParser(description="Run the basic package's application.")
20
+ parser.add_argument("--host", default="127.0.0.1", help="Bind address (default: 127.0.0.1).")
21
+ parser.add_argument("--port", type=int, default=8000, help="Bind port (default: 8000).")
22
+ parser.add_argument(
23
+ "--reload",
24
+ action="store_true",
25
+ help="Restart on source changes (development only).",
26
+ )
27
+ args = parser.parse_args()
28
+
29
+ uvicorn.run(_FACTORY, factory=True, host=args.host, port=args.port, reload=args.reload)
30
+
31
+
32
+ if __name__ == "__main__":
33
+ main()
@@ -0,0 +1,57 @@
1
+ """Programmatic migration entry points for the ``basic`` package.
2
+
3
+ Every package owns its migration chain and exposes the same two functions, so
4
+ a project initializes its whole database by calling each package's
5
+ ``run_migrations_online`` in dependency order (basic first, then the packages
6
+ built on it) — no alembic.ini paths, no working-directory assumptions.
7
+
8
+ The interactive CLI remains available for development: run ``alembic`` from
9
+ the package directory, which picks up the bundled alembic.ini. Both routes
10
+ share ``alembic/env.py`` and therefore the same version table.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from pathlib import Path
16
+
17
+ from alembic import command
18
+ from alembic.config import Config
19
+
20
+ # env.py lives next to this module inside the installed package, so the
21
+ # script location is correct regardless of where the package is imported from.
22
+ _SCRIPT_LOCATION = Path(__file__).resolve().parent
23
+
24
+
25
+ def make_config(database_url: str | None = None) -> Config:
26
+ """Build an Alembic config for this package's chain.
27
+
28
+ No ini file is involved: the script location is pinned to the installed
29
+ package and the URL is passed through explicitly — omitted entirely when
30
+ no URL is given, letting env.py fall back to application settings.
31
+ Logging configuration is likewise untouched: in-process migrations must
32
+ not reconfigure the host application's loggers.
33
+ """
34
+ config = Config()
35
+ config.set_main_option("script_location", str(_SCRIPT_LOCATION))
36
+ if database_url:
37
+ config.set_main_option("sqlalchemy.url", database_url)
38
+ return config
39
+
40
+
41
+ def run_migrations_online(database_url: str | None = None) -> None:
42
+ """Upgrade this package's chain to head against a live database.
43
+
44
+ Args:
45
+ database_url: sync (psycopg) DSN to migrate. When omitted, the
46
+ process runtime's current settings decide (see alembic/env.py).
47
+ """
48
+ command.upgrade(make_config(database_url), "head")
49
+
50
+
51
+ def run_migrations_offline(database_url: str | None = None) -> None:
52
+ """Print the equivalent upgrade SQL to stdout without connecting.
53
+
54
+ Offline mode still needs a URL (or settings) to render SQL for the right
55
+ dialect; nothing is executed against a database.
56
+ """
57
+ command.upgrade(make_config(database_url), "head", sql=True)
@@ -0,0 +1,91 @@
1
+ """Alembic migration environment for the ``basic`` package.
2
+
3
+ Runs on the *sync* psycopg driver (see ``Settings.sync_db_url``) while the
4
+ application itself uses asyncpg. The two drivers never share an engine.
5
+
6
+ This environment serves exactly one chain: the revisions in ``versions/``
7
+ owned by this package, tracked in its own version table (``VERSION_TABLE``
8
+ below). Sibling packages own their own chains and tables, so several packages
9
+ can migrate the same database independently (ADR-0015). The chain is applied
10
+ programmatically through ``cliver_playbook.app.basic.alembic`` — the entry
11
+ point a new project calls at initialization — or interactively via the
12
+ bundled alembic.ini.
13
+
14
+ URL resolution: an explicit ``sqlalchemy.url`` already set on the Alembic
15
+ config (the programmatic entry points pass the deploy/test URL that way)
16
+ wins; otherwise the URL derives from the runtime settings — the instance
17
+ bound by ``runtime.configure`` when the application is running in-process,
18
+ else this package's own ``Settings()``. Either path goes through the
19
+ ``settings`` proxy, so no config file is read while merely importing env.py.
20
+
21
+ Autogenerate support: ``target_metadata`` points at the package's ORM
22
+ declarative base so ``alembic revision --autogenerate`` diffs the real models.
23
+ """
24
+
25
+ from logging.config import fileConfig
26
+
27
+ from alembic import context
28
+ from sqlalchemy import engine_from_config, pool
29
+
30
+ from cliver_playbook.app.basic.db.base import Base
31
+ from cliver_playbook.app.basic.models import entities # noqa: F401 — imported for its table definitions
32
+ from cliver_playbook.app.basic.settings import settings
33
+
34
+ # Version table owned by THIS package's chain — never the default
35
+ # "alembic_version": sibling packages migrate the same database independently.
36
+ VERSION_TABLE = "alembic_version_basic"
37
+
38
+ config = context.config
39
+
40
+ if config.config_file_name is not None:
41
+ # disable_existing_loggers defaults to True, which silently disables every
42
+ # logger that already exists when this env runs — fatal when migrations
43
+ # run in-process (tests, scripted deploys) after the application's
44
+ # loggers have been created. False keeps them emitting; alembic.ini
45
+ # still owns the loggers it explicitly configures.
46
+ fileConfig(config.config_file_name, disable_existing_loggers=False)
47
+
48
+
49
+ def _database_url() -> str:
50
+ """Explicit config override, else the current settings' sync DSN."""
51
+ url = config.get_main_option("sqlalchemy.url")
52
+ return url if url else settings.sync_db_url
53
+
54
+
55
+ def run_migrations_offline() -> None:
56
+ """Emit SQL to stdout instead of touching a database."""
57
+ context.configure(
58
+ url=_database_url(),
59
+ target_metadata=Base.metadata,
60
+ literal_binds=True,
61
+ dialect_opts={"paramstyle": "named"},
62
+ version_table=VERSION_TABLE,
63
+ )
64
+
65
+ with context.begin_transaction():
66
+ context.run_migrations()
67
+
68
+
69
+ def run_migrations_online() -> None:
70
+ """Run migrations against a live database connection."""
71
+ connectable = engine_from_config(
72
+ {"sqlalchemy.url": _database_url()},
73
+ prefix="sqlalchemy.",
74
+ poolclass=pool.NullPool,
75
+ )
76
+
77
+ with connectable.connect() as connection:
78
+ context.configure(
79
+ connection=connection,
80
+ target_metadata=Base.metadata,
81
+ version_table=VERSION_TABLE,
82
+ )
83
+
84
+ with context.begin_transaction():
85
+ context.run_migrations()
86
+
87
+
88
+ if context.is_offline_mode():
89
+ run_migrations_offline()
90
+ else:
91
+ run_migrations_online()
@@ -0,0 +1,26 @@
1
+ """${message}
2
+
3
+ Revision ID: ${up_revision}
4
+ Revises: ${down_revision | comma,n}
5
+ Create Date: ${create_date}
6
+ """
7
+ from collections.abc import Sequence
8
+
9
+ import sqlalchemy as sa
10
+
11
+ from alembic import op
12
+ ${imports if imports else ""}
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = ${repr(up_revision)}
16
+ down_revision: str | Sequence[str] | None = ${repr(down_revision)}
17
+ branch_labels: str | Sequence[str] | None = ${repr(branch_labels)}
18
+ depends_on: str | Sequence[str] | None = ${repr(depends_on)}
19
+
20
+
21
+ def upgrade() -> None:
22
+ ${upgrades if upgrades else "pass"}
23
+
24
+
25
+ def downgrade() -> None:
26
+ ${downgrades if downgrades else "pass"}
@@ -0,0 +1,54 @@
1
+ """Basic package base schema: the demo `items` table.
2
+
3
+ This revision is the root of THIS package's migration chain. The chain lives
4
+ entirely inside cliver-playbook-app-basic: its head is tracked in the
5
+ ``alembic_version_basic`` table, and packages built on top of basic own their
6
+ own chains and version tables (ADR-0015) — no cross-package down_revision
7
+ links, so packages are applied in dependency order and evolve independently.
8
+
9
+ The items table backs a runnable example of the full CRUD slice. A project
10
+ that does not need item management deletes it together with the rest of the
11
+ demo (see the package README).
12
+
13
+ Revision ID: 0001_basic_items
14
+ Revises: -
15
+ Create Date: 2026-10-15
16
+ """
17
+
18
+ from collections.abc import Sequence
19
+
20
+ import sqlalchemy as sa
21
+ from alembic import op
22
+
23
+ revision: str = "0001_basic_items"
24
+ down_revision: str | Sequence[str] | None = None
25
+ branch_labels: str | Sequence[str] | None = None
26
+ depends_on: str | Sequence[str] | None = None
27
+
28
+
29
+ def upgrade() -> None:
30
+ op.create_table(
31
+ "items",
32
+ sa.Column("id", sa.BigInteger(), sa.Identity(always=True), primary_key=True),
33
+ sa.Column("name", sa.String(length=200), nullable=False),
34
+ sa.Column("description", sa.Text(), nullable=False, server_default=""),
35
+ sa.Column("quantity", sa.Integer(), nullable=False, server_default="0"),
36
+ sa.Column(
37
+ "created_at",
38
+ sa.DateTime(timezone=True),
39
+ nullable=False,
40
+ server_default=sa.text("now()"),
41
+ ),
42
+ sa.Column(
43
+ "updated_at",
44
+ sa.DateTime(timezone=True),
45
+ nullable=False,
46
+ server_default=sa.text("now()"),
47
+ ),
48
+ )
49
+ op.create_index("ix_items_created_at", "items", ["created_at"])
50
+
51
+
52
+ def downgrade() -> None:
53
+ op.drop_index("ix_items_created_at", table_name="items")
54
+ op.drop_table("items")
@@ -0,0 +1,47 @@
1
+ """Runtime settings overrides: one row per module-owned section.
2
+
3
+ See ADR-0021. The table stores only values an administrator changed at
4
+ runtime; environment and ``.env`` entries still win over them, and secrets are
5
+ never written here.
6
+
7
+ Revision ID: 0002_app_settings
8
+ Revises: 0001_basic_items
9
+ Create Date: 2026-10-19
10
+ """
11
+
12
+ from collections.abc import Sequence
13
+
14
+ import sqlalchemy as sa
15
+ from alembic import op
16
+ from sqlalchemy.dialects.postgresql import JSONB
17
+
18
+ revision: str = "0002_app_settings"
19
+ down_revision: str | Sequence[str] | None = "0001_basic_items"
20
+ branch_labels: str | Sequence[str] | None = None
21
+ depends_on: str | Sequence[str] | None = None
22
+
23
+
24
+ def upgrade() -> None:
25
+ op.create_table(
26
+ "app_settings",
27
+ sa.Column("section", sa.String(length=64), primary_key=True),
28
+ sa.Column(
29
+ "values",
30
+ JSONB(),
31
+ nullable=False,
32
+ server_default=sa.text("'{}'::jsonb"),
33
+ ),
34
+ # No FK to users: this package cannot depend on the identity package.
35
+ # The id is informational (who last changed the section).
36
+ sa.Column("updated_by", sa.BigInteger(), nullable=True),
37
+ sa.Column(
38
+ "updated_at",
39
+ sa.DateTime(timezone=True),
40
+ nullable=False,
41
+ server_default=sa.text("now()"),
42
+ ),
43
+ )
44
+
45
+
46
+ def downgrade() -> None:
47
+ op.drop_table("app_settings")
File without changes
@@ -0,0 +1,58 @@
1
+ """Item CRUD endpoints — the reference pattern for resource routers.
2
+
3
+ Layout convention: path params resolve the entity (404 when missing), request
4
+ bodies are validated Pydantic models, all persistence goes through the service
5
+ layer, and responses use the read schema.
6
+ """
7
+
8
+ from fastapi import APIRouter, Depends, HTTPException, Query, status
9
+ from sqlalchemy.ext.asyncio import AsyncSession
10
+
11
+ from cliver_playbook.app.basic.db.session import get_db
12
+ from cliver_playbook.app.basic.schemas.item import ItemCreate, ItemRead, ItemUpdate
13
+ from cliver_playbook.app.basic.services import items as items_service
14
+
15
+ router = APIRouter(prefix="/api/v1/items", tags=["items"])
16
+
17
+
18
+ @router.get("", response_model=list[ItemRead])
19
+ async def list_items(
20
+ limit: int = Query(default=50, ge=1, le=200),
21
+ offset: int = Query(default=0, ge=0),
22
+ db: AsyncSession = Depends(get_db),
23
+ ) -> list[ItemRead]:
24
+ items, _total = await items_service.list_items(db, limit=limit, offset=offset)
25
+ return [ItemRead.model_validate(i) for i in items]
26
+
27
+
28
+ @router.post("", response_model=ItemRead, status_code=status.HTTP_201_CREATED)
29
+ async def create_item(payload: ItemCreate, db: AsyncSession = Depends(get_db)) -> ItemRead:
30
+ item = await items_service.create_item(db, payload)
31
+ return ItemRead.model_validate(item)
32
+
33
+
34
+ @router.get("/{item_id}", response_model=ItemRead)
35
+ async def get_item(item_id: int, db: AsyncSession = Depends(get_db)) -> ItemRead:
36
+ item = await items_service.get_item(db, item_id)
37
+ if item is None:
38
+ raise HTTPException(status_code=404, detail="Item not found")
39
+ return ItemRead.model_validate(item)
40
+
41
+
42
+ @router.patch("/{item_id}", response_model=ItemRead)
43
+ async def update_item(
44
+ item_id: int, payload: ItemUpdate, db: AsyncSession = Depends(get_db)
45
+ ) -> ItemRead:
46
+ item = await items_service.get_item(db, item_id)
47
+ if item is None:
48
+ raise HTTPException(status_code=404, detail="Item not found")
49
+ updated = await items_service.update_item(db, item, payload)
50
+ return ItemRead.model_validate(updated)
51
+
52
+
53
+ @router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
54
+ async def delete_item(item_id: int, db: AsyncSession = Depends(get_db)) -> None:
55
+ item = await items_service.get_item(db, item_id)
56
+ if item is None:
57
+ raise HTTPException(status_code=404, detail="Item not found")
58
+ await items_service.delete_item(db, item)
@@ -0,0 +1,27 @@
1
+ """Meta endpoints: liveness with a real database ping, and version info."""
2
+
3
+ from fastapi import APIRouter, Depends
4
+ from sqlalchemy import text
5
+ from sqlalchemy.ext.asyncio import AsyncSession
6
+
7
+ from cliver_playbook.app.basic.db.session import get_db
8
+ from cliver_playbook.app.basic.settings import settings
9
+
10
+ # Static prefix: the API version is part of the URL surface, so it lives in
11
+ # the route table (greppable), not in settings — a router is built at import
12
+ # time and must not depend on which Settings instance happens to load first
13
+ # (see the note in settings.py).
14
+ router = APIRouter(prefix="/api/v1", tags=["meta"])
15
+
16
+
17
+ @router.get("/health")
18
+ async def health(db: AsyncSession = Depends(get_db)) -> dict:
19
+ """Liveness probe — verifies the process AND a real database round-trip."""
20
+ await db.execute(text("SELECT 1"))
21
+ return {"status": "ok"}
22
+
23
+
24
+ @router.get("/version")
25
+ async def version() -> dict:
26
+ """Report the application name (resolved per request through the settings proxy)."""
27
+ return {"app": settings.app_name, "api": "v1"}
@@ -0,0 +1,20 @@
1
+ """Router contract: the list of ``APIRouter``s this package contributes.
2
+
3
+ A composed application includes every package's ``ROUTERS`` list directly::
4
+
5
+ for router in [*basic.ROUTERS, *user.ROUTERS, *mcp.ROUTERS]:
6
+ app.include_router(router)
7
+
8
+ Each router carries its own unique path prefix, so the lists compose without
9
+ collisions. Cross-package composition never mounts sub-applications:
10
+ importing a package must not build an app, and a mounted sub-app hides its
11
+ routes from the parent's route table (ADR-0015).
12
+ """
13
+
14
+ from fastapi import APIRouter
15
+
16
+ from cliver_playbook.app.basic.api import items, meta
17
+
18
+ # List order is the include order; keep routers with more specific prefixes
19
+ # ahead of broader ones if prefixes ever overlap.
20
+ ROUTERS: list[APIRouter] = [meta.router, items.router]
@@ -0,0 +1,48 @@
1
+ """Self-contained application wrapper for the ``basic`` package.
2
+
3
+ ``create_app`` binds the process runtime (settings instance + database
4
+ engine) and assembles a FastAPI application from this package's ROUTERS —
5
+ the same composition a consumer project performs, so the standalone entry
6
+ point and a composed application can never drift apart.
7
+
8
+ Importing this module has no side effects: the application exists only once
9
+ ``create_app`` is called (uvicorn's ``--factory`` convention).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+
16
+ from fastapi import FastAPI
17
+
18
+ from cliver_playbook.app.basic import runtime
19
+ from cliver_playbook.app.basic.api.routes import ROUTERS
20
+ from cliver_playbook.app.basic.runtime_settings import settings_lifespan
21
+ from cliver_playbook.app.basic.settings import Settings
22
+
23
+ logger = logging.getLogger("cliver_playbook.app.basic")
24
+
25
+
26
+ def create_app(settings: Settings | None = None) -> FastAPI:
27
+ """Assemble this package's standalone FastAPI application.
28
+
29
+ Args:
30
+ settings: the Settings instance to bind to the process runtime.
31
+ Defaults to a fresh ``Settings()`` (layered resolution relative
32
+ to the current working directory). A composed application passes
33
+ its own — possibly subclassed — instance instead, which every
34
+ module-level ``settings`` proxy in the process then serves.
35
+
36
+ Returns:
37
+ The assembled application, ready for uvicorn or an ASGI test client.
38
+ """
39
+ resolved = settings if settings is not None else Settings()
40
+ runtime.configure(resolved)
41
+
42
+ logging.basicConfig(level=resolved.log_level.upper())
43
+ app = FastAPI(title=resolved.app_name, version="0.1.0", lifespan=settings_lifespan)
44
+ for router in ROUTERS:
45
+ app.include_router(router)
46
+
47
+ logger.info("Application assembled: %s", resolved.app_name)
48
+ return app