Development guide¶
How to work on Ospobox itself. The canonical repository is git.sr.ht/~sfermigier/ospobox.
Development setup¶
# Clone the repository
git clone https://git.sr.ht/~sfermigier/ospobox
cd ospobox
# Install all dependencies including dev tools
make dev
# Copy environment file
cp .env.example .env
# Run migrations
make migrate
# Start development server
make run
Project structure¶
ospobox/
├── src/ospobox/
│ ├── app.py # Litestar app factory
│ ├── config.py # Configuration (pydantic-settings)
│ ├── domain/
│ │ ├── models/ # SQLAlchemy models (Nouns)
│ │ └── logic/ # Pure functions (Verbs)
│ ├── persistence/
│ │ ├── repositories/ # Advanced Alchemy repositories
│ │ └── services/ # Advanced Alchemy services
│ ├── api/
│ │ ├── controllers/ # REST API controllers
│ │ └── dtos/ # Data transfer objects
│ ├── web/
│ │ ├── controllers/ # Web page controllers
│ │ └── templates/ # Jinja2 templates
│ ├── extensions/ # Chassis plugin surface (see below)
│ │ └── builtin/ # In-tree evidence sources, scorers, rules
│ ├── services/ # Application services (alerts, health,
│ │ # evidence, webhooks, organizations)
│ ├── platforms/ # Forge adapters (GitHub, GitLab, Codeberg,
│ │ # SourceHut)
│ ├── auth/ # Authentication (JWT, OAuth)
│ ├── workers/ # Background tasks (SAQ)
│ └── lib/ # Shared utilities
├── tests/
│ ├── a_unit/ # Unit tests (~70%)
│ ├── b_integration/ # Integration tests (~20%)
│ └── c_e2e/ # End-to-end tests (~10%)
├── alembic/ # Database migrations
├── docs/ # Documentation (Zensical)
└── notes/ # Project planning documents
Two plugin surfaces¶
platforms/ holds the forge adapters. extensions/ is the broader chassis surface: evidence sources, scorers and alert-rule evaluators, all loadable from a third-party package's entry points. Anything that decides what the data means almost certainly belongs there. See Extension points.
The schema comes from migrations¶
The application does not create tables at startup. Run make migrate before starting it, and after pulling changes. tests/test_migrations.py fails if the models and the migrations drift apart, so a new model needs a migration in the same change.
Make targets¶
| Command | Description |
|---|---|
make dev |
Install all dependencies |
make run |
Run development server |
make test |
Run test suite |
make lint |
ruff check, ty, ruff format --check, mypy |
make format |
Format and autofix (ruff), and the README's table of contents |
make all |
make test then make lint |
make migrate |
Run database migrations |
make migrate-new MSG="description" |
Create new migration |
make migrate-down |
Rollback last migration |
Code patterns¶
Nouns and Verbs¶
Ospobox follows a "Nouns and Verbs" pattern:
Models (Nouns) - Hold state, shallow methods:
# domain/models/organizations.py
class MonitoredOrganization(OspoboxBase):
__tablename__ = "monitored_organizations"
name: Mapped[str]
platform: Mapped[str]
account_id: Mapped[UUID] = mapped_column(ForeignKey("accounts.id"))
@property
def is_synced(self) -> bool:
return self.sync_status == SyncStatus.SYNCED
Logic (Verbs) - Pure functions over values:
# domain/logic/health_score.py
def weighted_total(scores: Mapping[str, float | None]) -> float | None:
"""The composite, or None where no factor had anything to read."""
weights = effective_weights(scores)
if not any(weights.values()):
return None
...
Most of domain/logic/ is pure. Six modules take an AsyncSession and
read the activity tables, because a count over a window is a query and
copying those rows into something pure first buys nothing. None of them
writes, orchestrates, or calls a forge.
Controllers¶
Controllers handle HTTP concerns only:
# api/controllers/organizations.py
class OrganizationsController(Controller):
path = "/api/v1/organizations"
@get("/")
async def list_organizations(
self,
session: AsyncSession,
request: Request,
) -> list[OrganizationDTO]:
# Get user from request
account_id = request.user.account_id
# Query database
orgs = await get_organizations_for_account(session, account_id)
# Return DTOs
return [OrganizationDTO.from_model(org) for org in orgs]
Testing¶
Use pytest with async support:
# tests/a_unit/domain/test_health_score.py
from ospobox.domain.logic.health_score import ActivityMetrics, factor_scores
class TestFactorScores:
def test_a_factor_with_nothing_to_read_abstains(self) -> None:
scores = factor_scores(ActivityMetrics())
assert scores["responsiveness"] is None
Integration tests with database:
# tests/b_integration/test_api_organizations.py
import pytest
from httpx2 import AsyncClient
@pytest.mark.anyio
async def test_create_organization(client: AsyncClient, session: AsyncSession):
response = await client.post(
"/api/v1/organizations/",
json={"platform": "github", "name": "test-org"},
)
assert response.status_code == 201
Database tests¶
Use flush() for test isolation, and let the fixture roll the transaction back:
async def test_create_user(db_session: AsyncSession):
user = User(email="test@example.com", name="Test")
db_session.add(user)
await db_session.flush() # Not commit!
# Refresh to get server-generated values
await db_session.refresh(user)
assert user.id is not None
assert user.created_at is not None
Running tests¶
# Run all tests
make test
# Run specific test file
pytest tests/a_unit/domain/test_health.py
# Run with coverage
pytest --cov=ospobox tests/
# Run only unit tests
pytest tests/a_unit/
# Run with verbose output
pytest -v tests/
Code quality¶
Linting¶
Type checking¶
make lint runs both type checkers. To run one on its own:
Check src only. A bare ty check also scans the test suite, whose
pre-existing diagnostics it will report as yours.
Pre-commit hooks¶
Install pre-commit hooks to catch issues before commit:
Database migrations¶
Creating a migration¶
After modifying models:
Review the generated migration in alembic/versions/, then apply:
Rolling back¶
API documentation¶
The API documentation is auto-generated from the code:
- Swagger UI: http://localhost:8000/docs
- OpenAPI JSON: http://localhost:8000/schema
Documentation¶
Documentation is built with Zensical:
Both read docs/zensical.toml, which is why the bare zensical commands
will not find the sources.
Debugging¶
Debug mode¶
Enable debug mode for detailed error pages:
SQL logging¶
Enable SQL query logging:
Development login¶
In debug mode, use the backdoor login:
- Email:
admin@admin - Password:
admin
Contributing¶
- Create a branch:
git checkout -b feature/my-feature - Make your changes, with a test for each one
- Run the checks:
make all - Commit, following the convention below
Commit messages¶
Follow conventional commits: