Skip to content

feat!: serve service info from config - #318

Merged
uniqueg merged 4 commits into
devfrom
feat/service-info-config
Oct 20, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/service-info-config

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

FOCA can now serve GA4GH service info (GET /service-info) from the configuration, with no app code and no database (#314):

  • New config section service_info (ServiceInfoConfig):
    • service: the service info, as per the GA4GH Service schema;
    • package (optional): the app's distribution package; its installed version is used as version unless service.version is set;
    • runtime_fields (optional): path to a function returning fields computed at runtime, called on each request.
  • Precedence: service > runtime fields > package version. Fields and list items set to null are removed (so config overlays can drop fields), except that a null version (in service or from the runtime fields) means "not set", so the next source applies.
  • Apps route the operation to foca.api.service_info.getServiceInfo (or GetServiceInfo, as in the WES and TES specs) in their specs (e.g., with x-openapi-router-controller: foca.api.service_info); security: [] makes it public.
  • Validation against the bundled GA4GH service-info 1.0.0 Service schema (with lenient uri and date-time format checks; no new optional dependencies), plus a JSON-serializability check:
    • when the config is loaded (required fields are only checked at startup if runtime_fields is set);
    • at startup in Foca.create_app, which also fails if an operation is routed to getServiceInfo but service_info is not configured;
    • on each request (errors are logged; clients get a generic 500, whatever the exception mapping).
  • Helpers live in the new module foca.utils.service_info, so foca.models.config does not import from foca.api.
  • New dependency: jsonschema>=4.17,<5.
  • Docs: new page docs/configuration/service-info.md, template, API reference, migration notes.

Closes #314

Breaking change

service_info used to be accepted as an arbitrary extra config key. It is now a validated section: apps that kept GA4GH fields directly under service_info must move them to service_info.service (or rename their custom key). See docs/migration-0.14.md.

Verification

Locally (Python 3.12):

  • ruff check ., ruff format --check .: passed
  • mypy foca: no issues in 34 source files
  • pytest (unit tests, MongoDB 7 locally, integration tests excluded) under coverage: 845 passed; coverage 100% (1580 statements)
  • mkdocs build --strict: no warnings
  • python -m build + twine check --strict: passed (the vendored spec is in the wheel and sdist)
  • gitleaks: no leaks
  • Two review rounds (adversarial and quality); all findings fixed.

Not run locally: the integration tests (need the Docker petstore app); CI runs them.

CI: all checks passed (lint, type check and build; unit tests on Python 3.10–3.14 with MongoDB 7.0, and 3.13 with MongoDB 8.0; petstore integration tests; Read the Docs).

🤖 Generated with Claude Code

Summary by Sourcery

Serve validated GA4GH service information directly from application configuration without requiring application code or database storage.

New Features:

  • Add configuration-driven GA4GH service-info serving for API endpoints, including package-derived and runtime-computed fields.

Enhancements:

  • Validate configured service information against the bundled GA4GH Service schema and ensure it is JSON-serializable at configuration load, startup, and request time.
  • Support precedence and null-removal rules across configured fields, runtime fields, and package versions, with compatible controller names for GA4GH specifications.
  • Fail app startup when routed service-info endpoints lack valid configuration, and return generic logged server errors for invalid request-time information.

Build:

  • Add jsonschema as a runtime dependency and bundle the GA4GH service-info schema as package data.

Documentation:

  • Document service-info configuration, routing, validation, runtime fields, and migration requirements.

Tests:

  • Add comprehensive tests covering configuration validation, merging, schema and JSON validation, endpoint routing, startup checks, runtime failures, and public access.

uniqueg and others added 3 commits October 20, 2026 22:08
Add a `service_info` config section and a controller for
`GET /service-info` (`foca.api.service_info.getServiceInfo`), so that
apps serve GA4GH service info from their configuration, without code or
a database of their own. The response is built from the configured
fields, the version of the app's package (`package`, unless set), and
an optional function for fields computed at runtime
(`runtime_fields`). The service info is validated against the GA4GH
`Service` schema (service-info 1.0.0, vendored) when the config is
loaded, when the app is created and on each request. `createdAt` and
`updatedAt` are optional and only served if set.

Closes #314

BREAKING CHANGE: `service_info` is now a validated FOCA config section
(`ServiceInfoConfig`) instead of an arbitrary extra top-level key left
to apps. Apps that kept GA4GH service info fields directly under
`service_info` must move them to `service_info.service`; apps using the
key for anything else must rename it. Otherwise, the configuration
fails validation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apply review findings to the service info support:

- Move the helpers (schema validation, format checks, package version
  lookup, runtime function import and call, merging) to a neutral
  module, `foca.utils.service_info`, with the vendored specification,
  so that `foca.models.config` no longer imports from `foca.api`. One
  helper, `merge_service_info()`, owns the precedence of the sources
  for both the config model and the controller.
- Refuse to start apps that route operations to `getServiceInfo`
  without `service_info` configured, detected from the view functions
  of the app (unwrapped), whichever resolver routed them.
- Require the service info to be JSON-serializable.
- Treat `service.version: null` as unset, so that the version is taken
  from the runtime fields or `package`.
- Raise `InvalidServiceInfo` for exceptions of the runtime fields
  function, chaining them; requests still fail with a generic 500.
- Rename `import_runtime_fields()` to `import_runtime_function()` and
  `package_fields()` to `lookup_package_version()`; the config exposes
  `package_version` instead of `package_fields`.
- Describe the URI check as lenient, not as RFC 3986.
- Mark `package` and `runtime_fields` in the config template as
  placeholders, and document the upgrade of apps using `service_info`.
- Share test data between test modules, test with a runtime function
  module that tests can toggle instead of patching private attributes,
  and test logged errors, full `operationId`s and `security: []`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Serve the controller also as `GetServiceInfo`, the operation name of
  the GA4GH WES and TES specifications (same function, so routes are
  still detected), and document both spellings.
- Treat `version: None` returned by the runtime fields function as
  unset, like in `service`, so that the package version applies.
- Answer requests the service info cannot be built for with a generic
  `500 Internal Server Error` from the controller, logging the error,
  also if apps map `ValueError` (base of `InvalidServiceInfo`) to other
  problem details.
- Comment out `package` and `runtime_fields` in the config template and
  set `service.version`, so that the section validates as copied
  (tested).
- Keep the upgrade guidance in the 0.14.0 migration notes only, explain
  the hand-written format checkers, and document the config properties.
- Tests: one fixture capturing logs after FOCA configured logging, a
  `REMOVE` sentinel for removing fields from test data (renamed to
  `service_info_data`), so that `None` can be set as a value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds configuration-driven GA4GH service-info serving: a validated and schema-backed service_info section resolves static, runtime, and package metadata, while a controller serves it with startup/request validation, routing checks, documentation, and comprehensive tests.

Sequence diagram for configuration-driven service info requests

sequenceDiagram
    participant Client
    participant Controller as foca.api.service_info.getServiceInfo
    participant Config as ServiceInfoConfig
    participant Runtime as runtime_fields
    participant Package as PackageMetadata
    participant Validator as validate_service_info

    Client->>Controller: GET /service-info
    Controller->>Config: get_service_info()
    Config->>Runtime: call_runtime_function()
    Runtime-->>Config: runtime fields
    Config->>Package: lookup_package_version()
    Package-->>Config: package version
    Config->>Config: merge_service_info()
    Config->>Validator: validate_service_info()
    Validator-->>Controller: validated JSON service info
    Controller-->>Client: 200 Service info

    alt InvalidServiceInfo or RuntimeError
        Controller-->>Client: 500 InternalServerError
    end
Loading

Flow diagram for service info precedence and validation

flowchart LR
    Service["service config"] --> Merge["merge_service_info()"]
    Runtime["runtime_fields function"] --> Merge
    Package["package metadata"] --> Merge
    Merge --> Validate["validate_service_info()"]
    Validate --> Response["GA4GH Service JSON"]
    Validate --> Error["InvalidServiceInfo"]
    Error --> Startup["startup failure or logged 500"]
Loading

File-Level Changes

Change Details Files
Adds a validated service_info configuration model with layered field resolution.
  • Introduces service, optional package-version fallback, and runtime-fields configuration.
  • Defines precedence and null-removal behavior, including special handling for version: null.
  • Validates configured data during config loading, while allowing required fields to be supplied at runtime.
foca/models/config.py
foca/utils/service_info.py
pyproject.toml
Implements GA4GH Service schema validation and reusable service-info utilities.
  • Bundles the GA4GH service-info 1.0.0 schema and validates URI, date-time, and JSON-serializability constraints.
  • Adds helpers for merging sources, removing nulls, resolving package versions, importing runtime functions, and wrapping runtime errors.
  • Keeps shared logic in foca.utils.service_info to avoid coupling configuration models to API controllers.
foca/utils/service_info.py
foca/utils/service-info.yaml
pyproject.toml
Adds controller support for serving service info through routed API operations.
  • Provides getServiceInfo, GetServiceInfo, and get_service_info entry points.
  • Builds and validates service info at startup and on every request, invoking runtime fields in app context.
  • Returns generic HTTP 500 responses and logs failures, while detecting routes that require unconfigured service info.
foca/api/service_info.py
foca/foca.py
Documents and templates the new configuration-driven GA4GH endpoint.
  • Adds configuration, migration, API reference, README, and template documentation.
  • Describes routing, authentication/public endpoint configuration, precedence, validation, and migration from the old free-form key.
README.md
docs/configuration/index.md
docs/configuration/service-info.md
docs/migration-0.14.md
docs/reference.md
mkdocs.yml
templates/config.yaml
Adds comprehensive coverage for configuration, merging, validation, startup checks, and HTTP behavior.
  • Tests null overlays, precedence, package and runtime versions, schema and format validation, and JSON serialization.
  • Tests routing aliases, public access, startup failures, per-request runtime failures, logging, and generic 500 handling.
tests/api/test_service_info.py
tests/models/test_config.py
tests/utils/test_service_info_utils.py
tests/test_foca.py
tests/test_files/service_info_data.py
tests/test_files/service_info_fields.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (791b390) to head (2e8739d).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #318    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           22        24     +2     
  Lines         1423      1583   +160     
==========================================
+ Hits          1423      1583   +160     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review October 20, 2026 20:37

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/utils/service_info.py" line_range="279" />
<code_context>
+    """
+    label = _runtime_label(path)
+    try:
+        fields = func()
+    except Exception as exc:
+        raise InvalidServiceInfo(f"{label} failed") from exc
</code_context>
<issue_to_address>
**Service info calls hang**

When the configured runtime-fields function waits on an unavailable or slow service, `call_runtime_function` invokes the configured function synchronously, so a stalled remote lookup blocks `Foca.create_app()` during startup or ties up request workers indefinitely. There is no timeout or fallback around the call.

Provide a bounded timeout for runtime-field computation, with an appropriate fallback or explicit failure.
</issue_to_address>

### Comment 2
<location path="foca/utils/service_info.py" line_range="80" />
<code_context>
+    return (
+        parts["hour"] < 24
+        and parts["minute"] < 60
+        and parts["second"] <= 60
+        and parts["offset_hour"] < 24
+        and parts["offset_minute"] < 60
</code_context>
<issue_to_address>
**Invalid leap seconds pass validation**

When a configured or runtime `createdAt` or `updatedAt` contains `:60` at a date and time that is not an actual leap second, `_is_date_time` accepts any timestamp with seconds set to `60`, so `validate_service_info` lets invalid RFC 3339 date-times pass and serves them as service info.

Accept seconds set to `60` only when the timestamp represents an actual RFC 3339 leap second.
</issue_to_address>

### Comment 3
<location path="foca/utils/service_info.py" line_range="120" />
<code_context>
+    """
+    if isinstance(data, Mapping):
+        return {
+            key: without_nulls(value)
+            for key, value in data.items()
+            if value is not None
</code_context>
<issue_to_address>
**Cyclic fields escape validation**

When a configured `runtime_fields` function returns a cyclic mapping, a runtime function returning a self-referential mapping makes `without_nulls()` recurse until Python raises `RecursionError`, before `validate_service_info()` can report `InvalidServiceInfo`; `Foca.create_app()` then fails with an unexpected exception instead of the documented validation error.

Detect recursive structures or catch `RecursionError` during merging and validation and raise `InvalidServiceInfo` with a useful message.
</issue_to_address>

### Comment 4
<location path="foca/api/service_info.py" line_range="111" />
<code_context>
+    """
+    try:
+        return get_service_info()
+    except (InvalidServiceInfo, RuntimeError) as exc:
+        logger.exception(f"Service info not served: {exc}")
+        raise InternalServerError() from exc
</code_context>
<issue_to_address>
**Mapped errors replace generic 500**

When the app’s exception mapping maps `InternalServerError` or one of its base classes to a non-500 status, fOCA’s generic exception handler applies the configured mapping to the `InternalServerError` raised by `getServiceInfo`, so clients receive the mapped status instead of the promised generic 500.

Make service-info failures bypass configured exception mappings and return the generic 500.

Also at `foca/api/service_info.py:113`.
</issue_to_address>

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: foca/utils/service_info.py:279, foca/utils/service_info.py:80, foca/utils/service_info.py:120, foca/api/service_info.py:111


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/utils/service_info.py Resolved
Comment thread foca/utils/service_info.py Resolved
Comment thread foca/utils/service_info.py Resolved
Comment thread foca/api/service_info.py Resolved
Raise InvalidServiceInfo instead of a RecursionError when fields are
nested too deeply or refer to themselves. Document that runtime field
functions are not timed out, and that a mapping of
InternalServerError applies to service info errors too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit b42d0f1 into dev Oct 20, 2026
13 checks passed
@uniqueg
uniqueg deleted the feat/service-info-config branch October 20, 2026 20:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant