Skip to content

feat: Add dynamic port binding to TCPSite#12167

Merged
Dreamsorcerer merged 10 commits intoaio-libs:masterfrom
rodrigobnogueira:dynamic-ports-finish
Mar 1, 2026
Merged

feat: Add dynamic port binding to TCPSite#12167
Dreamsorcerer merged 10 commits intoaio-libs:masterfrom
rodrigobnogueira:dynamic-ports-finish

Conversation

@rodrigobnogueira
Copy link
Copy Markdown
Member

What do these changes do?

This PR continues #10697 by @twhittock-disguise, adding a port property to web.TCPSite that returns the dynamically assigned port when the site is created with port=0.

Key changes:

  • Introduced _bound_port to track the actual runtime port without mutating _port (addressing @webknjaz's feedback).
  • The port property returns _bound_port after start(), or the requested _port before that.
  • Updated name property to use self.port so logging reflects the real bound port.
  • Updated examples/fake_server.py to use port=0 + site.port instead of the race-prone unused_port() helper.
  • Added documentation in docs/web_advanced.rst and docs/web_reference.rst.
  • Added test_tcpsite_ephemeral_port in tests/test_web_runner.py.

Are there changes in behavior for the user?

Yes. Users can now retrieve the actual bound port via site.port after calling await site.start(). This is especially useful when port=0 is used for ephemeral port allocation. Previously, users had to resort to the internal site._server.sockets[0].getsockname()[1] hack.

Is it a substantial burden for the maintainers to support this?

No. This is a small, self-contained change to TCPSite that adds a read-only property backed by a single new slot (_bound_port). It does not change any existing public API or break backward compatibility. The maintenance cost is minimal.

Related issue number

Fixes #10665
Continues #10697

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt
  • Add a new news fragment into the CHANGES/ folder

@psf-chronographer psf-chronographer bot added the bot:chronographer:provided There is a change note present in this PR label Feb 28, 2026
twhittock-disguise and others added 6 commits February 28, 2026 12:26
Co-authored-by: J. Nick Koston <[email protected]>
Finishes PR aio-libs#10697, replacing unused_port utility in examples and correctly tracking _bound_port against the resolved socket without mutating _port.
@codspeed-hq
Copy link
Copy Markdown

codspeed-hq bot commented Feb 28, 2026

Merging this PR will not alter performance

✅ 59 untouched benchmarks


Comparing rodrigobnogueira:dynamic-ports-finish (4888fa8) with master (2d03bc4)

Open in CodSpeed

@webknjaz
Copy link
Copy Markdown
Member

CHANGES.rst aren't supposed to be edited in PRs, nor manually. It's updated as a part of the release process by a tool called Towncrier.

@rodrigobnogueira rodrigobnogueira force-pushed the dynamic-ports-finish branch 2 times, most recently from dd3d778 to ee960d7 Compare February 28, 2026 15:55
@codecov
Copy link
Copy Markdown

codecov bot commented Feb 28, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.78%. Comparing base (2d03bc4) to head (4888fa8).
⚠️ Report is 4 commits behind head on master.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #12167   +/-   ##
=======================================
  Coverage   98.78%   98.78%           
=======================================
  Files         128      128           
  Lines       45327    45348   +21     
  Branches     2405     2407    +2     
=======================================
+ Hits        44777    44798   +21     
  Misses        390      390           
  Partials      160      160           
Flag Coverage Δ
CI-GHA 98.64% <100.00%> (+<0.01%) ⬆️
OS-Linux 98.38% <100.00%> (+<0.01%) ⬆️
OS-Windows 96.75% <100.00%> (-0.01%) ⬇️
OS-macOS 97.63% <100.00%> (+<0.01%) ⬆️
Py-3.10.11 97.19% <100.00%> (+<0.01%) ⬆️
Py-3.10.19 97.65% <100.00%> (-0.02%) ⬇️
Py-3.11.14 97.86% <100.00%> (+<0.01%) ⬆️
Py-3.11.9 97.39% <100.00%> (+<0.01%) ⬆️
Py-3.12.10 97.48% <100.00%> (+<0.01%) ⬆️
Py-3.12.12 97.96% <100.00%> (+<0.01%) ⬆️
Py-3.13.12 98.20% <100.00%> (-0.01%) ⬇️
Py-3.14.3 98.16% <100.00%> (+<0.01%) ⬆️
Py-3.14.3t 97.27% <100.00%> (+0.01%) ⬆️
Py-pypy3.11.13-7.3.20 97.30% <100.00%> (+<0.01%) ⬆️
VM-macos 97.63% <100.00%> (+<0.01%) ⬆️
VM-ubuntu 98.38% <100.00%> (+<0.01%) ⬆️
VM-windows 96.75% <100.00%> (-0.01%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@rodrigobnogueira rodrigobnogueira marked this pull request as ready for review February 28, 2026 18:38
@Dreamsorcerer Dreamsorcerer added the backport-3.14 Trigger automatic backporting to the 3.14 release branch by Patchback robot label Feb 28, 2026
Per maintainer feedback, the dynamic port binding explanation and example
is more useful in the TCPSite reference docs where users looking up
TCPSite will naturally find it, rather than buried in the advanced guide.
@Dreamsorcerer Dreamsorcerer merged commit b08d909 into aio-libs:master Mar 1, 2026
43 checks passed
@patchback
Copy link
Copy Markdown
Contributor

patchback bot commented Mar 1, 2026

Backport to 3.14: 💔 cherry-picking failed — conflicts found

❌ Failed to cleanly apply b08d909 on top of patchback/backports/3.14/b08d909a0cb303498513be6916ea4e8a50792f04/pr-12167

Backporting merged PR #12167 into master

  1. Ensure you have a local repo clone of your fork. Unless you cloned it
    from the upstream, this would be your origin remote.
  2. Make sure you have an upstream repo added as a remote too. In these
    instructions you'll refer to it by the name upstream. If you don't
    have it, here's how you can add it:
    $ git remote add upstream https://github.com/aio-libs/aiohttp.git
  3. Ensure you have the latest copy of upstream and prepare a branch
    that will hold the backported code:
    $ git fetch upstream
    $ git checkout -b patchback/backports/3.14/b08d909a0cb303498513be6916ea4e8a50792f04/pr-12167 upstream/3.14
  4. Now, cherry-pick PR feat: Add dynamic port binding to TCPSite #12167 contents into that branch:
    $ git cherry-pick -x b08d909a0cb303498513be6916ea4e8a50792f04
    If it'll yell at you with something like fatal: Commit b08d909a0cb303498513be6916ea4e8a50792f04 is a merge but no -m option was given., add -m 1 as follows instead:
    $ git cherry-pick -m1 -x b08d909a0cb303498513be6916ea4e8a50792f04
  5. At this point, you'll probably encounter some merge conflicts. You must
    resolve them in to preserve the patch from PR feat: Add dynamic port binding to TCPSite #12167 as close to the
    original as possible.
  6. Push this branch to your fork on GitHub:
    $ git push origin patchback/backports/3.14/b08d909a0cb303498513be6916ea4e8a50792f04/pr-12167
  7. Create a PR, ensure that the CI is green. If it's not — update it so that
    the tests and any other checks pass. This is it!
    Now relax and wait for the maintainers to process your pull request
    when they have some cycles to do reviews. Don't worry — they'll tell you if
    any improvements are necessary when the time comes!

🤖 @patchback
I'm built with octomachinery and
my source is open — https://github.com/sanitizers/patchback-github-app.

rodrigobnogueira added a commit to rodrigobnogueira/aiohttp that referenced this pull request Mar 1, 2026
Co-authored-by: Tom Whittock <[email protected]>
Co-authored-by: Sam Bull <[email protected]>
Co-authored-by: Tom Whittock <[email protected]>
Co-authored-by: J. Nick Koston <[email protected]>
Co-authored-by: rodrigo.nogueira <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
(cherry picked from commit b08d909)
Dreamsorcerer added a commit that referenced this pull request Mar 2, 2026
…12184)

Co-authored-by: Tom Whittock <[email protected]>
Co-authored-by: Sam Bull <[email protected]>
Co-authored-by: Tom Whittock <[email protected]>
Co-authored-by: J. Nick Koston <[email protected]>
Co-authored-by: rodrigo.nogueira <[email protected]>
self._reuse_port = reuse_port

@property
def port(self) -> int:
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rodrigobnogueira @Dreamsorcerer I was thinking that maybe there would be an additional requested_port or smth like that, perhaps. Have you considered such an API?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the property port in this PR is

    @property
    def port(self) -> int:
        if self._bound_port is not None:
            return self._bound_port
        return self._port

Wanna add a property such as below?

    @property
    def requested_port(self) -> int:
        return self._port

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or... maybe, for the sake of clarity, we could delete property port and have properties bound_port (returns _bound_port) and requested_port (returns _port)

Copy link
Copy Markdown
Contributor

@twhittock-disguise twhittock-disguise Mar 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bound port == requested port unless you specifically said you didn't care what port you get (requested port == 0)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not clear it would be particularly useful to have a separate requested_port. In most cases the developer will probably know the requested port anyway.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking of cases where some other system interfaces w/ aiohttp and would want to know if it's safe to cache the port. But that could be discussed later, when there's a better use case, I suppose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-3.14 Trigger automatic backporting to the 3.14 release branch by Patchback robot bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve support for dynamic port allocations

4 participants