agentengine-sdk-python 0.8.7__py3-none-any.whl → 0.8.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/METADATA +14 -9
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/RECORD +98 -68
- ksadk/__init__.py +2 -1
- ksadk/_build_provenance.json +1 -1
- ksadk/_mcp_compat.py +305 -0
- ksadk/agent.py +29 -0
- ksadk/agui/_agent_kernel.py +176 -142
- ksadk/agui/agent.py +74 -5
- ksadk/agui/hosted.py +343 -0
- ksadk/agui/request_identity.py +11 -0
- ksadk/agui/routes.py +77 -2
- ksadk/builders/code_builder.py +30 -23
- ksadk/builders/container_builder.py +5 -5
- ksadk/builders/mcp_builder.py +142 -0
- ksadk/builders/project_imports.py +66 -0
- ksadk/cli/cmd_mcp.py +1 -1
- ksadk/cli/cmd_run.py +2 -4
- ksadk/cli/cmd_web.py +8 -0
- ksadk/cli/runtime_bootstrap.py +4 -1
- ksadk/common/cloud_headers.py +33 -6
- ksadk/compat/adk_compat.py +2 -0
- ksadk/compat/adk_stream.py +35 -0
- ksadk/configs/env_registry.py +31 -0
- ksadk/conversations/projector.py +6 -0
- ksadk/conversations/runtime_observability.py +1 -0
- ksadk/detection/mcp_detector.py +80 -22
- ksadk/harness/__init__.py +3 -0
- ksadk/harness/service_presentation.py +44 -0
- ksadk/harness/service_runtime.py +1038 -0
- ksadk/interaction/providers/harness.py +9 -4
- ksadk/kernel/ingress.py +35 -25
- ksadk/kernel/worker.py +2 -2
- ksadk/kernel/worker_identity.py +15 -8
- ksadk/knowledge_base/client.py +10 -3
- ksadk/mcp_runtime/oauth/_agent.py +77 -9
- ksadk/mcp_runtime/oauth/langgraph.py +47 -15
- ksadk/mcp_runtime/oauth/local/broker.py +23 -1
- ksadk/mcp_runtime/oauth/tools.py +46 -8
- ksadk/mcp_runtime/oauth/transport.py +19 -2
- ksadk/memory/adk/backends/sdk_ltm_backend.py +21 -12
- ksadk/memory/scope_ids.py +49 -0
- ksadk/plugins/providers/harness.py +65 -28
- ksadk/plugins/providers/harness_service.py +198 -0
- ksadk/plugins/providers/harness_service_context.py +175 -0
- ksadk/plugins/providers/harness_service_hooks.py +168 -0
- ksadk/plugins/providers/harness_service_memory.py +479 -0
- ksadk/plugins/providers/platform_resources.py +2 -2
- ksadk/resource_runtime/langgraph.py +7 -3
- ksadk/resource_runtime/mcp_server.py +3 -3
- ksadk/resource_runtime/worker.py +19 -4
- ksadk/runners/_adk_canonical_stream.py +38 -10
- ksadk/runners/_adk_tunnel_history.py +96 -0
- ksadk/runners/_langgraph_canonical_stream.py +16 -0
- ksadk/runners/_langgraph_factory.py +79 -0
- ksadk/runners/_langgraph_runner_streams.py +6 -0
- ksadk/runners/_session_identity.py +8 -3
- ksadk/runners/adk_runner.py +95 -19
- ksadk/runners/langgraph_runner.py +15 -21
- ksadk/runtime/factory.py +17 -5
- ksadk/runtime/framework_adapters.py +10 -0
- ksadk/runtime/langgraph_checkpoint_view.py +28 -7
- ksadk/runtime/launch.py +2 -0
- ksadk/server/factory.py +55 -0
- ksadk/server/routes/common.py +2 -0
- ksadk/server/routes/harness_service_view.py +38 -0
- ksadk/server/routes/ui_bootstrap.py +16 -2
- ksadk/skills/mcp_server/server.py +239 -217
- ksadk/studio/contracts.py +8 -0
- ksadk/studio/mcp_runtime.py +23 -8
- ksadk/studio/native_mcp_disclosure.py +8 -6
- ksadk/studio/native_mcp_tool_port.py +3 -1
- ksadk/studio/native_memory_context.py +10 -8
- ksadk/studio/native_product.py +3 -4
- ksadk/studio/plugin_composition.py +8 -1
- ksadk/studio/plugin_native_activation.py +4 -2
- ksadk/studio/plugin_runtime.py +9 -0
- ksadk/studio/service.py +2 -0
- ksadk/tracing/setup.py +53 -3
- ksadk/tunnel/__init__.py +37 -0
- ksadk/tunnel/connector.py +384 -0
- ksadk/tunnel/discovery.py +107 -0
- ksadk/tunnel/failure.py +168 -0
- ksadk/tunnel/http_tools.py +100 -0
- ksadk/tunnel/langgraph.py +125 -0
- ksadk/tunnel/middleware.py +28 -0
- ksadk/tunnel/peers.py +872 -0
- ksadk/tunnel/protocol.py +97 -0
- ksadk/tunnel/registry.py +306 -0
- ksadk/tunnel/runtime.py +147 -0
- ksadk/tunnel/server.py +201 -0
- ksadk/tunnel/services.py +366 -0
- ksadk/tunnel/toolset.py +78 -0
- ksadk/version.py +1 -1
- ksadk_runtime_common/memory_backend/providers/mem0.py +20 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/WHEEL +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/entry_points.txt +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/licenses/LICENSE +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/top_level.txt +0 -0
ksadk/tunnel/peers.py
ADDED
|
@@ -0,0 +1,872 @@
|
|
|
1
|
+
"""Runtime-scoped peer discovery and authenticated streaming HTTP forwarding.
|
|
2
|
+
|
|
3
|
+
Only the dedicated internal listener uses this protocol. Connector credentials
|
|
4
|
+
never cross it. Every channel is mutually authenticated and every subsequent
|
|
5
|
+
frame is direction-bound, sequenced and HMAC authenticated.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import hashlib
|
|
12
|
+
import hmac
|
|
13
|
+
import ipaddress
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
import math
|
|
17
|
+
import os
|
|
18
|
+
import socket
|
|
19
|
+
import time
|
|
20
|
+
import uuid
|
|
21
|
+
from contextlib import contextmanager
|
|
22
|
+
from contextvars import ContextVar
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from urllib.parse import urlsplit
|
|
25
|
+
|
|
26
|
+
# The transport, response streams and MCP client must use the same backend,
|
|
27
|
+
# even when both httpx packages are installed in a legacy MCP environment.
|
|
28
|
+
from ksadk._mcp_compat import httpx_module
|
|
29
|
+
|
|
30
|
+
httpx = httpx_module()
|
|
31
|
+
from websockets.exceptions import ConnectionClosed, InvalidHandshake
|
|
32
|
+
from websockets.legacy.client import Connect
|
|
33
|
+
from websockets.legacy.server import serve
|
|
34
|
+
|
|
35
|
+
from .protocol import (
|
|
36
|
+
IncompletePeerDiscovery,
|
|
37
|
+
TunnelError,
|
|
38
|
+
TunnelLimits,
|
|
39
|
+
decode_request_body,
|
|
40
|
+
encode,
|
|
41
|
+
identifier,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
_PATH = "/ksadk-tunnel-peer"
|
|
45
|
+
_AUTH_WINDOW = 30
|
|
46
|
+
_CHALLENGE_HEADER = "X-KsADK-Peer-Challenge"
|
|
47
|
+
_MAX_LEGACY_NONCES = 4096
|
|
48
|
+
logger = logging.getLogger(__name__)
|
|
49
|
+
_ERROR_CODES = frozenset(
|
|
50
|
+
{
|
|
51
|
+
"busy",
|
|
52
|
+
"forbidden",
|
|
53
|
+
"disconnected",
|
|
54
|
+
"timeout",
|
|
55
|
+
"frame_too_large",
|
|
56
|
+
"local_service_error",
|
|
57
|
+
"local_mcp_error",
|
|
58
|
+
"invalid_request",
|
|
59
|
+
}
|
|
60
|
+
)
|
|
61
|
+
_current_operation = ContextVar("ksadk_tunnel_peer_operation", default=None)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class PeerOperation:
|
|
66
|
+
deadline: asyncio.Timeout
|
|
67
|
+
error: str | None = None
|
|
68
|
+
|
|
69
|
+
def fail(self, code):
|
|
70
|
+
self.error = code
|
|
71
|
+
if not self.deadline.expired():
|
|
72
|
+
self.deadline.reschedule(asyncio.get_running_loop().time())
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _json(value):
|
|
76
|
+
return json.dumps(
|
|
77
|
+
value, sort_keys=True, separators=(",", ":"), allow_nan=False, ensure_ascii=False
|
|
78
|
+
).encode()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _mac(key, *parts):
|
|
82
|
+
return hmac.new(
|
|
83
|
+
key,
|
|
84
|
+
b"\n".join(part if isinstance(part, bytes) else str(part).encode() for part in parts),
|
|
85
|
+
hashlib.sha256,
|
|
86
|
+
).hexdigest()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _wire_error(frame):
|
|
90
|
+
code = frame.get("error")
|
|
91
|
+
return code if isinstance(code, str) and code in _ERROR_CODES else "local_service_error"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def validate_owner(value):
|
|
95
|
+
if not isinstance(value, dict) or set(value) != {"address", "instance_id"}:
|
|
96
|
+
raise TunnelError("invalid_peer_owner")
|
|
97
|
+
identifier(value["instance_id"], "peer instance")
|
|
98
|
+
parsed = urlsplit("ws://" + value["address"])
|
|
99
|
+
if (
|
|
100
|
+
not parsed.hostname
|
|
101
|
+
or parsed.username
|
|
102
|
+
or parsed.password
|
|
103
|
+
or parsed.path
|
|
104
|
+
or parsed.query
|
|
105
|
+
or parsed.fragment
|
|
106
|
+
or parsed.port is None
|
|
107
|
+
):
|
|
108
|
+
raise TunnelError("invalid_peer_owner")
|
|
109
|
+
try:
|
|
110
|
+
ipaddress.ip_address(parsed.hostname)
|
|
111
|
+
except ValueError:
|
|
112
|
+
raise TunnelError("invalid_peer_owner") from None
|
|
113
|
+
return value
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass(frozen=True)
|
|
117
|
+
class PeerConfig:
|
|
118
|
+
runtime_id: str
|
|
119
|
+
service: str
|
|
120
|
+
secret: str = field(repr=False)
|
|
121
|
+
port: int = 8092
|
|
122
|
+
host: str = "0.0.0.0"
|
|
123
|
+
advertised_host: str | None = None
|
|
124
|
+
discovery_timeout: float = 3.0
|
|
125
|
+
max_peers: int = 64
|
|
126
|
+
ownership_cache_ttl: float = 2.0
|
|
127
|
+
topology_cache_ttl: float = 1.0
|
|
128
|
+
|
|
129
|
+
def __post_init__(self):
|
|
130
|
+
if (
|
|
131
|
+
not self.runtime_id
|
|
132
|
+
or not self.service
|
|
133
|
+
or not isinstance(self.secret, str)
|
|
134
|
+
or len(self.secret.encode()) < 32
|
|
135
|
+
or not 0 <= self.port <= 65535
|
|
136
|
+
or self.discovery_timeout <= 0
|
|
137
|
+
or self.max_peers < 1
|
|
138
|
+
or any(
|
|
139
|
+
not math.isfinite(value) or value <= 0
|
|
140
|
+
for value in (
|
|
141
|
+
self.discovery_timeout,
|
|
142
|
+
self.ownership_cache_ttl,
|
|
143
|
+
self.topology_cache_ttl,
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
):
|
|
147
|
+
raise ValueError("invalid runtime peer configuration (secret requires 32 bytes)")
|
|
148
|
+
|
|
149
|
+
@classmethod
|
|
150
|
+
def from_env(cls, *, tunnel_token: str | None = None):
|
|
151
|
+
secret = os.getenv("KSADK_TUNNEL_PEER_SECRET", "")
|
|
152
|
+
runtime_id = os.getenv("AGENT_RUNTIME_ID", "").strip()
|
|
153
|
+
if not runtime_id:
|
|
154
|
+
if secret:
|
|
155
|
+
raise ValueError("AGENT_RUNTIME_ID is required for runtime peer discovery")
|
|
156
|
+
return None # Local runs have no platform runtime identity.
|
|
157
|
+
if not secret:
|
|
158
|
+
if not tunnel_token or not tunnel_token.strip():
|
|
159
|
+
return None
|
|
160
|
+
secret = hmac.new(
|
|
161
|
+
tunnel_token.encode(),
|
|
162
|
+
("ksadk-tunnel-peer-v1:" + runtime_id).encode(),
|
|
163
|
+
hashlib.sha256,
|
|
164
|
+
).hexdigest()
|
|
165
|
+
return cls(
|
|
166
|
+
runtime_id,
|
|
167
|
+
os.getenv("KSADK_TUNNEL_PEER_SERVICE") or runtime_id + "-headless",
|
|
168
|
+
secret,
|
|
169
|
+
port=int(os.getenv("KSADK_TUNNEL_PEER_PORT", "8092")),
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@dataclass
|
|
174
|
+
class PeerCatalog:
|
|
175
|
+
connections: list[tuple[str, RemoteConnector]]
|
|
176
|
+
unavailable: bool
|
|
177
|
+
expires_at: float
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class _DirectConnect(Connect):
|
|
181
|
+
def handle_redirect(self, uri):
|
|
182
|
+
raise TunnelError("peer_auth_failed")
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class SignedSocket:
|
|
186
|
+
def __init__(self, ws, key, limits, *, server=False, on_close=None):
|
|
187
|
+
self.ws, self.key, self.limits = ws, key, limits
|
|
188
|
+
self.on_close = on_close
|
|
189
|
+
self.send_direction, self.recv_direction = ("s2c", "c2s") if server else ("c2s", "s2c")
|
|
190
|
+
self.sent = self.received = 0
|
|
191
|
+
|
|
192
|
+
async def send(self, payload):
|
|
193
|
+
encode(payload, self.limits)
|
|
194
|
+
frame = {
|
|
195
|
+
"seq": self.sent,
|
|
196
|
+
"payload": payload,
|
|
197
|
+
"mac": _mac(self.key, self.send_direction, self.sent, _json(payload)),
|
|
198
|
+
}
|
|
199
|
+
async with asyncio.timeout(self.limits.send_timeout):
|
|
200
|
+
await self.ws.send(
|
|
201
|
+
json.dumps(frame, separators=(",", ":"), allow_nan=False, ensure_ascii=False)
|
|
202
|
+
)
|
|
203
|
+
self.sent += 1
|
|
204
|
+
|
|
205
|
+
async def receive(self):
|
|
206
|
+
async with asyncio.timeout(self.limits.request_timeout):
|
|
207
|
+
raw = await self.ws.recv()
|
|
208
|
+
if not isinstance(raw, str) or len(raw.encode()) > self.limits.max_frame_bytes + 1024:
|
|
209
|
+
raise TunnelError("peer_auth_failed")
|
|
210
|
+
try:
|
|
211
|
+
frame = json.loads(raw)
|
|
212
|
+
if (
|
|
213
|
+
set(frame) != {"seq", "payload", "mac"}
|
|
214
|
+
or type(frame["seq"]) is not int
|
|
215
|
+
or frame["seq"] != self.received
|
|
216
|
+
or not isinstance(frame["mac"], str)
|
|
217
|
+
or not hmac.compare_digest(
|
|
218
|
+
frame["mac"],
|
|
219
|
+
_mac(self.key, self.recv_direction, frame["seq"], _json(frame["payload"])),
|
|
220
|
+
)
|
|
221
|
+
):
|
|
222
|
+
raise ValueError
|
|
223
|
+
encode(frame["payload"], self.limits)
|
|
224
|
+
except (ValueError, TypeError, KeyError):
|
|
225
|
+
raise TunnelError("peer_auth_failed") from None
|
|
226
|
+
self.received += 1
|
|
227
|
+
return frame["payload"]
|
|
228
|
+
|
|
229
|
+
async def close(self):
|
|
230
|
+
try:
|
|
231
|
+
async with asyncio.timeout(self.limits.send_timeout):
|
|
232
|
+
await self.ws.close()
|
|
233
|
+
except TimeoutError:
|
|
234
|
+
self.ws.fail_connection()
|
|
235
|
+
finally:
|
|
236
|
+
if self.on_close is not None:
|
|
237
|
+
self.on_close(self)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@dataclass(eq=False)
|
|
241
|
+
class RemoteConnector:
|
|
242
|
+
network: object = field(repr=False)
|
|
243
|
+
agent_id: str
|
|
244
|
+
connector_id: str
|
|
245
|
+
owner: dict
|
|
246
|
+
services: dict
|
|
247
|
+
limits: TunnelLimits
|
|
248
|
+
operations: set = field(default_factory=set, repr=False)
|
|
249
|
+
closed: bool = False
|
|
250
|
+
|
|
251
|
+
async def forward(self, service, request):
|
|
252
|
+
return await self.network.forward(self, service, request)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
class PeerStream(httpx.AsyncByteStream):
|
|
256
|
+
def __init__(self, channel, on_failure):
|
|
257
|
+
self.channel, self.done = channel, False
|
|
258
|
+
self.operation = _current_operation.get()
|
|
259
|
+
self.on_failure = on_failure
|
|
260
|
+
|
|
261
|
+
async def __aiter__(self):
|
|
262
|
+
received = 0
|
|
263
|
+
try:
|
|
264
|
+
while True:
|
|
265
|
+
frame = await self.channel.receive()
|
|
266
|
+
if frame.get("type") == "http_end":
|
|
267
|
+
self.done = True
|
|
268
|
+
return
|
|
269
|
+
if frame.get("type") == "http_error":
|
|
270
|
+
raise TunnelError(_wire_error(frame))
|
|
271
|
+
if frame.get("type") != "http_chunk" or not isinstance(frame.get("data"), str):
|
|
272
|
+
raise TunnelError("invalid_result")
|
|
273
|
+
data = frame["data"].encode()
|
|
274
|
+
received += len(data)
|
|
275
|
+
if received > self.channel.limits.max_response_bytes:
|
|
276
|
+
raise TunnelError("frame_too_large")
|
|
277
|
+
yield data
|
|
278
|
+
except (ConnectionClosed, OSError):
|
|
279
|
+
self.on_failure()
|
|
280
|
+
if self.operation is not None:
|
|
281
|
+
self.operation.fail("disconnected")
|
|
282
|
+
raise TunnelError("disconnected") from None
|
|
283
|
+
except Exception as exc:
|
|
284
|
+
self.on_failure()
|
|
285
|
+
# MCP can be waiting on a parsed SSE message. Wake exactly the
|
|
286
|
+
# parent operation; another call may share this owner/generation.
|
|
287
|
+
if self.operation is not None:
|
|
288
|
+
self.operation.fail(
|
|
289
|
+
exc.code if isinstance(exc, TunnelError) else "local_service_error"
|
|
290
|
+
)
|
|
291
|
+
raise
|
|
292
|
+
finally:
|
|
293
|
+
await self.aclose()
|
|
294
|
+
|
|
295
|
+
async def aclose(self):
|
|
296
|
+
channel, self.channel = self.channel, None
|
|
297
|
+
if channel is None:
|
|
298
|
+
return
|
|
299
|
+
try:
|
|
300
|
+
if not self.done:
|
|
301
|
+
await channel.send({"type": "http_cancel"})
|
|
302
|
+
except Exception:
|
|
303
|
+
pass
|
|
304
|
+
finally:
|
|
305
|
+
await channel.close()
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
class PeerNetwork:
|
|
309
|
+
def __init__(self, config, registry_provider, *, limits=None, resolver=None):
|
|
310
|
+
self.config, self.registry_provider = config, registry_provider
|
|
311
|
+
self.limits = limits or TunnelLimits()
|
|
312
|
+
self.instance_id = uuid.uuid4().hex
|
|
313
|
+
self.key = hmac.new(
|
|
314
|
+
config.secret.encode(), ("ksadk-peer-v1\n" + config.runtime_id).encode(), hashlib.sha256
|
|
315
|
+
).digest()
|
|
316
|
+
self.server = None
|
|
317
|
+
self.owner = None
|
|
318
|
+
self._resolver = resolver
|
|
319
|
+
self._legacy_nonces = {}
|
|
320
|
+
self._remotes = {}
|
|
321
|
+
self._catalogs = {}
|
|
322
|
+
self._discovery_lock = asyncio.Lock()
|
|
323
|
+
self._topology = set()
|
|
324
|
+
self._topology_expires_at = 0.0
|
|
325
|
+
self._handlers = set()
|
|
326
|
+
self._channels = {}
|
|
327
|
+
self._start_task = None
|
|
328
|
+
self._retry_start_at = 0.0
|
|
329
|
+
self._closing = False
|
|
330
|
+
|
|
331
|
+
@contextmanager
|
|
332
|
+
def operation_scope(self, deadline):
|
|
333
|
+
operation = PeerOperation(deadline)
|
|
334
|
+
token = _current_operation.set(operation)
|
|
335
|
+
try:
|
|
336
|
+
yield operation
|
|
337
|
+
finally:
|
|
338
|
+
_current_operation.reset(token)
|
|
339
|
+
|
|
340
|
+
def request_start(self):
|
|
341
|
+
"""Schedule one shared attempt without blocking Connector registration or I/O."""
|
|
342
|
+
if self._closing:
|
|
343
|
+
raise TunnelError("closed")
|
|
344
|
+
if self.server is not None or time.monotonic() < self._retry_start_at:
|
|
345
|
+
return None
|
|
346
|
+
if self._start_task is None or self._start_task.done():
|
|
347
|
+
self._start_task = asyncio.create_task(self._try_start_listener())
|
|
348
|
+
return self._start_task
|
|
349
|
+
|
|
350
|
+
async def start(self) -> bool:
|
|
351
|
+
attempt = self.request_start()
|
|
352
|
+
if attempt is not None:
|
|
353
|
+
await asyncio.shield(attempt)
|
|
354
|
+
return self.server is not None
|
|
355
|
+
|
|
356
|
+
async def _try_start_listener(self):
|
|
357
|
+
try:
|
|
358
|
+
async with asyncio.timeout(self.config.discovery_timeout):
|
|
359
|
+
await self._start_listener()
|
|
360
|
+
except (OSError, ValueError) as exc:
|
|
361
|
+
self._retry_start_at = time.monotonic() + self.config.topology_cache_ttl
|
|
362
|
+
logger.warning(
|
|
363
|
+
"Tunnel peer listener unavailable (%s); using local connectors", type(exc).__name__
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
async def _start_listener(self):
|
|
367
|
+
host = self.config.advertised_host
|
|
368
|
+
if host is None:
|
|
369
|
+
fqdn = await asyncio.to_thread(socket.getfqdn)
|
|
370
|
+
records = await asyncio.get_running_loop().getaddrinfo(
|
|
371
|
+
fqdn, None, type=socket.SOCK_STREAM
|
|
372
|
+
)
|
|
373
|
+
if not records:
|
|
374
|
+
raise OSError("no peer listener address")
|
|
375
|
+
host = records[0][4][0]
|
|
376
|
+
ipaddress.ip_address(host)
|
|
377
|
+
self.server = await serve(
|
|
378
|
+
self._accept,
|
|
379
|
+
self.config.host,
|
|
380
|
+
self.config.port,
|
|
381
|
+
extra_headers=lambda path, headers: {_CHALLENGE_HEADER: uuid.uuid4().hex},
|
|
382
|
+
max_size=self.limits.max_frame_bytes + 1024,
|
|
383
|
+
max_queue=8,
|
|
384
|
+
open_timeout=self.limits.registration_timeout,
|
|
385
|
+
close_timeout=self.limits.send_timeout,
|
|
386
|
+
ping_interval=self.limits.heartbeat_interval,
|
|
387
|
+
ping_timeout=self.limits.idle_timeout,
|
|
388
|
+
)
|
|
389
|
+
port = self.server.sockets[0].getsockname()[1]
|
|
390
|
+
address = f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
|
|
391
|
+
self.owner = {"address": address, "instance_id": self.instance_id}
|
|
392
|
+
|
|
393
|
+
async def addresses(self):
|
|
394
|
+
if time.monotonic() < self._topology_expires_at:
|
|
395
|
+
return set(self._topology)
|
|
396
|
+
async with asyncio.timeout(self.config.discovery_timeout):
|
|
397
|
+
if self._resolver is not None:
|
|
398
|
+
values = await self._resolver()
|
|
399
|
+
else:
|
|
400
|
+
records = await asyncio.get_running_loop().getaddrinfo(
|
|
401
|
+
self.config.service, self.config.port, type=socket.SOCK_STREAM
|
|
402
|
+
)
|
|
403
|
+
values = [
|
|
404
|
+
(
|
|
405
|
+
f"[{r[4][0]}]:{self.config.port}"
|
|
406
|
+
if ":" in r[4][0]
|
|
407
|
+
else f"{r[4][0]}:{self.config.port}"
|
|
408
|
+
)
|
|
409
|
+
for r in records
|
|
410
|
+
]
|
|
411
|
+
addresses = set(values)
|
|
412
|
+
if len(addresses) > self.config.max_peers:
|
|
413
|
+
raise TunnelError("peer_topology_limit")
|
|
414
|
+
for address in addresses:
|
|
415
|
+
validate_owner({"address": address, "instance_id": self.instance_id})
|
|
416
|
+
self._topology = addresses
|
|
417
|
+
self._topology_expires_at = time.monotonic() + self.config.topology_cache_ttl
|
|
418
|
+
return set(addresses)
|
|
419
|
+
|
|
420
|
+
async def _open(self, address, expected_instance=None):
|
|
421
|
+
if self._closing:
|
|
422
|
+
raise TunnelError("disconnected")
|
|
423
|
+
ws = None
|
|
424
|
+
try:
|
|
425
|
+
ws = await _DirectConnect(
|
|
426
|
+
f"ws://{address}{_PATH}",
|
|
427
|
+
open_timeout=self.config.discovery_timeout,
|
|
428
|
+
close_timeout=self.limits.send_timeout,
|
|
429
|
+
max_size=self.limits.max_frame_bytes + 1024,
|
|
430
|
+
max_queue=8,
|
|
431
|
+
)
|
|
432
|
+
hello = {
|
|
433
|
+
"type": "hello",
|
|
434
|
+
"runtime": self.config.runtime_id,
|
|
435
|
+
"timestamp": int(time.time()),
|
|
436
|
+
"nonce": uuid.uuid4().hex,
|
|
437
|
+
}
|
|
438
|
+
challenge = ws.response_headers.get(_CHALLENGE_HEADER)
|
|
439
|
+
if challenge is not None:
|
|
440
|
+
hello["challenge"] = challenge
|
|
441
|
+
hello["signature"] = _mac(self.key, _json(hello))
|
|
442
|
+
await ws.send(json.dumps(hello))
|
|
443
|
+
async with asyncio.timeout(self.config.discovery_timeout):
|
|
444
|
+
ack = json.loads(await ws.recv())
|
|
445
|
+
signature = ack.pop("signature", None)
|
|
446
|
+
if (
|
|
447
|
+
set(ack) != {"type", "nonce", "instance_id"}
|
|
448
|
+
or ack["type"] != "hello_ack"
|
|
449
|
+
or not isinstance(signature, str)
|
|
450
|
+
or not hmac.compare_digest(signature, _mac(self.key, hello["nonce"], _json(ack)))
|
|
451
|
+
or (expected_instance is not None and ack["instance_id"] != expected_instance)
|
|
452
|
+
):
|
|
453
|
+
raise TunnelError("peer_auth_failed")
|
|
454
|
+
identifier(ack["nonce"], "peer nonce")
|
|
455
|
+
identifier(ack["instance_id"], "peer instance")
|
|
456
|
+
if self._closing:
|
|
457
|
+
raise TunnelError("disconnected")
|
|
458
|
+
session_key = bytes.fromhex(_mac(self.key, "session", hello["nonce"], ack["nonce"]))
|
|
459
|
+
channel = SignedSocket(
|
|
460
|
+
ws,
|
|
461
|
+
session_key,
|
|
462
|
+
self.limits,
|
|
463
|
+
on_close=lambda socket: self._channels.pop(socket, None),
|
|
464
|
+
)
|
|
465
|
+
self._channels[channel] = _current_operation.get()
|
|
466
|
+
return channel, ack["instance_id"]
|
|
467
|
+
except BaseException:
|
|
468
|
+
if ws is not None:
|
|
469
|
+
await ws.close()
|
|
470
|
+
raise
|
|
471
|
+
|
|
472
|
+
async def _authenticate(self, ws):
|
|
473
|
+
async with asyncio.timeout(self.config.discovery_timeout):
|
|
474
|
+
hello = json.loads(await ws.recv())
|
|
475
|
+
signature = hello.pop("signature", None)
|
|
476
|
+
now = time.time()
|
|
477
|
+
fields = {"type", "runtime", "timestamp", "nonce"}
|
|
478
|
+
if "challenge" in hello:
|
|
479
|
+
fields.add("challenge")
|
|
480
|
+
if hello["challenge"] != ws.response_headers[_CHALLENGE_HEADER]:
|
|
481
|
+
raise TunnelError("peer_auth_failed")
|
|
482
|
+
if (
|
|
483
|
+
set(hello) != fields
|
|
484
|
+
or hello["type"] != "hello"
|
|
485
|
+
or hello["runtime"] != self.config.runtime_id
|
|
486
|
+
or type(hello["timestamp"]) is not int
|
|
487
|
+
or abs(now - hello["timestamp"]) > _AUTH_WINDOW
|
|
488
|
+
or not isinstance(hello["nonce"], str)
|
|
489
|
+
or len(hello["nonce"]) != 32
|
|
490
|
+
or not isinstance(signature, str)
|
|
491
|
+
or not hmac.compare_digest(signature, _mac(self.key, _json(hello)))
|
|
492
|
+
):
|
|
493
|
+
raise TunnelError("peer_auth_failed")
|
|
494
|
+
if "challenge" not in hello:
|
|
495
|
+
# Rolling upgrades: old clients cannot bind their signature to this socket.
|
|
496
|
+
self._legacy_nonces = {
|
|
497
|
+
n: seen for n, seen in self._legacy_nonces.items() if now - seen <= 2 * _AUTH_WINDOW
|
|
498
|
+
}
|
|
499
|
+
if (
|
|
500
|
+
hello["nonce"] in self._legacy_nonces
|
|
501
|
+
or len(self._legacy_nonces) >= _MAX_LEGACY_NONCES
|
|
502
|
+
):
|
|
503
|
+
raise TunnelError("peer_auth_failed")
|
|
504
|
+
self._legacy_nonces[hello["nonce"]] = now
|
|
505
|
+
ack = {"type": "hello_ack", "nonce": uuid.uuid4().hex, "instance_id": self.instance_id}
|
|
506
|
+
ack["signature"] = _mac(self.key, hello["nonce"], _json(ack))
|
|
507
|
+
await ws.send(json.dumps(ack))
|
|
508
|
+
session_key = bytes.fromhex(_mac(self.key, "session", hello["nonce"], ack["nonce"]))
|
|
509
|
+
return SignedSocket(ws, session_key, self.limits, server=True)
|
|
510
|
+
|
|
511
|
+
async def _accept(self, ws, path):
|
|
512
|
+
task = asyncio.current_task()
|
|
513
|
+
self._handlers.add(task)
|
|
514
|
+
relay = watcher = None
|
|
515
|
+
try:
|
|
516
|
+
if path != _PATH or len(self._handlers) > 3 * self.limits.max_inflight:
|
|
517
|
+
return
|
|
518
|
+
channel = await self._authenticate(ws)
|
|
519
|
+
payload = await channel.receive()
|
|
520
|
+
registry = self.registry_provider()
|
|
521
|
+
agent = identifier(payload.get("agent_id"), "agent_id")
|
|
522
|
+
if payload.get("type") == "discover" and set(payload) == {"type", "agent_id"}:
|
|
523
|
+
services = [
|
|
524
|
+
{
|
|
525
|
+
"name": service,
|
|
526
|
+
"connector_id": conn.connector_id,
|
|
527
|
+
"descriptor": conn.services[service],
|
|
528
|
+
}
|
|
529
|
+
for service, conn in (
|
|
530
|
+
registry.connections(agent) if registry is not None else []
|
|
531
|
+
)
|
|
532
|
+
]
|
|
533
|
+
await channel.send({"type": "discovery", "services": services})
|
|
534
|
+
return
|
|
535
|
+
if registry is None:
|
|
536
|
+
raise TunnelError("disconnected")
|
|
537
|
+
if set(payload) != {
|
|
538
|
+
"type",
|
|
539
|
+
"agent_id",
|
|
540
|
+
"service",
|
|
541
|
+
"connector_id",
|
|
542
|
+
"method",
|
|
543
|
+
"path",
|
|
544
|
+
"query",
|
|
545
|
+
"headers",
|
|
546
|
+
"body",
|
|
547
|
+
}:
|
|
548
|
+
raise TunnelError("invalid_request")
|
|
549
|
+
service = identifier(payload["service"], "service")
|
|
550
|
+
generation = identifier(payload["connector_id"], "connector_id")
|
|
551
|
+
conn = registry._connections.get((agent, service))
|
|
552
|
+
if (
|
|
553
|
+
payload["type"] != "http_request"
|
|
554
|
+
or conn is None
|
|
555
|
+
or conn.closed
|
|
556
|
+
or generation != conn.connector_id
|
|
557
|
+
):
|
|
558
|
+
raise TunnelError("disconnected")
|
|
559
|
+
if (
|
|
560
|
+
payload["method"] not in {"GET", "POST", "DELETE"}
|
|
561
|
+
or payload["query"] != ""
|
|
562
|
+
or not isinstance(payload["path"], str)
|
|
563
|
+
or "/" in payload["path"]
|
|
564
|
+
or not isinstance(payload["body"], str)
|
|
565
|
+
or not isinstance(payload["headers"], dict)
|
|
566
|
+
):
|
|
567
|
+
raise TunnelError("invalid_request")
|
|
568
|
+
request = httpx.Request(
|
|
569
|
+
payload["method"],
|
|
570
|
+
f"http://tunnel/{payload['path']}",
|
|
571
|
+
headers=payload["headers"],
|
|
572
|
+
content=payload["body"].encode(),
|
|
573
|
+
)
|
|
574
|
+
relay = asyncio.create_task(self._relay(channel, conn, service, request))
|
|
575
|
+
watcher = asyncio.create_task(channel.receive())
|
|
576
|
+
done, _ = await asyncio.wait({relay, watcher}, return_when=asyncio.FIRST_COMPLETED)
|
|
577
|
+
if watcher in done:
|
|
578
|
+
frame = watcher.result()
|
|
579
|
+
if frame != {"type": "http_cancel"}:
|
|
580
|
+
raise TunnelError("invalid_request")
|
|
581
|
+
else:
|
|
582
|
+
await relay
|
|
583
|
+
except asyncio.CancelledError:
|
|
584
|
+
raise
|
|
585
|
+
except Exception as exc:
|
|
586
|
+
try:
|
|
587
|
+
if "channel" in locals():
|
|
588
|
+
safe = {
|
|
589
|
+
"busy",
|
|
590
|
+
"forbidden",
|
|
591
|
+
"disconnected",
|
|
592
|
+
"timeout",
|
|
593
|
+
"frame_too_large",
|
|
594
|
+
"local_service_error",
|
|
595
|
+
"local_mcp_error",
|
|
596
|
+
"invalid_request",
|
|
597
|
+
}
|
|
598
|
+
code = (
|
|
599
|
+
exc.code
|
|
600
|
+
if isinstance(exc, TunnelError) and exc.code in safe
|
|
601
|
+
else (
|
|
602
|
+
"timeout"
|
|
603
|
+
if isinstance(exc, TimeoutError)
|
|
604
|
+
else (
|
|
605
|
+
"disconnected"
|
|
606
|
+
if isinstance(exc, (ConnectionClosed, OSError))
|
|
607
|
+
else "local_service_error"
|
|
608
|
+
)
|
|
609
|
+
)
|
|
610
|
+
)
|
|
611
|
+
await channel.send({"type": "http_error", "error": code})
|
|
612
|
+
except Exception:
|
|
613
|
+
pass
|
|
614
|
+
finally:
|
|
615
|
+
for active in (relay, watcher):
|
|
616
|
+
if active is not None:
|
|
617
|
+
active.cancel()
|
|
618
|
+
await asyncio.gather(
|
|
619
|
+
*(t for t in (relay, watcher) if t is not None), return_exceptions=True
|
|
620
|
+
)
|
|
621
|
+
self._handlers.discard(task)
|
|
622
|
+
try:
|
|
623
|
+
async with asyncio.timeout(self.limits.send_timeout):
|
|
624
|
+
await ws.close()
|
|
625
|
+
except TimeoutError:
|
|
626
|
+
ws.fail_connection()
|
|
627
|
+
|
|
628
|
+
async def _relay(self, channel, connection, service, request):
|
|
629
|
+
response = await connection.forward(service, request)
|
|
630
|
+
try:
|
|
631
|
+
await channel.send(
|
|
632
|
+
{
|
|
633
|
+
"type": "http_response",
|
|
634
|
+
"status": response.status_code,
|
|
635
|
+
"headers": dict(response.headers),
|
|
636
|
+
}
|
|
637
|
+
)
|
|
638
|
+
async for data in response.aiter_bytes():
|
|
639
|
+
await channel.send({"type": "http_chunk", "data": data.decode("utf-8")})
|
|
640
|
+
await channel.send({"type": "http_end"})
|
|
641
|
+
finally:
|
|
642
|
+
await response.aclose()
|
|
643
|
+
|
|
644
|
+
async def _discover_at(self, address, agent_id, expected_instance=None):
|
|
645
|
+
channel, instance = await self._open(address, expected_instance)
|
|
646
|
+
try:
|
|
647
|
+
await channel.send({"type": "discover", "agent_id": agent_id})
|
|
648
|
+
result = await channel.receive()
|
|
649
|
+
if result.get("type") != "discovery" or not isinstance(result.get("services"), list):
|
|
650
|
+
raise TunnelError("invalid_result")
|
|
651
|
+
return {"address": address, "instance_id": instance}, self._parse_services(
|
|
652
|
+
result["services"]
|
|
653
|
+
)
|
|
654
|
+
finally:
|
|
655
|
+
await channel.close()
|
|
656
|
+
|
|
657
|
+
def _parse_services(self, services):
|
|
658
|
+
from .server import _validate_descriptor
|
|
659
|
+
|
|
660
|
+
# A peer frame is size-bounded. The service count limit is per Connector.
|
|
661
|
+
descriptors = {}
|
|
662
|
+
for item in services:
|
|
663
|
+
if not isinstance(item, dict) or set(item) != {"name", "connector_id", "descriptor"}:
|
|
664
|
+
raise TunnelError("invalid_result")
|
|
665
|
+
descriptor = item["descriptor"]
|
|
666
|
+
if not isinstance(descriptor, dict) or descriptor.get("name") != item["name"]:
|
|
667
|
+
raise TunnelError("invalid_result")
|
|
668
|
+
try:
|
|
669
|
+
name = identifier(item["name"], "service")
|
|
670
|
+
generation = identifier(item["connector_id"], "connector_id")
|
|
671
|
+
_validate_descriptor(descriptor, self.limits)
|
|
672
|
+
except (KeyError, ValueError):
|
|
673
|
+
raise TunnelError("invalid_result") from None
|
|
674
|
+
group = descriptors.setdefault(generation, {})
|
|
675
|
+
if name in group or len(group) >= self.limits.max_services:
|
|
676
|
+
raise TunnelError("invalid_result")
|
|
677
|
+
group[name] = descriptor
|
|
678
|
+
return descriptors
|
|
679
|
+
|
|
680
|
+
def _remember(self, owner, agent_id, descriptors):
|
|
681
|
+
result = []
|
|
682
|
+
for generation, group in descriptors.items():
|
|
683
|
+
key = (owner["address"], owner["instance_id"], agent_id, generation)
|
|
684
|
+
connection = self._remotes.get(key)
|
|
685
|
+
if connection is None:
|
|
686
|
+
connection = RemoteConnector(self, agent_id, generation, owner, {}, self.limits)
|
|
687
|
+
self._remotes[key] = connection
|
|
688
|
+
connection.services = group
|
|
689
|
+
result.extend((name, connection) for name in group)
|
|
690
|
+
return result
|
|
691
|
+
|
|
692
|
+
def invalidate(self, owner):
|
|
693
|
+
"""Expire this owner's cached routes without cancelling other in-flight calls."""
|
|
694
|
+
# A subsequent authenticated lookup may confirm this exact generation.
|
|
695
|
+
# Its outstanding operation deadlines still consume the same budget.
|
|
696
|
+
for catalog in self._catalogs.values():
|
|
697
|
+
if any(connection.owner == owner for _, connection in catalog.connections):
|
|
698
|
+
catalog.expires_at = 0.0
|
|
699
|
+
self._topology_expires_at = 0.0
|
|
700
|
+
|
|
701
|
+
async def _probe(self, address, agent_id):
|
|
702
|
+
# Bound the whole discovery exchange, not only the TCP handshake.
|
|
703
|
+
async with asyncio.timeout(self.config.discovery_timeout):
|
|
704
|
+
return await self._discover_at(address, agent_id)
|
|
705
|
+
|
|
706
|
+
async def _refresh_catalog(self, agent_id):
|
|
707
|
+
try:
|
|
708
|
+
addresses = await self.addresses()
|
|
709
|
+
except (OSError, TimeoutError):
|
|
710
|
+
addresses = set()
|
|
711
|
+
unavailable = True
|
|
712
|
+
else:
|
|
713
|
+
addresses.discard(self.owner["address"])
|
|
714
|
+
unavailable = False
|
|
715
|
+
results = await asyncio.gather(
|
|
716
|
+
*(self._probe(addr, agent_id) for addr in addresses), return_exceptions=True
|
|
717
|
+
)
|
|
718
|
+
confirmed = []
|
|
719
|
+
for result in results:
|
|
720
|
+
if isinstance(result, (OSError, TimeoutError, ConnectionClosed, InvalidHandshake)):
|
|
721
|
+
# DNS may still advertise a terminating or not-yet-listening pod.
|
|
722
|
+
unavailable = True
|
|
723
|
+
continue
|
|
724
|
+
if isinstance(result, BaseException):
|
|
725
|
+
# Invalid authenticated metadata must never become a cached route.
|
|
726
|
+
raise TunnelError("peer_discovery_unavailable") from None
|
|
727
|
+
confirmed.append(result)
|
|
728
|
+
# Publish ownership only after every responding peer passed validation.
|
|
729
|
+
connections = [
|
|
730
|
+
route
|
|
731
|
+
for owner, descriptors in confirmed
|
|
732
|
+
for route in self._remember(owner, agent_id, descriptors)
|
|
733
|
+
]
|
|
734
|
+
if unavailable:
|
|
735
|
+
logger.warning(
|
|
736
|
+
"Tunnel peer discovery incomplete (%d confirmed services)", len(connections)
|
|
737
|
+
)
|
|
738
|
+
live = {
|
|
739
|
+
(conn.owner["address"], conn.owner["instance_id"], agent_id, conn.connector_id)
|
|
740
|
+
for _, conn in connections
|
|
741
|
+
}
|
|
742
|
+
self._remotes = {
|
|
743
|
+
key: conn
|
|
744
|
+
for key, conn in self._remotes.items()
|
|
745
|
+
if key[2] != agent_id or key in live or conn.operations
|
|
746
|
+
}
|
|
747
|
+
# Retry missing peers sooner, including an empty/negative catalog.
|
|
748
|
+
ttl = (
|
|
749
|
+
min(self.config.ownership_cache_ttl, 0.25)
|
|
750
|
+
if unavailable or not connections
|
|
751
|
+
else self.config.ownership_cache_ttl
|
|
752
|
+
)
|
|
753
|
+
return PeerCatalog(connections, unavailable, time.monotonic() + ttl)
|
|
754
|
+
|
|
755
|
+
async def discover(self, agent_id, *, has_local=False):
|
|
756
|
+
async with self._discovery_lock:
|
|
757
|
+
catalog = self._catalogs.get(agent_id)
|
|
758
|
+
if catalog is None or time.monotonic() >= catalog.expires_at:
|
|
759
|
+
catalog = await self._refresh_catalog(agent_id)
|
|
760
|
+
self._catalogs[agent_id] = catalog
|
|
761
|
+
if not catalog.connections and catalog.unavailable and not has_local:
|
|
762
|
+
raise IncompletePeerDiscovery()
|
|
763
|
+
return list(catalog.connections)
|
|
764
|
+
|
|
765
|
+
async def resolve(self, agent_id, service, connector_id, owner):
|
|
766
|
+
owner = validate_owner(owner)
|
|
767
|
+
key = (owner["address"], owner["instance_id"], agent_id, connector_id)
|
|
768
|
+
cached = self._remotes.get(key)
|
|
769
|
+
catalog = self._catalogs.get(agent_id)
|
|
770
|
+
if (
|
|
771
|
+
cached is not None
|
|
772
|
+
and service in cached.services
|
|
773
|
+
and catalog is not None
|
|
774
|
+
and time.monotonic() < catalog.expires_at
|
|
775
|
+
and any(conn is cached for _, conn in catalog.connections)
|
|
776
|
+
):
|
|
777
|
+
return cached
|
|
778
|
+
try:
|
|
779
|
+
if owner["address"] not in await self.addresses():
|
|
780
|
+
raise TunnelError("disconnected")
|
|
781
|
+
async with asyncio.timeout(self.config.discovery_timeout):
|
|
782
|
+
found_owner, descriptors = await self._discover_at(
|
|
783
|
+
owner["address"], agent_id, expected_instance=owner["instance_id"]
|
|
784
|
+
)
|
|
785
|
+
for name, conn in self._remember(found_owner, agent_id, descriptors):
|
|
786
|
+
if name == service and conn.connector_id == connector_id:
|
|
787
|
+
return conn
|
|
788
|
+
raise TunnelError("disconnected")
|
|
789
|
+
except (OSError, TimeoutError, ConnectionClosed, InvalidHandshake):
|
|
790
|
+
self.invalidate(owner)
|
|
791
|
+
# Ownership lookup happens before the tool request is sent.
|
|
792
|
+
raise TunnelError("disconnected") from None
|
|
793
|
+
except TunnelError:
|
|
794
|
+
self.invalidate(owner)
|
|
795
|
+
raise
|
|
796
|
+
|
|
797
|
+
async def forward(self, connection, service, request):
|
|
798
|
+
body = decode_request_body(await request.aread())
|
|
799
|
+
channel = None
|
|
800
|
+
try:
|
|
801
|
+
channel, _ = await self._open(
|
|
802
|
+
connection.owner["address"], connection.owner["instance_id"]
|
|
803
|
+
)
|
|
804
|
+
await channel.send(
|
|
805
|
+
{
|
|
806
|
+
"type": "http_request",
|
|
807
|
+
"agent_id": connection.agent_id,
|
|
808
|
+
"service": service,
|
|
809
|
+
"connector_id": connection.connector_id,
|
|
810
|
+
"method": request.method,
|
|
811
|
+
"path": request.url.path.strip("/"),
|
|
812
|
+
"query": request.url.query.decode("ascii"),
|
|
813
|
+
"headers": dict(request.headers),
|
|
814
|
+
"body": body,
|
|
815
|
+
}
|
|
816
|
+
)
|
|
817
|
+
frame = await channel.receive()
|
|
818
|
+
if frame.get("type") == "http_error":
|
|
819
|
+
raise TunnelError(_wire_error(frame))
|
|
820
|
+
if (
|
|
821
|
+
frame.get("type") != "http_response"
|
|
822
|
+
or type(frame.get("status")) is not int
|
|
823
|
+
or not 100 <= frame["status"] <= 599
|
|
824
|
+
or not isinstance(frame.get("headers"), dict)
|
|
825
|
+
):
|
|
826
|
+
raise TunnelError("disconnected")
|
|
827
|
+
return httpx.Response(
|
|
828
|
+
frame["status"],
|
|
829
|
+
headers=frame["headers"],
|
|
830
|
+
stream=PeerStream(channel, lambda: self.invalidate(connection.owner)),
|
|
831
|
+
)
|
|
832
|
+
except BaseException as exc:
|
|
833
|
+
if not isinstance(exc, asyncio.CancelledError):
|
|
834
|
+
self.invalidate(connection.owner)
|
|
835
|
+
if channel is not None:
|
|
836
|
+
try:
|
|
837
|
+
await channel.send({"type": "http_cancel"})
|
|
838
|
+
except Exception:
|
|
839
|
+
pass
|
|
840
|
+
await channel.close()
|
|
841
|
+
operation = _current_operation.get()
|
|
842
|
+
if operation is not None and isinstance(exc, Exception):
|
|
843
|
+
operation.fail(exc.code if isinstance(exc, TunnelError) else "disconnected")
|
|
844
|
+
raise
|
|
845
|
+
|
|
846
|
+
async def close(self):
|
|
847
|
+
self._closing = True
|
|
848
|
+
if self._start_task is not None:
|
|
849
|
+
self._start_task.cancel()
|
|
850
|
+
await asyncio.gather(self._start_task, return_exceptions=True)
|
|
851
|
+
# A disappearing caller pod must release outgoing streams as well as
|
|
852
|
+
# its inbound listener. Wake each affected MCP operation independently.
|
|
853
|
+
channels = list(self._channels.items())
|
|
854
|
+
for _, operation in channels:
|
|
855
|
+
if operation is not None:
|
|
856
|
+
operation.fail("disconnected")
|
|
857
|
+
await asyncio.gather(*(channel.close() for channel, _ in channels), return_exceptions=True)
|
|
858
|
+
self._catalogs.clear()
|
|
859
|
+
self._remotes.clear()
|
|
860
|
+
self._topology.clear()
|
|
861
|
+
if self.server is not None:
|
|
862
|
+
self.server.close()
|
|
863
|
+
try:
|
|
864
|
+
await asyncio.wait_for(self.server.wait_closed(), 2 * self.limits.send_timeout + 1)
|
|
865
|
+
except TimeoutError:
|
|
866
|
+
for task in list(self._handlers):
|
|
867
|
+
task.cancel()
|
|
868
|
+
await asyncio.wait_for(
|
|
869
|
+
asyncio.gather(*self._handlers, return_exceptions=True),
|
|
870
|
+
self.limits.send_timeout,
|
|
871
|
+
)
|
|
872
|
+
self.server = None
|