Skip to content

Automatic Port Numbers #117

Merged
mostlygeek merged 5 commits intomainfrom
auto-port-numbers
May 6, 2025
Merged

Automatic Port Numbers #117
mostlygeek merged 5 commits intomainfrom
auto-port-numbers

Conversation

@mostlygeek
Copy link
Copy Markdown
Owner

@mostlygeek mostlygeek commented May 5, 2025

Fixes #105

  • using ${PORT} in model.cmd will automatically be replaced with a internally managed port numbers
  • port numbers start at config.startPort, which defaults to 5800
  • model.proxy, if omitted will automatically be assigned http://localhost:${PORT}

Summary by CodeRabbit

  • Documentation

    • Updated instructions to describe automatic port assignment using a ${PORT} placeholder in model commands and proxies.
    • Added details about the new startPort configuration key and clarified default behaviors.
    • Revised model examples to demonstrate dynamic port assignment.
  • New Features

    • Introduced support for automatic port assignment for models using a configurable start port.
  • Tests

    • Added tests to verify automatic port assignment and validation of start port values.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented May 5, 2025

"""

Walkthrough

Automatic port assignment for model processes was implemented by introducing a ${PORT} placeholder in model commands and proxies. A new startPort configuration key allows users to specify the base port for assignment, defaulting to 5800. Documentation and tests were updated to reflect these changes, ensuring backward compatibility.

Changes

File(s) Change Summary
README.md Documented ${PORT} placeholder usage, new startPort config, updated examples, clarified proxy defaults.
proxy/config.go Added StartPort to config, implemented logic for ${PORT} replacement and automatic port assignment.
proxy/config_test.go Added/updated tests for default/invalid/explicit start port and automatic port assignment logic; adjusted assertions.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ConfigLoader
    participant ModelProcess

    User->>ConfigLoader: Provide config with models using ${PORT}
    ConfigLoader->>ConfigLoader: Assign StartPort (default 5800 or user-defined)
    ConfigLoader->>ConfigLoader: For each model with ${PORT}, assign incrementing port
    ConfigLoader->>ModelProcess: Launch model with cmd/proxy using assigned port
Loading

Assessment against linked issues

Objective Addressed Explanation
Allow usage of ${PORT} in cmd and substitute automatic port value (#105)
Support default and configurable port range, defaulting to sensible value (#105)
Default proxy to 127.0.0.1:$PORT if proxy config is blank (#105)
Ensure backward compatibility with existing configurations (#105)

Poem

Oh, what a joy for every port,
No more numbers to retort!
With ${PORT} I hop along,
Assigning ports where they belong.
From 5800 we now embark,
Each model finds its unique spark!
🐇✨
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3baf1f3 and 72b460c.

📒 Files selected for processing (1)
  • proxy/config.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • proxy/config.go
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
proxy/config.go (1)

115-121: StartPort validation logic looks good

The default port (5800) and validation logic are well implemented. However, the error message at line 120 mentions "start_port" while the YAML field is actually "startPort" (camelCase).

-		return Config{}, fmt.Errorf("start_port must be greater than 1")
+		return Config{}, fmt.Errorf("startPort must be greater than 1")
README.md (1)

195-195: Incomplete sentence in documentation

Line 195 contains an incomplete sentence "llama-s" that seems to be cut off.

Either complete the sentence or remove it.

proxy/config_test.go (1)

317-345: Consider adding test for boundary port values

While the current tests are good, consider adding a test case for very high port numbers to verify behavior when approaching system limits.

You could add a test case like:

t.Run("High port values", func(t *testing.T) {
    content := `
startPort: 65000
models:
  model1:
    cmd: svr --port ${PORT}
  model2:
    cmd: svr --port ${PORT}
`
    config, err := LoadConfigFromReader(strings.NewReader(content))
    if !assert.NoError(t, err) {
        t.Fatalf("Failed to load config: %v", err)
    }

    assert.Equal(t, 65000, config.StartPort)
    assert.Equal(t, "svr --port 65000", config.Models["model1"].Cmd)
    assert.Equal(t, "svr --port 65001", config.Models["model2"].Cmd)
})
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ca9063f and fee1f89.

📒 Files selected for processing (3)
  • README.md (3 hunks)
  • proxy/config.go (4 hunks)
  • proxy/config_test.go (2 hunks)
🔇 Additional comments (7)
proxy/config.go (1)

68-69: Good addition of StartPort field with clear purpose

The field is properly documented in the code with a descriptive comment and appropriate YAML tag.

README.md (4)

73-80: Clear documentation of the new automatic port feature

The explanation is concise and helpful, covering:

  • How to use the ${PORT} placeholder
  • Default values and configuration options
  • When proxy can be omitted

This will make it easy for users to adopt this feature.


121-121: Good example of ${PORT} usage in command

This updated example properly demonstrates the new placeholder functionality.


125-129: Comprehensive example showing ${PORT} in both proxy and Docker port mapping

This is a helpful example demonstrating the flexibility of the automatic port assignment feature with Docker containers.


94-95: Helpful comment about omitting proxy when using ${PORT}

This clarifies an important aspect of the feature for users.

proxy/config_test.go (2)

77-77: Appropriate update to existing test case

The test case was correctly updated to include the default StartPort value (5800).


284-347: Comprehensive test coverage for the automatic port assignment feature

The test suite is well-structured with separate test cases for:

  • Default port value (5800)
  • User-specified port values
  • Invalid port configurations (non-numeric and negative values)
  • Various automatic port assignment scenarios

The tests are thorough and cover the main functionality paths including:

  • Default proxy generation when none is provided
  • Replacement of ${PORT} in custom proxy URLs
  • Verification that models without ${PORT} remain unchanged

This will help ensure the feature remains stable during future changes.

Comment on lines +134 to +156
// iterate over the models and replace any ${PORT} with the next available port
// Get and sort all model IDs first, makes testing more consistent
modelIds := make([]string, 0, len(config.Models))
for modelId := range config.Models {
modelIds = append(modelIds, modelId)
}
sort.Strings(modelIds) // This guarantees stable iteration order

// iterate over the sorted models
nextPort := config.StartPort
for _, modelId := range modelIds {
modelConfig := config.Models[modelId]
if strings.Contains(modelConfig.Cmd, "${PORT}") {
modelConfig.Cmd = strings.ReplaceAll(modelConfig.Cmd, "${PORT}", strconv.Itoa(nextPort))
if modelConfig.Proxy == "" {
modelConfig.Proxy = fmt.Sprintf("http://localhost:%d", nextPort)
} else {
modelConfig.Proxy = strings.ReplaceAll(modelConfig.Proxy, "${PORT}", strconv.Itoa(nextPort))
}
nextPort++
config.Models[modelId] = modelConfig
}
}
Copy link
Copy Markdown

@coderabbitai coderabbitai bot May 5, 2025

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Well-implemented automatic port assignment logic

The implementation nicely handles:

  1. Sorting model IDs for consistent port assignment
  2. Replacing ${PORT} placeholders in commands
  3. Setting default proxy or updating existing proxy URLs
  4. Incrementing ports sequentially

I appreciate the thoughtful approach to ensure stable port assignments by sorting model IDs.

One concern is potential port conflicts with system services. Let's check if there's any validation to ensure assigned ports are available:


🏁 Script executed:

#!/bin/bash
# Search for system port availability checks
rg -A 3 "port.*avail|avail.*port|CheckPort"

Length of output: 347


Add port availability checks during automatic port assignment

The current logic in proxy/config.go (lines 134–156) sequentially assigns ports from StartPort without verifying they’re free, which may cause conflicts with existing services. Please integrate a check—e.g., attempt a temporary net.Listen on the candidate port and retry on error—before finalizing each assignment.

• File: proxy/config.go, lines 134–156
• Suggested approach:

for _, modelId := range modelIds {
    // find next free port
    for {
        ln, err := net.Listen("tcp", fmt.Sprintf(":%d", nextPort))
        if err != nil {
            nextPort++
            continue
        }
        ln.Close()
        break
    }
    // replace ${PORT} and set proxy as before
    ...
    nextPort++
}

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

this is fine it is up to the users to provide a good startPort for the range.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@mostlygeek Understood! Thanks for clarifying the design decision. I'll respect your approach of letting users manage their port range selection.


✏️ Learnings added
Learnt from: mostlygeek
PR: mostlygeek/llama-swap#117
File: proxy/config.go:0-0
Timestamp: 2025-05-05T23:54:14.185Z
Learning: In the llama-swap project, automatic port assignment does not include port availability checks. It's the user's responsibility to provide an appropriate startPort that doesn't conflict with other services.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@mostlygeek mostlygeek added the enhancement New feature or request label May 5, 2025
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
proxy/config.go (1)

134-158: Add port availability checks during automatic port assignment

The current logic sequentially assigns ports from StartPort without verifying they're free, which may cause conflicts with existing services.

Please integrate a check (e.g., attempt a temporary net.Listen on the candidate port and retry on error) before finalizing each assignment, as suggested in the previous review comment.

Additional imports needed:

import "net"

Example implementation:

for _, modelId := range modelIds {
    // find next free port
    for {
        ln, err := net.Listen("tcp", fmt.Sprintf(":%d", nextPort))
        if err != nil {
            nextPort++
            continue
        }
        ln.Close()
        break
    }
    
    // replace ${PORT} and set proxy as before
    modelConfig := config.Models[modelId]
    if strings.Contains(modelConfig.Cmd, "${PORT}") {
        modelConfig.Cmd = strings.ReplaceAll(modelConfig.Cmd, "${PORT}", strconv.Itoa(nextPort))
        if modelConfig.Proxy == "" {
            modelConfig.Proxy = fmt.Sprintf("http://localhost:%d", nextPort)
        } else {
            modelConfig.Proxy = strings.ReplaceAll(modelConfig.Proxy, "${PORT}", strconv.Itoa(nextPort))
        }
        nextPort++
        config.Models[modelId] = modelConfig
    } else if modelConfig.Proxy == "" {
        return Config{}, fmt.Errorf("model %s requires a proxy value when not using automatic ${PORT}", modelId)
    }
}
🧹 Nitpick comments (2)
proxy/config.go (2)

115-121: Improve validation for port ranges

The validation for StartPort ensures it's greater than 1, which is good, but could be enhanced to handle additional constraints:

  1. Ports ≤ 1024 are privileged on Unix systems and might require elevated permissions
  2. No upper bound check to ensure ports don't exceed the maximum valid port number (65535)

Consider implementing a more comprehensive validation:

if config.StartPort == 0 {
    // default to 5800
    config.StartPort = 5800
} else if config.StartPort < 1 {
    return Config{}, fmt.Errorf("start_port must be greater than 1")
+} else if config.StartPort <= 1024 {
+    // Warning: using system ports
+} else if config.StartPort > 65535 {
+    return Config{}, fmt.Errorf("startPort must be less than or equal to 65535")
}

120-120: Fix error message to match configuration field name

The error message refers to start_port with an underscore, but the YAML field is startPort (camelCase).

- return Config{}, fmt.Errorf("start_port must be greater than 1")
+ return Config{}, fmt.Errorf("startPort must be greater than 1")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fee1f89 and 3baf1f3.

📒 Files selected for processing (2)
  • proxy/config.go (4 hunks)
  • proxy/config_test.go (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • proxy/config_test.go
🔇 Additional comments (2)
proxy/config.go (2)

140-140: Well-implemented sorting for stable port assignments

Sorting the model IDs ensures consistent port assignments across application restarts, which is excellent for stability and testing.


147-152: Well-designed port substitution logic

The implementation correctly handles:

  1. Replacing ${PORT} placeholders in commands
  2. Setting default proxy URL when none is provided
  3. Updating existing proxy URLs that contain ${PORT}

@mostlygeek mostlygeek self-assigned this May 6, 2025
@mostlygeek mostlygeek merged commit 09e52c0 into main May 6, 2025
2 checks passed
@mostlygeek mostlygeek deleted the auto-port-numbers branch May 6, 2025 00:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Automatically create a PORT number for Processes

1 participant