Skip to content

feat: notify subscribers concurrently - #41

Merged
uniqueg merged 12 commits into
devfrom
feat/notify-concurrently
Nov 6, 2026
Merged

uniqueg merged 12 commits into
devfrom
feat/notify-concurrently

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Closes #34

Stacked on #37. Until that is merged, this diff against dev also shows its commits; review only the commits of this branch. The base is dev so that CI runs.

Summary

  • Pubgrade notifies all subscribers of a repository concurrently, each in its own thread up to the limit below, so a subscriber that fails or hangs affects no other one.
  • Each call has a timeout (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.
  • A build has a new field notifications with one result per subscription: delivered, failed or skipped, with the HTTP status. It contains no callback URLs or tokens, as builds are public.
  • New setting endpoints.subscriptions.max_per_repository (default 100), which also limits the threads per notification. Further registrations get a 403.
  • Users see and delete only their own subscriptions, and completing a build needs the token of the repository it belongs to.
  • README and API specification updated.

Verification

  • make test: 122 tests pass, 100% coverage.
  • The test test_notify_all_does_not_queue_behind_hanging_calls has 40 calls wait for each other, so it only passes if none is queued.
  • CI: all jobs passed, including CI passed.

Declined review findings

  • http_status in public results: reading builds shows only whether a subscriber's call worked, and registering subscriptions needs a verified user and can be closed.
  • Recording calls that were cancelled in a queue as their own result: up to the limit, each subscriber has its own thread, so nothing is queued.
  • A process-wide limit on threads: it would bring back queueing behind hanging calls.
  • A total deadline per call, and stopping calls that outlive the overall wait: requests has none, and threads can't be stopped from outside; this takes a subscriber that trickles its response on purpose. The result says failed, and the thread ends with the call.
  • An atomic limit at registration: threads stay bounded regardless.
  • Moving notifications off the request: the wait is documented to stay below the Route's limit.
  • Durable delivery records against duplicate notifications: sidecars treat the same image as done.
  • An index on repository_id, and validating the type of notification_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:

  • Notify repository subscribers concurrently with per-call timeouts and bounded concurrency.
  • Record per-subscription notification outcomes on builds, including delivery status and HTTP status.
  • Limit subscriptions per repository and expose configurable notification timeout and subscription limits.

Bug Fixes:

  • Restrict build completion to builds belonging to the target repository.
  • Restrict subscription viewing and deletion to subscriptions owned by the requesting user.

Enhancements:

  • Handle failed, timed-out, missing, and non-matching subscriptions without preventing other notifications from completing.

Documentation:

  • Document concurrent notifications, notification results, timeouts, and subscription limits in the README and API specification.

Tests:

  • Add coverage for concurrent delivery, timeout handling, failure isolation, subscription limits, access restrictions, and notification result storage.

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

sourcery-ai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This 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 notifications

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

Flow diagram for notification result recording

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

File-Level Changes

Change Details Files
Implemented concurrent, isolated subscriber notification with bounded overall wait time and per-request delivery outcomes.
  • Runs one notification per subscription in its own thread with application contexts.
  • Applies configurable connection/response timeouts and disables redirects.
  • Stores public-safe delivered, failed, or skipped results on completed builds.
  • Updates subscription state based on delivery success and handles missing subscriptions gracefully.
pubgrade/modules/endpoints/subscriptions.py
pubgrade/modules/endpoints/builds.py
pubgrade/config.yaml
pubgrade/api/pubgrade.yaml
README.md
tests/pubgrade/endpoints/test_subscriptions.py
Added subscription ownership enforcement and repository-level registration limits.
  • Limits subscriptions per repository and returns a dedicated 403 error when the limit is reached.
  • Restricts subscription lookup and deletion to subscriptions listed for the authenticated user.
pubgrade/modules/endpoints/subscriptions.py
pubgrade/errors/exceptions.py
tests/pubgrade/endpoints/test_subscriptions.py
Migrated project CI and container/chart development workflows to GitHub Actions and updated deployment defaults.
  • Adds test, Helm, smoke-test, image-scan, image-publishing, and aggregate gate jobs.
  • Moves test execution into the pinned application image and updates dependency handling for MongoDB compatibility.
  • Updates Helm chart metadata, image references, pull policies, documentation, and removes legacy Travis workflow files.
.github/dependabot.yml
.github/workflows/ci.yml
.github/workflows/main.yaml
.travis.yml
.trivyignore.yaml
Dockerfile
Makefile
helm/Chart.yaml
helm/values.yaml
README.md
setup.py
setup.cfg
tests/smoke.sh
Expanded automated coverage for concurrent notification behavior, isolation, result persistence, access control, and test-state cleanup.
  • Adds concurrency, timeout, failure isolation, deleted-subscription, secret-redaction, and ownership tests.
  • Adds a shared fixture to restore mutable mock data between tests.
  • Updates request mocks and build tests for application-context and response handling changes.
tests/conftest.py
tests/pubgrade/endpoints/test_subscriptions.py
tests/pubgrade/endpoints/test_builds.py
tests/pubgrade/test_server.py

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

@uniqueg
uniqueg marked this pull request as ready for review November 5, 2026 05:38

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


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

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]>
uniqueg and others added 4 commits November 6, 2026 05:01
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

codecov Bot commented Nov 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (10804d0) to head (c8db2e6).

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.
📢 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 merged commit 1092464 into dev Nov 6, 2026
24 of 25 checks passed
@uniqueg
uniqueg deleted the feat/notify-concurrently branch November 6, 2026 04:45
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: notify subscribers concurrently

1 participant