Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 58 additions & 3 deletions python/aerospike_native/_native.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ __all__ = [
"HLLWriteFlags",
"Histogram",
"HllOperation",
"Host",
"IndexTask",
"IndexType",
"Key",
Expand Down Expand Up @@ -4251,6 +4252,60 @@ class HllOperation:
(``HLLWriteFlags.X | HLLWriteFlags.Y``), or a raw ``int``.
"""

@typing.final
class Host:
r"""
Seed address of a cluster node.

Pass a list of these to :func:`new_client` (or :func:`new_client_blocking`)
instead of a seed string. Each field is taken as-is, so an IPv6 address
or a TLS name needs no quoting or bracketing.

Example::

seeds = [Host("10.0.0.1", 3000), Host("fd00::2", 3000)]
client = await new_client(ClientPolicy(), seeds)
"""
@property
def name(self) -> builtins.str:
r"""
Hostname or IP address.
"""
@property
def port(self) -> builtins.int:
r"""
Service port.
"""
@property
def tls_name(self) -> typing.Optional[builtins.str]:
r"""
TLS certificate name, or ``None`` for a host reached without TLS.
"""
def __eq__(self, other: builtins.object, /) -> builtins.bool: ...
def __hash__(self) -> builtins.int: ...
def __new__(cls, name: builtins.str, port: builtins.int, tls_name: typing.Optional[builtins.str] = None) -> _native.Host:
r"""
Create a Host.

Args:
name: Hostname or IP address. An IPv6 address is given bare,
e.g. ``"fd00::2"``, not ``"[fd00::2]"``.
port: Service port.
tls_name: Name the node's TLS certificate must carry. ``None``
(or blank) for a host reached without TLS.

Returns:
Host

Raises:
ValueError: If *name* is empty or bracketed.
"""
def __str__(self) -> builtins.str:
r"""
Seed-string form: ``name[:tls_name]:port``, IPv6 bracketed.
"""
def __repr__(self) -> builtins.str: ...

class IndexTask:
def query_status(self) -> typing.Awaitable[TaskStatus]: ...
def wait_till_complete(self, sleep_time: builtins.float = 0.25, timeout: typing.Optional[builtins.float] = 60.0) -> typing.Awaitable[bool]: ...
Expand Down Expand Up @@ -7057,7 +7112,7 @@ class _LocalClient:
Server-reported cluster name (see
:attr:`Client.server_cluster_name`).
"""
def __new__(cls, policy: _native.ClientPolicy, seeds: builtins.str) -> _native._LocalClient: ...
def __new__(cls, policy: _native.ClientPolicy, seeds: builtins.str | typing.Sequence[_native.Host]) -> _native._LocalClient: ...
def get_blocking(self, key: _native.Key, bins: typing.Optional[typing.Sequence[builtins.str]] = None, *, policy: typing.Optional[_native.ReadPolicy] = None, policy_sc: typing.Optional[_native.ReadPolicy] = None, filter_expression: typing.Optional[_native.FilterExpression] = None, txn: typing.Optional[_native.Txn] = None) -> _native.Record: ...
def put_blocking(self, key: _native.Key, bins: typing.Mapping[builtins.str, typing.Any], *, policy: typing.Optional[_native.WritePolicy] = None, policy_sc: typing.Optional[_native.WritePolicy] = None, txn: typing.Optional[_native.Txn] = None) -> None: ...
def delete_blocking(self, key: _native.Key, *, policy: typing.Optional[_native.WritePolicy] = None) -> builtins.bool: ...
Expand Down Expand Up @@ -7814,9 +7869,9 @@ def has_any_write_op(operations: typing.Sequence[typing.Any]) -> builtins.bool:
or the server rejects the per-node group.
"""

def new_client(policy: _native.ClientPolicy, seeds: builtins.str) -> typing.Awaitable[Client]: ...
def new_client(policy: _native.ClientPolicy, seeds: builtins.str | typing.Sequence[_native.Host]) -> typing.Awaitable[Client]: ...

def new_client_blocking(policy: _native.ClientPolicy, seeds: builtins.str) -> _native.Client:
def new_client_blocking(policy: _native.ClientPolicy, seeds: builtins.str | typing.Sequence[_native.Host]) -> _native.Client:
r"""
Synchronously create and connect a Client.

Expand Down
21 changes: 21 additions & 0 deletions python/tests/integration/blocking_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
CTX,
Filter,
FilterExpression as fe,
Host,
IndexType,
Key,
LoopVarPart,
Expand Down Expand Up @@ -770,6 +771,26 @@ def test_blocking_core_panic_is_catchable(connect, aerospike_host, use_services_
client.close_blocking()


@pytest.mark.parametrize(
"client_type", [new_client_blocking, _LocalClient], ids=["client", "local_client"],
)
def test_blocking_connect_with_hosts(client_type, aerospike_host, use_services_alternate):
"""Each blocking constructor connects from a list of Host."""
name, port = aerospike_host.rsplit(":", 1)
cp = ClientPolicy()
cp.use_services_alternate = use_services_alternate
client = client_type(cp, [Host(name, int(port))])
key = Key("test", "blocking", "hosts-1")
try:
client.put_blocking(key, {"v": 1}, policy=WritePolicy())
assert client.get_blocking(key, policy=ReadPolicy()).bins["v"] == 1
finally:
client.delete_blocking(key, policy=WritePolicy())
# The local client owns its runtime and shuts down on drop.
if not isinstance(client, _LocalClient):
client.close_blocking()


def test_blocking_create_set_index(aerospike_host, use_services_alternate):
cp = ClientPolicy()
cp.use_services_alternate = use_services_alternate
Expand Down
14 changes: 13 additions & 1 deletion python/tests/integration/client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import pytest

from aerospike_native import new_client, ClientPolicy
from aerospike_native import new_client, ClientPolicy, Host
from aerospike_native.exceptions import ConnectionError, ResultCode

async def test_connect():
Expand All @@ -28,6 +28,18 @@ async def test_connect():
client = await new_client(cp, os.environ.get("AEROSPIKE_HOST", "localhost:3000"))
assert client is not None

async def test_connect_with_hosts():
"""A list of Host connects, and seeds() reports it in seed-string form."""
name, port = os.environ.get("AEROSPIKE_HOST", "localhost:3000").rsplit(":", 1)
cp = ClientPolicy()
cp.use_services_alternate = True
client = await new_client(cp, [Host(name, int(port))])
try:
assert client.is_connected() is True
assert client.seeds() == f"{name}:{port}"
finally:
await client.close()

async def test_failed_connect():
"""Test basic client connection failure."""
client = None
Expand Down
77 changes: 77 additions & 0 deletions python/tests/unit/host_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Copyright 2023-2026 Aerospike, Inc.
#
# Portions may be licensed to Aerospike, Inc. under one or more contributor
# license agreements WHICH ARE COMPATIBLE WITH THE APACHE LICENSE, VERSION 2.0.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.

"""Unit tests for Host and the seed argument of the client constructors."""

import pytest
from aerospike_native import ClientPolicy, Host, new_client_blocking


class TestHost:
"""Host construction, formatting, and value semantics."""

def test_fields(self):
host = Host("db1.example.com", 4333, tls_name="db1")
assert (host.name, host.port, host.tls_name) == ("db1.example.com", 4333, "db1")

def test_blank_tls_name_is_none(self):
assert Host("db1", 3000, tls_name=" ").tls_name is None

@pytest.mark.parametrize(
("host", "seed"),
[
(Host("10.0.0.1", 3000), "10.0.0.1:3000"),
(Host("db1", 4333, tls_name="tls1"), "db1:tls1:4333"),
(Host("fd00::2", 3000), "[fd00::2]:3000"),
(Host("fd00::2", 4333, tls_name="tls1"), "[fd00::2]:tls1:4333"),
],
)
def test_str_is_seed_entry(self, host, seed):
assert str(host) == seed

def test_repr(self):
assert repr(Host("fd00::2", 3000)) == "Host('fd00::2', 3000)"
assert repr(Host("db1", 4333, tls_name="tls1")) == "Host('db1', 4333, tls_name='tls1')"

def test_equality_and_hash(self):
assert Host("db1", 3000) == Host("db1", 3000)
assert Host("db1", 3000) != Host("db1", 3000, tls_name="tls1")
assert len({Host("db1", 3000), Host("db1", 3000)}) == 1

def test_immutable(self):
with pytest.raises(AttributeError):
Host("db1", 3000).port = 3001 # type: ignore[misc]

@pytest.mark.parametrize("name", ["", "[fd00::2]"])
def test_rejects_invalid_name(self, name):
with pytest.raises(ValueError):
Host(name, 3000)

def test_rejects_out_of_range_port(self):
with pytest.raises(OverflowError):
Host("db1", 70000)


class TestSeedsArgument:
"""Seed values rejected before any connection attempt."""

def test_empty_host_list(self):
with pytest.raises(ValueError, match="at least one Host"):
new_client_blocking(ClientPolicy(), [])

@pytest.mark.parametrize("seeds", [["db1:3000"], 3000, None])
def test_wrong_type(self, seeds):
with pytest.raises(TypeError, match="str or a sequence of Host"):
new_client_blocking(ClientPolicy(), seeds)
13 changes: 7 additions & 6 deletions src/blocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ use pyo3_stub_gen::derive::gen_stub_pyfunction;
use tokio::runtime::Runtime;

use crate::errors::{panic_to_pyerr, RustClientError};
use crate::host::Seeds;
use crate::policies::ClientPolicy;
use crate::Client;

Expand Down Expand Up @@ -121,21 +122,21 @@ where
pub(crate) fn new_client_blocking(
py: Python<'_>,
policy: ClientPolicy,
seeds: String,
seeds: Seeds,
) -> PyResult<Client> {
let as_policy = policy._as.clone();
let as_seeds = seeds.clone();
let seed_string = seeds.to_seed_string();
let cluster_name = as_policy.cluster_name.clone();
log::debug!(target: "aerospike_native", "connecting (blocking) to {}", seed_string);
let raw = run_blocking(py, async move {
log::debug!(target: "aerospike_native", "connecting (blocking) to {}", as_seeds);
aerospike_core::Client::new(&as_policy, &as_seeds)
aerospike_core::Client::new(&as_policy, seeds.as_to_hosts())
.await
.map_err(|e| PyErr::from(RustClientError(e)))
})?;
log::debug!(target: "aerospike_native", "connected (blocking) to {}", seeds);
log::debug!(target: "aerospike_native", "connected (blocking) to {}", seed_string);
Ok(Client {
_as: Arc::new(raw),
seeds,
seeds: seed_string,
cluster_name,
bridge: None,
})
Expand Down
Loading
Loading