Repository navigation
feat: sync services with their service info - #363
Conversation
PUT /services/{serviceId}/sync turns it on after a successful fetch. A
daemon thread per worker syncs due services, without a task queue or
incoming requests; workers and replicas share the work by claiming
services in the database. Syncs change descriptive fields and type,
never the identifier, the URL or the roles, and keep the verification.
While sync is on, the URL can't change.
GET /services/{serviceId}/sync and GET /syncs serve the label, computed
when read, and a reason from a fixed set. New types follow the mode of
the deployment.
Refs #360
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Turning sync on fails if the service changed during the fetch, so that sync never starts for a URL that wasn't fetched. Syncs only write if the service is unchanged since the claim, as the fetched values may no longer fit. A new URL ends sync, should the deployment's sync be off. Services of admins get a limit of unused types of their own, as service info could add types without end otherwise. Identifiers that can't be stored return 400. Rules and docs brought up to date. Refs #360 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Versions that a sync leaves behind no longer count for the limit of unused types, so that releases don't stop syncs. Migrations leave the identifiers of services alone. A change during the first fetch returns 409, as the docs say. Refs #360 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideEnables registered services to stay synchronized with their public service-info documents through protected lifecycle APIs and a database-coordinated background scheduler, while preserving service identity and verification, applying type-policy rules, exposing computed sync health to clients, and documenting the operational and trust implications. Sequence diagram for enabling and applying service-info syncsequenceDiagram
actor Owner
participant API
participant ServiceInfo
participant Database
Owner->>API: PUT /services/{serviceId}/sync
API->>ServiceInfo: fetch_service_info()
ServiceInfo-->>API: service-info document
API->>API: service_values()
API->>API: decide_synced_type()
API->>Database: enable sync and apply fields
Database-->>API: sync state
API-->>Owner: Sync status
loop Every sync interval
API->>Database: _claim()
Database-->>API: due service claim
API->>ServiceInfo: fetch_service_info()
ServiceInfo-->>API: service-info document
API->>API: sync_service()
API->>Database: _write() fields and sync state
end
State diagram for service sync lifecyclestateDiagram-v2
[*] --> NoSync
NoSync --> SyncEnabled: PUT /services/{serviceId}/sync
SyncEnabled --> Synced: successful _apply()
SyncEnabled --> OutOfSync: failed fetch or rejected service info
Synced --> Synced: sync_service() succeeds
Synced --> OutOfSync: _failed() or stale lastSuccessAt
OutOfSync --> Synced: sync_service() succeeds
SyncEnabled --> NoSync: DELETE /services/{serviceId}/sync
Synced --> NoSync: DELETE /services/{serviceId}/sync
OutOfSync --> NoSync: DELETE /services/{serviceId}/sync
Flow diagram for scheduler claims and sync outcomesflowchart TD
A[Scheduler thread] --> B["_claim() due service"]
B -->|No service| C[Wait for next tick]
B -->|Claimed| D["sync_service()"]
D --> E{Fetch result}
E -->|Success| F["_apply()"]
E -->|Unreachable| G["_unreachable()"]
E -->|AddressNotAllowed or InvalidService| H["_failed()"]
G -->|Retries remain| C
G -->|Retries exhausted| H
F --> I[Write values and nextAttemptAt]
H --> J[Keep last values and record reason]
I --> C
J --> C
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 #363 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 25 26 +1
Lines 2874 3135 +261
==========================================
+ Hits 2874 3135 +261 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="620-624" />
<code_context>
+ user: Identifier that the service counts for (cf. `decide_synced_type()`).
+ """
+ stored = {field: service_type[field] for field in TYPE_FIELDS}
+ if get_collection("services").find_one(_services_of_type(stored), {"_id": True}):
+ return
+ get_collection("service_types").update_one(
+ {**stored, CREATED_BY: user, PENDING: {"$ne": True}},
+ {"$set": {CREATED_BY: None}},
+ )
+
</code_context>
<issue_to_address>
**In-use type loses its owner**
When a service registers with the old type after the usage check but before `release_left_type()` updates its creator, `release_left_type()` clears `createdBy` despite the new service using the type, so if the type later becomes unused it no longer counts against the original user's limit.
Make the usage check and creator update safe against a concurrent service registration.
</issue_to_address>
### Comment 2
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="601-604" />
<code_context>
+ if access_control.service_types == "controlled" or limit == 0:
+ return SyncedType.NOT_ALLOWED
+ if limit is not None and _count_unused_types(user, limit) >= limit:
+ return SyncedType.LIMIT
+ pending = access_control.service_types == "moderated"
+ store_service_type(service_type, created_by=user, pending=pending)
+ # the state stored, as another request may have added it meanwhile
+ return SyncedType.PENDING if is_pending(service_type) else SyncedType.APPROVED
+
</code_context>
<issue_to_address>
**Concurrent syncs exceed type limit**
When two syncs for one user encounter distinct new types while only one quota slot remains, `decide_synced_type()` checks the unused-type count before storing the type in a separate operation, so both syncs pass the check and store a type, exceeding the configured limit.
Make checking and reserving a user's type quota atomic across concurrent syncs.
</issue_to_address>
### Comment 3
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="589-590" />
<code_context>
+ in mode `moderated`, or can't be added: in mode `controlled`, or if the
+ limit is `0` (`NOT_ALLOWED`), or as the user is at the limit (`LIMIT`).
+ """
+ stored = get_collection("service_types").find_one(
+ dict(service_type), {"_id": False, PENDING: True}
+ )
+ if stored is not None:
</code_context>
<issue_to_address>
**Case changes reject registered types**
When service info changes only the casing of a registered type's group or artifact in controlled or moderated mode, `decide_synced_type()` uses an exact, case-sensitive type lookup, so controlled mode reports `version not allowed` and moderated mode creates a redundant pending type.
Match registered types case-insensitively for group and artifact, consistent with service identity.
Also at `cloud_registry/ga4gh/registry/sync.py:382`.
</issue_to_address>Linked issues
#360 feat: sync service info periodically · 8 of 8 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Provide GET, PUT and DELETE /services/{serviceId}/sync, and GET /syncs filtered by label. | ✅ Met | The endpoints and status filter are implemented and documented. |
| 2 | Run syncs in the background without Celery or incoming traffic, coordinate workers and replicas, and behave sensibly on restart. | ✅ Met | A per-worker daemon scheduler claims due services atomically in the database; persisted scheduling state and expiring claims support restarts. |
| 3 | Sync descriptive fields and type, never id, URL or owners; keep verification; retain the last values on failure. | ✅ Met | The sync applies only the declared synced fields and leaves identity, roles and verification unchanged; failures record state without applying fetched values. |
| 4 | Apply new service types according to open, moderated and controlled modes, and never create a type for another group, artifact or id. | ✅ Met | Type handling follows those modes, while identifier and API-type mismatches are rejected before adding a type. |
| 5 | Reject URL changes while sync is on. | ✅ Met | Service updates check the sync lock during validation and again when writing, including for concurrent changes. |
| 6 | Compute labels at read time, with no label without sync, synced only within two intervals of the last success, and out-of-sync otherwise; use fixed reasons and retry before counting unreachable failures. | ✅ Met | Read endpoints compute the label from sync state and interval; unreachable failures are recorded only after the configured retries. |
| 7 | Configure sync on or off (default on) and its interval (default 24 hours), and serve these settings in the service info. | ✅ Met | Both settings are configurable and exposed as registrationRules.serviceInfoSync. |
| 8 | Document the API, configuration and upgrades, and stress that verified and synced does not mean trusted. | ✅ Met | The API, configuration and upgrading docs cover sync; the API docs explicitly leave trust decisions to users. |
Sourcery assessment
Needs a human reviewer. 3 findings to address first, and the scheduler repeatedly fetches service-controlled URLs and exposes fixed failure reasons, so a registrant who can redirect a hostname may probe reachability on networks the deployment allows. Reverting stops future fetches, but cannot undo probes or information already observed, and it does not restore service fields or types already changed by sync.
Blocking findings: cloud_registry/ga4gh/registry/service_types.py:624, cloud_registry/ga4gh/registry/service_types.py:604, cloud_registry/ga4gh/registry/service_types.py:590
Summary
Second part of #358: services can follow their service info, and clients can see whether they do.
PUT /services/{serviceId}/syncturns sync on after a successful fetch of{url}/service-info(or syncs at once if it is on);DELETEturns it off. For owners, maintainers and admins; limited like imports, with the same502for every failed fetch.type, neverid,urlor roles, and keep the verification. On failure, the last values stay. While sync is on,PUT /services/{serviceId}with anotherurlreturns409(sync-url-locked).GET /services/{serviceId}/syncandGET /syncs?status=…serve the label, computed when read: no label without sync,syncedonly if the last success is within two intervals, otherwiseout-of-sync. Reasons are a fixed set; two retries within a cycle beforeunreachablecounts.openadds,moderatedwaits (version awaiting approval),controlledrefuses (version not allowed); another group, artifact oridnever creates a type (identity mismatch). Versions a sync leaves behind no longer count for the limit of unused types.sync(on),sync_interval_hours(24), read by clients throughregistrationRules.serviceInfoSync.Closes #360
Verification
libapt-pkgcome fromdev.tests/test_sync.py,tests/test_service_import.py,tests/test_namespace_subjects.py,ruff0.17.3,mypy,mkdocs build --strict.tests/test_sync.py::test_scheduler_end_to_end: the real scheduler thread syncs a local HTTP service without any request.address not allowed.Declined review findings
time.sleep(0.002)in tests: times have milliseconds, so 2 ms always differ.GET /syncs?status=in the database: the label depends on the current time, and the list is small.SyncedTypeas aStrEnum: its values are never served.Known limits
docs/configuration.mdsays so and how to restrict the reads.🤖 Generated with Claude Code