Skip to content

feat(config): add default Gunicorn settings - #463

Merged
uniqueg merged 4 commits into
devfrom
feat/gunicorn-config
Oct 24, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/gunicorn-config

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Moves cloud-registry's Gunicorn settings into FOCA, so that apps share one set of container defaults:

  • foca.gunicorn_config: a Gunicorn config module (gunicorn --config python:foca.gunicorn_config "wsgi:create_app()") with the settings of the issue: bind = ["0.0.0.0:8080"], one gthread worker with 4 threads, timeout = 30, graceful_timeout = 20, keepalive = 100, explicit request limits, accesslog = None, errorlog = "-", control_socket_disable = True, worker_tmp_dir set to /dev/shm if it is writable (else Gunicorn's default). preload_app and forwarded_allow_ips are not set. The module does not import Gunicorn. It has an __all__, so from foca.gunicorn_config import * exports only the settings.
  • Dependencies: gunicorn>=26.2,<27 goes into the dev extra only, for the tests. There is no gunicorn extra (the issue left this open and defaults to none).
  • Petstore example: the image runs gunicorn --config python:foca.gunicorn_config "wsgi:create_app()". The access-control example has no Gunicorn command (it runs the development server), so it is unchanged.
  • Tests (tests/test_gunicorn_config.py, from cloud-registry): Gunicorn loads the settings without the app, restoring sys.argv, the environment and the working directory. They also check that GUNICORN_CMD_ARGS overrides the settings, the keep-alive against proxies and worker_connections, the /dev/shm fallback (missing, read-only, or a file), that the module does not import Gunicorn, that the star import exports exactly the settings, and the petstore image's command. cloud-registry's health-check port test is left out, as the petstore image has no health check.
  • Docs: "Running in production" (docs/deployment.md) uses the module. It lists each setting and why it is set (no preloading, no control socket, keep-alive vs. proxy timeouts, graceful timeout vs. termination grace period) and shows both ways to override them (GUNICORN_CMD_ARGS, or an app module that star-imports FOCA's). docs/helm-chart.md links there from the gunicorn values. docs/migration-0.18.md mentions the change under "Other changes": it is opt-in, so no migration is needed.

Verification

  • coverage run -m pytest -m "not mongodb": all passed, 100% coverage
  • ruff check, ruff format --check, mypy: pass
  • mkdocs build --strict: pass
  • pre-commit run --all-files: pass
  • CI: all checks passed (unit tests on Python 3.11 to 3.15, lint, docs, image scans, petstore integration tests, petstore chart installed on kind)

Reviewed by the adversarial and quality reviewer subagents (2 rounds). Fixed: the access-log rationale (FOCA logs only the traffic of log_traffic controllers), the note that the Helm chart's keep-alive (75 s) applies instead of the module's, the sys.path leak of the test helper, a vacuous health-check test, and a tautological worker_tmp_dir assertion.

Sourcery: added a docs note to serve the app behind a buffering reverse proxy (slow uploads vs. few threads; the settings stay as the issue sets them), and a test that the heartbeat directory defaults to /dev/shm.

Declined review findings

  • Rationale repeated in module comments, docs and test docstrings (quality, medium): kept. The module is a config file that deployers read on its own, as in cloud-registry, and the issue asks the docs to explain the settings.
  • Test helper could use monkeypatch instead of manual restore (quality, low): kept as in cloud-registry. The helper is also called outside of fixtures.
  • Gunicorn version in three places (docs, petstore Dockerfile pin, dev extra) (quality, low): kept. They have different roles (supported range, image pin, docs).
  • Chart keep-alive default 75 vs. module 100 (both, low/medium): documented here. Aligning the chart's default is a Helm chart change and is proposed as a follow-up.

Open questions

None.

Closes #458

🤖 Generated with Claude Code

uniqueg and others added 3 commits October 24, 2026 13:45
Add `foca.gunicorn_config`, a Gunicorn config module with the container
settings of cloud-registry (bind 0.0.0.0:8080, one gthread worker with
four threads, timeouts below the pod's grace period, keep-alive longer
than that of proxies, explicit request limits, no access log, no
control socket, heartbeat files in /dev/shm if writable). It does not
import Gunicorn, which goes into the dev extra for the tests only.

The petstore image uses it. GUNICORN_CMD_ARGS still takes precedence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
List the settings of `foca.gunicorn_config` in "Running in production",
why they are set and how to override them; link to them from the Helm
chart's notes on its `gunicorn` values, and mention them in the
migration guide.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Correct the reason for no access log: FOCA logs only the traffic of
  controllers decorated with `log_traffic`
- Note that the Helm chart's keep-alive (75 seconds) applies instead
- Tests: restore `sys.path` after loading the settings, check the
  heartbeat directory against the helper, test the star import, and
  drop the health check test (the image has no health check)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.18.0 milestone Oct 24, 2026
@sourcery-ai

sourcery-ai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR introduces an opt-in, dependency-free foca.gunicorn_config module containing shared container defaults, adopts it in the petstore example, documents configuration rationale and override precedence—including Helm behavior—and adds comprehensive Gunicorn integration and filesystem fallback tests.

Sequence diagram for Gunicorn configuration precedence

sequenceDiagram
    participant App as App container
    participant Gunicorn
    participant Config as foca.gunicorn_config
    participant Env as GUNICORN_CMD_ARGS
    participant WSGI as wsgi:create_app

    App->>Gunicorn: Start with --config python:foca.gunicorn_config
    Gunicorn->>Config: Load default settings
    Gunicorn->>Env: Read overrides
    Env-->>Gunicorn: Override matching settings
    Gunicorn->>WSGI: Create app in worker process
    WSGI-->>Gunicorn: WSGI application
Loading

File-Level Changes

Change Details Files
Adds a reusable, dependency-free Gunicorn Python configuration module with container-oriented defaults and safe /dev/shm handling.
  • Defines binding, gthread worker sizing, timeouts, keep-alive, request limits, logging, control-socket, and temporary-directory settings.
  • Keeps Gunicorn out of FOCA runtime imports and restricts star-import exports with __all__.
  • Falls back to Gunicorn's temporary-directory behavior when /dev/shm is unavailable or unwritable.
foca/gunicorn_config.py
Integrates the shared Gunicorn configuration into the example image and documents its opt-in and override behavior.
  • Updates the petstore image to load foca.gunicorn_config.
  • Documents setting rationale, deliberate omissions, GUNICORN_CMD_ARGS precedence, app-specific override modules, and Helm chart interactions.
  • Links Helm guidance and records the opt-in behavior in migration notes.
examples/petstore/Dockerfile
docs/deployment.md
docs/helm-chart.md
docs/migration-0.18.md
Adds focused validation of Gunicorn loading, configuration precedence, environment isolation, exports, filesystem fallbacks, and image integration.
  • Tests settings through Gunicorn without loading the application.
  • Verifies command-line overrides, restoration of process state, no Gunicorn import, exact star-import exports, and the petstore command.
  • Covers writable, missing, read-only, and file-based /dev/shm cases.
tests/test_gunicorn_config.py
Adds Gunicorn only as a development/test dependency while preserving FOCA's runtime independence from it.
  • Pins the tested Gunicorn range in the dev extra.
  • Does not add Gunicorn to runtime dependencies or a dedicated production extra.
pyproject.toml

Assessment against linked issues

Issue Objective Addressed Explanation
#458 Add foca.gunicorn_config with the specified container defaults, without importing Gunicorn, and allow command-line overrides and app-specific overrides. ✅
#458 Add tests covering Gunicorn loading the settings, precedence of GUNICORN_CMD_ARGS, keep-alive constraints, /dev/shm fallback behavior, and the petstore command. ✅
#458 Switch the petstore example to the config module and document the settings, rationale, override options, and Helm chart integration. ✅

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

@codecov

codecov Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (dc4b4c6) to head (339140b).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #463   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           28        29    +1     
  Lines         3266      3287   +21     
=========================================
+ Hits          3266      3287   +21     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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 marked this pull request as ready for review October 24, 2026 12:03

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

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

## Individual Comments

### Comment 1
<location path="foca/gunicorn_config.py" line_range="50-52" />
<code_context>
+bind = ["0.0.0.0:8080"]
+
+# One process with a few threads, as each worker loads the whole app
+worker_class = "gthread"
+workers = 1
+threads = 4
+
+# Workers whose main loop does not report to Gunicorn for `timeout` seconds
</code_context>
<issue_to_address>
**Slow uploads exhaust request threads**

When an external client can reach an app with `server.max_content_length` unset and no upstream request-size or read-time limit, `gthread` serves requests in only four threads, and the worker timeout does not count requests running in those threads. With no effective body or read-time limit, slow uploads occupy all four threads and the app stops serving requests, including to authenticated users.

Ensure the default deployment enforces a finite request-body limit and an appropriate upstream read timeout, or use worker settings that prevent slow requests from indefinitely exhausting the available request threads.
</issue_to_address>

### Comment 2
<location path="tests/test_gunicorn_config.py" line_range="105" />
<code_context>
+    assert not cfg.preload_app
+    # Not set: Gunicorn's defaults
+    assert cfg.forwarded_allow_ips == Config().forwarded_allow_ips
+    assert cfg.worker_tmp_dir == _worker_tmp_dir()
+
+
</code_context>
<issue_to_address>
**Disk-backed heartbeat files pass**

When the helper's default path is changed to `/tmp` while `/dev/shm` is writable, `test_settings` compares `cfg.worker_tmp_dir` with `_worker_tmp_dir()` at `tests/test_gunicorn_config.py:105`; if both use `/tmp` instead of `/dev/shm`, they still match. The helper tests pass an explicit `tmp_path` at `:184`, so they also pass without checking the default path.

Add an assertion that the default selects `/dev/shm` when it is writable.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: foca/gunicorn_config.py:52, tests/test_gunicorn_config.py:105


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

Comment thread foca/gunicorn_config.py Resolved
Comment thread tests/test_gunicorn_config.py Resolved
- Docs: serve the app behind a reverse proxy that buffers requests, as
  slow uploads would otherwise keep the few threads of a worker busy
- Test that the heartbeat directory is `/dev/shm` by default

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 0be1f73 into dev Oct 24, 2026
32 checks passed
@uniqueg
uniqueg deleted the feat/gunicorn-config branch October 24, 2026 12:15
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(config): add default Gunicorn settings

1 participant