Repository navigation
feat!: serve service info from config - #318
Conversation
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]>
Reviewer's GuideAdds configuration-driven GA4GH service-info serving: a validated and schema-backed Sequence diagram for configuration-driven service info requestssequenceDiagram
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
Flow diagram for service info precedence and validationflowchart 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"]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
Summary
FOCA can now serve GA4GH service info (
GET /service-info) from the configuration, with no app code and no database (#314):service_info(ServiceInfoConfig):service: the service info, as per the GA4GHServiceschema;package(optional): the app's distribution package; its installed version is used asversionunlessservice.versionis set;runtime_fields(optional): path to a function returning fields computed at runtime, called on each request.service> runtime fields > package version. Fields and list items set tonullare removed (so config overlays can drop fields), except that anullversion(inserviceor from the runtime fields) means "not set", so the next source applies.foca.api.service_info.getServiceInfo(orGetServiceInfo, as in the WES and TES specs) in their specs (e.g., withx-openapi-router-controller: foca.api.service_info);security: []makes it public.Serviceschema (with lenienturianddate-timeformat checks; no new optional dependencies), plus a JSON-serializability check:runtime_fieldsis set);Foca.create_app, which also fails if an operation is routed togetServiceInfobutservice_infois not configured;foca.utils.service_info, sofoca.models.configdoes not import fromfoca.api.jsonschema>=4.17,<5.docs/configuration/service-info.md, template, API reference, migration notes.Closes #314
Breaking change
service_infoused to be accepted as an arbitrary extra config key. It is now a validated section: apps that kept GA4GH fields directly underservice_infomust move them toservice_info.service(or rename their custom key). Seedocs/migration-0.14.md.Verification
Locally (Python 3.12):
ruff check .,ruff format --check .: passedmypy foca: no issues in 34 source filespytest(unit tests, MongoDB 7 locally, integration tests excluded) under coverage: 845 passed; coverage 100% (1580 statements)mkdocs build --strict: no warningspython -m build+twine check --strict: passed (the vendored spec is in the wheel and sdist)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:
Enhancements:
Build:
Documentation:
Tests: