diff --git a/CHANGELOG.md b/CHANGELOG.md index aa9666f..28f8fd7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,12 @@ [agntcy/dir]: https://github.com/agntcy/dir [agntcy/dir-sdk-python]: https://github.com/agntcy/dir-sdk-python +## Unreleased + +### Added + +- `RuntimeClient` for the runtime discovery API (`agntcy.dir.runtime.v1.DiscoveryService`): `get_workload` and `list_workloads` (with all `ListWorkloadsRequest` filters). It connects to dir-runtime's own address, separately from `Client`, so Directory credentials are never sent to it. Models are exposed as `agntcy.dir_sdk.models.runtime_v1`. + ## 1.8.1 (2026-10-21) ### Changed diff --git a/Taskfile.yml b/Taskfile.yml index 75dc48f..4e75d6c 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -41,6 +41,12 @@ vars: KIND_CLUSTER_NAME: "sdk-py-test" + # dir-runtime serves the runtime discovery API (agntcy.dir.runtime.v1) on its own address. + # renovate: datasource=github-releases depName=agntcy/dir-runtime versioning=semver + RUNTIME_VERSION: '{{ .RUNTIME_VERSION | default "v1.5.0" }}' + RUNTIME_API_HOSTPORT: '{{ .RUNTIME_API_HOSTPORT | default "18888" }}' + RUNTIME_API_NODEPORT: '{{ .RUNTIME_API_NODEPORT | default "30180" }}' + tasks: # --------------------------------------------------------------------------- # SDK tasks (top-level, user-facing) @@ -76,6 +82,8 @@ tasks: - | export COSIGN_PATH="$(printf "%s" "${COSIGN_PATH:-{{ .COSIGN_BIN }}}")" export DIRCTL_PATH="$(printf "%s" "${DIRCTL_PATH:-{{ .DIRCTL_BIN }}}")" + export DIRECTORY_RUNTIME_ADDRESS="localhost:{{ .RUNTIME_API_HOSTPORT }}" + export RUNTIME_E2E_WORKLOAD_NAME="sdk-runtime-e2e" # Run SDK tests '{{ .UV_BIN }}' run pytest \ @@ -210,7 +218,7 @@ tasks: deps: - task: test-env:setup-cluster vars: - KIND_EXTRA_PORT_MAPPING: "{{.API_HOSTPORT}}:{{.API_NODEPORT}},{{.METRICS_HOSTPORT}}:{{.METRICS_NODEPORT}}" + KIND_EXTRA_PORT_MAPPING: "{{.API_HOSTPORT}}:{{.API_NODEPORT}},{{.METRICS_HOSTPORT}}:{{.METRICS_NODEPORT}},{{.RUNTIME_API_HOSTPORT}}:{{.RUNTIME_API_NODEPORT}}" vars: # Kind args KIND_CLUSTER_NAME: '{{ .KIND_CLUSTER_NAME | default "sdk-py-test" }}' @@ -270,6 +278,49 @@ tasks: --wait-for-jobs \ --timeout "15m" + # Deploy dir-runtime and the workload it discovers + - task: test-env:runtime:deploy + + test-env:runtime:deploy: + desc: Deploy dir-runtime and a labelled workload for the runtime discovery E2E tests + deps: + - deps:helm + - deps:kubectl + - deps:kind + vars: + KIND_CLUSTER_NAME: '{{ .KIND_CLUSTER_NAME | default "sdk-py-test" }}' + preconditions: + - which docker + - which curl + cmds: + - | + set -euo pipefail + SRC="$(mktemp -d)" + trap 'rm -rf "$SRC"' EXIT + curl -sfL "https://github.com/agntcy/dir-runtime/archive/refs/tags/{{ .RUNTIME_VERSION }}.tar.gz" | tar -xz -C "$SRC" --strip-components=1 + + # The published dir-runtime-server image contains the discovery binary + # (same digest as dir-runtime-discovery), so build the server from source. + docker build -q -f "$SRC/server/Dockerfile" --target production -t dir-runtime-server:sdk-e2e "$SRC" + {{ .KIND_BIN }} load docker-image dir-runtime-server:sdk-e2e --name {{ .KIND_CLUSTER_NAME }} + + {{ .HELM_BIN }} install runtime "$SRC/install/chart" \ + --namespace dir-runtime \ + --create-namespace \ + --set discovery.image.tag="{{ trimPrefix "v" .RUNTIME_VERSION }}" \ + --set server.image.repository=dir-runtime-server \ + --set server.image.tag=sdk-e2e \ + --set server.image.pullPolicy=Never \ + --set discovery.config.store.crd.namespace=dir-runtime \ + --set server.config.store.crd.namespace=dir-runtime \ + --set server.service.type=NodePort \ + --set server.service.nodePort="{{ .RUNTIME_API_NODEPORT }}" \ + --wait \ + --timeout "5m" + + {{ .KUBECTL_BIN }} apply -f "{{ .ROOT_DIR }}/tests/runtime-e2e/workload.yaml" + {{ .KUBECTL_BIN }} wait --for=condition=Ready pod/sdk-runtime-e2e --timeout=2m + test-env:deploy:cleanup: desc: Cleanup Kubernetes environment for local deployment deps: diff --git a/dir-sdk-python/agntcy/dir_sdk/client/__init__.py b/dir-sdk-python/agntcy/dir_sdk/client/__init__.py index 5aff8ec..8c3f1f3 100644 --- a/dir-sdk-python/agntcy/dir_sdk/client/__init__.py +++ b/dir-sdk-python/agntcy/dir_sdk/client/__init__.py @@ -4,5 +4,6 @@ from agntcy.dir_sdk.client.auth.oauth_pkce import OAuthPkceError from agntcy.dir_sdk.client.client import Client from agntcy.dir_sdk.client.config import Config +from agntcy.dir_sdk.client.runtime_client import RuntimeClient -__all__ = ["Client", "Config", "OAuthPkceError"] +__all__ = ["Client", "Config", "OAuthPkceError", "RuntimeClient"] diff --git a/dir-sdk-python/agntcy/dir_sdk/client/runtime_client.py b/dir-sdk-python/agntcy/dir_sdk/client/runtime_client.py new file mode 100644 index 0000000..4f013d6 --- /dev/null +++ b/dir-sdk-python/agntcy/dir_sdk/client/runtime_client.py @@ -0,0 +1,55 @@ +# Copyright AGNTCY Contributors (https://github.com/agntcy) +# SPDX-License-Identifier: Apache-2.0 + +"""Client for the runtime discovery API served by dir-runtime.""" + +from __future__ import annotations + +import logging +from collections.abc import Sequence + +import grpc +from agntcy.dir_sdk.client.services.runtime import RuntimeService +from agntcy.dir_sdk.models import runtime_v1 + +logger = logging.getLogger("agntcy.dir_sdk.runtime") + + +class RuntimeClient: + """Client for ``agntcy.dir.runtime.v1.DiscoveryService``. + + dir-runtime (and ``dirctl daemon``) runs at its own address, so this is + separate from :class:`~agntcy.dir_sdk.client.Client`: the Directory's + credentials, such as the OIDC token, are never sent to it. + """ + + DEFAULT_SERVER_ADDRESS = "localhost:8888" + + def __init__( + self, + server_address: str = DEFAULT_SERVER_ADDRESS, + channel: grpc.Channel | None = None, + ) -> None: + self.server_address = server_address + self.channel = channel or grpc.insecure_channel(server_address) + + # Expose the raw stub for advanced callers. + self.discovery_client = runtime_v1.DiscoveryServiceStub(self.channel) + self.runtime_service = RuntimeService(self.discovery_client, logger) + + def close(self) -> None: + self.channel.close() + + def get_workload( + self, + req: runtime_v1.GetWorkloadRequest, + metadata: Sequence[tuple[str, str]] | None = None, + ) -> runtime_v1.Workload: + return self.runtime_service.get_workload(req, metadata) + + def list_workloads( + self, + req: runtime_v1.ListWorkloadsRequest, + metadata: Sequence[tuple[str, str]] | None = None, + ) -> list[runtime_v1.Workload]: + return self.runtime_service.list_workloads(req, metadata) diff --git a/dir-sdk-python/agntcy/dir_sdk/client/services/__init__.py b/dir-sdk-python/agntcy/dir_sdk/client/services/__init__.py index c1b5668..ab8cf56 100644 --- a/dir-sdk-python/agntcy/dir_sdk/client/services/__init__.py +++ b/dir-sdk-python/agntcy/dir_sdk/client/services/__init__.py @@ -7,6 +7,7 @@ from agntcy.dir_sdk.client.services.identity import IdentityService from agntcy.dir_sdk.client.services.publication import PublicationService from agntcy.dir_sdk.client.services.routing import RoutingService +from agntcy.dir_sdk.client.services.runtime import RuntimeService from agntcy.dir_sdk.client.services.search import SearchService from agntcy.dir_sdk.client.services.signing import SignService from agntcy.dir_sdk.client.services.store import StoreService @@ -17,6 +18,7 @@ "IdentityService", "PublicationService", "RoutingService", + "RuntimeService", "SearchService", "SignService", "StoreService", diff --git a/dir-sdk-python/agntcy/dir_sdk/client/services/runtime.py b/dir-sdk-python/agntcy/dir_sdk/client/services/runtime.py new file mode 100644 index 0000000..42d58d3 --- /dev/null +++ b/dir-sdk-python/agntcy/dir_sdk/client/services/runtime.py @@ -0,0 +1,44 @@ +# Copyright AGNTCY Contributors (https://github.com/agntcy) +# SPDX-License-Identifier: Apache-2.0 + +"""Runtime discovery service wrappers.""" + +from __future__ import annotations + +import logging +from collections.abc import Sequence + +from agntcy.dir_sdk.client.services.base import RpcServiceBase +from agntcy.dir_sdk.models import runtime_v1 + + +class RuntimeService(RpcServiceBase): + def __init__( + self, + discovery_client: runtime_v1.DiscoveryServiceStub, + logger: logging.Logger, + ) -> None: + super().__init__(logger) + self._discovery_client = discovery_client + + def get_workload( + self, + req: runtime_v1.GetWorkloadRequest, + metadata: Sequence[tuple[str, str]] | None = None, + ) -> runtime_v1.Workload: + return self._invoke( + "get_workload", + "Failed to get workload", + lambda: self._discovery_client.GetWorkload(req, metadata=metadata), + ) + + def list_workloads( + self, + req: runtime_v1.ListWorkloadsRequest, + metadata: Sequence[tuple[str, str]] | None = None, + ) -> list[runtime_v1.Workload]: + return self._collect_stream( + "list_workloads", + "Failed to list workloads", + lambda: self._discovery_client.ListWorkloads(req, metadata=metadata), + ) diff --git a/dir-sdk-python/agntcy/dir_sdk/models/__init__.py b/dir-sdk-python/agntcy/dir_sdk/models/__init__.py index 158ecb4..2acd8d5 100644 --- a/dir-sdk-python/agntcy/dir_sdk/models/__init__.py +++ b/dir-sdk-python/agntcy/dir_sdk/models/__init__.py @@ -8,6 +8,7 @@ from . import events_v1 as events_v1 from . import identity_v1 as identity_v1 from . import routing_v1 as routing_v1 +from . import runtime_v1 as runtime_v1 from . import search_v1 as search_v1 from . import sign_v1 as sign_v1 from . import store_v1 as store_v1 diff --git a/dir-sdk-python/agntcy/dir_sdk/models/runtime_v1.py b/dir-sdk-python/agntcy/dir_sdk/models/runtime_v1.py new file mode 100644 index 0000000..5206586 --- /dev/null +++ b/dir-sdk-python/agntcy/dir_sdk/models/runtime_v1.py @@ -0,0 +1,6 @@ +# Copyright AGNTCY Contributors (https://github.com/agntcy) +# SPDX-License-Identifier: Apache-2.0 + +from agntcy.dir.runtime.v1.discovery_service_pb2 import * +from agntcy.dir.runtime.v1.discovery_service_pb2_grpc import * +from agntcy.dir.runtime.v1.workload_pb2 import * diff --git a/dir-sdk-python/agntcy/dir_sdk/tests/test_runtime.py b/dir-sdk-python/agntcy/dir_sdk/tests/test_runtime.py new file mode 100644 index 0000000..f425549 --- /dev/null +++ b/dir-sdk-python/agntcy/dir_sdk/tests/test_runtime.py @@ -0,0 +1,81 @@ +# Copyright AGNTCY Contributors (https://github.com/agntcy) +# SPDX-License-Identifier: Apache-2.0 + +"""Tests for the runtime discovery client against an in-process server.""" + +from __future__ import annotations + +import unittest +from collections.abc import Iterator +from concurrent import futures + +import grpc +from agntcy.dir_sdk.client import RuntimeClient +from agntcy.dir_sdk.models import runtime_v1 + +WORKLOADS = [ + runtime_v1.Workload( + id="a", + runtime="docker", + locators=[ + runtime_v1.WorkloadLocator(protocol="http", url="http://10.0.0.1:80") + ], + ), + runtime_v1.Workload(id="b", runtime="kubernetes"), +] + + +class FakeDiscovery(runtime_v1.DiscoveryServiceServicer): + """In-process dir-runtime; applies only the runtime_types filter.""" + + def GetWorkload( # noqa: N802 + self, + request: runtime_v1.GetWorkloadRequest, + context: grpc.ServicerContext, + ) -> runtime_v1.Workload: + for w in WORKLOADS: + if w.id == request.id: + return w + context.abort(grpc.StatusCode.NOT_FOUND, request.id) + raise AssertionError # abort() raises; unreachable + + def ListWorkloads( # noqa: N802 + self, + request: runtime_v1.ListWorkloadsRequest, + _context: grpc.ServicerContext, + ) -> Iterator[runtime_v1.Workload]: + for w in WORKLOADS: + if not request.runtime_types or w.runtime in request.runtime_types: + yield w + + +class TestRuntimeClient(unittest.TestCase): + def setUp(self) -> None: + self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=2)) + runtime_v1.add_DiscoveryServiceServicer_to_server(FakeDiscovery(), self.server) + port = self.server.add_insecure_port("127.0.0.1:0") + self.server.start() + self.client = RuntimeClient(f"127.0.0.1:{port}") + + def tearDown(self) -> None: + self.client.close() + self.server.stop(None) + + def test_list_workloads_with_filters(self) -> None: + everything = self.client.list_workloads(runtime_v1.ListWorkloadsRequest()) + assert [w.id for w in everything] == ["a", "b"] + + docker = self.client.list_workloads( + runtime_v1.ListWorkloadsRequest(runtime_types=["docker"]) + ) + assert len(docker) == 1 + assert docker[0].locators[0].url == "http://10.0.0.1:80" + + def test_get_workload(self) -> None: + w = self.client.get_workload(runtime_v1.GetWorkloadRequest(id="b")) + assert w.runtime == "kubernetes" + + def test_get_workload_not_found(self) -> None: + with self.assertRaises(grpc.RpcError) as ctx: + self.client.get_workload(runtime_v1.GetWorkloadRequest(id="missing")) + assert ctx.exception.code() == grpc.StatusCode.NOT_FOUND diff --git a/dir-sdk-python/agntcy/dir_sdk/tests/test_runtime_e2e.py b/dir-sdk-python/agntcy/dir_sdk/tests/test_runtime_e2e.py new file mode 100644 index 0000000..3f014c5 --- /dev/null +++ b/dir-sdk-python/agntcy/dir_sdk/tests/test_runtime_e2e.py @@ -0,0 +1,91 @@ +# Copyright AGNTCY Contributors (https://github.com/agntcy) +# SPDX-License-Identifier: Apache-2.0 + +"""End-to-end tests of the runtime discovery client. + +They run against a real dir-runtime that discovers a labelled pod, and skip +unless ``DIRECTORY_RUNTIME_ADDRESS`` is set. ``task test`` sets it after +deploying dir-runtime and the pod (``tests/runtime-e2e/workload.yaml``) to the +kind cluster. +""" + +from __future__ import annotations + +import os +import time +import unittest + +import grpc +from agntcy.dir_sdk.client import RuntimeClient +from agntcy.dir_sdk.models import runtime_v1 + +ADDRESS = os.environ.get("DIRECTORY_RUNTIME_ADDRESS", "") +NAME = os.environ.get("RUNTIME_E2E_WORKLOAD_NAME", "") +LABELS = {"org.agntcy/discover": "true"} + + +@unittest.skipUnless(ADDRESS, "DIRECTORY_RUNTIME_ADDRESS not set") +class TestRuntimeE2E(unittest.TestCase): + def setUp(self) -> None: + self.client = RuntimeClient(ADDRESS) + + def tearDown(self) -> None: + self.client.close() + + def _list( + self, + labels: dict[str, str] | None = None, + runtime_types: list[str] | None = None, + locator_protocols: list[str] | None = None, + ) -> list[runtime_v1.Workload]: + return self.client.list_workloads( + runtime_v1.ListWorkloadsRequest( + labels=LABELS if labels is None else labels, + runtime_types=runtime_types, + locator_protocols=locator_protocols, + ) + ) + + def _discovered(self) -> runtime_v1.Workload: + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + for w in self._list(): + if w.name == NAME: + return w + time.sleep(2) + self.fail(f"workload {NAME} was never discovered") + + def _matches( + self, + labels: dict[str, str] | None = None, + runtime_types: list[str] | None = None, + locator_protocols: list[str] | None = None, + ) -> bool: + listed = self._list(labels, runtime_types, locator_protocols) + return any(w.name == NAME for w in listed) + + def test_lists_and_gets_the_discovered_workload(self) -> None: + listed = self._discovered() + assert listed.runtime == "kubernetes" + assert listed.type == "pod" + assert any( + loc.protocol == "tcp" and loc.url.startswith("tcp://") + for loc in listed.locators + ) + + got = self.client.get_workload(runtime_v1.GetWorkloadRequest(id=listed.id)) + assert got.id == listed.id + assert got.name == NAME + + def test_filters_narrow_the_result(self) -> None: + self._discovered() + assert self._matches(runtime_types=["KUBERNETES"]) + assert self._matches(locator_protocols=["tcp"]) + assert not self._matches(runtime_types=["docker"]) + assert not self._matches(locator_protocols=["slim"]) + assert not self._matches(labels={"org.agntcy/discover": "false"}) + + def test_unknown_workload_fails(self) -> None: + with self.assertRaises(grpc.RpcError) as ctx: + self.client.get_workload(runtime_v1.GetWorkloadRequest(id="does-not-exist")) + assert "not found" in str(ctx.exception.details()) diff --git a/tests/runtime-e2e/workload.yaml b/tests/runtime-e2e/workload.yaml new file mode 100644 index 0000000..1ab822a --- /dev/null +++ b/tests/runtime-e2e/workload.yaml @@ -0,0 +1,18 @@ +# Copyright AGNTCY Contributors (https://github.com/agntcy) +# SPDX-License-Identifier: Apache-2.0 + +# Workload the runtime discovery E2E tests expect dir-runtime to discover: +# dir-runtime's Kubernetes adapter picks up pods labelled org.agntcy/discover. +apiVersion: v1 +kind: Pod +metadata: + name: sdk-runtime-e2e + namespace: default + labels: + org.agntcy/discover: "true" +spec: + containers: + - name: web + image: nginx:alpine + ports: + - containerPort: 80 diff --git a/uv.lock b/uv.lock index adf51e2..3a5a86b 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.15'", @@ -78,7 +78,7 @@ wheels = [ [[package]] name = "agntcy-dir-protocolbuffers-pyi" -version = "36.2.0.1.20261006085230+1106da22f446" +version = "36.2.0.1.20261021152154+2602649e5543" source = { registry = "https://buf.build/gen/python" } dependencies = [ { name = "bufbuild-protovalidate-protocolbuffers-pyi" }, @@ -87,7 +87,7 @@ dependencies = [ { name = "types-protobuf" }, ] wheels = [ - { url = "https://buf.build/gen/python/agntcy-dir-protocolbuffers-pyi/agntcy_dir_protocolbuffers_pyi-36.2.0.1.20261006085230+1106da22f446-py3-none-any.whl", upload-time = "2026-10-06T08:52:30Z" }, + { url = "https://buf.build/gen/python/agntcy-dir-protocolbuffers-pyi/agntcy_dir_protocolbuffers_pyi-36.2.0.1.20261021152154+2602649e5543-py3-none-any.whl", upload-time = "2026-10-21T15:21:54Z" }, ] [[package]] @@ -707,7 +707,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -728,14 +728,14 @@ wheels = [ [[package]] name = "googleapis-googleapis-protocolbuffers-pyi" -version = "36.2.0.1.20260414192239+c17df5b2beca" +version = "36.2.0.1.20261015202054+8ac61b9e5023" source = { registry = "https://buf.build/gen/python" } dependencies = [ { name = "protobuf" }, { name = "types-protobuf" }, ] wheels = [ - { url = "https://buf.build/gen/python/googleapis-googleapis-protocolbuffers-pyi/googleapis_googleapis_protocolbuffers_pyi-36.2.0.1.20260414192239+c17df5b2beca-py3-none-any.whl", upload-time = "2026-09-19T01:44:49Z" }, + { url = "https://buf.build/gen/python/googleapis-googleapis-protocolbuffers-pyi/googleapis_googleapis_protocolbuffers_pyi-36.2.0.1.20261015202054+8ac61b9e5023-py3-none-any.whl", upload-time = "2026-10-15T20:20:54Z" }, ] [[package]]