Skip to content

feat: publish prebuilt images without a build - #42

Merged
uniqueg merged 19 commits into
devfrom
feat/publish-prebuilt-images
Nov 6, 2026
Merged

uniqueg merged 19 commits into
devfrom
feat/publish-prebuilt-images

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Closes #33

Stacked on #37 and #34's branch. Until those are merged, this diff against dev also shows their commits; review only the commits of this branch. The base is dev so that CI runs.

Summary

  • New setting endpoints.builds.enabled, off by default: POST /repositories/{id}/builds then takes a prebuilt image from the repository's own CI, checks it and notifies the subscribers, without creating a build pod. Turned on, the former builds work as before. Images need a valid reference with a tag in both modes.
  • Registration of repositories, users and subscriptions can be closed by configuration after setup (registration_enabled in endpoints.repository, endpoints.user and endpoints.subscriptions, default on); further registrations get a 403.
  • A subscription's value can be *, for any value of its type.
  • README updated (usage, configuration, queries); the smoke test covers publishing.

Verification

  • make test: 153 tests pass, 100% coverage.
  • tests/smoke.sh against the image with MongoDB, in CI.
  • CI: all jobs passed, including CI passed.

Declined review findings

The same points as in #41 where they appear here again: atomic limit at registration, a total deadline per call, and an index on repository_id.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Enable prebuilt image publishing by default while retaining the optional in-application build workflow.

New Features:

  • Support publishing a prebuilt, tagged image and notifying repository subscribers without creating a build pod.
  • Allow subscription values of * to match any value of the selected commit field.

Enhancements:

  • Allow repository, user, and subscription registration to be disabled after initial setup.
  • Validate published image references and return clear errors for unsupported build requests.

Documentation:

  • Update usage, configuration, API descriptions, and subscription query documentation for prebuilt image publishing and registration controls.

Tests:

  • Add coverage for prebuilt publishing, image validation, wildcard subscriptions, registration controls, and smoke-test publishing.

uniqueg and others added 10 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]>
With builds off, the default, the POST takes one prebuilt image and
notifies subscribers. Build requests and PUT get a 403. Registration can
be closed by configuration, and a subscription value `*` matches any tag
or branch, as registering again won't work then.

Closes #33

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]>
…ages

# Conflicts:
#	pubgrade/errors/exceptions.py
#	pubgrade/modules/endpoints/subscriptions.py
#	tests/pubgrade/endpoints/test_subscriptions.py
@sourcery-ai

sourcery-ai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR introduces configuration-controlled prebuilt image publishing with concurrent, observable subscription notifications, adds registration hardening and wildcard matching, and moves the project to Docker-based testing, Helm deployment defaults, and GitHub Actions image publishing.

Sequence diagram for prebuilt image publishing

sequenceDiagram
    actor CI
    participant API
    participant Builds
    participant MongoDB
    participant Subscribers

    CI->>API: POST /repositories/{id}/builds
    API->>Builds: register_builds(repository_id, access_token, build_data)
    Builds->>Builds: validate_prebuilt_image(build_data)
    Builds->>MongoDB: insert build with status QUEUED
    Builds->>Subscribers: notify_all_subscriptions(subscription_ids, image, build_id)
    par Notify each subscription
        Subscribers->>Subscribers: notify_subscriptions(subscription_id, image, build_id)
        Subscribers-->>Subscribers: delivered, failed, or skipped
    end
    Subscribers->>MongoDB: update build notifications
    Builds->>MongoDB: update build status and finished_at
    API-->>CI: build id and notification results
Loading

State diagram for build modes

stateDiagram-v2
    [*] --> RequestReceived
    RequestReceived --> PrebuiltPublishing: builds_enabled() is false
    RequestReceived --> PubgradeBuild: builds_enabled() is true
    PrebuiltPublishing --> ImageValidated: validate_prebuilt_image(build_data)
    ImageValidated --> NotifySubscriptions: publish_prebuilt_image(build_id, image, subscriptions)
    NotifySubscriptions --> Succeeded: no failed notifications
    NotifySubscriptions --> Failed: one or more failed notifications
    PubgradeBuild --> BuildPod: register_builds creates build path
    BuildPod --> Succeeded: build_completed(build_id)
    BuildPod --> Failed: build fails
Loading

Flow diagram for registration hardening

flowchart TD
    UserRegistration[Register user] --> UserSetting{user.registration_enabled}
    RepositoryRegistration[Register repository] --> RepositorySetting{repository.registration_enabled}
    SubscriptionRegistration[Register subscription] --> SubscriptionSetting{subscriptions.registration_enabled}
    UserSetting -->|true| UserCreated[User created]
    UserSetting -->|false| UserForbidden[403 RegistrationDisabled]
    RepositorySetting -->|true| RepositoryCreated[Repository created]
    RepositorySetting -->|false| RepositoryForbidden[403 RegistrationDisabled]
    SubscriptionSetting -->|true| SubscriptionLimit{max_per_repository reached}
    SubscriptionSetting -->|false| SubscriptionForbidden[403 RegistrationDisabled]
    SubscriptionLimit -->|no| SubscriptionCreated[Subscription created]
    SubscriptionLimit -->|yes| LimitForbidden[403 TooManySubscriptions]
Loading

File-Level Changes

Change Details Files
Add a prebuilt-image publishing path that validates tagged images, bypasses pod creation when internal builds are disabled, notifies subscriptions, and records notification outcomes.
  • Gate the existing internal build workflow and build completion endpoint with the new endpoints.builds.enabled setting.
  • Require exactly one tagged image for prebuilt publishing and reject build-only fields when the build path is disabled.
  • Persist build completion status and per-subscription notification results, including handling missing or failed subscribers.
  • Run subscriber callbacks concurrently with configurable timeouts, wildcard subscription matching, redirect protection, and sanitized result records.
pubgrade/modules/endpoints/builds.py
pubgrade/modules/endpoints/subscriptions.py
pubgrade/config.yaml
pubgrade/api/pubgrade.yaml
pubgrade/errors/exceptions.py
tests/pubgrade/endpoints/test_builds.py
tests/pubgrade/endpoints/test_subscriptions.py
tests/smoke.sh
Add configuration controls for closing repository, user, and subscription registration and enforce subscription ownership and capacity limits.
  • Return 403 when each registration type is disabled by configuration.
  • Limit subscriptions per repository with a configurable maximum.
  • Restrict subscription retrieval and deletion to subscriptions listed for the authenticated user.
  • Add corresponding exception mappings and coverage.
pubgrade/modules/endpoints/repositories.py
pubgrade/modules/endpoints/users.py
pubgrade/modules/endpoints/subscriptions.py
pubgrade/config.yaml
pubgrade/errors/exceptions.py
tests/pubgrade/endpoints/test_repositories.py
tests/pubgrade/endpoints/test_users.py
tests/pubgrade/endpoints/test_subscriptions.py
Modernize container, Helm, development, and CI workflows around the FOCA-based image and automated image publication.
  • Move testing and smoke validation into Docker-based GitHub Actions workflows with a required aggregate gate.
  • Publish main and updater images on dev with commit, branch, and date tags plus SBOM and provenance.
  • Update Helm chart metadata, default images, pull policies, Make targets, dependency handling, and documentation.
  • Add Dependabot configuration and Trivy ignore configuration while removing legacy Travis CI.
.github/workflows/ci.yml
.github/dependabot.yml
.trivyignore.yaml
Dockerfile
Makefile
helm/Chart.yaml
helm/values.yaml
setup.py
setup.cfg
README.md
.github/workflows/main.yaml
.travis.yml
Strengthen test isolation and expand endpoint coverage for publishing, notification behavior, registration controls, and smoke-test execution.
  • Restore shared mock data between tests and adapt request mocks to response status and timeout parameters.
  • Cover concurrent notifications, timeout bounds, wildcard matching, invalid images, authorization ordering, and configuration-driven 403 responses.
  • Add an end-to-end shell smoke test against the containerized application and MongoDB.
tests/conftest.py
tests/pubgrade/endpoints/test_builds.py
tests/pubgrade/endpoints/test_subscriptions.py
tests/pubgrade/endpoints/test_repositories.py
tests/pubgrade/endpoints/test_users.py
tests/pubgrade/test_server.py
tests/mock_data.py
tests/smoke.sh

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 6 issues

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

## Individual Comments

### Comment 1
<location path="pubgrade/modules/endpoints/builds.py" line_range="154" />
<code_context>
     if data_from_db["access_token"] != access_token:
         raise Unauthorized
+    if not all(
+        IMAGE_WITH_TAG.fullmatch(image["name"]) for image in build_data["images"]
+    ):
+        raise InvalidImage
</code_context>
<issue_to_address>
**Invalid images cause server errors**

When the request has an empty image list or an image without a name, `all()` accepts an empty list, and the validation expression raises `KeyError` for a missing `name`; with builds enabled, `register_builds` later indexes `images[0]` and raises `IndexError` after inserting the build. Callers get a server error and the queued build remains stored.

Reject empty image lists and entries without a name before inserting a build.
</issue_to_address>

### Comment 2
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="104" />
<code_context>
     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>
**Concurrent registrations exceed the cap**

When registrations for the same repository run concurrently while its subscription count is near the configured maximum, the separate `count_documents` check and insert let each registration observe a count below the maximum and then insert; the repository exceeds its configured cap, allowing notification fanout to exceed the intended limit.

Enforce the per-repository limit atomically with subscription registration.

Also at `pubgrade/modules/endpoints/subscriptions.py:420`.
</issue_to_address>

### Comment 3
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="352-353" />
<code_context>
+            },
+            data=json.dumps({"image_name": name, "tag": tag}),
+            timeout=_notification_timeout(),
+            allow_redirects=False,
+            stream=True,
         )
-        subscription_type = subscription_object["type"]
</code_context>
<issue_to_address>
**Timed-out callbacks still apply updates**

When a callback keeps its socket active beyond the aggregate wait deadline and later returns successfully, requests' timeout limits socket inactivity, not total elapsed time, and `executor.shutdown(wait=False)` leaves unfinished workers running. The publish records the notification as failed, but the callback later updates the subscription successfully and repeated publishes can accumulate workers.

Enforce a total callback deadline and prevent callbacks that outlive it from applying updates.

Also at `pubgrade/modules/endpoints/subscriptions.py:425-429`.
</issue_to_address>

### Comment 4
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="420" />
<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>
**Existing repositories exceed thread cap**

When an existing repository has more subscriptions than the configured maximum when this version is deployed, repositories that already have more subscriptions than the new limit still pass their full ID list to `notify_all_subscriptions`; the executor creates one worker per ID, so a notification can start far more threads than `max_per_repository` allows and exhaust app resources.

Bound notification workers independently of registration history, and handle or migrate repositories that already exceed the configured maximum.
</issue_to_address>

### Comment 5
<location path="pubgrade/modules/endpoints/builds.py" line_range="39-41" />
<code_context>
     BASE_DIR = '/pubgrade_temp_files'

+# An image with a tag (no digest), optionally with a registry and its port
+IMAGE_WITH_TAG = re.compile(
+    r"[a-zA-Z0-9][a-zA-Z0-9._:/-]*:[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}"
+)
+
+
</code_context>
<issue_to_address>
**Invalid image references reach subscribers**

When a caller supplies an uppercase repository component or an extra colon in an image reference, `IMAGE_WITH_TAG` accepts references Docker rejects; `register_builds` accepts them and subscribers receive image names and tags that deployment tooling cannot pull.

Validate image references with Docker-compatible rules before accepting them.
</issue_to_address>

### Comment 6
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="103-108" />
<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
+    ):
+        raise TooManySubscriptions
     for i in range(retries):
         logger.debug(f"Trying to insert/update object: try {i}" + str(data))
</code_context>
<issue_to_address>
**Subscription checks scan the collection**

When the subscriptions collection grows, `count_documents` filters on `repository_id`, but the collection has no index on that field, so each registration scans the growing collection and increases registration latency and database load.

Add an index on `repository_id` to the subscriptions collection.
</issue_to_address>

Linked issues

#33 feat: publish prebuilt images without a build · 7 of 7 met

# Requirement Status Notes
1 The builds setting is off by default. ✅ Met The config sets endpoints.builds.enabled: False, and the code also defaults to off if the setting is absent.
2 With builds off, POST publishes a prebuilt image, notifies matching subscribers, and records the build without cloning or starting a build. ✅ Met The prebuilt path inserts the build and notifies subscribers without calling create_build; notification results and the final build status are stored.
3 Build requests and PUT return a 4xx when builds are off. ✅ Met Requests containing a Dockerfile location or registry token, and calls to the build-completion path, raise BuildsDisabled (403).
4 Repository and subscription registration can be closed by configuration, with registration on by default. ✅ Met Both settings default to true and raise RegistrationDisabled when set to false.
5 A subscription value of * matches any tag or branch. ✅ Met Notification matching accepts * for the subscription's type, while still requiring that type to be present in head_commit.
6 Update the README and API spec. ✅ Met The README documents publishing, configuration, and wildcard matching; the API spec describes the prebuilt-image path and notification results.
7 Unit tests cover the behavior. ✅ Met Tests cover prebuilt publishing, rejected build requests and invalid images, disabled PUT, closed repository/subscription registration, and wildcard matching.

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and with builds disabled by default, publishing a build sends image-update callbacks to repository subscribers, which may cause their deployments to pull and run the named image; an incorrect image or notification can therefore affect systems outside this service. Reverting stops future notifications but cannot retract callbacks already sent or deployments already changed.

Blocking findings: pubgrade/modules/endpoints/builds.py:154, pubgrade/modules/endpoints/subscriptions.py:104, pubgrade/modules/endpoints/subscriptions.py:353, pubgrade/modules/endpoints/subscriptions.py:420, pubgrade/modules/endpoints/builds.py:41, and 1 more


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

Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
uniqueg and others added 8 commits November 5, 2026 06:45
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]>
Image references follow Docker's rules, and requests without images or
image names get a 400 instead of a server error.

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

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (dev@1092464). Learn more about missing BASE report.

Additional details and impacted files
@@           Coverage Diff           @@
##             dev       #42   +/-   ##
=======================================
  Coverage       ?   100.00%           
=======================================
  Files          ?         7           
  Lines          ?       669           
  Branches       ?         0           
=======================================
  Hits           ?       669           
  Misses         ?         0           
  Partials       ?         0           

☔ 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.

…images

# Conflicts:
#	README.md
#	pubgrade/config.yaml
#	pubgrade/errors/exceptions.py
#	pubgrade/modules/endpoints/subscriptions.py
#	tests/pubgrade/endpoints/test_subscriptions.py
@uniqueg
uniqueg merged commit 37c1f32 into dev Nov 6, 2026
24 of 25 checks passed
@uniqueg
uniqueg deleted the feat/publish-prebuilt-images branch November 6, 2026 04:49
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: publish prebuilt images without a build

1 participant