tuna-sdk 0.1.0__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.
tuna_sdk/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ """Open tuna.am tunnels from Python code.
2
+
3
+ ``listen`` returns a Tunnel that receives connections arriving at the tunnel's
4
+ public address as ``(reader, writer)`` streams. ``forward`` proxies them to a
5
+ local address. ``tuna_sdk.sync`` offers the same without asyncio.
6
+
7
+ A tunnel survives network failures: it reconnects with backoff and keeps its
8
+ public address. It ends on close, cancellation or a permanent error (see
9
+ is_permanent).
10
+ """
11
+
12
+ from . import sync
13
+ from ._api import ServerError
14
+ from ._tunnel import (
15
+ DEFAULT_SERVER_URL,
16
+ VERSION,
17
+ ClosedError,
18
+ Event,
19
+ EventType,
20
+ KeepAliveTimeoutError,
21
+ Options,
22
+ TerminatedError,
23
+ Tunnel,
24
+ forward,
25
+ is_permanent,
26
+ listen,
27
+ )
28
+
29
+ __version__ = VERSION
30
+
31
+ __all__ = [
32
+ "DEFAULT_SERVER_URL",
33
+ "VERSION",
34
+ "ClosedError",
35
+ "Event",
36
+ "EventType",
37
+ "KeepAliveTimeoutError",
38
+ "Options",
39
+ "ServerError",
40
+ "TerminatedError",
41
+ "Tunnel",
42
+ "forward",
43
+ "is_permanent",
44
+ "listen",
45
+ "sync",
46
+ ]
tuna_sdk/_api.py ADDED
@@ -0,0 +1,153 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import contextlib
5
+ import json
6
+ import ssl
7
+ import threading
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from collections.abc import Callable, Mapping
12
+ from email.message import Message
13
+ from typing import Any, TypeVar
14
+
15
+ API_TIMEOUT = 15.0
16
+ MAX_RESPONSE_SIZE = 1 << 20
17
+ MAX_RETRY_AFTER = 300.0
18
+
19
+ _PERMANENT_CODES = frozenset(
20
+ {
21
+ "PaymentRequired",
22
+ "Unauthorized",
23
+ "AuthorizationRequired",
24
+ "Forbidden",
25
+ "BadRequest",
26
+ "NotFound",
27
+ "UpgradeRequired",
28
+ }
29
+ )
30
+
31
+ T = TypeVar("T")
32
+ Headers = Mapping[str, str] | Message
33
+
34
+
35
+ class ServerError(Exception):
36
+ """An error response from the tuna.am API."""
37
+
38
+ status: int
39
+ """HTTP status code."""
40
+ code: str
41
+ """Machine-readable error code."""
42
+ message: str
43
+ """Human-readable error text."""
44
+ request_id: str
45
+ """Identifies the request for tuna.am support."""
46
+ retry_after: float
47
+ """Delay in seconds requested by the server, zero if none."""
48
+
49
+ def __init__(self, status: int, code: str = "", message: str = "", request_id: str = "", retry_after: float = 0.0):
50
+ super().__init__(status, code, message, request_id, retry_after)
51
+ self.status = status
52
+ self.code = code
53
+ self.message = message
54
+ self.request_id = request_id
55
+ self.retry_after = retry_after
56
+ self.before_first_connect = False
57
+
58
+ def __str__(self) -> str:
59
+ if self.request_id:
60
+ return f"tuna: {self.message} (request id {self.request_id})"
61
+ return f"tuna: {self.message}"
62
+
63
+ def permanent(self) -> bool:
64
+ if 300 <= self.status < 400:
65
+ return True
66
+ if self.before_first_connect and 400 <= self.status < 500 and self.status not in (408, 429):
67
+ return True
68
+ return self.code in _PERMANENT_CODES
69
+
70
+
71
+ def check_server_url(url: str) -> None:
72
+ u = urllib.parse.urlsplit(url)
73
+ if u.scheme not in ("https", "http") or not u.netloc:
74
+ raise ValueError(f'tuna: invalid server URL "{url}": want https://host')
75
+
76
+
77
+ def server_error(status: int, headers: Headers, body: bytes) -> ServerError:
78
+ se = ServerError(status)
79
+ if 300 <= status < 400:
80
+ se.message = f'server redirects to "{headers.get("Location", "")}", check the server URL'
81
+ else:
82
+ try:
83
+ data = json.loads(body)
84
+ except ValueError:
85
+ data = None
86
+ if isinstance(data, dict):
87
+ se.code = str(data.get("code") or "")
88
+ se.message = str(data.get("error") or "")
89
+ se.request_id = str(data.get("request_id") or "")
90
+ if not se.message:
91
+ se.message = f"server responded with status {status}"
92
+ try:
93
+ sec = int(headers.get("Retry-After", ""))
94
+ except ValueError:
95
+ sec = 0
96
+ if sec > 0:
97
+ se.retry_after = min(float(sec), MAX_RETRY_AFTER)
98
+ return se
99
+
100
+
101
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
102
+ def redirect_request(self, *args: Any, **kwargs: Any) -> None:
103
+ return None
104
+
105
+
106
+ def _post(url: str, body: bytes, user_agent: str, context: ssl.SSLContext | None) -> tuple[int, Headers, bytes]:
107
+ opener = urllib.request.build_opener(_NoRedirect, urllib.request.HTTPSHandler(context=context))
108
+ req = urllib.request.Request(
109
+ url, data=body, method="POST", headers={"User-Agent": user_agent, "Content-Type": "application/json"}
110
+ )
111
+ try:
112
+ with opener.open(req, timeout=API_TIMEOUT) as resp:
113
+ return resp.status, resp.headers, resp.read(MAX_RESPONSE_SIZE)
114
+ except urllib.error.HTTPError as e:
115
+ with e:
116
+ return e.code, e.headers, e.read(MAX_RESPONSE_SIZE)
117
+
118
+
119
+ async def in_thread(fn: Callable[..., T], *args: Any) -> T:
120
+ loop = asyncio.get_running_loop()
121
+ fut: asyncio.Future[T] = loop.create_future()
122
+
123
+ def settle(result: Any, exc: BaseException | None) -> None:
124
+ if fut.done():
125
+ return
126
+ if exc is not None:
127
+ fut.set_exception(exc)
128
+ else:
129
+ fut.set_result(result)
130
+
131
+ def work() -> None:
132
+ try:
133
+ result, exc = fn(*args), None
134
+ except Exception as e:
135
+ result, exc = None, e
136
+ with contextlib.suppress(RuntimeError):
137
+ loop.call_soon_threadsafe(settle, result, exc)
138
+
139
+ threading.Thread(target=work, daemon=True).start()
140
+ return await fut
141
+
142
+
143
+ async def post_json(
144
+ server_url: str, path: str, user_agent: str, payload: Any, context: ssl.SSLContext | None
145
+ ) -> dict[str, Any]:
146
+ url = server_url.rstrip("/") + path
147
+ status, headers, body = await in_thread(_post, url, json.dumps(payload).encode(), user_agent, context)
148
+ if not 200 <= status <= 299:
149
+ raise server_error(status, headers, body)
150
+ data = json.loads(body)
151
+ if not isinstance(data, dict):
152
+ raise ValueError("tuna: unexpected response from the server")
153
+ return data
tuna_sdk/_tunnel.py ADDED
@@ -0,0 +1,621 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import contextlib
5
+ import dataclasses
6
+ import json
7
+ import os
8
+ import platform
9
+ import random
10
+ import ssl
11
+ import sys
12
+ import unicodedata
13
+ from collections.abc import AsyncIterator, Callable, Coroutine, Generator
14
+ from typing import Any, Literal
15
+
16
+ import asyncssh
17
+
18
+ from ._api import ServerError, check_server_url, post_json
19
+
20
+ VERSION = "0.1.0"
21
+ """The SDK version."""
22
+ DEFAULT_SERVER_URL = "https://api.tuna.am"
23
+ """The tuna.am API used when Options.server_url is empty."""
24
+
25
+ CLIENT_VERSION = 2
26
+ SSH_USER = "tuna"
27
+ DIAL_TIMEOUT = 10.0
28
+ EVENTS_DRAIN_TIMEOUT = 1.0
29
+ EVENTS_COMMAND = "events"
30
+ MIN_BACKOFF = 1.0
31
+ MAX_BACKOFF = 15.0
32
+ KEEPALIVE_INTERVAL = 5.0
33
+ KEEPALIVE_COUNT_MAX = 2
34
+
35
+ EventType = Literal[
36
+ "connected", "reconnected", "reconnecting", "banner", "session_expiring", "terminated", "local_error"
37
+ ]
38
+
39
+ Stream = tuple["asyncssh.SSHReader[bytes]", "asyncssh.SSHWriter[bytes]"]
40
+
41
+ _background: set[asyncio.Future[Any]] = set()
42
+
43
+
44
+ def spawn(coro: Coroutine[Any, Any, Any]) -> asyncio.Future[Any]:
45
+ task = asyncio.ensure_future(coro)
46
+ _background.add(task)
47
+ task.add_done_callback(_background.discard)
48
+ return task
49
+
50
+
51
+ @dataclasses.dataclass(frozen=True)
52
+ class Event:
53
+ """A change in the tunnel state."""
54
+
55
+ type: str
56
+ """One of connected, reconnected, reconnecting, banner, session_expiring, terminated, local_error."""
57
+ url: str = ""
58
+ """Public address, set for connected and reconnected."""
59
+ message: str = ""
60
+ """Human-readable text, set for banner and terminated."""
61
+ reason: str = ""
62
+ """Machine-readable cause, set for terminated."""
63
+ error: BaseException | None = None
64
+ """The cause, set for reconnecting and local_error."""
65
+ retry_in: float = 0.0
66
+ """Seconds before the next attempt, set for reconnecting."""
67
+ expires_in: float = 0.0
68
+ """Seconds left, set for session_expiring."""
69
+
70
+
71
+ @dataclasses.dataclass
72
+ class Options:
73
+ """Tunnel settings. Only protocol is required."""
74
+
75
+ protocol: str
76
+ """ "http" or "tcp"."""
77
+ api_key: str = ""
78
+ """API key with the tunnels:connect scope. Defaults to the TUNA_API_KEY environment variable."""
79
+ location: str = ""
80
+ """Only for names and ports reserved in the legacy "ru" or "nl" zones. Empty lets the server pick."""
81
+ subdomain: str = ""
82
+ """Reserved subdomain for HTTP tunnels."""
83
+ domain: str = ""
84
+ """Custom domain for HTTP tunnels."""
85
+ port: str = ""
86
+ """Reserved TCP port or its alias."""
87
+ proxy_protocol: int = 0
88
+ """PROXY protocol header version (1 or 2) for TCP tunnels."""
89
+ cidr_allow: list[str] = dataclasses.field(default_factory=list)
90
+ """Client CIDRs allowed to reach a TCP tunnel."""
91
+ cidr_deny: list[str] = dataclasses.field(default_factory=list)
92
+ """Client CIDRs rejected by a TCP tunnel."""
93
+ server_url: str = ""
94
+ """The tuna.am API address. Defaults to DEFAULT_SERVER_URL."""
95
+ ssl_context: ssl.SSLContext | None = None
96
+ """TLS settings for the API. None means the system roots."""
97
+ client_name: str = ""
98
+ """Client name reported to the server. Defaults to "tuna-sdk-python/<VERSION>"."""
99
+ connect_timeout: float | None = None
100
+ """Seconds to wait for the tunnel to come up for the first time. None means no limit."""
101
+ on_event: Callable[[Event], None] | None = None
102
+ """Receives tunnel events on the event loop. Calls never overlap; exceptions are ignored."""
103
+
104
+
105
+ class TerminatedError(Exception):
106
+ """The server closed the tunnel for good."""
107
+
108
+ reason: str
109
+ """Machine-readable cause, e.g. "deleted" or "session_limit"."""
110
+
111
+ def __init__(self, reason: str):
112
+ super().__init__(reason)
113
+ self.reason = reason
114
+
115
+ def __str__(self) -> str:
116
+ return "tuna: " + self.message
117
+
118
+ @property
119
+ def message(self) -> str:
120
+ """Human-readable cause."""
121
+ return _TERMINATE_MESSAGES.get(self.reason, f"tunnel terminated by server ({self.reason})")
122
+
123
+
124
+ _TERMINATE_MESSAGES = {
125
+ "deleted": "tunnel was deleted",
126
+ "suspended": "tunnel was suspended",
127
+ "session_limit": "session time limit reached",
128
+ "session_ended": "client session ended",
129
+ "reconnect": "tunnel was taken over by another connection",
130
+ }
131
+
132
+
133
+ class KeepAliveTimeoutError(ConnectionError):
134
+ """The node stopped answering keepalive requests."""
135
+
136
+ def __init__(self) -> None:
137
+ super().__init__("tuna: keepalive timeout")
138
+
139
+
140
+ class ClosedError(Exception):
141
+ """The tunnel is closed."""
142
+
143
+ def __init__(self) -> None:
144
+ super().__init__("tuna: tunnel is closed")
145
+
146
+
147
+ def is_permanent(err: BaseException | None) -> bool:
148
+ """Reports whether retrying after err is pointless."""
149
+ return isinstance(err, TerminatedError) or (isinstance(err, ServerError) and err.permanent())
150
+
151
+
152
+ def retry_delay(backoff: float, err: BaseException | None) -> float:
153
+ wait = min(MAX_BACKOFF, MIN_BACKOFF + random.uniform(0, backoff))
154
+ if isinstance(err, ServerError) and err.retry_after > wait:
155
+ wait = err.retry_after
156
+ return wait
157
+
158
+
159
+ def public_url(cr: dict[str, Any], protocol: str) -> str:
160
+ if cr.get("public_url"):
161
+ return str(cr["public_url"])
162
+ if protocol == "tcp":
163
+ return f"tcp://{cr.get('domain_name', '')}:{cr.get('endpoint_port', 0)}"
164
+ return "https://" + str(cr.get("domain_name", ""))
165
+
166
+
167
+ def split_host_port(addr: str) -> tuple[str, int]:
168
+ host, sep, port = addr.rpartition(":")
169
+ if not sep or not port.isdigit():
170
+ raise ValueError(f'tuna: address "{addr}" is not host:port')
171
+ return host.removeprefix("[").removesuffix("]"), int(port)
172
+
173
+
174
+ def parse_event(line: str) -> dict[str, Any] | None:
175
+ try:
176
+ ev = json.loads(line)
177
+ except ValueError:
178
+ return None
179
+ return ev if isinstance(ev, dict) else None
180
+
181
+
182
+ def _os_arch() -> tuple[str, str]:
183
+ goos = {"win32": "windows", "cygwin": "windows"}.get(sys.platform, sys.platform)
184
+ goos = "linux" if goos.startswith("linux") else goos.rstrip("0123456789")
185
+ m = platform.machine().lower()
186
+ arch = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64", "i686": "386", "i386": "386"}
187
+ return goos, arch.get(m, m)
188
+
189
+
190
+ def _connection_error(exc: BaseException | None) -> BaseException:
191
+ if isinstance(exc, asyncssh.ConnectionLost) and "keepalive" in exc.reason:
192
+ return KeepAliveTimeoutError()
193
+ return ConnectionError(f"tuna: connection to node lost: {exc or 'closed'}")
194
+
195
+
196
+ class _Session:
197
+ def __init__(self, loop: asyncio.AbstractEventLoop):
198
+ self.dead: asyncio.Future[BaseException] = loop.create_future()
199
+ self.conn: asyncssh.SSHClientConnection | None = None
200
+ self.events: asyncio.Task[None] | None = None
201
+ self.active = 0
202
+ self.closing = False
203
+
204
+ def fail(self, err: BaseException) -> None:
205
+ if not self.dead.done():
206
+ self.dead.set_result(err)
207
+ if self.conn is not None:
208
+ self.conn.close()
209
+
210
+ def release(self) -> None:
211
+ self.active -= 1
212
+ if self.closing and self.active == 0:
213
+ self.fail(ClosedError())
214
+
215
+ def lost(self, exc: BaseException | None) -> None:
216
+ err = _connection_error(exc)
217
+ if self.events is None or self.events.done():
218
+ self.fail(err)
219
+ return
220
+
221
+ async def drain() -> None:
222
+ assert self.events is not None
223
+ await asyncio.wait([self.events], timeout=EVENTS_DRAIN_TIMEOUT)
224
+ self.fail(err)
225
+
226
+ spawn(drain())
227
+
228
+
229
+ class _Client(asyncssh.SSHClient):
230
+ def __init__(self, session: _Session):
231
+ self._session = session
232
+
233
+ def connection_lost(self, exc: Exception | None) -> None:
234
+ self._session.lost(exc)
235
+
236
+
237
+ class Tunnel:
238
+ """A tunnel that receives connections arriving at its public address.
239
+
240
+ It survives reconnects; accept fails only after close or a permanent error.
241
+ Iterating over it with ``async for`` yields connections until it is closed.
242
+ """
243
+
244
+ def __init__(self, o: Options, forwards_to: str = ""):
245
+ o = dataclasses.replace(o, cidr_allow=list(o.cidr_allow), cidr_deny=list(o.cidr_deny))
246
+ if not o.api_key:
247
+ o.api_key = os.environ.get("TUNA_API_KEY", "")
248
+ if not o.api_key:
249
+ raise ValueError("tuna: API key is required: set Options.api_key or TUNA_API_KEY")
250
+ if o.protocol not in ("http", "tcp"):
251
+ raise ValueError(f'tuna: unsupported protocol "{o.protocol}"')
252
+ if not o.server_url:
253
+ o.server_url = DEFAULT_SERVER_URL
254
+ check_server_url(o.server_url)
255
+ if not o.client_name:
256
+ o.client_name = "tuna-sdk-python/" + VERSION
257
+ if any(unicodedata.category(c) == "Cc" for c in o.client_name):
258
+ raise ValueError("tuna: client_name must not contain control characters")
259
+ self._o = o
260
+ self._forwards_to = forwards_to
261
+ self._url = ""
262
+ self._loop = asyncio.get_running_loop()
263
+ self._conns: asyncio.Queue[Stream | None] = asyncio.Queue()
264
+ self._ready = asyncio.Event()
265
+ self._done: asyncio.Future[BaseException] = self._loop.create_future()
266
+ self._closed = False
267
+ self._session: _Session | None = None
268
+ self._last_err: BaseException | None = None
269
+ self._ever_up = False
270
+ self._session_id = ""
271
+ self._banner_shown = False
272
+ self._task = self._loop.create_task(self._main())
273
+
274
+ @property
275
+ def url(self) -> str:
276
+ """The current public address, e.g. https://name.tuna.am or tcp://ru.tuna.am:40000."""
277
+ return self._url
278
+
279
+ async def accept(self) -> Stream:
280
+ """Waits for the next connection to the public address.
281
+
282
+ Raises ClosedError after close, or the permanent error that ended the tunnel.
283
+ """
284
+ item = await self._conns.get()
285
+ if item is None:
286
+ self._conns.put_nowait(None)
287
+ err = self._done.result() if self._done.done() else ClosedError()
288
+ raise err
289
+ return item
290
+
291
+ async def __aiter__(self) -> AsyncIterator[Stream]:
292
+ while True:
293
+ try:
294
+ yield await self.accept()
295
+ except ClosedError:
296
+ return
297
+
298
+ def close(self) -> None:
299
+ """Stops accepting connections and reconnecting.
300
+
301
+ Connections accepted earlier keep working: the tunnel stays connected to
302
+ the node until the last of them is closed. Does not wait.
303
+ """
304
+ if self._closed:
305
+ return
306
+ self._closed = True
307
+ self._drain()
308
+ s = self._session
309
+ if s is None:
310
+ self._task.cancel()
311
+ return
312
+ s.closing = True
313
+ if s.active == 0:
314
+ s.fail(ClosedError())
315
+
316
+ def abort(self) -> None:
317
+ """Closes the tunnel together with every accepted connection."""
318
+ self._closed = True
319
+ self._drain()
320
+ self._task.cancel()
321
+
322
+ async def wait_closed(self) -> None:
323
+ """Waits until the tunnel is closed or ends with an error."""
324
+ await asyncio.shield(self._done)
325
+
326
+ async def __aenter__(self) -> Tunnel:
327
+ return self
328
+
329
+ async def __aexit__(self, *exc: object) -> None:
330
+ self.close()
331
+
332
+ def _emit(self, e: Event) -> None:
333
+ if self._o.on_event is None:
334
+ return
335
+ with contextlib.suppress(Exception):
336
+ self._o.on_event(e)
337
+
338
+ def _finish(self, err: BaseException) -> None:
339
+ if not self._done.done():
340
+ self._done.set_result(err)
341
+ self._drain()
342
+
343
+ def _drain(self) -> None:
344
+ while not self._conns.empty():
345
+ item = self._conns.get_nowait()
346
+ if item is not None:
347
+ item[1].close()
348
+ self._conns.put_nowait(None)
349
+
350
+ async def _start(self) -> None:
351
+ waiter = asyncio.ensure_future(self._ready.wait())
352
+ try:
353
+ await asyncio.wait(
354
+ [waiter, self._done], timeout=self._o.connect_timeout, return_when=asyncio.FIRST_COMPLETED
355
+ )
356
+ except BaseException:
357
+ self.abort()
358
+ raise
359
+ finally:
360
+ waiter.cancel()
361
+ if self._ready.is_set():
362
+ return
363
+ if self._done.done():
364
+ raise self._done.result()
365
+ self.abort()
366
+ with contextlib.suppress(asyncio.CancelledError):
367
+ await self._task
368
+ msg = f"tuna: tunnel did not come up within {self._o.connect_timeout:g}s"
369
+ if self._last_err is not None:
370
+ msg += f" (last attempt: {self._last_err})"
371
+ raise TimeoutError(msg)
372
+
373
+ async def _main(self) -> None:
374
+ try:
375
+ await self._run()
376
+ except asyncio.CancelledError:
377
+ self._finish(ClosedError())
378
+ except BaseException as e:
379
+ self._finish(e)
380
+
381
+ async def _run(self) -> None:
382
+ backoff = MIN_BACKOFF
383
+ while True:
384
+ connected, err = await self._run_session()
385
+ if self._closed:
386
+ self._finish(ClosedError())
387
+ return
388
+ if not self._ever_up and isinstance(err, ServerError):
389
+ err.before_first_connect = True
390
+ self._last_err = err
391
+ if is_permanent(err):
392
+ if isinstance(err, TerminatedError):
393
+ self._emit(Event("terminated", reason=err.reason, message=err.message))
394
+ self._finish(err)
395
+ return
396
+ if connected:
397
+ backoff = MIN_BACKOFF
398
+ wait = retry_delay(backoff, err)
399
+ self._emit(Event("reconnecting", error=err, retry_in=wait))
400
+ await asyncio.sleep(wait)
401
+ backoff = min(backoff * 2, MAX_BACKOFF)
402
+
403
+ def _request(self) -> dict[str, Any]:
404
+ o = self._o
405
+ goos, arch = _os_arch()
406
+ body: dict[str, Any] = {
407
+ "client_version": CLIENT_VERSION,
408
+ "client_name": o.client_name,
409
+ "sdk_version": VERSION,
410
+ "forwards_to": self._forwards_to,
411
+ "protocol": o.protocol,
412
+ "location": o.location,
413
+ "subdomain": o.subdomain,
414
+ "domain": o.domain,
415
+ "token": o.api_key,
416
+ "os": goos,
417
+ "arch": arch,
418
+ "port_or_alias": o.port,
419
+ "tunnel_session_id": self._session_id,
420
+ "proxy_protocol": o.proxy_protocol,
421
+ }
422
+ if o.cidr_allow:
423
+ body["cidr_allow_list"] = o.cidr_allow
424
+ if o.cidr_deny:
425
+ body["cidr_deny_list"] = o.cidr_deny
426
+ return body
427
+
428
+ async def _run_session(self) -> tuple[bool, BaseException]:
429
+ s = _Session(self._loop)
430
+ try:
431
+ return await self._session_body(s)
432
+ except asyncio.CancelledError:
433
+ raise
434
+ except Exception as e:
435
+ return self._ever_up and s is self._session, e
436
+ finally:
437
+ self._session = None
438
+ if s.conn is not None:
439
+ s.conn.close()
440
+ if s.events is not None:
441
+ s.events.cancel()
442
+
443
+ async def _session_body(self, s: _Session) -> tuple[bool, BaseException]:
444
+ o = self._o
445
+ cr = await post_json(o.server_url, "/v1/connect", o.client_name, self._request(), o.ssl_context)
446
+ self._session_id = str(cr.get("tunnel_session_id") or "")
447
+ banner = str(cr.get("banner") or "")
448
+ if banner and not self._banner_shown:
449
+ self._banner_shown = True
450
+ self._emit(Event("banner", message=banner))
451
+
452
+ try:
453
+ keys = [asyncssh.import_public_key(str(hk.get("key", ""))) for hk in cr.get("host_keys") or []]
454
+ except (asyncssh.KeyImportError, ValueError) as e:
455
+ raise ValueError(f"tuna: parse host key: {e}") from e
456
+ host, port = split_host_port(str(cr.get("address", "")))
457
+ s.conn = await asyncio.wait_for(
458
+ asyncssh.connect(
459
+ host,
460
+ port,
461
+ username=SSH_USER,
462
+ password=str(cr.get("token", "")),
463
+ known_hosts=(keys, [], []),
464
+ client_factory=lambda: _Client(s),
465
+ client_keys=None,
466
+ agent_path=None,
467
+ config=None,
468
+ gss_host=None,
469
+ preferred_auth="password",
470
+ connect_timeout=DIAL_TIMEOUT,
471
+ keepalive_interval=KEEPALIVE_INTERVAL,
472
+ keepalive_count_max=KEEPALIVE_COUNT_MAX,
473
+ ),
474
+ DIAL_TIMEOUT + 1,
475
+ )
476
+
477
+ try:
478
+ await s.conn.start_server(self._handler_factory(s), "127.0.0.1", 0)
479
+ except Exception as e:
480
+ if s.dead.done():
481
+ return False, s.dead.result()
482
+ raise RuntimeError(f"tuna: remote forward: {e}") from e
483
+
484
+ self._session = s
485
+ s.events = self._loop.create_task(self._read_events(s))
486
+ self._url = public_url(cr, o.protocol)
487
+ if self._ever_up:
488
+ self._emit(Event("reconnected", url=self._url))
489
+ else:
490
+ self._ever_up = True
491
+ self._emit(Event("connected", url=self._url))
492
+ self._ready.set()
493
+ if self._closed:
494
+ s.closing = True
495
+ if s.active == 0:
496
+ s.fail(ClosedError())
497
+ return True, await s.dead
498
+
499
+ def _handler_factory(self, s: _Session) -> Callable[[str, int], Callable[..., None]]:
500
+ def reject(reader: asyncssh.SSHReader[bytes], writer: asyncssh.SSHWriter[bytes]) -> None:
501
+ writer.close()
502
+
503
+ def handler(reader: asyncssh.SSHReader[bytes], writer: asyncssh.SSHWriter[bytes]) -> None:
504
+ s.active += 1
505
+ spawn(self._track(s, writer))
506
+ if s.dead.done() or self._closed:
507
+ writer.close()
508
+ return
509
+ self._conns.put_nowait((reader, writer))
510
+
511
+ def factory(orig_host: str, orig_port: int) -> Callable[..., None]:
512
+ return reject if s.closing else handler
513
+
514
+ return factory
515
+
516
+ async def _track(self, s: _Session, writer: asyncssh.SSHWriter[bytes]) -> None:
517
+ try:
518
+ await writer.channel.wait_closed()
519
+ finally:
520
+ s.release()
521
+
522
+ async def _read_events(self, s: _Session) -> None:
523
+ assert s.conn is not None
524
+ try:
525
+ _, stdout, _ = await s.conn.open_session(command=EVENTS_COMMAND)
526
+ async for line in stdout:
527
+ ev = parse_event(line)
528
+ if ev is None:
529
+ continue
530
+ if ev.get("type") == "terminate":
531
+ s.fail(TerminatedError(str(ev.get("reason") or "")))
532
+ return
533
+ if ev.get("type") == "session_expiring":
534
+ with contextlib.suppress(TypeError, ValueError):
535
+ self._emit(Event("session_expiring", expires_in=float(ev.get("expires_in") or 0)))
536
+ except (asyncssh.Error, OSError):
537
+ return
538
+
539
+ async def _pipe(self, reader: asyncssh.SSHReader[bytes], writer: asyncssh.SSHWriter[bytes], addr: str) -> None:
540
+ try:
541
+ if addr.startswith("unix://"):
542
+ conn = asyncio.open_unix_connection(addr.removeprefix("unix://"))
543
+ else:
544
+ conn = asyncio.open_connection(*split_host_port(addr))
545
+ lr, lw = await asyncio.wait_for(conn, DIAL_TIMEOUT)
546
+ except (OSError, TimeoutError, ValueError) as e:
547
+ writer.close()
548
+ self._emit(Event("local_error", error=e))
549
+ return
550
+ await pipe(reader, writer, lr, lw)
551
+
552
+
553
+ async def _copy(src: Any, dst: Any) -> None:
554
+ with contextlib.suppress(Exception):
555
+ while data := await src.read(32768):
556
+ dst.write(data)
557
+ await dst.drain()
558
+
559
+
560
+ async def pipe(
561
+ reader: asyncssh.SSHReader[bytes],
562
+ writer: asyncssh.SSHWriter[bytes],
563
+ local_reader: asyncio.StreamReader,
564
+ local_writer: asyncio.StreamWriter,
565
+ ) -> None:
566
+ tasks = [asyncio.ensure_future(_copy(reader, local_writer)), asyncio.ensure_future(_copy(local_reader, writer))]
567
+ try:
568
+ await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
569
+ finally:
570
+ for t in tasks:
571
+ t.cancel()
572
+ writer.close()
573
+ local_writer.close()
574
+
575
+
576
+ class _Listen:
577
+ def __init__(self, options: Options):
578
+ self._options = options
579
+ self._tunnel: Tunnel | None = None
580
+
581
+ def __await__(self) -> Generator[Any, None, Tunnel]:
582
+ return self._open().__await__()
583
+
584
+ async def _open(self) -> Tunnel:
585
+ t = Tunnel(self._options)
586
+ await t._start()
587
+ return t
588
+
589
+ async def __aenter__(self) -> Tunnel:
590
+ self._tunnel = await self._open()
591
+ return self._tunnel
592
+
593
+ async def __aexit__(self, *exc: object) -> None:
594
+ if self._tunnel is not None:
595
+ self._tunnel.close()
596
+
597
+
598
+ def listen(options: Options) -> _Listen:
599
+ """Connects the tunnel and returns it once it is up.
600
+
601
+ Use as ``tunnel = await listen(...)`` or ``async with listen(...) as tunnel``;
602
+ leaving the block closes the tunnel like Tunnel.close. Raises the permanent
603
+ error if one occurs first, or TimeoutError after Options.connect_timeout.
604
+ """
605
+ return _Listen(options)
606
+
607
+
608
+ async def forward(options: Options, addr: str) -> None:
609
+ """Proxies tunnel connections to addr ("host:port" or "unix:///path.sock").
610
+
611
+ Runs until a permanent error, which is raised, or until the task is cancelled,
612
+ which closes the tunnel with every connection.
613
+ """
614
+ t = Tunnel(options, addr)
615
+ try:
616
+ await t._start()
617
+ while True:
618
+ reader, writer = await t.accept()
619
+ spawn(t._pipe(reader, writer, addr))
620
+ finally:
621
+ t.abort()
tuna_sdk/py.typed ADDED
File without changes
tuna_sdk/sync.py ADDED
@@ -0,0 +1,108 @@
1
+ """Blocking API for code without asyncio.
2
+
3
+ The tunnel runs on an event loop in a background thread, so it also works
4
+ where a loop is already running, such as Jupyter. Options.on_event is called
5
+ from that thread.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import socket
12
+ import threading
13
+ from collections.abc import Coroutine, Iterator
14
+ from typing import Any, TypeVar
15
+
16
+ from . import _tunnel
17
+ from ._tunnel import ClosedError, Options
18
+
19
+ T = TypeVar("T")
20
+
21
+ _loop: asyncio.AbstractEventLoop | None = None
22
+ _lock = threading.Lock()
23
+
24
+
25
+ def _background_loop() -> asyncio.AbstractEventLoop:
26
+ global _loop
27
+ with _lock:
28
+ if _loop is None:
29
+ _loop = asyncio.new_event_loop()
30
+ threading.Thread(target=_loop.run_forever, name="tuna-sdk", daemon=True).start()
31
+ return _loop
32
+
33
+
34
+ def _wait(coro: Coroutine[Any, Any, T]) -> T:
35
+ fut = asyncio.run_coroutine_threadsafe(coro, _background_loop())
36
+ try:
37
+ return fut.result()
38
+ except BaseException:
39
+ fut.cancel()
40
+ raise
41
+
42
+
43
+ def forward(options: Options, addr: str) -> None:
44
+ """Proxies tunnel connections to addr ("host:port" or "unix:///path.sock").
45
+
46
+ Blocks until a permanent error, which is raised. KeyboardInterrupt closes
47
+ the tunnel and propagates.
48
+ """
49
+ _wait(_tunnel.forward(options, addr))
50
+
51
+
52
+ class Tunnel:
53
+ """A blocking tunnel; accept returns connected sockets."""
54
+
55
+ def __init__(self, tunnel: _tunnel.Tunnel):
56
+ self._tunnel = tunnel
57
+
58
+ @property
59
+ def url(self) -> str:
60
+ """The current public address."""
61
+ return self._tunnel.url
62
+
63
+ def accept(self) -> socket.socket:
64
+ """Waits for the next connection and returns it as a blocking socket.
65
+
66
+ Raises ClosedError after close, or the permanent error that ended the tunnel.
67
+ """
68
+ return _wait(self._accept())
69
+
70
+ async def _accept(self) -> socket.socket:
71
+ reader, writer = await self._tunnel.accept()
72
+ app, side = socket.socketpair()
73
+ local_reader, local_writer = await asyncio.open_connection(sock=side)
74
+ _tunnel.spawn(_tunnel.pipe(reader, writer, local_reader, local_writer))
75
+ return app
76
+
77
+ def __iter__(self) -> Iterator[socket.socket]:
78
+ while True:
79
+ try:
80
+ yield self.accept()
81
+ except ClosedError:
82
+ return
83
+
84
+ def close(self) -> None:
85
+ """Stops accepting and reconnecting; accepted connections keep working."""
86
+ _background_loop().call_soon_threadsafe(self._tunnel.close)
87
+
88
+ def abort(self) -> None:
89
+ """Closes the tunnel together with every accepted connection."""
90
+ _background_loop().call_soon_threadsafe(self._tunnel.abort)
91
+
92
+ def __enter__(self) -> Tunnel:
93
+ return self
94
+
95
+ def __exit__(self, *exc: object) -> None:
96
+ self.close()
97
+
98
+
99
+ def listen(options: Options) -> Tunnel:
100
+ """Connects the tunnel and returns it once it is up.
101
+
102
+ Raises the permanent error if one occurs first, or TimeoutError after
103
+ Options.connect_timeout.
104
+ """
105
+ return Tunnel(_wait(_tunnel.listen(options)._open()))
106
+
107
+
108
+ __all__ = ["Tunnel", "forward", "listen"]
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.5
2
+ Name: tuna-sdk
3
+ Version: 0.1.0
4
+ Summary: Open tuna.am tunnels from Python code
5
+ Project-URL: Homepage, https://tuna.am
6
+ Project-URL: Source, https://github.com/yuccastream/tuna-sdk-python
7
+ Author-email: "tuna.am authors" <info@tuna.am>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: localhost,ssh,tuna,tunnel,webhook
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Internet
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: asyncssh<3,>=2.24.1
19
+ Description-Content-Type: text/markdown
20
+
21
+ # tuna-sdk-python
22
+
23
+ [![PyPI](https://img.shields.io/pypi/v/tuna-sdk.svg)](https://pypi.org/project/tuna-sdk/)
24
+
25
+ Open [tuna.am](https://tuna.am) tunnels straight from Python code: expose a
26
+ local HTTP or TCP service at a public address without installing the `tuna`
27
+ CLI.
28
+
29
+ - Two ways in: `listen` hands you each incoming connection as a
30
+ `(reader, writer)` stream pair, `forward` proxies connections to a local
31
+ address.
32
+ - asyncio first, with a blocking `tuna_sdk.sync` API that also works in
33
+ Jupyter.
34
+ - Survives network failures: reconnects with backoff and keeps the same
35
+ public address.
36
+ - Small: the only dependency is [asyncssh](https://pypi.org/project/asyncssh/).
37
+ - Typed: ships `py.typed`.
38
+
39
+ The API is not stable yet: it may change before v1.
40
+
41
+ ## Install
42
+
43
+ ```shell
44
+ pip install tuna-sdk
45
+ ```
46
+
47
+ The module name is `tuna_sdk`. Requires Python 3.10 or later.
48
+
49
+ ## Authentication
50
+
51
+ Create an API key with the `tunnels:connect` scope at
52
+ [my.tuna.am](https://my.tuna.am) and pass it in `Options.api_key` or the
53
+ `TUNA_API_KEY` environment variable.
54
+
55
+ ## Forward to a local service
56
+
57
+ ```python
58
+ import asyncio
59
+ import tuna_sdk
60
+
61
+
62
+ def on_event(e: tuna_sdk.Event) -> None:
63
+ if e.type == "connected":
64
+ print("forwarding", e.url, "-> 127.0.0.1:8080")
65
+
66
+
67
+ asyncio.run(tuna_sdk.forward(tuna_sdk.Options(protocol="http", on_event=on_event), "127.0.0.1:8080"))
68
+ ```
69
+
70
+ The local address is `host:port` or `unix:///path/to.sock`. `forward` runs
71
+ until the task is cancelled or the tunnel ends for good.
72
+
73
+ Without asyncio:
74
+
75
+ ```python
76
+ tuna_sdk.sync.forward(tuna_sdk.Options(protocol="tcp", port="my-db"), "127.0.0.1:5432")
77
+ ```
78
+
79
+ ## Accept connections yourself
80
+
81
+ ```python
82
+ async def main() -> None:
83
+ async with tuna_sdk.listen(tuna_sdk.Options(protocol="tcp")) as tunnel:
84
+ print("public URL:", tunnel.url)
85
+ async for reader, writer in tunnel:
86
+ asyncio.ensure_future(handle(reader, writer))
87
+ ```
88
+
89
+ `reader` and `writer` are asyncssh `SSHReader` and `SSHWriter` objects with
90
+ the same methods as asyncio streams (`read`, `readline`, `write`, `drain`,
91
+ `close`). `await tunnel.accept()` returns the next pair.
92
+
93
+ `tuna_sdk.sync.listen` returns a tunnel whose `accept()` gives a regular
94
+ blocking `socket.socket`, so it plugs into `socketserver` and similar code:
95
+
96
+ ```python
97
+ with tuna_sdk.sync.listen(tuna_sdk.Options(protocol="http")) as tunnel:
98
+ print("public URL:", tunnel.url)
99
+ for sock in tunnel:
100
+ handle(sock)
101
+ ```
102
+
103
+ Leaving the `with` block, or calling `close()`, stops accepting and
104
+ reconnecting; connections accepted earlier keep working and the tunnel stays
105
+ connected until the last of them is closed. `abort()` cuts them off too.
106
+
107
+ [`examples/runner.py`](examples/runner.py) is a complete command-line client
108
+ built on the SDK.
109
+
110
+ ## Options
111
+
112
+ | Field | Meaning |
113
+ |---|---|
114
+ | `protocol` | `http` or `tcp`, required |
115
+ | `api_key` | API key, defaults to `$TUNA_API_KEY` |
116
+ | `subdomain`, `domain` | reserved subdomain or custom domain for HTTP |
117
+ | `port` | reserved TCP port or its alias |
118
+ | `proxy_protocol` | PROXY protocol header version for TCP: `1` or `2` |
119
+ | `cidr_allow`, `cidr_deny` | client CIDRs filtered by the tuna.am node, TCP only |
120
+ | `location` | only for names and ports reserved in the legacy `ru` or `nl` zones; empty lets the server pick |
121
+ | `on_event` | callback for tunnel events |
122
+ | `connect_timeout` | seconds to wait for the first connection; `None` means no limit |
123
+ | `server_url`, `ssl_context`, `client_name` | API address, TLS settings for it, client name reported to the server |
124
+
125
+ ## Events and errors
126
+
127
+ `on_event` receives an `Event` with `type` one of `connected`,
128
+ `reconnecting`, `reconnected`, `banner`, `session_expiring`, `terminated` and
129
+ `local_error`. Calls never overlap and run on the event loop (for
130
+ `tuna_sdk.sync`, on its background thread), so keep the callback short.
131
+
132
+ Network failures and temporary server errors are retried: the pause grows from
133
+ 1 to 15 seconds with random jitter, and `Retry-After` is respected. The tunnel
134
+ ends with an exception when retrying is pointless; check it with
135
+ `is_permanent`:
136
+
137
+ - `ServerError` — the API rejected the request: bad or revoked key, missing
138
+ scope, unknown reserved name, unpaid plan. Has `status`, `code`, `message`
139
+ and `request_id`;
140
+ - `TerminatedError` — the server closed the tunnel: it was deleted,
141
+ suspended or hit the session time limit. Has `reason`.
142
+
143
+ A connection the node stopped answering is reported in a `reconnecting` event
144
+ with `KeepAliveTimeoutError`. `accept` raises `ClosedError` after `close`.
145
+
146
+ ## Behaviour worth knowing
147
+
148
+ - When either side of a forwarded connection closes, the connection is closed
149
+ in both directions.
150
+ - The `Host` header and the PROXY protocol header reach your service as sent.
151
+ - The API client is `urllib` and honours `HTTPS_PROXY`. Connections to
152
+ tuna.am nodes are plain SSH over TCP and do not use the proxy.
153
+ - Use `ssl_context` for a private CA.
154
+
155
+ ## Contributing
156
+
157
+ This repository is a read-only mirror of the SDK directory in the tuna.am
158
+ monorepo. Issues and pull requests are welcome here: accepted changes are
159
+ applied upstream and come back with the next release.
160
+
161
+ ## License
162
+
163
+ [MIT](LICENSE). asyncssh is a separate package under EPL-2.0 or
164
+ GPL-2.0-or-later.
@@ -0,0 +1,9 @@
1
+ tuna_sdk/__init__.py,sha256=9-y2uSNc8qsadP7WASmp0qcrqt8Z-qLq2AwvAsSTZlo,996
2
+ tuna_sdk/_api.py,sha256=luEOJY7cDV7rBJ2nY8g_cRV235t-qfqVQxfq7Zk4WFo,4889
3
+ tuna_sdk/_tunnel.py,sha256=_C5OEdvZgdnuWNsOk98087toTW47EBLg0ttdTc7uXWc,21497
4
+ tuna_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ tuna_sdk/sync.py,sha256=080WGIGnABTcKRHUaMHJC4UJ-M_NtZblsmxP5dgiQEw,3128
6
+ tuna_sdk-0.1.0.dist-info/METADATA,sha256=FK9R_TxTpA5VvrLzHxyAFlI2fdSAa7FkgesChEX9QbI,5883
7
+ tuna_sdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ tuna_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=wDgR8h_fA_gJw2PvaJgpqIEQ69X-319FsYR7Fx5Vjao,1072
9
+ tuna_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tuna.am authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.