Repository navigation
feat: publish prebuilt images without a build - #42
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]>
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]>
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
Reviewer's GuideThis 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 publishingsequenceDiagram
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
State diagram for build modesstateDiagram-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
Flow diagram for registration hardeningflowchart 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]
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 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
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]>
…images # Conflicts: # tests/smoke.sh
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
…images # Conflicts: # README.md # pubgrade/config.yaml # pubgrade/errors/exceptions.py # pubgrade/modules/endpoints/subscriptions.py # tests/pubgrade/endpoints/test_subscriptions.py
Closes #33
Stacked on #37 and #34's branch. Until those are merged, this diff against
devalso shows their commits; review only the commits of this branch. The base isdevso that CI runs.Summary
endpoints.builds.enabled, off by default:POST /repositories/{id}/buildsthen 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_enabledinendpoints.repository,endpoints.userandendpoints.subscriptions, default on); further registrations get a 403.valuecan be*, for any value of its type.Verification
make test: 153 tests pass, 100% coverage.tests/smoke.shagainst the image with MongoDB, in CI.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:
*to match any value of the selected commit field.Enhancements:
Documentation:
Tests: