Repository navigation
feat: notify subscribers concurrently - #41
Conversation
Inserting shared mock data into a collection adds an `_id`, and later tests couldn't serialize it. Two more tests lacked an app context. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Replaces Travis and `main.yaml`. Tests run in the image. The smoke test uses MongoDB 7, which needs a newer pymongo than FOCA 0.7 pins. Excludes `.env*` from the image build context. Closes #32 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each call has a timeout and follows no redirects. A failure stays with its subscriber, and other than 2xx counts as one. The build stores one result per subscriber, without URLs or tokens. Closes #34 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A shared thread limit let calls that hang keep later subscribers in the queue until the overall wait ended, so these were never called. Each subscriber now gets a thread, and the setting `endpoints.subscriptions.max_per_repository` (default: 100) limits the number of subscriptions per repository, and with it the threads. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR changes build completion to notify repository subscribers concurrently with per-call timeouts, safe public result recording, and configurable subscription limits, while enforcing ownership access and adding comprehensive tests. It also migrates CI and deployment defaults from legacy workflows to GitHub Actions and the updated Helm/image setup. Sequence diagram for concurrent subscriber notificationssequenceDiagram
participant Build as Build completion
participant Coordinator as notify_all_subscriptions
participant WorkerA as Subscriber worker A
participant WorkerB as Subscriber worker B
participant CallbackA as Subscriber callback A
participant CallbackB as Subscriber callback B
participant Store as Build store
Build->>Coordinator: notify_all_subscriptions(subscription_ids, image, build_id)
par Notify subscription A
Coordinator->>WorkerA: notify(subscription_id)
WorkerA->>CallbackA: requests.request(PUT, callback_url, timeout, allow_redirects=False)
CallbackA-->>WorkerA: HTTP status or timeout
WorkerA-->>Coordinator: _notification_result()
and Notify subscription B
Coordinator->>WorkerB: notify(subscription_id)
WorkerB->>CallbackB: requests.request(PUT, callback_url, timeout, allow_redirects=False)
CallbackB-->>WorkerB: HTTP status or timeout
WorkerB-->>Coordinator: _notification_result()
end
Coordinator->>Store: update_one(build_id, notifications)
Flow diagram for notification result recordingflowchart LR
A[Build completion] --> B[notify_all_subscriptions]
B --> C{Subscription matches build?}
C -->|No or missing| D[skipped]
C -->|Yes| E[notify_subscriptions]
E --> F{2xx response before timeout?}
F -->|Yes| G[delivered]
F -->|No, error, or timeout| H[failed]
D --> I[Build notifications]
G --> I
H --> I
I --> J[update_one build]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 9 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="410" />
<code_context>
+
+ results: List[Dict[str, Any]] = []
+ if subscription_ids:
+ executor = ThreadPoolExecutor(max_workers=len(subscription_ids))
+ futures = {
+ executor.submit(notify, subscription_id): subscription_id
</code_context>
<issue_to_address>
**Notification threads exhaust process resources**
When many repositories complete builds concurrently or completion requests are replayed while callbacks remain in flight, each `notify_all_subscriptions` call creates a separate executor with one worker per subscription, so concurrent calls have no process-wide thread bound and exhaust resources, causing requests to fail.
Use a process-wide bound on active notification workers instead of creating an independently unbounded executor for each call.
</issue_to_address>
### Comment 2
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="428" />
<code_context>
+ ]
+ app.config["FOCA"].db.dbs["pubgradeStore"].collections[
+ "builds"
+ ].client.update_one({"id": build_id}, {"$set": {"notifications": results}})
+ return results
+
</code_context>
<issue_to_address>
**Other repositories receive subscriber results**
When a caller with a valid project token for repository A submits a known build ID from repository B, `build_completed` validates the token against repository A but does not verify that `build_id` belongs to A; `notify_all_subscriptions` therefore writes A's subscriber IDs and outcomes onto repository B's public build, exposing cross-repository subscriber activity and allowing A's caller to overwrite B's notification results.
Verify that the build belongs to the token-authenticated repository before processing completion or storing notification results.
</issue_to_address>
### Comment 3
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="96-98" />
<code_context>
raise Unauthorized
if data_from_db_repository is None:
raise RepositoryNotFound
+ if db_collection_subscriptions.count_documents(
+ {"repository_id": data["repository_id"]}
+ ) >= current_app.config["FOCA"].endpoints["subscriptions"].get(
+ "max_per_repository", DEFAULT_MAX_SUBSCRIPTIONS
+ ):
</code_context>
<issue_to_address>
**Repository subscription limits are exceeded**
When multiple registrations for the same repository overlap near the configured maximum, the count check and later insert are separate operations, so concurrent registrations both pass the check and insert, pushing the repository above `max_per_repository` and allowing notification fan-out to exceed the intended cap.
Enforce the per-repository limit atomically with registration, or otherwise serialize registrations for each repository.
</issue_to_address>
### Comment 4
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="341" />
<code_context>
+ "Content-Type": "application/json",
+ },
+ data=json.dumps({"image_name": name, "tag": tag}),
+ timeout=_notification_timeout(),
+ allow_redirects=False,
+ stream=True,
</code_context>
<issue_to_address>
**Timed-out callbacks keep running**
When a callback trickles response-header bytes often enough to avoid the socket inactivity timeout but takes longer than the overall notification wait, `requests.request` treats its timeout as socket inactivity, not a total deadline, and `executor.shutdown(wait=False)` does not stop the worker. The build can record a failed result while the callback later updates subscription state, and repeated builds can accumulate blocked threads.
Enforce a total callback deadline and ensure workers that exceed the notification wait cannot continue running or update subscription state.
Also at `pubgrade/modules/endpoints/subscriptions.py:415-424`.
</issue_to_address>
### Comment 5
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="416" />
<code_context>
+ for subscription_id in subscription_ids
+ }
+ done, _ = wait(
+ futures, timeout=2 * _notification_timeout() + NOTIFICATION_MARGIN
+ )
+ # Calls that are still running end with their timeouts
</code_context>
<issue_to_address>
**Build completion exceeds route timeout**
When subscriber calls run near their timeout and the preceding build-completion work takes more than the remaining route budget, `notify_all_subscriptions` can wait 25 seconds at the default timeout, in addition to the signing request, database updates, and pod cleanup that `build_completed` performs first. When that work takes more than the remaining route budget, the caller receives a gateway timeout even though the server continues processing; a retry can repeat completion work.
Move notification work off the completion request or reduce its total wait budget to leave room for preceding work and the route timeout.
Also at `pubgrade/modules/endpoints/builds.py:517-521`.
</issue_to_address>
### Comment 6
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="416-419" />
<code_context>
+ for subscription_id in subscription_ids
+ }
+ done, _ = wait(
+ futures, timeout=2 * _notification_timeout() + NOTIFICATION_MARGIN
+ )
+ # Calls that are still running end with their timeouts
+ executor.shutdown(wait=False)
+ results = [
+ future.result()
</code_context>
<issue_to_address>
**Timed-out workers send late callbacks**
When a worker's database lookups take longer than the overall notification wait and then recover, `wait` records unfinished futures as failed, but `shutdown(wait=False)` does not stop them. If a worker is delayed in its database lookups and later resumes, `notify_subscriptions` can still send the callback after the build has stored a failed result, so a retry can deliver it twice.
Pass a deadline into each worker and prevent it from starting an external callback after that deadline, or keep results pending until the worker has actually stopped.
</issue_to_address>
### Comment 7
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="360-362" />
<code_context>
- datetime.datetime.now().isoformat()
- )
- del subscription_object["_id"]
- db_collection_subscriptions.update_one(
- {"id": subscription_id}, {"$set": subscription_object}
- )
- # Retrieve callback URL for the side-car service (at
- # deployment) from subscription collection, build payload
</code_context>
<issue_to_address>
**Successful callbacks are recorded as failures**
When the callback responds successfully but the following subscription write fails, the callback can accept the image before the subscription `update_one` fails. The worker then returns `failed`, and the build records that result even though the subscriber received the notification; retrying build completion sends it again because no durable per-build delivery record or idempotency key prevents a duplicate.
Make delivery retries idempotent with a per-build/subscription key and persist delivery state so callback acceptance and reported outcome can be reconciled.
</issue_to_address>
### Comment 8
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="96-97" />
<code_context>
raise Unauthorized
if data_from_db_repository is None:
raise RepositoryNotFound
+ if db_collection_subscriptions.count_documents(
+ {"repository_id": data["repository_id"]}
+ ) >= current_app.config["FOCA"].endpoints["subscriptions"].get(
+ "max_per_repository", DEFAULT_MAX_SUBSCRIPTIONS
</code_context>
<issue_to_address>
**Registration count scans subscriptions**
When the subscriptions collection grows beyond a small deployment, mongoDB has no index on `repository_id` in the configured subscriptions collection, so `count_documents` scans the collection for each registration. As the total number of subscriptions grows, registration latency and database work grow with it.
Add an index on `subscriptions.repository_id` for the registration count query.
</issue_to_address>
### Comment 9
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="438-440" />
<code_context>
+ Returns:
+ The setting `endpoints.subscriptions.notification_timeout`, in seconds.
+ """
+ return current_app.config["FOCA"].endpoints["subscriptions"].get(
+ "notification_timeout", DEFAULT_NOTIFICATION_TIMEOUT
+ )
+
+
</code_context>
<issue_to_address>
**Malformed timeout breaks completion**
When `endpoints.subscriptions.notification_timeout` is set to a nonnumeric value such as a string or null, `_notification_timeout()` returns the configured value without validation, so `wait`'s `2 * timeout + NOTIFICATION_MARGIN` raises `TypeError` for a nonnumeric value after worker threads have been submitted. Build completion then fails and notification results are not stored.
Validate the setting as a positive numeric timeout before starting notification workers.
Also at `pubgrade/modules/endpoints/subscriptions.py:416`.
</issue_to_address>Linked issues
#34 feat: notify subscribers concurrently · 5 of 5 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Notify subscribers concurrently, with a timeout per call | ✅ Met | Each subscription is submitted to its own thread, and the request uses the configurable notification timeout. |
| 2 | One failure doesn't stop the others; responses other than 2xx count as failures | ✅ Met | Notification errors are converted to per-subscription failures, and only 2xx responses are marked delivered. |
| 3 | Store the result per subscriber on the build and return it from GET, without callback URLs or tokens | ✅ Met | The build stores a result for each subscription, and build retrieval returns that field; results contain the subscription ID, result, HTTP status, and completion time. |
| 4 | Update the README and API spec | ✅ Met | The README describes notification behavior and results, and the API spec defines the notifications field and result schema. |
| 5 | Unit tests and docs cover this | ✅ Met | The change adds tests for concurrency, failures, timeouts, stored results, and updates the README and API spec. |
Sourcery assessment
Needs a human reviewer. 9 findings to address first, and CI now publishes mutable dev images, and the Helm defaults always pull them, so a bad push can reach deployments before it is reverted. Reverting does not undo an image already deployed or an external deployment triggered by a subscriber notification.
Blocking findings: pubgrade/modules/endpoints/subscriptions.py:410, pubgrade/modules/endpoints/subscriptions.py:428, pubgrade/modules/endpoints/subscriptions.py:98, pubgrade/modules/endpoints/subscriptions.py:341, pubgrade/modules/endpoints/subscriptions.py:416, and 4 more
Threads per notification stay within the limit of subscriptions, also for lists longer than that. Completing a build needs the token of the repository that the build belongs to. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Push both images by digest in the environment dev-images, scan exactly those digests, then attest, sign with Sigstore and tag them, as cloud-registry does. Report unit test coverage to Codecov. Drop the date tag, which the other repos don't publish. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Always write the coverage report and hand it to the host user, also when tests fail. Document the environment, secrets and variable that publishing needs, and how to verify an image's signature. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #41 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 7 7
Lines 605 629 +24
=========================================
+ Hits 605 629 +24 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Closes #34
Stacked on #37. Until that is merged, this diff against
devalso shows its commits; review only the commits of this branch. The base isdevso that CI runs.Summary
endpoints.subscriptions.notification_timeout, default 10 s, for connecting and for the response) and doesn't follow redirects; calls that go on past both timeouts count as failed.notificationswith one result per subscription:delivered,failedorskipped, with the HTTP status. It contains no callback URLs or tokens, as builds are public.endpoints.subscriptions.max_per_repository(default 100), which also limits the threads per notification. Further registrations get a 403.Verification
make test: 122 tests pass, 100% coverage.test_notify_all_does_not_queue_behind_hanging_callshas 40 calls wait for each other, so it only passes if none is queued.CI passed.Declined review findings
http_statusin public results: reading builds shows only whether a subscriber's call worked, and registering subscriptions needs a verified user and can be closed.requestshas none, and threads can't be stopped from outside; this takes a subscriber that trickles its response on purpose. The result saysfailed, and the thread ends with the call.repository_id, and validating the type ofnotification_timeout: few subscriptions, and an operator's configuration.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Deliver repository subscription notifications concurrently while exposing safe, bounded delivery results and enforcing ownership and repository access controls.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: