Skip to content

feat: Retrieve actual port from Server instances (API and Insights servers) - #4021

Merged
SandPod merged 5 commits into
mainfrom
copilot/fix-c22b5bc7-07e0-4f67-95fa-bc0235f7b172
Oct 6, 2025
Merged

SandPod merged 5 commits into
mainfrom
copilot/fix-c22b5bc7-07e0-4f67-95fa-bc0235f7b172

Conversation

Copilot AI commented Sep 30, 2025 •

Copy link
Copy Markdown
Contributor

Summary

This PR implements the ability to retrieve the actual bound port from Server instances (both API and Insights servers) when using dynamic port allocation (port 0).

Changes Made

Modified packages/serverpod/lib/src/server/server.dart:

  • ✅ Added _actualPort field to cache the actual bound port after server starts
  • ✅ Changed port getter to return _actualPort ?? _port (cached value)
  • ✅ Updated start() method to set _actualPort = ioServer.port after binding
  • ✅ Private _port field stores the configured port value
  • ✅ Updated constructor to accept port as a parameter and initialize _port
  • ✅ Error message uses _port which is correct since binding hasn't succeeded yet
  • ✅ Log message uses the port getter which returns the actual bound port

Servers Fixed:

How It Works

Before server starts:

  • _actualPort is null
  • port getter returns _port (the configured port, could be 0 for dynamic allocation)

After server starts:

  • _actualPort is set to the actual bound port from ioServer.port
  • port getter returns _actualPort (the cached actual port value)

Use Cases Enabled

  1. ✅ Dynamic port allocation by setting port to 0 in test configurations
  2. ✅ Retrieving the actual port after server starts for making network requests to API, Insights, or Web servers
  3. ✅ Concurrent test execution without port conflicts
  4. ✅ Performance optimization - port value is cached instead of being read repeatedly

Implementation Details

The implementation follows the same pattern as PR #3775 for the WebServer:

  • Uses _actualPort field to cache the bound port after server starts
  • Port getter returns the cached value for efficiency

Test Results

✅ All 713 unit tests in packages/serverpod pass successfully
✅ Code formatted and analyzed with no issues
✅ Existing integration tests already use server.port and serviceServer.port, confirming backward compatibility

Fixes #3949.

Original prompt

This section details on the original issue you should resolve

<issue_title>Retrieve the port from the server</issue_title>
<issue_description>### Problem to Solve

The real port in use cannot be retrieved from the server instance. The one that is accessible today is taken from the constructor input, but if I set the port to 0, which means take any port that is available, the real port in use will be different. That port is today not accessible from the outside of the start method (that lives in the framework).

Proposal

Modify the server getter of port to return the real port, something like this:

Which would return the real port if available, otherwise the input port.

// server.dart
int get port => _ioServer?.port ?? _port;

The ports would also need to be accessible from the test framework, as the server object is hidden in there. Perhaps this would warrant another test method? E.g. withRelic instead of withServerpod, for example.

Use Case

In the test framework, the port is set to 0 by default, which is a very good default, as that enables concurrent tests. But if I want to make network calls to any of the servers api, insights, web, I'm not able to do that as I cannot retrieve the port.

In my specific case I would like to make a network request to the webserver.

Alternatives

Hard-code the port, but then you lose the ability to run concurrently.

Additional context

No response

How experienced are you with this library?

Expert - Experienced and comfortable with using this library in complex projects

Are you interested in working on a PR for this?

  • I want to work on this</issue_description>

<agent_instructions>This pull request implements something similair: #3775

Assert that this fix i applied both to the Serverpod and the Insights server.</agent_instructions>

Comments on the Issue (you are @copilot in this section)

@christerswahn This should be already fixed in PR #3775 . Does it not work? @Isakdl You are right! But it is only for the web server! So in fact my bug report is slightly wrong, we get the real port for the web server, but not the others!
Fixes #3949

💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Summary by CodeRabbit

  • Bug Fixes

    • Server now reports the actual bound port after startup (including when using an ephemeral port), improving accuracy in logs and diagnostics.
    • Startup error messages now reference the correct port, making troubleshooting clearer.
  • New Features

    • Added a public way to read the effective port the server is bound to at runtime.

Copilot AI changed the title [WIP] Retrieve the port from the server feat: Retrieve actual port from Server instances (API and Insights servers) Sep 30, 2025
Copilot AI requested a review from SandPod September 30, 2025 14:00

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@coderabbitai full review

@SandPod

SandPod commented Oct 3, 2025

Copy link
Copy Markdown
Contributor

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Oct 3, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai

coderabbitai Bot commented Oct 3, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Adds a private _port field, a public port getter returning _ioServer?.port ?? _port, updates the Server constructor to accept int port and assign _port, and switches internal binding/error reporting to use _port or the bound port via _ioServer.

Changes

Cohort / File(s) Summary
Server port handling refactor
packages/serverpod/lib/src/server/server.dart
- Added private final int _port; and public getter int get port => _ioServer?.port ?? _port
- Constructor now takes required int port and assigns _port
- Startup and error handling now reference _port/_ioServer?.port to reflect the actual bound port

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as Application
  participant Server as Server
  participant IO as _ioServer (HTTP)

  rect rgba(230,240,255,0.5)
    App->>Server: new Server(port)
    Note right of Server: Store configured\nport in _port
    App->>Server: start()
    Server->>IO: bind(_port)
    IO-->>Server: bound (port may differ, e.g., 0->random)
    Note right of Server: _ioServer set\n(port reflects actual binding)
  end

  rect rgba(240,230,255,0.5)
    App->>Server: get port
    alt _ioServer bound
      Server-->>App: _ioServer.port
    else not yet bound
      Server-->>App: _port
    end
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The description thoroughly covers the problem, solution, implementation details, use cases, and testing outcomes, and correctly cites a specific issue fix, but it omits the repository’s required “## Pre-launch Checklist” section that ensures compliance with contribution guidelines. Please add the “## Pre-launch Checklist” section from the repository template, including the checklist items confirming contribution process, style compliance, tests added, and all tests passing.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title concisely describes the main change of allowing retrieval of the actual bound port from Server instances for API and Insights servers and follows the conventional "feat:" prefix, making it clear and specific to the core change.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

Note

Free review on us!

CodeRabbit is offering free reviews until Wed Oct 08 2025 to showcase some of the refinements we've made.

Comment @coderabbitai help to get the list of available commands and usage tips.

@SandPod

SandPod commented Oct 3, 2025

Copy link
Copy Markdown
Contributor

@copilot please address or answer my review comments.

Copilot AI requested a review from SandPod October 3, 2025 17:24
@SandPod
SandPod marked this pull request as ready for review October 3, 2025 17:33
@SandPod
SandPod requested a review from a team October 3, 2025 17:34

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖

@marcelomendoncasoares marcelomendoncasoares left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Just one comment regarding testing, if we think it's needed.

@SandPod
SandPod merged commit c095976 into main Oct 6, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 6, 2025
@SandPod
SandPod deleted the copilot/fix-c22b5bc7-07e0-4f67-95fa-bc0235f7b172 branch October 6, 2025 06:56
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Retrieve the port from the server

3 participants