Repository navigation
fix!: service info id, precedence and headers - #96
Conversation
- POST /service-info requires `id` (400 instead of a 500 `KeyError`) - The most recently written service info is served, tracked in an internal `_writtenAt` field: posted service info is kept on restart unless the service info in the config changes. Before, the document with the highest `_id` was served, so posted service info with another `id` shadowed the config forever. - `Location` is the public URL of the service info endpoint: the configured scheme, host and port, `api_path` as a path prefix, and the API path, without duplicate slashes - The empty 201 response has no `Content-Type` - Error responses declare `application/problem+json`, the media type FOCA returns, in addition to `application/json` (in `additions.openapi.yaml`, so the GA4GH specifications stay unchanged) Closes #75 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Document the precedence rule in the README and config - Test documents written before write times were tracked - Write times with fixed microsecond precision - Errors of POST /service-info are application/problem+json Co-Authored-By: Claude Opus 5.5 <[email protected]>
Startup compared the config with the stored document, so service info posted with the configured identifier was replaced on every restart. Store a hash of the config last written (`_configHash`), carry it over when service info with that identifier is posted, and write the config on startup only when its hash changes. Documents without the hash that equal the config are kept, as before. Include the WSGI script root in the `Location` header and fix the `api_path` docstring. BREAKING CHANGE: `id` is required in posted service info, and `api_path` is now a prefix in front of the API base path in public URLs rather than the path of the service info endpoint. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Service info stored before config hashes were added and equal to the config was kept on startup without a hash, so service info posted with the configured identifier afterwards was still replaced on the next restart. Record the hash on such documents. Also look up the hash before the stored service info, test that internal fields are hidden, and document the new `api_path` meaning. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThe PR fixes service-info registration precedence by recording write times and configuration hashes, preserves posted data across restarts unless startup configuration changes, requires service IDs, and corrects response headers and public URL construction for proxy deployments. It also updates the OpenAPI error media types and documentation, with tests covering legacy data, hidden metadata, precedence, validation, and Location behavior. Sequence diagram for service-info registration and precedencesequenceDiagram
participant App
participant RegisterServiceInfo
participant Database
App->>RegisterServiceInfo: set_service_info_from_config()
RegisterServiceInfo->>RegisterServiceInfo: _get_config_hash(id)
RegisterServiceInfo->>Database: find_one(id, _configHash)
alt config hash unchanged
RegisterServiceInfo-->>App: keep existing service info
else config changed or hash missing
RegisterServiceInfo->>RegisterServiceInfo: _get_stored_service_info(id)
RegisterServiceInfo->>Database: find_one(id)
RegisterServiceInfo->>Database: replace_one(id, _writtenAt, _configHash)
RegisterServiceInfo-->>App: service info registered
end
App->>RegisterServiceInfo: get_service_info()
RegisterServiceInfo->>Database: find sorted by _writtenAt desc, _id desc
Database-->>RegisterServiceInfo: most recently written document
RegisterServiceInfo-->>App: public service info
Sequence diagram for posting service info with Location headersequenceDiagram
actor Client
participant API
participant RegisterServiceInfo
participant Database
Client->>API: POST /service-info
API->>API: RegisterServiceInfo()
API->>RegisterServiceInfo: set_service_info_from_app_context(data)
RegisterServiceInfo->>Database: replace_one(id, _writtenAt, preserved _configHash)
RegisterServiceInfo->>RegisterServiceInfo: _get_headers()
RegisterServiceInfo-->>API: Location header
API-->>Client: 201 empty response with Location only
File-Level Changes
Assessment against linked issues
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 #96 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 7 7
Lines 204 224 +20
=========================================
+ Hits 204 224 +20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 7 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="cloud_registry/ga4gh/registry/service_info.py" line_range="145-148" />
<code_context>
+ config_hash: Hash of the service info config last written to the
+ document, if any.
+ """
+ written_at = datetime.now(timezone.utc).isoformat(timespec="microseconds")
+ replacement = {**data, WRITTEN_AT: written_at}
+ if config_hash is not None:
+ replacement[CONFIG_HASH] = config_hash
self.collection.replace_one(
filter={"id": data["id"]},
</code_context>
<issue_to_address>
**Posted info loses its metadata**
When old and new application versions share the database during a rolling deployment and an old instance handles a POST, the old instance replaces the document without `_writtenAt` or `_configHash`. New readers treat it as legacy, and startup can overwrite the posted service info with config, so callers see stale or lost service info.
Make the rolling-deployment write path preserve the metadata, or prevent old instances from writing documents that new instances depend on.
</issue_to_address>
### Comment 2
<location path="cloud_registry/ga4gh/registry/service_info.py" line_range="127" />
<code_context>
- self._upsert_service_info(data=self._add_timestamps(data=data, stored=stored))
+ self._upsert_service_info(
+ data=self._add_timestamps(data=data, stored=stored),
+ config_hash=self._get_config_hash(id=data["id"]),
+ )
return self._get_headers()
</code_context>
<issue_to_address>
**Posted info is overwritten by config**
When startup changes or migrates the configured document while a POST for that identifier is in progress, the POST can replace the document with a stale or missing `_configHash` after startup writes the current hash. On the next restart, `set_service_info_from_config` sees a mismatch and replaces the posted service info with config.
Update the document so a concurrent POST cannot restore a stale hash or remove the hash written by startup.
Also at `cloud_registry/ga4gh/registry/service_info.py:97-99`, `cloud_registry/ga4gh/registry/service_info.py:149`.
</issue_to_address>
### Comment 3
<location path="cloud_registry/ga4gh/registry/service_info.py" line_range="150-152" />
<code_context>
+ if config_hash is not None:
+ replacement[CONFIG_HASH] = config_hash
self.collection.replace_one(
filter={"id": data["id"]},
- replacement=data,
+ replacement=replacement,
upsert=True,
)
</code_context>
<issue_to_address>
**Concurrent writes duplicate identifiers**
When two app instances write service info with the same identifier before either insert is visible to the other, two instances upsert the same previously absent `id` concurrently; both `replace_one` calls can insert because only MongoDB’s generated `_id` is unique. The collection then contains duplicate service-info documents for one identifier, so later reads and updates can select or replace the wrong copy.
Enforce a unique database index on `id` and handle duplicate-key upsert races by updating the existing document.
</issue_to_address>
### Comment 4
<location path="cloud_registry/ga4gh/registry/service_info.py" line_range="64" />
<code_context>
- self.collection.find({}, {"_id": False})
- .sort([("_id", -1)])
+ self.collection.find({}, PROJECTION)
+ .sort([(WRITTEN_AT, -1), ("_id", -1)])
.limit(1)
.next()
</code_context>
<issue_to_address>
**Reads fail as the collection grows**
When many distinct service-info IDs have accumulated, `get_service_info` sorts by `_writtenAt` without a matching index, so MongoDB scans and sorts an increasingly large collection and can exceed its sort resources. `/service-info` requests then fail.
Create an index that supports the sort used by `get_service_info`.
</issue_to_address>
### Comment 5
<location path="cloud_registry/ga4gh/registry/service_info.py" line_range="145-146" />
<code_context>
+ config_hash: Hash of the service info config last written to the
+ document, if any.
+ """
+ written_at = datetime.now(timezone.utc).isoformat(timespec="microseconds")
+ replacement = {**data, WRITTEN_AT: written_at}
+ if config_hash is not None:
+ replacement[CONFIG_HASH] = config_hash
</code_context>
<issue_to_address>
**Retry resurrects stale info**
When a client retries a POST whose successful response was lost, after another service-info ID has been posted, the retried POST replaces its service-info document and assigns it a fresh `_writtenAt`. If another ID was posted after the original request, the retry makes the older payload appear newest, so GET serves stale info.
Make retries identifiable and deduplicate them, or reject stale writes using a version or conditional update.
</issue_to_address>
### Comment 6
<location path="cloud_registry/ga4gh/registry/server.py" line_range="133" />
<code_context>
service_info = RegisterServiceInfo()
headers = service_info.set_service_info_from_app_context(data=_get_request_object())
- return None, 201, headers
+ response = Response(status=201, headers=headers)
+ # The body is empty, so it has no media type (Flask sets a default one)
+ del response.headers["Content-Type"]
</code_context>
<issue_to_address>
**Location is missing from API spec**
When a consumer relies on the published OpenAPI contract to discover response headers, openAPI consumers see a 201 response with no declared headers, so generated clients and contract-based tooling cannot discover the `Location` header that `postServiceInfo` returns.
Declare the `Location` response header in the `/service-info` 201 response.
</issue_to_address>
### Comment 7
<location path="tests/test_app.py" line_range="275" />
<code_context>
+ spec = client.get(f"{BASE}/openapi.json").json
+ declared = spec["paths"]["/services/{serviceId}"]["get"]["responses"]["404"]
+ name = declared["$ref"].rsplit("/", 1)[-1]
+ assert response.mimetype in spec["components"]["responses"][name]["content"]
+
+
</code_context>
<issue_to_address>
**Error media type regression passes**
When an error response regresses to `application/json`, when `/services/unknown` returns `application/json`, `test_error_media_type` at line 275 still passes because the additions spec declares that media type too, so the test does not catch the required `application/problem+json` response.
Assert that the response mimetype is exactly `application/problem+json`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 6 findings to address first, and if the write-time ordering or config-hash check is wrong, the service can keep serving stale or unintended service info from MongoDB across restarts. That value outlives a revert, but can be replaced by posting corrected info or changing the config.
Blocking findings: cloud_registry/ga4gh/registry/service_info.py:148, cloud_registry/ga4gh/registry/service_info.py:127, cloud_registry/ga4gh/registry/service_info.py:152, cloud_registry/ga4gh/registry/service_info.py:64, cloud_registry/ga4gh/registry/service_info.py:146, and 1 more
Declare the `Location` header of `POST /service-info` responses in the specification, and assert that error responses are problem details. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Fixes the service info bugs collected in #75.
id:ServiceRegisterrequiresid; requests without it get a 400._writtenAt, sorted descending, then_id). On startup, the service info fromconfig.yamlis written only if the config changed since it was last written (sha256 of the config in the internal_configHashon the document with the configuredid; carried over when service info with thatidis posted). Posted service info, with the same or anotherid, is therefore kept on restarts unless the config changes. Documents written by earlier versions that equal the config are kept and get the hash recorded.POST /service-inforeturns an empty 201 with only aLocationheader (noContent-Type).Location={url_prefix}://{host}:{port}/+api_path+ script root + request path.application/problem+jsonin the additions spec (follow-up from feat!: upgrade to FOCA 0.14.0 #65/feat!: upgrade to FOCA 0.14.0 #92).Closes #75
Breaking changes
idis required in posted service info.custom.endpoints.service.api_pathis now a path prefix in front of the API base path in public URLs (e.g., behind a reverse proxy), empty for none. It previously held the API base path itself (e.g.,ga4gh/registry/v1); deployments must remove that value.Verification
pytest: 84 passed (Python 3.10, offline); new tests for missingid, response headers, precedence (otherid, sameidplus restart, changed config), legacy documents (incl. legacy then POST), hidden internal fields, script root inLocation, problem+json errors, declaredLocationheader.ruff check,ruff format --check,mypy cloud_registry tests: clean.gitleaks dir .: no leaks.Open questions
None. Declined review findings:
idit asked for exists already._get_headersreadsrequest.path(documented: must be called in a request context); the expected-headers literal in mock data and YAML anchors in the spec were kept for readability.🤖 Generated with Claude Code