| 1 |
import re |
| 2 |
from types import MappingProxyType |
| 3 |
from typing import Callable, Mapping, Optional |
| 4 |
from urllib.parse import ParseResult, parse_qs, unquote, urlparse |
| 5 |
|
| 6 |
from valkey.asyncio.connection import ( |
| 7 |
ConnectKwargs, |
| 8 |
) |
| 9 |
from valkey.asyncio.connection import SSLConnection as SSLConnectionAsync |
| 10 |
from valkey.asyncio.connection import ( |
| 11 |
UnixDomainSocketConnection as UnixDomainSocketConnectionAsync, |
| 12 |
) |
| 13 |
from valkey.connection import SSLConnection, UnixDomainSocketConnection |
| 14 |
|
| 15 |
|
| 16 |
def to_bool(value) -> Optional[bool]: |
| 17 |
if value is None or value == "": |
| 18 |
return None |
| 19 |
if isinstance(value, str) and value.upper() in FALSE_STRINGS: |
| 20 |
return False |
| 21 |
return bool(value) |
| 22 |
|
| 23 |
|
| 24 |
FALSE_STRINGS = ("0", "F", "FALSE", "N", "NO") |
| 25 |
|
| 26 |
URL_QUERY_ARGUMENT_PARSERS: Mapping[str, Callable[..., object]] = MappingProxyType( |
| 27 |
{ |
| 28 |
"db": int, |
| 29 |
"socket_timeout": float, |
| 30 |
"socket_connect_timeout": float, |
| 31 |
"socket_keepalive": to_bool, |
| 32 |
"retry_on_timeout": to_bool, |
| 33 |
"max_connections": int, |
| 34 |
"health_check_interval": int, |
| 35 |
"ssl_check_hostname": to_bool, |
| 36 |
"timeout": float, |
| 37 |
} |
| 38 |
) |
| 39 |
|
| 40 |
|
| 41 |
def parse_url(url: str, async_connection: bool): |
| 42 |
supported_schemes = ["valkey", "valkeys", "redis", "rediss", "unix"] |
| 43 |
parsed: ParseResult = urlparse(url) |
| 44 |
kwargs: ConnectKwargs = {} |
| 45 |
lower_url = url.lower() |
| 46 |
pattern = re.compile( |
| 47 |
r"^(?:" + "|".join(map(re.escape, supported_schemes)) + r")://" |
| 48 |
) |
| 49 |
if not pattern.match(lower_url) and not lower_url.startswith("unix:"): |
| 50 |
raise ValueError( |
| 51 |
f"Valkey URL must specify one of the following schemes {supported_schemes}" |
| 52 |
) |
| 53 |
|
| 54 |
for name, value_list in parse_qs(parsed.query).items(): |
| 55 |
if value_list and len(value_list) > 0: |
| 56 |
value = unquote(value_list[0]) |
| 57 |
parser = URL_QUERY_ARGUMENT_PARSERS.get(name) |
| 58 |
if parser: |
| 59 |
try: |
| 60 |
kwargs[name] = parser(value) |
| 61 |
except (TypeError, ValueError): |
| 62 |
raise ValueError(f"Invalid value for `{name}` in connection URL.") |
| 63 |
else: |
| 64 |
kwargs[name] = value |
| 65 |
|
| 66 |
if parsed.username: |
| 67 |
kwargs["username"] = unquote(parsed.username) |
| 68 |
if parsed.password: |
| 69 |
kwargs["password"] = unquote(parsed.password) |
| 70 |
|
| 71 |
# We only support valkey://, valkeys://, redis://, rediss://, and unix:// schemes. |
| 72 |
if parsed.scheme == "unix": |
| 73 |
if parsed.path: |
| 74 |
kwargs["path"] = unquote(parsed.path) |
| 75 |
kwargs["connection_class"] = ( |
| 76 |
UnixDomainSocketConnectionAsync |
| 77 |
if async_connection |
| 78 |
else UnixDomainSocketConnection |
| 79 |
) |
| 80 |
|
| 81 |
elif parsed.scheme in supported_schemes: |
| 82 |
if parsed.hostname: |
| 83 |
kwargs["host"] = unquote(parsed.hostname) |
| 84 |
if parsed.port: |
| 85 |
kwargs["port"] = int(parsed.port) |
| 86 |
|
| 87 |
# If there's a path argument, use it as the db argument if a |
| 88 |
# querystring value wasn't specified |
| 89 |
if parsed.path and "db" not in kwargs: |
| 90 |
try: |
| 91 |
kwargs["db"] = int(unquote(parsed.path).replace("/", "")) |
| 92 |
except (AttributeError, ValueError): |
| 93 |
pass |
| 94 |
|
| 95 |
if parsed.scheme in ("valkeys", "rediss"): |
| 96 |
kwargs["connection_class"] = ( |
| 97 |
SSLConnectionAsync if async_connection else SSLConnection |
| 98 |
) |
| 99 |
else: |
| 100 |
raise ValueError( |
| 101 |
f"Valkey URL must specify one of the following schemes {supported_schemes}" |
| 102 |
) |
| 103 |
|
| 104 |
return kwargs |