feat(cloud-store): support SQLite and PostgreSQL engines
This commit is contained in:
@@ -1,8 +1,41 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
from cloud.control_config import CloudControlConfig, load_control_config
|
||||
from cloud.database import CloudDatabase
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
|
||||
DatabaseFactory = Callable[[CloudControlConfig], CloudDatabase]
|
||||
|
||||
|
||||
def create_app(
|
||||
*,
|
||||
config: CloudControlConfig | None = None,
|
||||
database_factory: DatabaseFactory | None = None,
|
||||
) -> FastAPI:
|
||||
"""Create the independently deployable cloud API application."""
|
||||
return FastAPI(title="Device Cloud API")
|
||||
control_config = config or load_control_config()
|
||||
build_database = database_factory or _default_database_factory
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
database = build_database(control_config)
|
||||
app.state.cloud_config = control_config
|
||||
app.state.database = database
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
database.close()
|
||||
|
||||
return FastAPI(title="Device Cloud API", lifespan=lifespan)
|
||||
|
||||
|
||||
def _default_database_factory(config: CloudControlConfig) -> CloudDatabase:
|
||||
return CloudDatabase(
|
||||
config.database_url,
|
||||
create_schema=config.environment != "production",
|
||||
)
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from cloud_api.app import create_app
|
||||
from cloud.control_config import CloudControlConfig
|
||||
|
||||
|
||||
def test_create_app_returns_independent_cloud_application() -> None:
|
||||
@@ -8,3 +11,23 @@ def test_create_app_returns_independent_cloud_application() -> None:
|
||||
|
||||
assert app.title == "Device Cloud API"
|
||||
assert callable(create_app)
|
||||
|
||||
|
||||
def test_cloud_application_owns_database_lifecycle() -> None:
|
||||
events: list[str] = []
|
||||
|
||||
class FakeDatabase:
|
||||
def close(self) -> None:
|
||||
events.append("closed")
|
||||
|
||||
fake_database = FakeDatabase()
|
||||
app = create_app(
|
||||
config=CloudControlConfig(database_url="sqlite:///:memory:"),
|
||||
database_factory=lambda _config: fake_database, # type: ignore[arg-type,return-value]
|
||||
)
|
||||
|
||||
with TestClient(app):
|
||||
assert app.state.database is fake_database
|
||||
assert events == []
|
||||
|
||||
assert events == ["closed"]
|
||||
|
||||
Reference in New Issue
Block a user