Skip to content

feat: sync services with their service info - #363

Merged
uniqueg merged 3 commits into
devfrom
feat/service-info-sync
Nov 5, 2026
Merged

uniqueg merged 3 commits into
devfrom
feat/service-info-sync

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Second part of #358: services can follow their service info, and clients can see whether they do.

  • PUT /services/{serviceId}/sync turns sync on after a successful fetch of {url}/service-info (or syncs at once if it is on); DELETE turns it off. For owners, maintainers and admins; limited like imports, with the same 502 for every failed fetch.
  • Syncs change descriptive fields and type, never id, url or roles, and keep the verification. On failure, the last values stay. While sync is on, PUT /services/{serviceId} with another url returns 409 (sync-url-locked).
  • GET /services/{serviceId}/sync and GET /syncs?status=… serve the label, computed when read: no label without sync, synced only if the last success is within two intervals, otherwise out-of-sync. Reasons are a fixed set; two retries within a cycle before unreachable counts.
  • Types follow the mode of the deployment as decided: open adds, moderated waits (version awaiting approval), controlled refuses (version not allowed); another group, artifact or id never creates a type (identity mismatch). Versions a sync leaves behind no longer count for the limit of unused types.
  • Scheduler: a daemon thread per worker, without Celery or incoming traffic. Workers and replicas claim due services in one atomic write (one indexed query per minute with a single worker). State is in the database, so restarts lose nothing; a dead worker's claim expires after 5 minutes.
  • Config: sync (on), sync_interval_hours (24), read by clients through registrationRules.serviceInfoSync.
  • Docs: API, configuration, access control, upgrade notes, release notes. They stress that verified and synced doesn't mean trusted, and recommend public service info.

Closes #360

Verification

  • CI on the final commit: all checks passed, including tests on mongomock and MongoDB 7.0, the smoke test, chart, docs, image scan and Sourcery. Two open Trivy notes for libapt-pkg come from dev.
  • Full suite with coverage locally (mongomock, Helm 3.22.1), before the last review round: 2269 passed, 11 skipped, 100%. After that round: tests/test_sync.py, tests/test_service_import.py, tests/test_namespace_subjects.py, ruff 0.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.
  • The CI smoke test inserts a due service and waits for the scheduler in the running image to report address not allowed.
  • Not run: against real public services.

Declined review findings

  • Clock patches instead of time.sleep(0.002) in tests: times have milliseconds, so 2 ms always differ.
  • Filtering GET /syncs?status= in the database: the label depends on the current time, and the list is small.
  • SyncedType as a StrEnum: its values are never served.
  • Sourcery: making the release of a left type atomic (the outcome is only a slightly more lenient limit); an atomic reservation of the limit (registrations check and store the same way); comparing stored types case-insensitively (they compare as written, as for registrations).

Known limits

  • Reasons are public, as decided, so whoever controls a host name can point it elsewhere after turning sync on and learn whether a name resolves to a public address: one probe per service and interval. docs/configuration.md says so and how to restrict the reads.

🤖 Generated with Claude Code

uniqueg and others added 3 commits November 5, 2026 03:02
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]>
@sourcery-ai

sourcery-ai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Enables 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 sync

sequenceDiagram
    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
Loading

State diagram for service sync lifecycle

stateDiagram-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
Loading

Flow diagram for scheduler claims and sync outcomes

flowchart 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
Loading

File-Level Changes

Change Details Files
Adds service-info synchronization lifecycle and status APIs with access control, failure semantics, identity checks, and URL locking.
  • Introduces PUT, DELETE, and GET service sync endpoints plus GET /syncs.
  • Fetches service info before enabling sync and preserves prior values on failed background attempts.
  • Restricts synchronized updates to descriptive fields and compatible types while preserving identity, roles, and verification.
  • Prevents URL changes while synchronization is enabled and exposes sync-related conflict codes.
cloud_registry/ga4gh/registry/sync.py
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/service.py
cloud_registry/ga4gh/registry/service_import.py
cloud_registry/api/additions.openapi.yaml
cloud_registry/api/patches/login-for-reads.yaml
cloud_registry/config.yaml
Implements database-backed background scheduling across workers and replicas without request or task-queue involvement.
  • Starts a daemon scheduler thread per worker and caps due times on startup.
  • Atomically claims due services using an indexed next-attempt field with five-minute claim expiry.
  • Stores attempts, successes, retries, failure reasons, and next attempts in service state so restarts retain progress.
  • Retries unreachable services within a cycle and computes synced/out-of-sync labels at read time.
cloud_registry/ga4gh/registry/sync.py
cloud_registry/app.py
cloud_registry/config.yaml
Integrates synchronized service types with registration policies and client-visible deployment configuration.
  • Applies new versions according to open, moderated, and controlled type modes.
  • Rejects identifier or group/artifact mismatches and manages unused-type accounting for synced services.
  • Publishes sync enablement and interval through registrationRules.serviceInfoSync.
  • Excludes service-owned type subjects from namespace migration handling.
cloud_registry/ga4gh/registry/service_types.py
cloud_registry/ga4gh/registry/service_info.py
cloud_registry/namespace_subjects.py
cloud_registry/service_models/custom_config.py
Documents and validates the synchronization feature across API behavior, operations, security, and end-to-end execution.
  • Documents endpoints, statuses, reasons, trust limitations, configuration, access control, upgrades, and release notes.
  • Adds broad unit and integration coverage for concurrency, type policy, retries, scheduler behavior, and real HTTP fetching.
  • Extends CI smoke coverage to verify scheduler activity without incoming traffic.
tests/test_sync.py
tests/test_namespace_subjects.py
tests/ga4gh/registry/test_service_info.py
tests/test_app.py
.github/workflows/ci.yml
docs/api.md
docs/configuration.md
docs/access-control.md
docs/upgrading.md
docs/releases/1.0.0rc2.md

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 Nov 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (0db1b0c) to head (b120b1e).
⚠️ Report is 1 commits behind head on dev.

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.
📢 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 November 5, 2026 02:20

@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 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


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

@uniqueg
uniqueg merged commit db14ffc into dev Nov 5, 2026
44 checks passed
@uniqueg
uniqueg deleted the feat/service-info-sync branch November 5, 2026 02:38
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.

feat: sync service info periodically

1 participant