Skip to content

feat: read PORT in foca.gunicorn_config - #662

Merged
uniqueg merged 3 commits into
devfrom
feat/619-gunicorn-port
Nov 4, 2026
Merged

uniqueg merged 3 commits into
devfrom
feat/619-gunicorn-port

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

foca.gunicorn_config now binds to the port in PORT, by default 8080. Values other than an integer from 1 to 65535 stop the server with a clear error. The chart keeps 8080 and doesn't set PORT. Deployment docs updated.

Closes #619

Light lane: a default configuration value with a trivial check and tests; no auth, release workflow or chart change.

Verification

  • ruff check, ruff format --check, mypy, ast-grep scan, mkdocs build --strict: pass.
  • coverage run -m pytest with MongoDB 7.0: 3387 passed, 1 skipped, 100% coverage.
  • CI: see the checks of this PR.

🤖 Generated with Claude Code

Summary by Sourcery

Configure Gunicorn to honor a validated PORT environment variable for platform deployments while preserving the existing default port.

New Features:

  • Allow Gunicorn to bind to the port specified by the PORT environment variable, while retaining port 8080 by default.

Enhancements:

  • Reject invalid PORT values with a clear startup error.
  • Document platform-provided ports, chart behavior, and low-port requirements.

Tests:

  • Add coverage for default, valid, invalid, and environment-driven Gunicorn port configuration.

Platforms such as Cloud Run, Knative and Heroku-style PaaS inject PORT,
which the fixed bind address hid. Bind to that port, by default 8080,
and stop with a clear error if it isn't an integer from 1 to 65535. The
chart keeps 8080 and doesn't set PORT.

Closes #619

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

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Gunicorn now reads PORT when loaded, defaults to 8080 for chart compatibility, and fails clearly for values outside the integer range 1–65535. Deployment documentation and focused tests cover the parsing rules, error cases, and resulting bind address.

Sequence diagram for PORT-based Gunicorn binding

sequenceDiagram
    participant Environment
    participant GunicornConfig
    participant Gunicorn
    Environment->>GunicornConfig: _get_port()
    GunicornConfig->>Environment: os.environ.get(PORT)
    alt PORT is unset
        GunicornConfig-->>Gunicorn: bind = 0.0.0.0:8080
    else PORT is valid
        GunicornConfig-->>Gunicorn: bind = 0.0.0.0:PORT
    else PORT is invalid
        GunicornConfig-->>Gunicorn: ValueError
    end
Loading

File-Level Changes

Change Details Files
Added validated environment-based port selection for Gunicorn while preserving the chart-compatible default.
  • Introduced a default port of 8080 and an upper bound of 65535.
  • Read PORT at module load time and format the bind address accordingly.
  • Reject unset-invalid values, non-ASCII/non-numeric strings, and ports outside 1–65535 with a descriptive ValueError.
foca/gunicorn_config.py
Added documentation explaining PORT behavior across deployment environments.
  • Documented the default 8080 binding and PORT override.
  • Clarified that the Helm chart does not set PORT and retains its fixed service/probe port.
  • Described validation failures for invalid PORT values.
docs/deployment.md
Added coverage for port parsing and Gunicorn module binding.
  • Tested unset, valid boundary, and invalid PORT values.
  • Verified that loading the configuration module binds to the configured port.
tests/test_gunicorn_config.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

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #662   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           56        56           
  Lines         7189      7198    +9     
=========================================
+ Hits          7189      7198    +9     
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 November 4, 2026 03:02

@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 3 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="66" />
<code_context>
+    if value is None:
+        return _DEFAULT_PORT
+    # `isascii()`, as `int()` also takes other digits, signs and whitespace
+    if not (value.isascii() and value.isdigit() and 1 <= int(value) <= _MAX_PORT):
+        raise ValueError(
+            f"Environment variable PORT must be an integer between 1 and "
</code_context>
<issue_to_address>
**Low ports fail in non-root containers**

When `PORT` is set below 1024 and the runtime does not grant permission to bind privileged ports, `_get_port()` accepts values such as `80`, but Gunicorn cannot bind ports below 1024 as the documented image's UID 1000 without `CAP_NET_BIND_SERVICE` or a permissive system setting. Gunicorn then fails during startup and the container does not serve traffic.

Reject ports below 1024 unless the deployment grants the required capability, or document and configure that capability for low-port deployments.
</issue_to_address>

### Comment 2
<location path="foca/gunicorn_config.py" line_range="66" />
<code_context>
+    if value is None:
+        return _DEFAULT_PORT
+    # `isascii()`, as `int()` also takes other digits, signs and whitespace
+    if not (value.isascii() and value.isdigit() and 1 <= int(value) <= _MAX_PORT):
+        raise ValueError(
+            f"Environment variable PORT must be an integer between 1 and "
</code_context>
<issue_to_address>
**Valid long ports fail conversion**

When PORT has more ASCII digits than Python's configured integer-conversion limit, including a zero-padded valid port, `_get_port()` calls `int(value)` before its range check, so Python raises its digit-limit `ValueError` even for a valid zero-padded port and Gunicorn exits without the promised PORT-specific range diagnostic.

Check the decimal string's range without converting an over-limit string while preserving valid leading-zero values, and raise the PORT-specific range error for invalid values.
</issue_to_address>

### Comment 3
<location path="foca/gunicorn_config.py" line_range="76" />
<code_context>
+
+# Address of the app (the app config's `server` settings apply to the
+# development server only)
+bind = [f"0.0.0.0:{_get_port()}"]

 # One process with a few threads, as each worker loads the whole app
</code_context>
<issue_to_address>
**Tests fail with an injected port**

When the test process inherits a valid `PORT` other than 8080, `bind` uses the injected port, but `test_settings` and `test_petstore_command` still assert `0.0.0.0:8080`, so pytest fails.

Make the tests independent of the injected runtime `PORT`, or derive their expected bind address from it.
</issue_to_address>

Linked issues

#619 feat: read PORT in foca.gunicorn_config · 4 of 4 met

# Requirement Status Notes
1 Bind to PORT, defaulting to 8080, and reject values outside 1–65535 with a clear error. ✅ Met foca/gunicorn_config.py reads PORT, validates it, and builds bind from the resulting port.
2 Keep the chart on 8080 and do not set PORT there. ✅ Met The chart remains unchanged; its service and probes use 8080, and PORT is not set in the chart.
3 Test unset, valid, and invalid PORT values, with 100% coverage. ✅ Met Tests cover unset, valid, invalid, and module-level binding behavior; the project enforces 100% coverage and the PR reports it passing.
4 Mention PORT in the deployment documentation. ✅ Met docs/deployment.md documents PORT-based binding and the chart's fixed port.

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and if PORT is invalid, Gunicorn fails to start; if it names a port the platform or service does not expect, the app can become unreachable. Reverting restores the fixed port, but it cannot undo requests missed during an outage.

Blocking findings: foca/gunicorn_config.py:66, foca/gunicorn_config.py:66, foca/gunicorn_config.py:76


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

Comment thread foca/gunicorn_config.py Resolved
Comment thread foca/gunicorn_config.py Resolved
Comment thread foca/gunicorn_config.py Resolved
uniqueg and others added 2 commits November 4, 2026 04:10
Check the length of PORT before converting it, so that very long values
get the error that names the variable, not the digit limit of int(). Make
the tests independent of a PORT in the test environment, and document
that ports below 1024 need a capability for non-root users.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

Linked issues

#619 feat: read PORT in foca.gunicorn_config · 3 of 4 met

# Requirement Status Notes
1 Read PORT, default to 8080, and validate it as an integer from 1 to 65535 with a clear error otherwise. 🟡 Partly met The port is read, defaulted, and range-checked, but the length check rejects zero-padded values such as 000080, which represent the valid port 80.
2 Keep the chart on port 8080 and have it not set PORT. ✅ Met The chart's container port, Service, and probes remain on 8080, and the chart does not set PORT.
3 Test unset, valid, and invalid PORT values, with 100% coverage. ✅ Met Tests cover unset, valid, and invalid values and verify the configured bind; the PR reports 100% coverage.
4 Mention PORT in the deployment documentation. ✅ Met The deployment settings table documents PORT handling and validation.

Comment thread foca/gunicorn_config.py Resolved

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

Sourcery assessment

Approved.

@uniqueg
uniqueg merged commit 2b383e1 into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the feat/619-gunicorn-port branch November 4, 2026 03:25
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: read PORT in foca.gunicorn_config

1 participant