Repository navigation
feat(chart): add Celery worker and broker - #381
Conversation
Add optional templates to the library chart foca-common, all off by default, so the output of existing values stays the same: - workerDeployment: Celery worker with the app's image, config overlay, MongoDB credentials and security contexts, run with worker.command - brokerDeployment, brokerService, brokerNetworkPolicy: bundled RabbitMQ 4.3 (non-root, read-only root file system, data in an emptyDir), reachable only from the app's and the worker's pods - CELERY_BROKER_URL and CELERY_RESULT_BACKEND (optional) for the app and the worker from the Secret broker.existingSecret, which also works for external brokers; MongoDB's NetworkPolicy admits the worker The values schema, the petstore example (values, templates, a worker entry point and values for CI), tests, a snapshot and the docs cover them. App charts without worker and broker values render as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Install the petstore chart a second time on kind, with the Celery worker and the bundled broker (ci/celery-values.yaml). CI creates the Secret with the broker URL, lints the chart with each CI values file and checks that the worker logs that it is ready, without errors. Closes #351 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- CI: ignore Celery's connection retries while the broker starts, keep polling if kubectl logs fails, and correct the step's comment - Docs and values: the broker's Service is named like the app's resources with the suffix -broker; fix the wrapping and indentation - Worker template: same conditional env form as the app's, and a note to keep it in line with the app's Deployment - Tests: broker settings and required image, worker following the app's image values, explicit labels and names (incl. truncation) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThe PR adds opt-in Celery worker and RabbitMQ support to the foca-common Helm library, wires broker configuration securely through Kubernetes Secrets, updates the petstore example and documentation, and adds comprehensive template and kind-cluster CI coverage while retaining backward-compatible default output. Sequence diagram for worker startup and broker connectionsequenceDiagram
participant Worker as CeleryWorker
participant Secret as KubernetesSecret
participant Broker as RabbitMQ
Worker->>Secret: Read CELERY_BROKER_URL
Worker->>Broker: Connect to AMQP 5672
alt broker is starting
Broker-->>Worker: Connection refused
Worker->>Broker: Retry connection
else broker is ready
Broker-->>Worker: AMQP connection accepted
Worker->>Broker: Declare Celery queues
Broker-->>Worker: Queues declared
Worker-->>Worker: Log ready
end
Flow diagram for secure broker configuration modesflowchart TD
Secret[broker.existingSecret]
Enabled{Worker or bundled broker enabled?}
Fail[Helm rendering fails]
App[App receives CELERY_BROKER_URL]
Worker[Worker receives broker settings]
Bundled{broker.enabled?}
External[Use external broker]
RabbitMQ[Deploy RabbitMQ and Service]
Secret --> Enabled
Enabled -->|No| App
Enabled -->|Yes, Secret missing| Fail
Enabled -->|Yes, Secret present| App
App --> Bundled
Bundled -->|No| External
Bundled -->|Yes| RabbitMQ
Secret -->|username and password| RabbitMQ
Secret -->|broker URL and optional result backend| Worker
RabbitMQ --> Worker
File-Level Changes
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 #381 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 26 26
Lines 2337 2337
=========================================
Hits 2337 2337
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
The kind installation showed that RabbitMQ 4.3 denies transient non-exclusive queues by default (deprecated feature transient_nonexcl_queues), which Celery declares for the rpc:// result backend (FOCA's default) and for remote control, so the worker failed to start. Permit them in a config file of the bundled broker (new template brokerConfigMap, mounted into /etc/rabbitmq/conf.d, with a checksum annotation), and document the setting for external brokers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="charts/foca-common/templates/_worker.tpl" line_range="52-69" />
<code_context>
+ - image: {{ include "foca-common.image" . | quote }}
</code_context>
<issue_to_address>
**Disconnected workers report ready**
When the broker is unavailable or unreachable and Celery keeps retrying without exiting, celery retries its broker connection while the worker container stays running, and with no readiness probe Kubernetes marks the pod Ready and the Deployment available. Rollouts and health checks therefore report success while queued tasks are not processed.
Add a readiness check that reflects successful broker connectivity, or otherwise expose worker readiness so Kubernetes does not treat a disconnected worker as available.
</issue_to_address>
### Comment 2
<location path="charts/foca-common/tests/test_templates.py" line_range="1056-1061" />
<code_context>
+ "broker"
+ )
+ (rule,) = policy["ingress"]
+ peers = [peer["podSelector"]["matchLabels"] for peer in rule["from"]]
+ assert [labels["app.kubernetes.io/component"] for labels in peers] == [
+ "app",
+ "worker",
+ ]
+ assert {labels["app.kubernetes.io/instance"] for labels in peers} == {"petstore"}
+ assert rule["ports"] == [{"port": 5672, "protocol": "TCP"}]
+ docs = render(*CELERY, "--set", "broker.networkPolicy.enabled=false")
</code_context>
<issue_to_address>
**Network policy tests miss app identity**
When a policy selector retains component and instance labels but drops `app.kubernetes.io/name`, `test_broker_network_policy` at lines 1056–1061 checks peer components and instances, and `test_mongodb_network_policy_admits_worker` at lines 1070–1074 checks only components. Both pass if selectors omit `app.kubernetes.io/name`, allowing unrelated pods with matching labels to connect.
Assert the complete expected selector labels for each allowed peer.
Also at `charts/foca-common/tests/test_templates.py:1070-1074`.
</issue_to_address>
### Comment 3
<location path="charts/foca-common/tests/test_templates.py" line_range="879" />
<code_context>
+
+def test_celery_resources(render: Callable[..., Docs]) -> None:
+ """The worker and the broker add their resources."""
+ assert set(render(*CELERY)) - set(render()) == {
+ ("Deployment", WORKER),
+ ("Deployment", BROKER),
</code_context>
<issue_to_address>
**Celery resource removals go unnoticed**
When a regression removes an existing resource only when Celery is enabled, `test_celery_resources` at line 879 subtracts the default resources from the Celery render, so any default resources removed by that render are never checked and the test still passes as long as the new resources appear.
Assert that the Celery render contains the complete default resource set as well as the new resources.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 3 findings to address first, and the bundled broker stores queued tasks in an emptyDir, so replacing its pod permanently loses any tasks still queued there; reverting the chart cannot restore them. The loss is limited to tasks in that broker’s queue, and the bundled broker is opt-in.
Blocking findings: charts/foca-common/templates/_worker.tpl:69, charts/foca-common/tests/test_templates.py:1061, charts/foca-common/tests/test_templates.py:879
Address Sourcery's review: worker.readinessProbe and worker.livenessProbe (Kubernetes probe specs, none by default) let deployments check the worker's broker connection, e.g., with celery inspect ping. The tests now compare the NetworkPolicies' peer selectors in full and check that the Celery render keeps all default resources. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
This PR adds an optional Celery worker and message broker to the library chart
foca-common, following #312. Everything is off by default, and existing values render the same output as before: the four existing snapshots are unchanged.foca-common.workerDeployment,worker.*values): a Deployment with the app's image, run withworker.command. It gets the app's config overlay, MongoDB credentials, security contexts (non-root, read-only root file system) and/tmp. Further values:replicas, optionalreadinessProbe/livenessProbe(probe specs, none by default, e.g.,celery inspect ping; added for Sourcery's review),terminationGracePeriodSeconds(Celery's warm shutdown),resources,tmpSizeLimit.foca-common.brokerDeployment,brokerService,brokerNetworkPolicy,broker.*values):rabbitmq:4.3), as FOCA's Celery factory defaults topyamqp://with therpc://result backend.emptyDir(dataSizeLimit), and logs go to stdout only (RABBITMQ_LOGS=-).Recreatestrategy keeps one broker at a time.foca-common.brokerConfigMap, mounted into/etc/rabbitmq/conf.d) permits transient non-exclusive queues. RabbitMQ 4.3 denies them by default (deprecated featuretransient_nonexcl_queues), but Celery declares them for therpc://result backend (FOCA's default) and for remote control. The first kind run failed on exactly this. The docs give the setting for external RabbitMQ brokers.usernameandpassword.broker.existingSecret), never from plain values:CELERY_BROKER_URLis read from the keybroker-url.CELERY_RESULT_BACKENDis read from the optional keyresult-backend(optional: true, falling back tojobs.backend).<fullname>-workerand<fullname>-broker, truncated like-mongodb, with collision checks.workerandbroker.workerandbrokersections inapp-values.schema.json, copied to the petstore schema.worker.py(Celery entry point viaFoca.create_celery_app()) and ajobssection inconfig.yaml.ci/celery-values.yaml.charts.yml):ci/*-values.yaml.docs/helm-chart.mdcovers the templates, values, deployment notes (Secret layout with an example, Service name, persistence) and the CI install.docs/configuration/jobs.mdlinks to it.chart-v0.1.0hasn't been released yet (nochart-v*tags).Closes #351
Design choice for review: the bundled RabbitMQ keeps queued tasks in an
emptyDir, so they are lost when its pod is replaced. This is documented invalues.yamland the docs, with an external broker recommended for durable queues. A PVC would also need a stable RabbitMQ node name (e.g.,RABBITMQ_NODENAME=rabbit@localhost). Adding it later is backwards compatible, e.g., asbroker.persistence.Verification
pytest charts/foca-common/tests(Helm 3.22.1, as in CI): 119 passed. That is 93 before, plus 23 new template tests, acelerysnapshot and lints with both CI values files. The existing four snapshots are unchanged.helm lint --strictfor the library, and for the petstore chart with bothci/*-values.yaml: pass.helm dependency build:Chart.lockunchanged.ruff check,ruff format --check,mypy,mkdocs build --strict: pass. The nested code block in the docs was checked in the rendered HTML.actionlint 1.7.12 with shellcheck 0.11.0 on
charts.yml: pass.worker.pyimported locally with an overlay pointing to MongoDB on port 12345: it creates the Celery app with the broker URL fromCELERY_BROKER_URL.python -m celery --app worker:celery_appresolves.CI: all checks pass. In the kind job, both releases install and their
helm testpasses.celery@petstore-celery-worker-... ready.INTERNAL_ERROR - Feature transient_nonexcl_queues is deprecated.Sourcery: three threads, all fixed and resolved: optional worker probes, full selector labels in the NetworkPolicy tests, and the Celery render keeping all default resources.
Declined review findings
_worker.tplnotes that the two must stay in line, and a test compares the worker's env (minus Gunicorn), mounts, volumes and security contexts with the app's.helm testchecks the app's MongoDB access.worker.commandhas nominItemsin the schema. Declined, as it's consistent with the other values: "required if enabled" is checked by the template with a clear message.Open questions
None.
🤖 Generated with Claude Code