Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add url normalization for list of URLs #557

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

OnSuorce
Copy link

@OnSuorce OnSuorce commented May 7, 2024

This PR is related to issue #545 and #556 .

Changes

Extracted the normalization logic into a new method which is then called to both normalize URL s from a single string and multiple string from a List.

def _normalize_url(self, url: str):
        """
        Normalizes and validates a connection URL to ensure compatibility.
        Adds default schemes and ports if missing, and checks for a valid hostname.
        """
        try:
            if "nats://" in url or "tls://" in url:
                # Closer to how the Go client handles this.
                # e.g. nats://localhost:4222
                uri = urlparse(url)
            elif "ws://" in url or "wss://" in url:
                uri = urlparse(url)
            elif ":" in url:
                # Expand the scheme for the user
                # e.g. localhost:4222
                uri = urlparse(f"nats://{url}")
            else:
                # Just use the endpoint with the default NATS port.
                # e.g. demo.nats.io
                uri = urlparse(f"nats://{url}:4222")

            # In case only endpoint with scheme was set.
            # e.g. nats://demo.nats.io or localhost:
            # the ws and wss do not need a default port as the transport will assume 80 and 443, respectively
            if uri.port is None and uri.scheme not in ("ws", "wss"):
                # Set default NATS port 4222 if no port is specified
                uri = urlparse(f"nats://{uri.hostname}:4222")

            if uri.hostname is None or uri.hostname == "none":
                # Validates the hostname
                raise errors.Error("nats: invalid hostname in connect url")

            return uri
        except ValueError:
            raise errors.Error("nats: invalid connect url option")

Added simple check to split a string containing ","

if isinstance(connect_url, str) and "," in connect_url:
            connect_url = connect_url.strip().split(",")

Added tests to check new syntax even though they are not annotated to be actually tested

…t tests to cover new syntax

Signed-off-by: Matteo Bianchi <[email protected]>
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.

1 participant