Repository navigation
feat: limit services per user - #286
Conversation
Users other than admins may only have registered `custom.access_control.max_services_per_user` of the registered services (default 50, `null` for no limit, `0` for admins only); further `POST /services` get `409` with code `services-limit`. Services count for the user who registered them, stored in the hidden field `_createdBy` (kept on updates and renames, not served; `null` for services registered by admins in admin mode). A counter per user (collection `service_counts`) is reserved with an atomic conditional `$inc` before the service is stored, released on failed registrations and on deletes, so concurrent registrations can't exceed the limit. On startup, the app adds the user to services stored before (the only user owner, if any) and reconciles the counters. The limit is published in the registration rules of the service info, and documented in the configuration, access control, API and upgrade docs. Closes #124 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # cloud_registry/config.yaml # cloud_registry/service_models/custom_config.py # docs/configuration.md # docs/upgrading.md
- Concurrent first registrations of a user no longer get a spurious `services-limit`: a counter inserted by a concurrent request is incremented by a retry without upsert (MongoDB doesn't retry upserts whose filter isn't the key alone). - The subject migration (`namespace_subjects`) namespaces `_createdBy` of services and moves the counters of bare users. - Deletes use `find_one_and_delete`: the tests that hook into deletes of services follow it (they failed on real MongoDB only). - The limit's detail no longer claims a count the user may not have (e.g., with a limit of `0`); `reserve_service()` returns nothing; the release on failed registrations catches `Exception`. - Docs: drift bound of the counters, the key in the chart README, the upgrade query with the deployment's limit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Failed registrations release the reservation only if the service wasn't stored (e.g., a read after the insert failed). - The subject migration deletes a bare counter before it adds its value to the namespaced one, so concurrent changes aren't lost; it uses one helper for namespaced subjects, and its docstring names `services`. - The log of refused registrations names the limit, not a count. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideIntroduces a default limit of 50 registered services per non-admin user, enforced with atomic per-user MongoDB counters and hidden creator metadata, including cleanup, startup reconciliation, subject migration, API publication, documentation, and comprehensive concurrency and lifecycle coverage. Sequence diagram for atomic service registration limitssequenceDiagram
actor User
participant API as POST /services
participant Counters as service_counts
participant Services as services
User->>API: postService()
API->>Counters: reserve_service(user)
alt reservation below configured limit
Counters-->>API: atomic increment succeeds
API->>Services: register_metadata()
alt service storage fails
API->>Counters: release_service(user)
end
API-->>User: 201 Created
else limit reached
Counters-->>API: reservation rejected
API-->>User: 409 services-limit
end
Sequence diagram for service deletion and counter releasesequenceDiagram
actor User
participant API as DELETE /services/{serviceId}
participant Services as services
participant Counters as service_counts
User->>API: deleteService(serviceId)
API->>Services: find_one_and_delete(serviceId)
Services-->>API: deleted service with _createdBy
API->>Counters: release_service(_createdBy)
API-->>User: deletion succeeds
Entity relationship diagram for service registration counterserDiagram
SERVICES {
string id PK
string _createdBy
}
SERVICE_COUNTS {
string _id PK
int count
}
SERVICE_COUNTS ||--o{ SERVICES : counts
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 #286 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 21 22 +1
Lines 2195 2321 +126
==========================================
+ Hits 2195 2321 +126 ☔ 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/server.py" line_range="304-308" />
<code_context>
+ store_pending_type(service.data.get("type"))
+ service.pending = is_pending(type_document(service.data.get("type")))
+ service.register_metadata()
+ except Exception:
+ # unless the service was stored (e.g., a read after the insert
+ # failed)
+ if not service.was_created:
+ release_service(service.created_by)
+ raise
+ except (InvalidService, UnusedTypesLimit, ServicesLimit) as exc:
</code_context>
<issue_to_address>
**Ambiguous writes corrupt service counts**
When mongoDB commits a service insert or delete but the client receives an error before the write result or corresponding counter update is confirmed, `RegisterService.register_metadata()` leaves `was_created` false until `insert_one()` returns, so `_register_service()` releases a reservation for a service that is already stored; when `find_one_and_delete()` commits but reports an error, deletion cleanup skips the decrement. Counts drift, allowing registrations beyond the limit or blocking valid registrations until startup reconciliation.
Determine whether each service write committed after an ambiguous error, then safely apply or reconcile its corresponding counter change before returning.
Also at `cloud_registry/ga4gh/registry/server.py:184`.
</issue_to_address>
### Comment 2
<location path="cloud_registry/ga4gh/registry/service_limits.py" line_range="96" />
<code_context>
+ limit = get_custom_config(CustomConfig).access_control.max_services_per_user
+ counts = get_collection(SERVICE_COUNTS)
+ if limit is None:
+ counts.update_one({"_id": user}, {"$inc": {COUNT: 1}}, upsert=True)
+ return
+ if limit > 0 and _increment_below(user, limit):
</code_context>
<issue_to_address>
**Concurrent reservations corrupt counts**
When the limit is `null` and concurrent registrations make the first reservations for the same user, `counts.update_one(..., upsert=True)` can raise `DuplicateKeyError` when the same user makes concurrent first reservations. Unlike `_increment_below()`, this path does not retry; `_register_service()` then releases a reservation this request never acquired, so the caller gets a 500 and the other request’s count is decremented.
Handle `DuplicateKeyError` in the unbounded branch by retrying the increment without upsert, without releasing a count unless this request incremented it.
</issue_to_address>
### Comment 3
<location path="cloud_registry/ga4gh/registry/service_limits.py" line_range="96" />
<code_context>
+ limit = get_custom_config(CustomConfig).access_control.max_services_per_user
+ counts = get_collection(SERVICE_COUNTS)
+ if limit is None:
+ counts.update_one({"_id": user}, {"$inc": {COUNT: 1}}, upsert=True)
+ return
+ if limit > 0 and _increment_below(user, limit):
</code_context>
<issue_to_address>
**Ambiguous reservations block users**
When mongoDB applies the increment but the client receives an error before the operation is acknowledged, `update_one` can commit the counter increment and then raise when its acknowledgment times out. `reserve_service` propagates that exception, and `_register_service` has not yet entered the cleanup `try`, so the reservation remains and later registrations can be refused until startup reconciliation.
Handle ambiguous reservation failures by reconciling the affected user’s counter against stored services before returning the error, without blindly decrementing a reservation that may not have been applied.
Also at `cloud_registry/ga4gh/registry/server.py:298`.
</issue_to_address>
### Comment 4
<location path="cloud_registry/ga4gh/registry/service_limits.py" line_range="242" />
<code_context>
+ query: dict[str, Any] = {"_id": user}
+ query[COUNT] = before if before is not None else {"$exists": False}
+ try:
+ result = counts.update_one(query, {"$set": {COUNT: after}}, upsert=True)
+ except DuplicateKeyError:
+ # changed or added concurrently
</code_context>
<issue_to_address>
**Startup erases an active reservation**
When a POST reserves a place before the startup counter snapshot, but stores its service only after the startup aggregate is read and the counter is reset, `reconcile_service_counts()` can set the counter to the number of stored services even though it includes a reservation for a service not stored yet. That reservation is lost when the service is inserted, so a subsequent registration can pass the limit and leave the user over it.
Prevent startup reconciliation from overwriting in-flight reservations, for example by quiescing registrations while reconciling or tracking reservations separately from stored-service counts.
</issue_to_address>
### Comment 5
<location path="cloud_registry/namespace_subjects.py" line_range="223-224" />
<code_context>
+ count += 1
+ if not dry_run:
+ services.update_one(
+ {"_id": service["_id"]},
+ {"$set": {SERVICE_CREATOR: _namespaced(namespace, subject)}},
+ )
+ counters = get_collection(SERVICE_COUNTS)
</code_context>
<issue_to_address>
**Migration restores a deleted service count**
When A service is deleted after its creator is namespaced but before its bare counter is transferred, and the namespaced counter is absent or zero, `_namespace_services()` rewrites the creator before the bare counter moves, so the delete does not reduce that stale bare count; the migration then transfers it to the namespaced user. The user is overcounted and registrations are refused until startup reconciliation.
Coordinate creator rewriting and counter transfer with deletions so a deleted service's count cannot be transferred.
Also at `cloud_registry/namespace_subjects.py:233-239`.
</issue_to_address>
### Comment 6
<location path="tests/test_service_limits.py" line_range="646-647" />
<code_context>
+ Returns:
+ The only user owner.
+ """
+ mongo_client[DB]["services"].update_many(
+ {CREATED_BY: {"$exists": False}}, {"$set": {CREATED_BY: "other"}}
+ )
+ return owner(path)
</code_context>
<issue_to_address>
**Backfill test masks no-op**
When the startup backfill iterates a service but does not perform its guarded update after calling `_single_user_owner`, `test_creators_added_concurrently` passes even if `add_service_creators()` never applies its own update: the patched `set_first` writes `other` to every missing service before the final assertion, so the test doesn't verify that the backfill preserves a concurrent value.
Make the simulated concurrent update occur independently of the helper call, then assert that the backfill leaves that inserted value intact.
</issue_to_address>
### Comment 7
<location path="tests/test_service_limits.py" line_range="738" />
<code_context>
+ DuplicateKeyError: For counters.
+ """
+ if self.name == SERVICE_COUNTS:
+ raise DuplicateKeyError("duplicate")
+ return update_one(self, *args, **kwargs)
+
</code_context>
<issue_to_address>
**Duplicate-key test masks no-op**
When the reconciliation update encounters the simulated `DuplicateKeyError`, `test_counters_inserted_meanwhile` passes if `reconcile_service_counts()` does nothing: the patched `update_one` raises without inserting a counter, and the test expects the collection to remain empty. It therefore doesn't verify that a counter inserted concurrently survives reconciliation.
Insert the counter in the patched method before raising `DuplicateKeyError`, and assert that reconciliation leaves that counter unchanged.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 7 findings to address first, and a mistaken creator attribution can persist on a service and skew which user’s quota is consumed; startup reconciliation repairs counters, but it does not correct an attribution that was already written. Reverting removes the registration limit, though any incorrect attribution data may need manual repair.
Blocking findings: cloud_registry/ga4gh/registry/server.py:308, cloud_registry/ga4gh/registry/service_limits.py:96, cloud_registry/ga4gh/registry/service_limits.py:96, cloud_registry/ga4gh/registry/service_limits.py:242, cloud_registry/namespace_subjects.py:224, and 2 more
Without a limit, a first reservation that loses a concurrent counter insert increments the inserted counter instead of failing. The tests of the concurrent backfill and of counters inserted during reconciliation now fail if the code under test does nothing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Users other than admins may only have registered a limited number of the
registered services:
custom.access_control.max_services_per_user, default50,
null= no limit,0= admins only. FurtherPOST /servicesget409with code
services-limit. Config only (Helm: viaconfig), likemax_unused_service_types._createdBy(not served; kept on updates and renames;nullfor servicesthat admins register in admin mode). A service keeps counting for its
creator whatever its roles later, so handing it to a group doesn't free a
place. Updates, renames, role grants and accepted invitations never fail
on the limit.
service_counts) is reserved with anatomic conditional
$incbefore the service is stored. It is released onfailed registrations and on deletes (
find_one_and_deletereturns thecreator), so concurrent registrations can't exceed the limit. A
concurrent first reservation that loses the counter insert retries without
upsert.
owner(no or several user owners: they count for nobody). The countersare then reconciled with the stored services (compare-and-set, so
concurrent requests aren't overwritten).
namespace_subjects): also namespaces_createdBy, and moves the counters of bare users.registration_rules.max_services_per_user).Documented in the API spec, docs/configuration.md "Services per user",
access control, API, docs/upgrading.md "From 0.6.0", and the chart
README's rate-limit section.
limits, already documented); the issue's Helm-values step is dropped for
consistency with the type limit.
Closes #124
Release notes (for v1.0.0rc1, under Features)
(
custom.access_control.max_services_per_user;nullturns the limitoff,
0lets only admins register). This is a behaviour change fordeployments with heavy users; see "From 0.6.0" in the upgrade guide
(feat: limit services and writes per user #124, feat: limit services per user #286)
Verification
coverage run -m pytest(mongomock): 1509 passed, 262 skipped, coverage100%.
1515 passed, 255 skipped (before the last review fixes; their tests,
tests/test_service_limits.py,test_namespace_subjects.pyandtest_issuers.py, passed against it afterwards). This covers concurrent registrations (30parallel POSTs, limit 5: exactly 5 pass), concurrent reservations, and
concurrent first reservations of fresh users (no spurious refusals).
pre-commit run --all-files(ruff, mypy, semgrep, ast-grep, gitleaks,actionlint): passed.
mkdocs build --strict: passed.Docs, Chart, Smoke test, Scan image, Release readiness, CodeQL, Read the Docs).
Declined review findings
Backfill makes one role lookup per service without
_createdBy(N+1 on the first start): it's a one-off. Later starts query the new
index and find none.
Production projection of the delete includes
id(a mongomock quirkreturns no document for projections without fields). It's harmless and
commented.
Release guard catches
Exception, notBaseException: a worker abort(e.g., a Gunicorn timeout) can leave one reservation. It's corrected
when the worker restarts, because
create_app()reconciles in everyworker.
Sourcery: drift after writes whose acknowledgement is lost, drift from
reservations in flight during startup reconciliation, and a delete during
the subject migration. Each is bounded (one per affected request),
reconciled when any worker starts, and documented; avoiding them would
need transactions (replica sets) or a distributed lock.
Open questions
None.
🤖 Generated with Claude Code