Skip to content

refactor!: remove duplicated and unused code - #95

Merged
uniqueg merged 4 commits into
devfrom
refactor/cleanup
Oct 20, 2026
Merged

uniqueg merged 4 commits into
devfrom
refactor/cleanup

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Remove duplicated and unused code (closes #74). #94 already added the collection helper (cloud_registry/utils.py), %-style logging and model_dump().

  • POST and PUT /services and POST /service-info share the request body check. POST and PUT also share the registration (_register_service).
  • GET /services/types computes the distinct types in MongoDB ($group and $sort). It returns them sorted by group, artifact and version; before, the order changed between calls. This also removes the getServices.__wrapped__ call and its type: ignore.
  • GET /services/{serviceId} uses a projection instead of deleting _id.
  • Removed unused code:
    • ValidationError
    • RegisterService.was_replaced
    • MetaVersionConfig and the meta_version config key
    • the config file check in app.py (FOCA raises an OSError naming the file)
  • Fully qualified module paths:
    • cloud_registry.service_models.custom_config.CustomConfig
    • x-openapi-router-controller: cloud_registry.ga4gh.registry.server
    • x-bearerInfoFunc: foca.security.auth.validate_token, the same function that app.py re-exported
  • The image starts the app with python -m cloud_registry.app; Compose and Helm use the image's command. The tests no longer add cloud_registry/ to sys.path.
  • get_custom_config() checks the type of the custom config instead of casting it.
  • deployment/README.md: a corrected upgrade procedure (see "Breaking changes").

Breaking changes

  • custom.endpoints.services.meta_version is removed. FOCA config models forbid unknown keys, so custom configs that still set it are rejected at startup. The key was never read.
  • Configs must use the new module paths above, because the app no longer runs from inside cloud_registry/.
  • Helm: the app-config ConfigMap is generated once, by a plain Job, from the config in the image. Helm resets it to its empty placeholder on every helm upgrade, and a changed image makes the Job update fail. The README now says to delete the Job before every upgrade and wait for it. This applies after feat!: upgrade to FOCA 0.14.0 #92 (FOCA 0.14) already, which changed the config format too. Running the Job as a Helm hook belongs to Helm chart: configure app via values and FOCA overlays #67.

Verification

  • pytest: 75 passed (Python 3.10, FOCA 0.14.0). New tests:
    • the types are returned in the same, sorted order, by group, then artifact, then version;
    • the missing config error names the file.
    • The order tests fail on the old code.
  • ruff, mypy, ast-grep: pass.
  • Adversarial review:
    • Checked the types aggregation against MongoDB 7.0 and mongomock: missing fields, null, mixed key order. The results are the same as before for data stored through the API; extra keys inside type are rejected by the spec.
    • Started the app from outside the repo with the old config (fails: meta_version, then module paths) and the new one (starts).
    • Checked that foca.security.auth.validate_token is the same function as before.
  • Maintainability review: its findings are applied (shared body check, sort-order test, error messages).
  • Both reviews, 2 rounds each.

Not verified: the Helm procedure on a cluster: there is no cluster here. It is derived from the chart, update-config-map.sh and Helm 3's three-way merge.

Notes

  • Declined: sharing the custom_config_model string between app.py and the test fixture. The fixture spelling it out also tests the path.

🤖 Generated with Claude Code

Summary by Sourcery

Refactor duplicated service handling and remove obsolete configuration and runtime code while standardizing application startup and deployment configuration.

Bug Fixes:

  • Make service-type listings deterministic by returning distinct types sorted by group, artifact, and version.

Enhancements:

  • Consolidate shared request validation and service registration paths.
  • Remove obsolete validation, replacement-state, and metadata-version code.
  • Use fully qualified module paths and type-check custom configuration loading.
  • Run the application as a Python module and simplify database response handling.

Build:

  • Update the container entrypoint to launch the application with its module path.

Deployment:

  • Document the required Helm upgrade procedure for regenerating the application configuration Job and ConfigMap.

Documentation:

  • Document the revised Helm upgrade workflow and related upgrade requirements.

Tests:

  • Add coverage for deterministic service-type ordering and missing configuration errors.

uniqueg and others added 4 commits October 20, 2026 07:04
- POST and PUT /services share one function
- GET /services/types computes the distinct types in MongoDB and
  returns them sorted by group, artifact and version (the order used
  to change between calls)
- GET /services/{serviceId} uses a projection instead of deleting `_id`
- Remove unused code: `ValidationError`, `RegisterService.was_replaced`,
  the `meta_version` config and `MetaVersionConfig`, and the config
  file check in `app.py` (FOCA raises an `OSError` itself)
- Use fully qualified module paths in `app.py` and `config.yaml`, so
  that the app runs as an installed package; the image starts it with
  `python -m cloud_registry.app`
- `get_custom_config()` checks the type of the custom config, which is
  now imported under its own module path

BREAKING CHANGE: the `custom.endpoints.services.meta_version` config key
is removed; custom configs that still set it are rejected.

Closes #74

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- POST /service-info uses the same JSON object check as POST and PUT
  /services
- Test the sort order of service types by group and version too
- Test the missing config error by its path
- Explain why the custom config type check needs the full model path

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The configmap Job generates the app config only at installation, so a
new config format (FOCA 0.14, no `meta_version`, module paths) needs
the Job to run again before the app restarts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Helm resets the generated app config on every upgrade and cannot
update the configmap Job when the image changes, so the Job must be
deleted before every upgrade, not only for config format changes.
Also name `custom_config_model` in the custom config type error.

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

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR removes duplicated endpoint logic and unused configuration/state, replaces service-type computation with deterministic MongoDB aggregation, and standardizes package-qualified startup and configuration loading. Tests cover stable type ordering and configuration error reporting, while deployment documentation reflects the required Helm upgrade procedure.

Sequence diagram for shared service registration endpoints

sequenceDiagram
    participant Client
    participant API as Registry API
    participant RegisterService
    participant MongoDB

    Client->>API: POST /services
    API->>API: _register_service()
    API->>API: _get_request_object()
    API->>RegisterService: RegisterService(data, id=None)
    RegisterService->>MongoDB: register_metadata()
    API-->>Client: service id

    Client->>API: PUT /services/{serviceId}
    API->>API: _register_service(service_id)
    API->>API: _get_request_object()
    API->>RegisterService: RegisterService(data, id=serviceId)
    RegisterService->>MongoDB: register_metadata()
    API-->>Client: service id

    Client->>API: POST /service-info
    API->>API: _get_request_object()
    API->>RegisterService: RegisterServiceInfo.set_service_info_from_app_context(data)
    API-->>Client: 201 response
Loading

Flow diagram for deterministic service type listing

flowchart LR
    Request[GET /services/types] --> Aggregate[MongoDB aggregate]
    Aggregate --> Group[$group by type.group, artifact, version]
    Group --> Sort[$sort by group, artifact, version]
    Sort --> Response[Return distinct sorted types]
Loading

File-Level Changes

Change Details Files
Consolidate service endpoint request validation and registration while removing obsolete state and exception code.
  • Centralize JSON-object validation for service-info and service registration requests.
  • Share registration logic between POST and PUT service endpoints.
  • Remove unused replacement tracking, validation exception, and related documentation/tests.
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/service.py
cloud_registry/ga4gh/registry/service_info.py
cloud_registry/exceptions.py
tests/ga4gh/registry/test_service.py
Make service type retrieval deterministic and avoid in-memory endpoint recursion.
  • Replace the wrapped GET-services call with a MongoDB aggregation that groups distinct type fields.
  • Sort results by group, artifact, and version in the database.
  • Use a MongoDB projection to omit IDs from single-service responses.
cloud_registry/ga4gh/registry/server.py
tests/ga4gh/registry/test_server.py
tests/test_app.py
Modernize application startup and configuration loading for package-qualified imports.
  • Run the application as the cloud_registry.app module.
  • Update custom config, router controller, and authentication function paths to fully qualified modules.
  • Validate that the loaded custom configuration is the expected type and remove the obsolete meta_version configuration model/key.
Dockerfile
cloud_registry/app.py
cloud_registry/config.yaml
cloud_registry/service_models/custom_config.py
cloud_registry/utils.py
tests/conftest.py
tests/mock_data.py
tests/test_utils.py
tests/test_app.py
Align deployment tooling documentation with the image command and Helm configuration-generation lifecycle.
  • Document deleting the existing ConfigMap Job before upgrades and waiting for completion afterward.
  • Clarify the image-provided configuration and app-name-dependent Job naming.
deployment/README.md

Assessment against linked issues

Issue Objective Addressed Explanation
#74 Centralize collection-client lookups and consolidate the shared request validation and service-registration logic for POST and PUT. ✅
#74 Return distinct service types in a stable order and use a database projection to omit _id when fetching a service by ID. ✅
#74 Remove the identified dead code and modernize configuration, startup, logging, and model serialization for package-based app startup. ❌ The PR removes the listed unused configuration and state, updates module paths and startup, and the PR body says logging and model_dump() were handled in #94. However, the diff does not remove the explicitly identified unused import string # noqa: F401 from service.py, so this objective is not fully met.

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 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (3d3d843) to head (2521cf2).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev       #95   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            7         7           
  Lines          225       204   -21     
=========================================
- Hits           225       204   -21     

☔ 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 20, 2026 05:11

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

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="deployment/README.md" line_range="30" />
<code_context>
+   `deployment` folder:
 ```
+kubectl delete job configmap-job-<appName> -n namespace
 helm upgrade cloud-registry . -n namespace
+kubectl wait --for=condition=complete --timeout=5m job/configmap-job-<appName> -n namespace
 ```
</code_context>
<issue_to_address>
**Upgrade can restart app with empty config**

When an upgrade changes the image or otherwise triggers a Deployment rollout before the config Job has patched `app-config`, helm rolls out the changed Deployment while the ConfigMap still contains its placeholder, so FOCA rejects the mounted config and the app pods fail startup until the Job patches the ConfigMap and deletes them. The upgrade therefore causes an outage during the configuration step.

Make the config Job complete before the Deployment rolls out, for example by using an appropriately ordered Helm hook or a staged upgrade procedure that waits for the Job before updating the Deployment.
</issue_to_address>

### Comment 2
<location path="deployment/README.md" line_range="31" />
<code_context>
 ```
+kubectl delete job configmap-job-<appName> -n namespace
 helm upgrade cloud-registry . -n namespace
+kubectl wait --for=condition=complete --timeout=5m job/configmap-job-<appName> -n namespace
 ```
 `namespace` is the name of the namespace where the cluster was installed.
</code_context>
<issue_to_address>
**Upgrade reports success with stale config**

When the Kubernetes API rejects or fails to apply the ConfigMap PATCH during an upgrade, `update-config-map.sh` does not check the ConfigMap PATCH result, so it continues to delete app pods and exits successfully even when the patch fails. The Job then completes and this wait succeeds while `app-config` still contains Helm’s placeholder, leaving the restarted pods unable to load configuration.

Make the script fail when the PATCH is unsuccessful and verify the ConfigMap update before reporting Job success.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: deployment/README.md:30, deployment/README.md:31


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

Comment thread deployment/README.md Resolved
Comment thread deployment/README.md Resolved
@uniqueg
uniqueg merged commit 85af437 into dev Oct 20, 2026
10 checks passed
@uniqueg
uniqueg deleted the refactor/cleanup branch October 20, 2026 05:15
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.

Refactor: remove duplicated and unused code

1 participant