Skip to content

feat: register and control service types - #241

Merged
uniqueg merged 4 commits into
devfrom
feat/service-types
Oct 25, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/service-types

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Service types get their own collection (service_types, unique on group, artifact and version as written), and deployments configure who may add them.

  • GET /services/types lists the stored types, sorted.
  • POST /services/types adds a type (201; 409 if it is registered). The user who added it is stored with it (created_by), but not served.
  • DELETE /services/types?group=...&artifact=...&version=... removes a type: admins only, in every mode (no policy for other users). It is refused with 409 ("Service type is in use. If you really want to revoke it, edit or delete all services that depend on it.") while a service has the type, also if a service gets it during the removal (then the type is stored again).
  • Registering or updating a service stores its type.
  • New option custom.access_control.service_types:
    • open (default, the previous behaviour): any authenticated user may add types.
    • controlled: only admins may add types; services of other users must have a registered type (400, naming it).
  • GET /me returns may_add_service_types, so that UIs can offer adding types.
  • On startup, the app stores the types of registered services (idempotent), so nothing disappears on upgrade.
  • Docs: api.md (Service types), configuration.md (Service types), access-control.md (Current user), upgrading.md (Service types: restart after a rolling update; list-style policy overlays must add add-service-types).
  • CI smoke test: stores the type of the service it inserts, and checks that POST /services/types needs a login.

Closes #235

Decisions

  • DELETE via query parameters: Connexion 2 passes no request body to DELETE handlers, and RFC 9110 gives DELETE bodies no defined meaning.
  • Exact matching: types are compared as written (no case folding), like the existing GET /services/types.
  • created_by is not served: it is internal (e.g., for audits); types added on startup have none. A registration in progress while an admin removes its type stores the type again; it is then stored without the user if they may not add types (documented in the module).
  • Not breaking: the default mode open keeps the previous behaviour; requests that worked before still work.

Verification

  • pre-commit run --all-files: all passed.
  • pytest (mongomock): 1180 passed, 228 skipped (Helm chart tests; Helm isn't installed locally), 100% coverage.
  • pytest against MongoDB 7.0.34: all passed.
  • mkdocs build --strict: passed.
  • Review: two rounds of the adversarial and quality reviewers; findings fixed except those below.

Declined review findings

  • Per-type lock against a removal racing a registration (adversarial, low): the invariant (every type of a service is stored) holds; the type is stored again without the user. A lock or version counter isn't worth it here; documented instead.
  • Re-seeding types outside startup for rolling updates (adversarial, low): documented a restart after the rollout instead, as for add_service_keys.
  • Deriving may_add_service_types from the casbin policy (adversarial, low): the mode option is the supported control; the docs and the config comment say to keep the policy.
  • Return 404 as a problem response instead of raising NotFound (quality, low): raising NotFound is the repo's convention (e.g., verification.py).
  • Inline the response aliases and IN_USE; frozenset in add_service_types (quality, low): readability only.
  • "since 0.5.0" in upgrading.md (quality): kept, as this targets 0.5.0.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Introduce persistent service-type management with configurable registration access and safeguards for services that depend on registered types.

New Features:

  • Add persistent service-type registration with public listing, authenticated creation, and admin-only removal.
  • Support configurable open or controlled access to adding service types, including validation of service registrations and may_add_service_types in GET /me.

Bug Fixes:

  • Preserve service types across upgrades by seeding stored services' types at startup and preventing removal of types used by services.

Enhancements:

  • Track the user who registered each service type internally while keeping that metadata out of API responses.
  • Document service-type management, configuration, access control, and upgrade behavior.

CI:

  • Update the MongoDB smoke test to seed a service type and verify unauthenticated type registration is rejected.

Documentation:

  • Document the service-type API, access-control option, current-user capability, and rolling-upgrade considerations.

Tests:

  • Add coverage for service-type registration, validation, access modes, lifecycle, concurrency, startup migration, and configuration.

uniqueg and others added 3 commits October 25, 2026 21:35
Service types are stored in their own collection (service_types),
unique as written, with the user who added them (created_by, not
served). GET /services/types lists the stored types. POST
/services/types adds one; DELETE /services/types (type named by query
parameters, as Connexion passes no DELETE bodies) removes one, for
admins only in every mode, and is refused with 409 while services have
the type. Registering or updating a service stores its type.

The new option custom.access_control.service_types sets who may add
types: open (the default, the previous behaviour) lets any
authenticated user add them; controlled lets only admins add them, and
services of other users must have a stored type (400, naming it).
GET /me tells clients whether they may add types
(may_add_service_types).

On startup, the app stores the types of registered services
(idempotent), so nothing disappears on upgrade. The smoke test stores
the type of the service it inserts.

Closes #235

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Store types re-added by registrations without the user if they may not
add types, simplify the removal of types, and document that overlays
must keep the add-service-types rule and that rolling updates need a
restart to store all types. Test the mode setting of service types.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Test that types not stored are not found, and that types that services
have can't be removed, also if they aren't stored; tidy docstrings.

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

sourcery-ai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR introduces a persistent, independently managed service-type registry, integrates type storage and validation into service registration and updates, adds open versus admin-controlled access modes with /me capability reporting, protects deletion while types are in use, migrates existing service types at startup, and updates documentation and test coverage accordingly.

Sequence diagram for controlled service registration

sequenceDiagram
    actor User
    participant API
    participant Access as AccessControl
    participant Types as ServiceTypeRegistry
    participant Services as ServicesCollection

    User->>API: POST /services
    API->>Access: may_add_service_types()
    Access-->>API: false
    API->>Types: check_service_type(type)
    Types->>Types: service_type_exists(type)
    alt type not registered
        Types-->>API: UnregisteredServiceType
        API-->>User: 400 Bad Request
    else type registered
        Types-->>API: allowed
        API->>Services: register service
        API->>Types: store_service_type(type)
        API-->>User: 201 Created
    end
Loading

Sequence diagram for protected service-type removal

sequenceDiagram
    actor Admin
    participant API
    participant Types as ServiceTypeRegistry
    participant Services as ServicesCollection

    Admin->>API: DELETE /services/types?group=...&artifact=...&version=...
    API->>Types: _type_in_use(type)
    alt service uses type
        Types->>Services: count matching services
        Services-->>Types: in use
        Types-->>API: Conflict
        API-->>Admin: 409 Conflict
    else type unused
        Types->>Types: find_one_and_delete(type)
        Types->>Services: _type_in_use(type)
        alt registration raced with removal
            Types->>Types: store_service_type(type)
            Types-->>API: Conflict
            API-->>Admin: 409 Conflict
        else no service uses type
            API-->>Admin: removed type
        end
    end
Loading

Entity relationship diagram for service types

erDiagram
    SERVICES {
        string service_id
        object type
    }
    SERVICE_TYPES {
        string group
        string artifact
        string version
        string created_by
    }
    SERVICES }o--|| SERVICE_TYPES : uses
Loading

File-Level Changes

Change Details Files
Adds a persistent service-type registry with public listing, authenticated creation, and admin-only deletion APIs.
  • Introduces the service_types collection with a unique compound index and internal created_by metadata.
  • Moves GET /services/types from deriving types from services to sorted collection reads.
  • Adds POST and DELETE handlers with validation, duplicate/not-found handling, admin enforcement, and in-use conflict protection.
  • Handles deletion/registration races by restoring a type when a concurrent service begins using it.
cloud_registry/ga4gh/registry/service_types.py
cloud_registry/ga4gh/registry/server.py
cloud_registry/api/additions.openapi.yaml
cloud_registry/config.yaml
Introduces configurable access control for adding service types and enforces it during service lifecycle operations.
  • Adds custom.access_control.service_types with open and controlled modes, defaulting to open.
  • Allows admins or permitted users to add types explicitly or through service registration/update; restricts other users in controlled mode to already registered types.
  • Exposes may_add_service_types through GET /me.
  • Keeps the existing policy rule for POST authorization while documenting configuration and policy-overlay requirements.
cloud_registry/service_models/custom_config.py
cloud_registry/ga4gh/registry/permissions.py
cloud_registry/ga4gh/registry/server.py
cloud_registry/config.yaml
cloud_registry/api/additions.openapi.yaml
Preserves service-type registrations across existing data and concurrent service changes.
  • Stores each valid service type after service registration or update.
  • Seeds missing types from existing services during application startup in an idempotent migration.
  • Retains type registrations after their services are removed until an administrator explicitly revokes them.
cloud_registry/app.py
cloud_registry/ga4gh/registry/service_types.py
cloud_registry/ga4gh/registry/server.py
Expands API, operational, and upgrade documentation for service-type management.
  • Documents endpoints, exact matching, authorization modes, deletion behavior, and in-use conflicts.
  • Documents /me capability reporting and startup migration behavior.
  • Documents rolling-update restart requirements and policy-list overlay changes.
docs/api.md
docs/configuration.md
docs/access-control.md
docs/upgrading.md
cloud_registry/api/additions.openapi.yaml
Extends automated coverage and MongoDB smoke validation for the new persistence and authorization behavior.
  • Adds unit and integration tests for validation, sorting, metadata, access modes, lifecycle behavior, concurrency, and startup migration.
  • Updates test collection/index setup for the new compound index.
  • Seeds service-type data and verifies unauthenticated POST rejection in CI.
tests/ga4gh/registry/test_service_types.py
tests/test_service_types.py
tests/conftest.py
tests/mock_data.py
tests/test_access_control.py
tests/service_models/test_custom_config.py
.github/workflows/ci.yml

Assessment against linked issues

Issue Objective Addressed Explanation
#235 Persist service types independently of services, expose APIs to list, register, and remove them, migrate types from existing services, and prevent removal while a service uses a type. ✅
#235 Support open and controlled policies for adding types, enforce the controlled policy for service registration and updates, and report the caller's ability to add types through GET /me. ✅
#235 Restrict type removal to admins in every mode, document the behavior and configuration, and preserve compatibility by defaulting to the existing open behavior. ✅

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 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (bed9298) to head (41c933f).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #241    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           16        17     +1     
  Lines         1375      1480   +105     
==========================================
+ Hits          1375      1480   +105     

☔ 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 25, 2026 21:28

@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/server.py" line_range="261-264" />
<code_context>
         return problem(exc.hidden())
+    # also if the type was removed concurrently, as a service has it now;
+    # without the user if they may not add types (only then)
+    service_type = type_document(service.data["type"])
+    if service_type is not None:
+        created_by = get_current_subject() if may_add_service_types() else None
+        store_service_type(service_type, created_by=created_by)
     if service.verification_removed:
         logger.info(
</code_context>
<issue_to_address>
**Failed writes leave partial service state**

When the service write succeeds but the subsequent service-type write or restore fails, `store_service_type` propagates the database error after `register_metadata` commits the service, so `_register_service` returns an error before type and owner setup completes. The service remains persisted without the expected type or owner assignment, and callers see a failed request despite the persisted change.

Make service persistence, service-type storage or restoration, and owner setup atomic, or roll back or complete the changes before returning an error.

Also at `cloud_registry/ga4gh/registry/service_types.py:321`.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="314-322" />
<code_context>
+        cloud_registry.exceptions.NotFound: The type is not stored.
+    """
+    document = {"group": group, "artifact": artifact, "version": version}
+    if _type_in_use(document):
+        return problem(Conflict(IN_USE))
+    removed = get_collection("service_types").find_one_and_delete(dict(document))
+    if removed is None:
</code_context>
<issue_to_address>
**Deleted types remain in use**

When a registration passes its type check, then writes its service after `deleteServiceType`'s second usage check, `deleteServiceType` finishes its usage check and returns success before the registration writes its service and `store_service_type` recreates the type, so the caller sees a successful removal even though the type remains in use.

Coordinate registration and deletion so the type cannot be recreated after the deletion check and before registration completes.

Also at `cloud_registry/ga4gh/registry/server.py:235-264`.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="139" />
<code_context>
+        written).
+    """
+    query = {f"type.{field}": value for field, value in service_type.items()}
+    return get_collection("services").count_documents(query, limit=1) > 0
+
+
</code_context>
<issue_to_address>
**Type removal scans all services**

When the registry has many services and an admin removes a type, `_type_in_use` filters on the three nested `type` fields, but the services collection has no index on them. MongoDB therefore scans the services collection for each removal check, making the admin delete request increasingly slow as the registry grows.

Add a compound index on `type.group`, `type.artifact`, and `type.version` to the services collection.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and a registration or explicit type addition writes a persistent, publicly listed service-type record; reverting the code does not remove those records. They are generally repairable by an admin, though types used by services require those services to be changed or deleted first.

Blocking findings: cloud_registry/ga4gh/registry/server.py:264, cloud_registry/ga4gh/registry/service_types.py:322, cloud_registry/ga4gh/registry/service_types.py:139


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

Comment thread cloud_registry/ga4gh/registry/server.py Resolved
Removals of service types check whether a service has the type; index
the type fields of services so that this doesn't scan all services.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit df986fc into dev Oct 25, 2026
19 checks passed
@uniqueg
uniqueg deleted the feat/service-types branch October 25, 2026 21:43
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: register and control service types

1 participant