Skip to content

About

Service to manage and monitor processes and jobs

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

service-processes

Branch Status
develop Build Status codecov
main Build Status codecov

Service processes provides an API for managing and monitoring pipelines, decoupling consumers from Airflow's native API.

Development

This service uses the FastAPI framework.

Dependencies

Prerequisites on host for development and build:

  • python version 3.14
  • uv
  • docker and docker compose

Setup

To create and activate a virtual Python environment with all dependencies installed:

make setup

Then run local dependencies (PostgreSQL and OpenTelemetry)

make docker-compose-up

Then run the server from a separate terminal

make serve

Database

Local development uses PostgreSQL 18. make docker-compose-up creates the application database and its non-administrator role on its first run. The local connection settings are in .env.default (DB_HOST, DB_PORT, DB_NAME, DB_USER, and DB_PW), and are read automatically by the application.

Deployed environments set the same DB_* variables. The connection URL is built from them, so the user and password don't need to be URL-encoded.

DB_CONNECT_TIMEOUT (in seconds, default 10) limits how long establishing a new connection may take. On startup, the application pings the database and fails if it is not reachable within this timeout.

Endpoints can receive a request-scoped async session with DatabaseSessionDep:

from sqlalchemy import select

from app.core.database import DatabaseSessionDep


async def list_processes(session: DatabaseSessionDep):
    result = await session.execute(select(Process))
    return result.scalars().all()

The dependency does not commit transactions. Read endpoints can execute queries directly; write endpoints should use an explicit async with session.begin(): block. The connection pool is created with the FastAPI lifespan and disposed during shutdown.

Note

PostgreSQL initialization scripts run only when the data directory is empty. To recreate the local database after changing its initial users or database name, stop Compose and remove .volumes/postgresql (this deletes local database data) before starting it again.

Database Migrations

The database schema is managed with Alembic. The ORM models live in app/models/ and the migration scripts in migrations/versions/. Alembic is configured in alembic.ini, and the database connection is taken from the application settings (DB_*, see above).

With the local database running (make docker-compose-up), apply all pending migrations:

make db-upgrade

To change the schema, edit or add models in app/models/ (new models must be imported in app/models/__init__.py so that Alembic detects them), then generate a migration:

make db-revision m="add status to process"

This creates a file such as migrations/versions/2026_10_15_1511-ee7947955462_add_status_to_process.py. Autogenerate does not detect everything (e.g. table or column renames, some type changes), so always review the generated script before applying it with make db-upgrade.

Local sample data

docker/seed-local-data.sql contains sample processes for local development, e.g. one that triggers the dummy DAG of the local Airflow. Load it after the migrations:

make db-seed

The script is idempotent: re-running it updates existing rows to the values in the file. Add new sample data there instead of inserting it manually.

Other useful targets:

make db-downgrade   # revert the last migration
make db-history     # show the migration history
make db-check       # fail if the models have changes without a migration

Constraint names are generated by the naming convention defined in app/models/base.py, so avoid hardcoding constraint names in migrations.

Linting and Formatting

This project uses ruff as linter and formatter. It also uses ty as type checker.

To lint and type check use

make lint

To format

make format

Pre-Commit Hooks

This project uses pre-commit hook to lint and type-check before committing. Pre-commits hooks can either be bypassed entirely with the --no-verify option (git commit --no-verify ...), or individually using the SKIP environment variable (SKIP=lint git commit ...).

Updating Packages

All packages used in production are pinned to a major version. Automatically updating these packages will use the latest minor (or patch) version available. Packages used for development, on the other hand, are not pinned unless they need to be used with a specific version of a production package (for example, boto3-stubs for boto3).

To update the packages to the latest minor/compatible versions, run:

uv sync --upgrade

To see what major/incompatible releases would be available, run:

uv pip list --outdated

To update packages to a new major release, run:

uv add "fastapi[standard]~=v0.141"

Testing

This project uses pytest for testing, to start the tests enter

make test

OpenAPI

FastAPI automatically generates an OpenAPI schema, so each path operation should define its request parameters and responses using pydantic models to ensure they are properly documented. To view the OpenAPI documentation, run:

make serve

And then open:

Authorization during local development

In production the service runs behind oauth2-proxy, which sets the X-Auth-Request-* headers (e.g. the access token used for authorization). Locally, these headers are set by the nginx of docker-compose.yml, which listens on port 8000 and forwards to the app on port 8080. So use port 8000, requesting the app directly on port 8080 results in 401 Unauthorized on protected endpoints.

With USE_LOCAL_VERIFIED_PERMISSIONS=true (default in .env.default), AWS Verified Permissions is replaced by a dummy authorizer allowing all requests. The dummy is not part of the docker image, so make dockerrun requires USE_LOCAL_VERIFIED_PERMISSIONS=false and access to a real policy store.

All docs related paths (openapi.json, docs, redoc and their internal/ variants) can be prefixed with the DOC_PREFIX_PATH setting, e.g. DOC_PREFIX_PATH=/specs serves Swagger under /specs/docs.

Airflow during local development

Starting a process triggers a DAG run in Airflow. For local development, a single container Airflow (airflow standalone, SQLite) is part of docker-compose.yml. It is not started by make docker-compose-up, as it is heavy and takes about a minute to start:

make start-airflow   # waits until Airflow is healthy
make stop-airflow

The Airflow UI is at http://localhost:8081 (user service, password local, set in the command of the airflow service). DAGs are loaded from docker/airflow/dags/. It contains a dummy DAG for the process in app/models/insert.sql, which only logs the conf it was triggered with. Add a DAG with the dag_id of every other process you want to start locally.

In the cluster, the service gets its Airflow token by exchanging its Kubernetes service account token. Locally, it logs in with username and password instead, configured in .env.default:

AIRFLOW_HOST=http://localhost:8081
USE_LOCAL_AIRFLOW=true
AIRFLOW_LOCAL_USERNAME=service
AIRFLOW_LOCAL_PASSWORD=local

Observability

The service supports OpenTelemetry logging, tracing, and metrics.

Metrics

FastAPI auto-instrumentation metrics

The FastAPIInstrumentor (backed by opentelemetry-instrumentation-asgi) emits the following metrics automatically for every HTTP request. The default semantic-convention mode (DEFAULT) uses the old HTTP semconv attribute names.

Metric name Type Unit Description
http.server.request.duration Histogram s Duration of inbound HTTP requests
http.server.request.body.size Histogram By Size of HTTP request messages (compressed)
http.server.response.body.size Histogram By Size of HTTP response messages (compressed)
http.server.active_requests UpDownCounter {request} Number of currently in-flight HTTP requests

Attributes attached to http.server.request.duration, http.server.request.body.size, and http.server.response.body.size:

Attribute Example Description
url.scheme http URL scheme
network.protocol.version 1.1 Network protocol version
http.request.method GET HTTP request method
http.route / HTTP route
http.response.status_code 200 HTTP response status code

Attributes attached to http.server.active_requests:

Attribute Example
http.request.method GET
url.scheme http

Note

The metrics above are from the new semantic convention for HTTP. They need to be enabled by setting OTEL_SEMCONV_STABILITY_OPT_IN=http in your environment. Use OTEL_SEMCONV_STABILITY_OPT_IN=http/dup to emit both old and new metrics simultaneously during a migration.

In production deployments, telemetry can be exported using the configured OTLP exporters, typically to an OpenTelemetry Collector or any OTLP-compatible observability platform. Only the OTLP exporter is currently implemented by the application configuration layer.

By default, local development with the FastAPI dev server (make serve) runs with OpenTelemetry disabled and uses standard Python console logging for a simpler and more readable developer experience.

See OpenTelemetry Python Instrumentation documentation for more information about adding tracing and metrics inside the application code.

Logging implementation

The application uses the OpenTelemetry LoggerProvider directly to export logs.

Warning

The deprecated opentelemetry-instrumentation-logging package is intentionally not used, as LoggerProvider already associates logs with the active trace/span context and provides native structured OTEL log exporting.

Local OTEL testing

To test the full OTEL configuration locally (logs, traces, and metrics exported through OpenTelemetry), use the provided OTEL environment configuration and run the application with Docker:

  1. Start the local otel collector

    make start-otel
  2. In a new shell start the application

    cp .env.otel .env
    make dockerrun

This configuration enables the OTLP exporters and sends telemetry to the local configured OpenTelemetry collector endpoint created via make start-otel.

Then you will see OTEL logs and metrics in the first shell in which you started make start-otel and you can see the full trace using jaeger trace explorer at http://localhost:16686

Deployment

Database Migrations

The application does not run migrations on startup; they must be applied before the new version of the application starts. The docker image contains the migration scripts and Alembic, but its entrypoint is uvicorn, so the entrypoint must be overridden to run them:

docker run --rm --env DB_HOST=... --env DB_PORT=... --env DB_NAME=... --env DB_USER=... \
    --env DB_PW=... --entrypoint alembic <image> upgrade head

If the application is deployed with ArgoCD, the best option is a Job that runs as a PreSync hook. ArgoCD runs the job once per sync, before it applies the other manifests, and continues the sync only if the job succeeds. A failed migration therefore leaves the running version of the application untouched. Setting command overrides the image entrypoint, and the image working directory already contains the alembic.ini with the Alembic configuration:

apiVersion: batch/v1
kind: Job
metadata:
  name: service-processes-db-migrations
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
  backoffLimit: 0
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: db-migrations
          image: <registry>/swissgeo/service-processes:<version>
          command: ["alembic", "upgrade", "head"]
          envFrom:
            - secretRef:
                name: service-processes-db

Here the service-processes-db secret contains the keys DB_HOST, DB_PORT, DB_NAME, DB_USER and DB_PW. The BeforeHookCreation delete policy keeps the job (and its logs) until the next sync, which deletes it before creating it again.

Warning

PreSync hooks run before the other manifests of the application are applied. If the secret is part of the same ArgoCD application, it does not exist yet on the first sync; it must then also be created as a PreSync hook with a lower argocd.argoproj.io/sync-wave, or be managed outside of the application.

Without ArgoCD, this can be done with an init container that uses the same image as the application:

spec:
  template:
    spec:
      initContainers:
        - name: db-migrations
          image: <registry>/swissgeo/service-processes:<version>
          command: ["alembic", "upgrade", "head"]
          envFrom:
            - secretRef:
                name: service-processes-db
      containers:
        - name: service-processes
          image: <registry>/swissgeo/service-processes:<version>
          envFrom:
            - secretRef:
                name: service-processes-db

Warning

An init container runs in every pod, so with several replicas the migrations may be started concurrently.

During a rolling update, the old and new versions of the application run side by side against the migrated schema. Migrations must therefore stay backward compatible with the previous version: for example, add a nullable column first and only drop or rename columns in a later release, once no running version uses them anymore.

About

Service to manage and monitor processes and jobs

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages