neruton 0.2.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.
- neruton/__init__.py +107 -0
- neruton/__main__.py +10 -0
- neruton/_version.py +11 -0
- neruton/cli.py +258 -0
- neruton/client.py +1017 -0
- neruton/config.py +188 -0
- neruton/errors.py +64 -0
- neruton/forwarder.py +810 -0
- neruton/protocol.py +358 -0
- neruton/py.typed +0 -0
- neruton/ui.py +127 -0
- neruton/yamux.py +974 -0
- neruton-0.2.0.dist-info/METADATA +136 -0
- neruton-0.2.0.dist-info/RECORD +18 -0
- neruton-0.2.0.dist-info/WHEEL +5 -0
- neruton-0.2.0.dist-info/entry_points.txt +2 -0
- neruton-0.2.0.dist-info/licenses/LICENSE +21 -0
- neruton-0.2.0.dist-info/top_level.txt +1 -0
neruton/client.py
ADDED
|
@@ -0,0 +1,1017 @@
|
|
|
1
|
+
"""Async & Sync Neruton tunnel client API over WebSocket + Yamux."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import concurrent.futures
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Callable, Dict, Generator, Optional, Set, Tuple, Union
|
|
11
|
+
|
|
12
|
+
import websockets
|
|
13
|
+
import websockets.exceptions
|
|
14
|
+
|
|
15
|
+
from ._version import __version__
|
|
16
|
+
from .config import resolve_server_and_token
|
|
17
|
+
from .errors import (
|
|
18
|
+
AuthError,
|
|
19
|
+
NerutonError,
|
|
20
|
+
RegistrationError,
|
|
21
|
+
TunnelConnectionError,
|
|
22
|
+
)
|
|
23
|
+
from .forwarder import (
|
|
24
|
+
RequestCallback,
|
|
25
|
+
TargetConfig,
|
|
26
|
+
build_ssl_context,
|
|
27
|
+
handle_yamux_stream,
|
|
28
|
+
)
|
|
29
|
+
from .protocol import (
|
|
30
|
+
RegisterRequest,
|
|
31
|
+
RegisterResponse,
|
|
32
|
+
build_tunnel_ws_url,
|
|
33
|
+
format_401_error,
|
|
34
|
+
is_non_retryable_rejection,
|
|
35
|
+
normalize_target_url,
|
|
36
|
+
validate_prefix,
|
|
37
|
+
)
|
|
38
|
+
from .yamux import GoAwayCode, Mode, WsByteTransport, YamuxSession
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
from websockets.asyncio.client import connect as _ws_connect_modern
|
|
42
|
+
|
|
43
|
+
_HAS_MODERN_WS = True
|
|
44
|
+
except ImportError: # pragma: no cover - websockets 12.x fallback
|
|
45
|
+
_ws_connect_modern = None # type: ignore[assignment]
|
|
46
|
+
_HAS_MODERN_WS = False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
ConnectCallback = Callable[[RegisterResponse], None]
|
|
50
|
+
DisconnectCallback = Callable[[str], None]
|
|
51
|
+
ReconnectCallback = Callable[[int, float, str], None]
|
|
52
|
+
ErrorCallback = Callable[[Exception], None]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _extract_http_status_and_body(exc: BaseException) -> Tuple[Optional[int], Optional[bytes]]:
|
|
56
|
+
# websockets >= 13: InvalidStatus(response=Response(status_code=..., body=...))
|
|
57
|
+
response = getattr(exc, "response", None)
|
|
58
|
+
if response is not None:
|
|
59
|
+
status_code = getattr(response, "status_code", None)
|
|
60
|
+
body = getattr(response, "body", None)
|
|
61
|
+
if isinstance(status_code, int):
|
|
62
|
+
return status_code, body if isinstance(body, (bytes, bytearray)) else None
|
|
63
|
+
# websockets 12.x legacy: InvalidStatusCode(status_code=...)
|
|
64
|
+
status_code = getattr(exc, "status_code", None)
|
|
65
|
+
if isinstance(status_code, int):
|
|
66
|
+
return status_code, None
|
|
67
|
+
return None, None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def _open_websocket(
|
|
71
|
+
ws_url: str,
|
|
72
|
+
*,
|
|
73
|
+
token: Optional[str],
|
|
74
|
+
no_tls_verify: bool,
|
|
75
|
+
open_timeout: float = 10.0,
|
|
76
|
+
ping_interval: Optional[float] = 20.0,
|
|
77
|
+
ping_timeout: Optional[float] = 20.0,
|
|
78
|
+
) -> Any:
|
|
79
|
+
headers = {}
|
|
80
|
+
if token:
|
|
81
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
82
|
+
|
|
83
|
+
kwargs: Dict[str, Any] = {
|
|
84
|
+
"compression": None,
|
|
85
|
+
"max_size": None,
|
|
86
|
+
"open_timeout": open_timeout,
|
|
87
|
+
"ping_interval": ping_interval,
|
|
88
|
+
"ping_timeout": ping_timeout,
|
|
89
|
+
"close_timeout": 5.0,
|
|
90
|
+
}
|
|
91
|
+
if ws_url.startswith("wss://"):
|
|
92
|
+
kwargs["ssl"] = build_ssl_context(no_tls_verify=no_tls_verify)
|
|
93
|
+
|
|
94
|
+
try:
|
|
95
|
+
if _HAS_MODERN_WS and _ws_connect_modern is not None:
|
|
96
|
+
if headers:
|
|
97
|
+
kwargs["additional_headers"] = headers
|
|
98
|
+
return await _ws_connect_modern(ws_url, **kwargs)
|
|
99
|
+
else: # pragma: no cover - websockets 12.x fallback
|
|
100
|
+
if headers:
|
|
101
|
+
kwargs["extra_headers"] = headers
|
|
102
|
+
return await websockets.connect(ws_url, **kwargs) # type: ignore[attr-defined]
|
|
103
|
+
except Exception as exc:
|
|
104
|
+
status_code, body = _extract_http_status_and_body(exc)
|
|
105
|
+
if status_code == 401:
|
|
106
|
+
msg, server_msg = format_401_error(body, had_token=bool(token))
|
|
107
|
+
raise AuthError(msg, status_code=401, server_message=server_msg) from exc
|
|
108
|
+
raise TunnelConnectionError(f"connect failed: {exc}") from exc
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
async def _perform_registration(
|
|
112
|
+
ws: Any,
|
|
113
|
+
*,
|
|
114
|
+
prefix: Optional[str],
|
|
115
|
+
target_url: str,
|
|
116
|
+
ever_connected: bool,
|
|
117
|
+
timeout: float = 10.0,
|
|
118
|
+
) -> RegisterResponse:
|
|
119
|
+
reg_req = RegisterRequest(
|
|
120
|
+
prefix=prefix,
|
|
121
|
+
target_url=target_url,
|
|
122
|
+
client_version=__version__,
|
|
123
|
+
)
|
|
124
|
+
try:
|
|
125
|
+
await ws.send(reg_req.to_json())
|
|
126
|
+
except Exception as exc:
|
|
127
|
+
raise TunnelConnectionError(f"failed sending registration: {exc}") from exc
|
|
128
|
+
|
|
129
|
+
async def _recv_reply() -> RegisterResponse:
|
|
130
|
+
while True:
|
|
131
|
+
msg = await ws.recv()
|
|
132
|
+
if isinstance(msg, str):
|
|
133
|
+
try:
|
|
134
|
+
return RegisterResponse.from_json(msg)
|
|
135
|
+
except ValueError as exc:
|
|
136
|
+
raise TunnelConnectionError(
|
|
137
|
+
f"invalid server response JSON: {exc}"
|
|
138
|
+
) from exc
|
|
139
|
+
|
|
140
|
+
try:
|
|
141
|
+
resp = await asyncio.wait_for(_recv_reply(), timeout=timeout)
|
|
142
|
+
except asyncio.TimeoutError as exc:
|
|
143
|
+
raise TunnelConnectionError("registration timed out") from exc
|
|
144
|
+
except TunnelConnectionError:
|
|
145
|
+
raise
|
|
146
|
+
except Exception as exc:
|
|
147
|
+
raise TunnelConnectionError(f"connection closed before registration reply: {exc}") from exc
|
|
148
|
+
|
|
149
|
+
if not resp.ok:
|
|
150
|
+
err_msg = resp.error or "registration rejected by server"
|
|
151
|
+
non_retryable = (not ever_connected) or is_non_retryable_rejection(err_msg)
|
|
152
|
+
raise RegistrationError(
|
|
153
|
+
f"Registration rejected: {err_msg}"
|
|
154
|
+
if non_retryable
|
|
155
|
+
else f"re-registration rejected: {err_msg}",
|
|
156
|
+
retryable=not non_retryable,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
return resp
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class Tunnel:
|
|
163
|
+
"""Active async Neruton tunnel forwarding traffic to a local HTTP/WebSocket service."""
|
|
164
|
+
|
|
165
|
+
def __init__(
|
|
166
|
+
self,
|
|
167
|
+
*,
|
|
168
|
+
target_url: str,
|
|
169
|
+
server: str,
|
|
170
|
+
token: Optional[str] = None,
|
|
171
|
+
subdomain: Optional[str] = None,
|
|
172
|
+
no_tls_verify: bool = False,
|
|
173
|
+
host_header: Optional[str] = None,
|
|
174
|
+
reconnect: bool = True,
|
|
175
|
+
retry_initial: bool = False,
|
|
176
|
+
initial_backoff: float = 1.0,
|
|
177
|
+
max_backoff: float = 30.0,
|
|
178
|
+
handshake_timeout: float = 10.0,
|
|
179
|
+
ping_interval: Optional[float] = 20.0,
|
|
180
|
+
ping_timeout: Optional[float] = 20.0,
|
|
181
|
+
on_connect: Optional[ConnectCallback] = None,
|
|
182
|
+
on_disconnect: Optional[DisconnectCallback] = None,
|
|
183
|
+
on_reconnect: Optional[ReconnectCallback] = None,
|
|
184
|
+
on_request: Optional[RequestCallback] = None,
|
|
185
|
+
on_error: Optional[ErrorCallback] = None,
|
|
186
|
+
) -> None:
|
|
187
|
+
self._normalized_target = normalize_target_url(target_url)
|
|
188
|
+
self._ws_url = build_tunnel_ws_url(server)
|
|
189
|
+
self._server_url = server
|
|
190
|
+
self._token = token.strip() if token and token.strip() else None
|
|
191
|
+
self._no_tls_verify = no_tls_verify
|
|
192
|
+
self._reconnect = reconnect
|
|
193
|
+
self._retry_initial = retry_initial
|
|
194
|
+
self._initial_backoff = initial_backoff
|
|
195
|
+
self._max_backoff = max_backoff
|
|
196
|
+
self._handshake_timeout = handshake_timeout
|
|
197
|
+
self._ping_interval = ping_interval
|
|
198
|
+
self._ping_timeout = ping_timeout
|
|
199
|
+
|
|
200
|
+
if subdomain is not None and subdomain.strip():
|
|
201
|
+
self._sticky_prefix: Optional[str] = validate_prefix(subdomain)
|
|
202
|
+
else:
|
|
203
|
+
self._sticky_prefix = None
|
|
204
|
+
|
|
205
|
+
self._target_cfg = TargetConfig.from_url(
|
|
206
|
+
self._normalized_target,
|
|
207
|
+
host_header=host_header,
|
|
208
|
+
no_tls_verify=no_tls_verify,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
self._on_connect = on_connect
|
|
212
|
+
self._on_disconnect = on_disconnect
|
|
213
|
+
self._on_reconnect = on_reconnect
|
|
214
|
+
self._on_request = on_request
|
|
215
|
+
self._on_error = on_error
|
|
216
|
+
|
|
217
|
+
self._registration: Optional[RegisterResponse] = None
|
|
218
|
+
self._session: Optional[YamuxSession] = None
|
|
219
|
+
self._pending_ws: Optional[Any] = None
|
|
220
|
+
self._runner_task: Optional[asyncio.Task[None]] = None
|
|
221
|
+
self._connect_task: Optional[asyncio.Task[Tuple[Any, RegisterResponse]]] = None
|
|
222
|
+
self._stream_tasks: Set[asyncio.Task[None]] = set()
|
|
223
|
+
self._stop_event: Optional[asyncio.Event] = None
|
|
224
|
+
self._ever_connected = False
|
|
225
|
+
self._connected = False
|
|
226
|
+
self._closed = False
|
|
227
|
+
self._fatal_error: Optional[Exception] = None
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def registration(self) -> Optional[RegisterResponse]:
|
|
231
|
+
return self._registration
|
|
232
|
+
|
|
233
|
+
@property
|
|
234
|
+
def public_url(self) -> str:
|
|
235
|
+
return self._registration.public_url if self._registration else ""
|
|
236
|
+
|
|
237
|
+
@property
|
|
238
|
+
def preview_url(self) -> str:
|
|
239
|
+
return self._registration.preview_url if self._registration else ""
|
|
240
|
+
|
|
241
|
+
@property
|
|
242
|
+
def path_url(self) -> str:
|
|
243
|
+
return self._registration.path_url if self._registration else ""
|
|
244
|
+
|
|
245
|
+
@property
|
|
246
|
+
def dashboard_url(self) -> str:
|
|
247
|
+
return self._registration.dashboard_url if self._registration else ""
|
|
248
|
+
|
|
249
|
+
@property
|
|
250
|
+
def prefix(self) -> str:
|
|
251
|
+
return self._registration.prefix if self._registration else (self._sticky_prefix or "")
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def tunnel_id(self) -> str:
|
|
255
|
+
return self._registration.tunnel_id if self._registration else ""
|
|
256
|
+
|
|
257
|
+
@property
|
|
258
|
+
def owner_username(self) -> Optional[str]:
|
|
259
|
+
return self._registration.owner_username if self._registration else None
|
|
260
|
+
|
|
261
|
+
@property
|
|
262
|
+
def token_name(self) -> Optional[str]:
|
|
263
|
+
return self._registration.token_name if self._registration else None
|
|
264
|
+
|
|
265
|
+
@property
|
|
266
|
+
def target_url(self) -> str:
|
|
267
|
+
return self._normalized_target
|
|
268
|
+
|
|
269
|
+
@property
|
|
270
|
+
def server_url(self) -> str:
|
|
271
|
+
return self._server_url
|
|
272
|
+
|
|
273
|
+
@property
|
|
274
|
+
def ws_url(self) -> str:
|
|
275
|
+
return self._ws_url
|
|
276
|
+
|
|
277
|
+
@property
|
|
278
|
+
def connected(self) -> bool:
|
|
279
|
+
return self._connected
|
|
280
|
+
|
|
281
|
+
@property
|
|
282
|
+
def closed(self) -> bool:
|
|
283
|
+
return self._closed
|
|
284
|
+
|
|
285
|
+
@staticmethod
|
|
286
|
+
async def _safe_close_ws(ws: Any) -> None:
|
|
287
|
+
try:
|
|
288
|
+
await ws.close()
|
|
289
|
+
except Exception:
|
|
290
|
+
pass
|
|
291
|
+
|
|
292
|
+
async def start(self) -> Tunnel:
|
|
293
|
+
"""Establish the initial tunnel connection and start forwarding inbound streams."""
|
|
294
|
+
if self._runner_task is not None or self._closed:
|
|
295
|
+
return self
|
|
296
|
+
|
|
297
|
+
if self._stop_event is None:
|
|
298
|
+
self._stop_event = asyncio.Event()
|
|
299
|
+
backoff = self._initial_backoff
|
|
300
|
+
attempt = 0
|
|
301
|
+
|
|
302
|
+
while True:
|
|
303
|
+
if self._closed:
|
|
304
|
+
return self
|
|
305
|
+
try:
|
|
306
|
+
pair = await self._connect_and_register_cancellable()
|
|
307
|
+
if pair is None:
|
|
308
|
+
self._closed = True
|
|
309
|
+
return self
|
|
310
|
+
ws, reg = pair
|
|
311
|
+
break
|
|
312
|
+
except (AuthError, RegistrationError) as exc:
|
|
313
|
+
if isinstance(exc, RegistrationError) and exc.retryable and self._retry_initial:
|
|
314
|
+
reason = str(exc)
|
|
315
|
+
else:
|
|
316
|
+
self._closed = True
|
|
317
|
+
self._fatal_error = exc
|
|
318
|
+
raise
|
|
319
|
+
except TunnelConnectionError as exc:
|
|
320
|
+
if not self._retry_initial:
|
|
321
|
+
self._closed = True
|
|
322
|
+
self._fatal_error = exc
|
|
323
|
+
raise
|
|
324
|
+
reason = str(exc)
|
|
325
|
+
|
|
326
|
+
attempt += 1
|
|
327
|
+
self._safe_callback(self._on_reconnect, attempt, backoff, reason)
|
|
328
|
+
if await self._sleep_or_stop(backoff):
|
|
329
|
+
self._closed = True
|
|
330
|
+
return self
|
|
331
|
+
backoff = min(backoff * 2.0, self._max_backoff)
|
|
332
|
+
|
|
333
|
+
if self._closed:
|
|
334
|
+
await self._safe_close_ws(ws)
|
|
335
|
+
return self
|
|
336
|
+
|
|
337
|
+
self._apply_registration(reg)
|
|
338
|
+
session = self._spawn_session(ws)
|
|
339
|
+
self._runner_task = asyncio.create_task(
|
|
340
|
+
self._run_loop(session, time.monotonic()),
|
|
341
|
+
name=f"neruton-tunnel-{self.prefix}",
|
|
342
|
+
)
|
|
343
|
+
return self
|
|
344
|
+
|
|
345
|
+
async def _connect_and_register_cancellable(
|
|
346
|
+
self,
|
|
347
|
+
) -> Optional[Tuple[Any, RegisterResponse]]:
|
|
348
|
+
if self._closed:
|
|
349
|
+
return None
|
|
350
|
+
if self._stop_event is None:
|
|
351
|
+
self._stop_event = asyncio.Event()
|
|
352
|
+
|
|
353
|
+
connect_task: asyncio.Task[Tuple[Any, RegisterResponse]] = asyncio.create_task(
|
|
354
|
+
self._connect_and_register(),
|
|
355
|
+
name="neruton-connect",
|
|
356
|
+
)
|
|
357
|
+
self._connect_task = connect_task
|
|
358
|
+
stop_waiter = asyncio.create_task(self._stop_event.wait(), name="neruton-stop-wait")
|
|
359
|
+
try:
|
|
360
|
+
done, _ = await asyncio.wait(
|
|
361
|
+
{connect_task, stop_waiter},
|
|
362
|
+
return_when=asyncio.FIRST_COMPLETED,
|
|
363
|
+
)
|
|
364
|
+
if connect_task in done:
|
|
365
|
+
if connect_task.cancelled():
|
|
366
|
+
return None
|
|
367
|
+
ws, reg = connect_task.result()
|
|
368
|
+
if self._closed:
|
|
369
|
+
await self._safe_close_ws(ws)
|
|
370
|
+
return None
|
|
371
|
+
return ws, reg
|
|
372
|
+
|
|
373
|
+
# close() fired while connect/registration was still in flight.
|
|
374
|
+
connect_task.cancel()
|
|
375
|
+
try:
|
|
376
|
+
ws, _ = await connect_task
|
|
377
|
+
except BaseException:
|
|
378
|
+
return None
|
|
379
|
+
await self._safe_close_ws(ws)
|
|
380
|
+
return None
|
|
381
|
+
finally:
|
|
382
|
+
if not stop_waiter.done():
|
|
383
|
+
stop_waiter.cancel()
|
|
384
|
+
try:
|
|
385
|
+
await stop_waiter
|
|
386
|
+
except (asyncio.CancelledError, Exception):
|
|
387
|
+
pass
|
|
388
|
+
if not connect_task.done():
|
|
389
|
+
connect_task.cancel()
|
|
390
|
+
try:
|
|
391
|
+
ws, _ = await connect_task
|
|
392
|
+
except BaseException:
|
|
393
|
+
pass
|
|
394
|
+
else:
|
|
395
|
+
await self._safe_close_ws(ws)
|
|
396
|
+
if self._connect_task is connect_task:
|
|
397
|
+
self._connect_task = None
|
|
398
|
+
|
|
399
|
+
async def _connect_and_register(self) -> Tuple[Any, RegisterResponse]:
|
|
400
|
+
ws = await _open_websocket(
|
|
401
|
+
self._ws_url,
|
|
402
|
+
token=self._token,
|
|
403
|
+
no_tls_verify=self._no_tls_verify,
|
|
404
|
+
open_timeout=self._handshake_timeout,
|
|
405
|
+
ping_interval=self._ping_interval,
|
|
406
|
+
ping_timeout=self._ping_timeout,
|
|
407
|
+
)
|
|
408
|
+
self._pending_ws = ws
|
|
409
|
+
try:
|
|
410
|
+
if self._closed:
|
|
411
|
+
raise asyncio.CancelledError()
|
|
412
|
+
reg = await _perform_registration(
|
|
413
|
+
ws,
|
|
414
|
+
prefix=self._sticky_prefix,
|
|
415
|
+
target_url=self._normalized_target,
|
|
416
|
+
ever_connected=self._ever_connected,
|
|
417
|
+
timeout=self._handshake_timeout,
|
|
418
|
+
)
|
|
419
|
+
return ws, reg
|
|
420
|
+
except BaseException:
|
|
421
|
+
if self._pending_ws is ws:
|
|
422
|
+
self._pending_ws = None
|
|
423
|
+
await self._safe_close_ws(ws)
|
|
424
|
+
raise
|
|
425
|
+
|
|
426
|
+
def _apply_registration(self, reg: RegisterResponse) -> None:
|
|
427
|
+
self._registration = reg
|
|
428
|
+
self._sticky_prefix = reg.prefix
|
|
429
|
+
self._ever_connected = True
|
|
430
|
+
self._connected = True
|
|
431
|
+
self._safe_callback(self._on_connect, reg)
|
|
432
|
+
|
|
433
|
+
def _spawn_session(self, ws: Any) -> YamuxSession:
|
|
434
|
+
if self._pending_ws is ws:
|
|
435
|
+
self._pending_ws = None
|
|
436
|
+
transport = WsByteTransport(ws)
|
|
437
|
+
session = YamuxSession(transport, Mode.SERVER).start()
|
|
438
|
+
self._session = session
|
|
439
|
+
return session
|
|
440
|
+
|
|
441
|
+
async def _serve_session(self, session: YamuxSession) -> str:
|
|
442
|
+
try:
|
|
443
|
+
while not self._closed:
|
|
444
|
+
stream = await session.accept()
|
|
445
|
+
if stream is None:
|
|
446
|
+
break
|
|
447
|
+
task = asyncio.create_task(
|
|
448
|
+
handle_yamux_stream(
|
|
449
|
+
stream,
|
|
450
|
+
self._target_cfg,
|
|
451
|
+
on_request=self._on_request,
|
|
452
|
+
),
|
|
453
|
+
name=f"neruton-stream-{stream.stream_id}",
|
|
454
|
+
)
|
|
455
|
+
self._stream_tasks.add(task)
|
|
456
|
+
task.add_done_callback(self._stream_tasks.discard)
|
|
457
|
+
finally:
|
|
458
|
+
self._connected = False
|
|
459
|
+
await session.close(GoAwayCode.NORMAL)
|
|
460
|
+
if self._session is session:
|
|
461
|
+
self._session = None
|
|
462
|
+
|
|
463
|
+
if session.error is not None:
|
|
464
|
+
return f"tunnel stream closed: {session.error}"
|
|
465
|
+
return "tunnel stream closed by server"
|
|
466
|
+
|
|
467
|
+
async def _run_loop(self, initial_session: YamuxSession, connected_at: float) -> None:
|
|
468
|
+
session: Optional[YamuxSession] = initial_session
|
|
469
|
+
backoff = self._initial_backoff
|
|
470
|
+
attempt = 0
|
|
471
|
+
reason = "connection failed"
|
|
472
|
+
|
|
473
|
+
try:
|
|
474
|
+
while not self._closed:
|
|
475
|
+
if session is not None:
|
|
476
|
+
reason = await self._serve_session(session)
|
|
477
|
+
session = None
|
|
478
|
+
if self._closed:
|
|
479
|
+
return
|
|
480
|
+
self._safe_callback(self._on_disconnect, reason)
|
|
481
|
+
if not self._reconnect:
|
|
482
|
+
return
|
|
483
|
+
if time.monotonic() - connected_at >= 10.0:
|
|
484
|
+
backoff = self._initial_backoff
|
|
485
|
+
attempt = 0
|
|
486
|
+
|
|
487
|
+
attempt += 1
|
|
488
|
+
self._safe_callback(self._on_reconnect, attempt, backoff, reason)
|
|
489
|
+
if await self._sleep_or_stop(backoff):
|
|
490
|
+
return
|
|
491
|
+
backoff = min(backoff * 2.0, self._max_backoff)
|
|
492
|
+
|
|
493
|
+
try:
|
|
494
|
+
connected_at = time.monotonic()
|
|
495
|
+
pair = await self._connect_and_register_cancellable()
|
|
496
|
+
except AuthError as exc:
|
|
497
|
+
self._fatal_error = exc
|
|
498
|
+
self._safe_callback(self._on_error, exc)
|
|
499
|
+
return
|
|
500
|
+
except RegistrationError as exc:
|
|
501
|
+
if not exc.retryable:
|
|
502
|
+
self._fatal_error = exc
|
|
503
|
+
self._safe_callback(self._on_error, exc)
|
|
504
|
+
return
|
|
505
|
+
reason = str(exc)
|
|
506
|
+
self._safe_callback(self._on_disconnect, reason)
|
|
507
|
+
continue
|
|
508
|
+
except TunnelConnectionError as exc:
|
|
509
|
+
reason = str(exc)
|
|
510
|
+
self._safe_callback(self._on_disconnect, reason)
|
|
511
|
+
continue
|
|
512
|
+
|
|
513
|
+
if pair is None:
|
|
514
|
+
return
|
|
515
|
+
ws, reg = pair
|
|
516
|
+
if self._closed:
|
|
517
|
+
await self._safe_close_ws(ws)
|
|
518
|
+
return
|
|
519
|
+
|
|
520
|
+
self._apply_registration(reg)
|
|
521
|
+
session = self._spawn_session(ws)
|
|
522
|
+
except asyncio.CancelledError:
|
|
523
|
+
return
|
|
524
|
+
finally:
|
|
525
|
+
if session is not None:
|
|
526
|
+
try:
|
|
527
|
+
await session.close(GoAwayCode.NORMAL)
|
|
528
|
+
except Exception:
|
|
529
|
+
pass
|
|
530
|
+
if self._session is session:
|
|
531
|
+
self._session = None
|
|
532
|
+
self._connected = False
|
|
533
|
+
self._closed = True
|
|
534
|
+
|
|
535
|
+
async def _sleep_or_stop(self, seconds: float) -> bool:
|
|
536
|
+
if self._stop_event is None or self._stop_event.is_set():
|
|
537
|
+
return True
|
|
538
|
+
try:
|
|
539
|
+
await asyncio.wait_for(self._stop_event.wait(), timeout=seconds)
|
|
540
|
+
return True
|
|
541
|
+
except asyncio.TimeoutError:
|
|
542
|
+
return self._closed
|
|
543
|
+
|
|
544
|
+
@staticmethod
|
|
545
|
+
def _safe_callback(cb: Optional[Callable[..., Any]], *args: Any) -> None:
|
|
546
|
+
if cb is None:
|
|
547
|
+
return
|
|
548
|
+
try:
|
|
549
|
+
cb(*args)
|
|
550
|
+
except Exception:
|
|
551
|
+
pass
|
|
552
|
+
|
|
553
|
+
async def wait(self) -> None:
|
|
554
|
+
"""Wait until the tunnel closes. Re-raises fatal errors (such as revoked token 401)."""
|
|
555
|
+
if self._runner_task is not None:
|
|
556
|
+
await self._runner_task
|
|
557
|
+
if self._fatal_error is not None:
|
|
558
|
+
raise self._fatal_error
|
|
559
|
+
|
|
560
|
+
async def close(self) -> None:
|
|
561
|
+
"""Gracefully shut down the tunnel, sending Yamux GoAway and closing the WebSocket."""
|
|
562
|
+
if (
|
|
563
|
+
self._closed
|
|
564
|
+
and self._runner_task is None
|
|
565
|
+
and self._connect_task is None
|
|
566
|
+
and self._pending_ws is None
|
|
567
|
+
and self._session is None
|
|
568
|
+
):
|
|
569
|
+
return
|
|
570
|
+
self._closed = True
|
|
571
|
+
self._connected = False
|
|
572
|
+
if self._stop_event is not None:
|
|
573
|
+
self._stop_event.set()
|
|
574
|
+
|
|
575
|
+
connect_task = self._connect_task
|
|
576
|
+
if connect_task is not None and not connect_task.done():
|
|
577
|
+
connect_task.cancel()
|
|
578
|
+
try:
|
|
579
|
+
await asyncio.wait_for(asyncio.shield(connect_task), timeout=2.0)
|
|
580
|
+
except BaseException:
|
|
581
|
+
pass
|
|
582
|
+
|
|
583
|
+
pending_ws = self._pending_ws
|
|
584
|
+
if pending_ws is not None:
|
|
585
|
+
self._pending_ws = None
|
|
586
|
+
await self._safe_close_ws(pending_ws)
|
|
587
|
+
|
|
588
|
+
session = self._session
|
|
589
|
+
if session is not None:
|
|
590
|
+
try:
|
|
591
|
+
await session.close(GoAwayCode.NORMAL)
|
|
592
|
+
except Exception:
|
|
593
|
+
pass
|
|
594
|
+
|
|
595
|
+
for task in list(self._stream_tasks):
|
|
596
|
+
if not task.done():
|
|
597
|
+
task.cancel()
|
|
598
|
+
if self._stream_tasks:
|
|
599
|
+
await asyncio.gather(*list(self._stream_tasks), return_exceptions=True)
|
|
600
|
+
self._stream_tasks.clear()
|
|
601
|
+
|
|
602
|
+
runner = self._runner_task
|
|
603
|
+
if runner is not None and not runner.done():
|
|
604
|
+
try:
|
|
605
|
+
await asyncio.wait_for(runner, timeout=2.0)
|
|
606
|
+
except asyncio.TimeoutError:
|
|
607
|
+
runner.cancel()
|
|
608
|
+
try:
|
|
609
|
+
await runner
|
|
610
|
+
except (asyncio.CancelledError, Exception):
|
|
611
|
+
pass
|
|
612
|
+
|
|
613
|
+
async def __aenter__(self) -> Tunnel:
|
|
614
|
+
if self._runner_task is None:
|
|
615
|
+
await self.start()
|
|
616
|
+
return self
|
|
617
|
+
|
|
618
|
+
async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
619
|
+
await self.close()
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
class _TunnelConnectContext:
|
|
623
|
+
"""Dual awaitable + async context manager returned by `neruton.connect()`/`forward()`/`http()`.
|
|
624
|
+
|
|
625
|
+
Supports both:
|
|
626
|
+
async with neruton.connect("http://127.0.0.1:3000") as tunnel:
|
|
627
|
+
...
|
|
628
|
+
and:
|
|
629
|
+
tunnel = await neruton.connect("http://127.0.0.1:3000")
|
|
630
|
+
"""
|
|
631
|
+
|
|
632
|
+
def __init__(self, tunnel: Tunnel) -> None:
|
|
633
|
+
self._tunnel = tunnel
|
|
634
|
+
|
|
635
|
+
def __await__(self) -> Generator[Any, None, Tunnel]:
|
|
636
|
+
return self._tunnel.start().__await__()
|
|
637
|
+
|
|
638
|
+
async def __aenter__(self) -> Tunnel:
|
|
639
|
+
return await self._tunnel.start()
|
|
640
|
+
|
|
641
|
+
async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
642
|
+
await self._tunnel.close()
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def _resolve_target_arg(
|
|
646
|
+
target: Optional[Union[int, str]],
|
|
647
|
+
url: Optional[str],
|
|
648
|
+
) -> str:
|
|
649
|
+
if target is not None and url is not None:
|
|
650
|
+
raise ValueError("pass either positional target/port or keyword 'url', not both")
|
|
651
|
+
if url is not None:
|
|
652
|
+
return url
|
|
653
|
+
if target is not None:
|
|
654
|
+
return str(target)
|
|
655
|
+
raise ValueError("a local target port or URL is required")
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def _build_tunnel(
|
|
659
|
+
target: Optional[Union[int, str]] = None,
|
|
660
|
+
*,
|
|
661
|
+
url: Optional[str] = None,
|
|
662
|
+
server: Optional[str] = None,
|
|
663
|
+
token: Optional[str] = None,
|
|
664
|
+
subdomain: Optional[str] = None,
|
|
665
|
+
no_tls_verify: bool = False,
|
|
666
|
+
host_header: Optional[str] = None,
|
|
667
|
+
config_file: Optional[Union[str, Path]] = None,
|
|
668
|
+
reconnect: bool = True,
|
|
669
|
+
retry_initial: bool = False,
|
|
670
|
+
initial_backoff: float = 1.0,
|
|
671
|
+
max_backoff: float = 30.0,
|
|
672
|
+
handshake_timeout: float = 10.0,
|
|
673
|
+
ping_interval: Optional[float] = 20.0,
|
|
674
|
+
ping_timeout: Optional[float] = 20.0,
|
|
675
|
+
on_connect: Optional[ConnectCallback] = None,
|
|
676
|
+
on_disconnect: Optional[DisconnectCallback] = None,
|
|
677
|
+
on_reconnect: Optional[ReconnectCallback] = None,
|
|
678
|
+
on_request: Optional[RequestCallback] = None,
|
|
679
|
+
on_error: Optional[ErrorCallback] = None,
|
|
680
|
+
) -> Tunnel:
|
|
681
|
+
target_str = _resolve_target_arg(target, url)
|
|
682
|
+
resolved_server, resolved_token = resolve_server_and_token(
|
|
683
|
+
server=server,
|
|
684
|
+
token=token,
|
|
685
|
+
config_file=config_file,
|
|
686
|
+
)
|
|
687
|
+
return Tunnel(
|
|
688
|
+
target_url=target_str,
|
|
689
|
+
server=resolved_server,
|
|
690
|
+
token=resolved_token,
|
|
691
|
+
subdomain=subdomain,
|
|
692
|
+
no_tls_verify=no_tls_verify,
|
|
693
|
+
host_header=host_header,
|
|
694
|
+
reconnect=reconnect,
|
|
695
|
+
retry_initial=retry_initial,
|
|
696
|
+
initial_backoff=initial_backoff,
|
|
697
|
+
max_backoff=max_backoff,
|
|
698
|
+
handshake_timeout=handshake_timeout,
|
|
699
|
+
ping_interval=ping_interval,
|
|
700
|
+
ping_timeout=ping_timeout,
|
|
701
|
+
on_connect=on_connect,
|
|
702
|
+
on_disconnect=on_disconnect,
|
|
703
|
+
on_reconnect=on_reconnect,
|
|
704
|
+
on_request=on_request,
|
|
705
|
+
on_error=on_error,
|
|
706
|
+
)
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
def connect(
|
|
710
|
+
target: Optional[Union[int, str]] = None,
|
|
711
|
+
*,
|
|
712
|
+
url: Optional[str] = None,
|
|
713
|
+
server: Optional[str] = None,
|
|
714
|
+
token: Optional[str] = None,
|
|
715
|
+
subdomain: Optional[str] = None,
|
|
716
|
+
no_tls_verify: bool = False,
|
|
717
|
+
host_header: Optional[str] = None,
|
|
718
|
+
config_file: Optional[Union[str, Path]] = None,
|
|
719
|
+
reconnect: bool = True,
|
|
720
|
+
retry_initial: bool = False,
|
|
721
|
+
initial_backoff: float = 1.0,
|
|
722
|
+
max_backoff: float = 30.0,
|
|
723
|
+
handshake_timeout: float = 10.0,
|
|
724
|
+
ping_interval: Optional[float] = 20.0,
|
|
725
|
+
ping_timeout: Optional[float] = 20.0,
|
|
726
|
+
on_connect: Optional[ConnectCallback] = None,
|
|
727
|
+
on_disconnect: Optional[DisconnectCallback] = None,
|
|
728
|
+
on_reconnect: Optional[ReconnectCallback] = None,
|
|
729
|
+
on_request: Optional[RequestCallback] = None,
|
|
730
|
+
on_error: Optional[ErrorCallback] = None,
|
|
731
|
+
) -> _TunnelConnectContext:
|
|
732
|
+
"""Connect an async Neruton tunnel.
|
|
733
|
+
|
|
734
|
+
Can be awaited directly (`tunnel = await neruton.connect(...)`) or used as an
|
|
735
|
+
async context manager (`async with neruton.connect(...) as tunnel:`).
|
|
736
|
+
"""
|
|
737
|
+
tunnel = _build_tunnel(
|
|
738
|
+
target,
|
|
739
|
+
url=url,
|
|
740
|
+
server=server,
|
|
741
|
+
token=token,
|
|
742
|
+
subdomain=subdomain,
|
|
743
|
+
no_tls_verify=no_tls_verify,
|
|
744
|
+
host_header=host_header,
|
|
745
|
+
config_file=config_file,
|
|
746
|
+
reconnect=reconnect,
|
|
747
|
+
retry_initial=retry_initial,
|
|
748
|
+
initial_backoff=initial_backoff,
|
|
749
|
+
max_backoff=max_backoff,
|
|
750
|
+
handshake_timeout=handshake_timeout,
|
|
751
|
+
ping_interval=ping_interval,
|
|
752
|
+
ping_timeout=ping_timeout,
|
|
753
|
+
on_connect=on_connect,
|
|
754
|
+
on_disconnect=on_disconnect,
|
|
755
|
+
on_reconnect=on_reconnect,
|
|
756
|
+
on_request=on_request,
|
|
757
|
+
on_error=on_error,
|
|
758
|
+
)
|
|
759
|
+
return _TunnelConnectContext(tunnel)
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def forward(
|
|
763
|
+
port_or_url: Union[int, str],
|
|
764
|
+
*,
|
|
765
|
+
server: Optional[str] = None,
|
|
766
|
+
token: Optional[str] = None,
|
|
767
|
+
subdomain: Optional[str] = None,
|
|
768
|
+
no_tls_verify: bool = False,
|
|
769
|
+
host_header: Optional[str] = None,
|
|
770
|
+
config_file: Optional[Union[str, Path]] = None,
|
|
771
|
+
reconnect: bool = True,
|
|
772
|
+
retry_initial: bool = False,
|
|
773
|
+
on_connect: Optional[ConnectCallback] = None,
|
|
774
|
+
on_disconnect: Optional[DisconnectCallback] = None,
|
|
775
|
+
on_reconnect: Optional[ReconnectCallback] = None,
|
|
776
|
+
on_request: Optional[RequestCallback] = None,
|
|
777
|
+
on_error: Optional[ErrorCallback] = None,
|
|
778
|
+
) -> _TunnelConnectContext:
|
|
779
|
+
"""Shorthand async API for forwarding a local port or URL (e.g. `neruton.forward(3000)`)."""
|
|
780
|
+
return connect(
|
|
781
|
+
port_or_url,
|
|
782
|
+
server=server,
|
|
783
|
+
token=token,
|
|
784
|
+
subdomain=subdomain,
|
|
785
|
+
no_tls_verify=no_tls_verify,
|
|
786
|
+
host_header=host_header,
|
|
787
|
+
config_file=config_file,
|
|
788
|
+
reconnect=reconnect,
|
|
789
|
+
retry_initial=retry_initial,
|
|
790
|
+
on_connect=on_connect,
|
|
791
|
+
on_disconnect=on_disconnect,
|
|
792
|
+
on_reconnect=on_reconnect,
|
|
793
|
+
on_request=on_request,
|
|
794
|
+
on_error=on_error,
|
|
795
|
+
)
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def http(
|
|
799
|
+
port_or_url: Union[int, str],
|
|
800
|
+
*,
|
|
801
|
+
server: Optional[str] = None,
|
|
802
|
+
token: Optional[str] = None,
|
|
803
|
+
subdomain: Optional[str] = None,
|
|
804
|
+
no_tls_verify: bool = False,
|
|
805
|
+
host_header: Optional[str] = None,
|
|
806
|
+
config_file: Optional[Union[str, Path]] = None,
|
|
807
|
+
reconnect: bool = True,
|
|
808
|
+
retry_initial: bool = False,
|
|
809
|
+
on_connect: Optional[ConnectCallback] = None,
|
|
810
|
+
on_disconnect: Optional[DisconnectCallback] = None,
|
|
811
|
+
on_reconnect: Optional[ReconnectCallback] = None,
|
|
812
|
+
on_request: Optional[RequestCallback] = None,
|
|
813
|
+
on_error: Optional[ErrorCallback] = None,
|
|
814
|
+
) -> _TunnelConnectContext:
|
|
815
|
+
"""Alias for `neruton.forward(port_or_url, ...)` mirroring `neruton http <port>`."""
|
|
816
|
+
return forward(
|
|
817
|
+
port_or_url,
|
|
818
|
+
server=server,
|
|
819
|
+
token=token,
|
|
820
|
+
subdomain=subdomain,
|
|
821
|
+
no_tls_verify=no_tls_verify,
|
|
822
|
+
host_header=host_header,
|
|
823
|
+
config_file=config_file,
|
|
824
|
+
reconnect=reconnect,
|
|
825
|
+
retry_initial=retry_initial,
|
|
826
|
+
on_connect=on_connect,
|
|
827
|
+
on_disconnect=on_disconnect,
|
|
828
|
+
on_reconnect=on_reconnect,
|
|
829
|
+
on_request=on_request,
|
|
830
|
+
on_error=on_error,
|
|
831
|
+
)
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
class SyncTunnel:
|
|
835
|
+
"""Synchronous Neruton tunnel backed by a dedicated daemon event-loop thread.
|
|
836
|
+
|
|
837
|
+
Designed for Flask, Django, FastAPI scripts, notebooks, and synchronous CLIs.
|
|
838
|
+
"""
|
|
839
|
+
|
|
840
|
+
def __init__(self, tunnel: Tunnel) -> None:
|
|
841
|
+
self._tunnel = tunnel
|
|
842
|
+
self._loop = asyncio.new_event_loop()
|
|
843
|
+
self._ready = threading.Event()
|
|
844
|
+
self._closed_lock = threading.Lock()
|
|
845
|
+
self._closed = False
|
|
846
|
+
|
|
847
|
+
self._thread = threading.Thread(
|
|
848
|
+
target=self._run_loop_thread,
|
|
849
|
+
name="neruton-sync-tunnel",
|
|
850
|
+
daemon=True,
|
|
851
|
+
)
|
|
852
|
+
self._thread.start()
|
|
853
|
+
self._ready.wait()
|
|
854
|
+
|
|
855
|
+
try:
|
|
856
|
+
fut = asyncio.run_coroutine_threadsafe(self._tunnel.start(), self._loop)
|
|
857
|
+
fut.result()
|
|
858
|
+
except Exception:
|
|
859
|
+
self._shutdown_loop()
|
|
860
|
+
raise
|
|
861
|
+
|
|
862
|
+
def _run_loop_thread(self) -> None:
|
|
863
|
+
asyncio.set_event_loop(self._loop)
|
|
864
|
+
self._ready.set()
|
|
865
|
+
try:
|
|
866
|
+
self._loop.run_forever()
|
|
867
|
+
finally:
|
|
868
|
+
pending = asyncio.all_tasks(self._loop)
|
|
869
|
+
for task in pending:
|
|
870
|
+
task.cancel()
|
|
871
|
+
if pending:
|
|
872
|
+
self._loop.run_until_complete(
|
|
873
|
+
asyncio.gather(*pending, return_exceptions=True)
|
|
874
|
+
)
|
|
875
|
+
self._loop.close()
|
|
876
|
+
|
|
877
|
+
def _shutdown_loop(self) -> None:
|
|
878
|
+
if not self._loop.is_closed():
|
|
879
|
+
try:
|
|
880
|
+
self._loop.call_soon_threadsafe(self._loop.stop)
|
|
881
|
+
except RuntimeError:
|
|
882
|
+
pass
|
|
883
|
+
if self._thread.is_alive() and threading.current_thread() is not self._thread:
|
|
884
|
+
self._thread.join(timeout=5.0)
|
|
885
|
+
|
|
886
|
+
@property
|
|
887
|
+
def public_url(self) -> str:
|
|
888
|
+
return self._tunnel.public_url
|
|
889
|
+
|
|
890
|
+
@property
|
|
891
|
+
def preview_url(self) -> str:
|
|
892
|
+
return self._tunnel.preview_url
|
|
893
|
+
|
|
894
|
+
@property
|
|
895
|
+
def path_url(self) -> str:
|
|
896
|
+
return self._tunnel.path_url
|
|
897
|
+
|
|
898
|
+
@property
|
|
899
|
+
def dashboard_url(self) -> str:
|
|
900
|
+
return self._tunnel.dashboard_url
|
|
901
|
+
|
|
902
|
+
@property
|
|
903
|
+
def prefix(self) -> str:
|
|
904
|
+
return self._tunnel.prefix
|
|
905
|
+
|
|
906
|
+
@property
|
|
907
|
+
def tunnel_id(self) -> str:
|
|
908
|
+
return self._tunnel.tunnel_id
|
|
909
|
+
|
|
910
|
+
@property
|
|
911
|
+
def owner_username(self) -> Optional[str]:
|
|
912
|
+
return self._tunnel.owner_username
|
|
913
|
+
|
|
914
|
+
@property
|
|
915
|
+
def token_name(self) -> Optional[str]:
|
|
916
|
+
return self._tunnel.token_name
|
|
917
|
+
|
|
918
|
+
@property
|
|
919
|
+
def target_url(self) -> str:
|
|
920
|
+
return self._tunnel.target_url
|
|
921
|
+
|
|
922
|
+
@property
|
|
923
|
+
def server_url(self) -> str:
|
|
924
|
+
return self._tunnel.server_url
|
|
925
|
+
|
|
926
|
+
@property
|
|
927
|
+
def connected(self) -> bool:
|
|
928
|
+
return self._tunnel.connected
|
|
929
|
+
|
|
930
|
+
@property
|
|
931
|
+
def closed(self) -> bool:
|
|
932
|
+
return self._closed or self._tunnel.closed
|
|
933
|
+
|
|
934
|
+
def wait(self, timeout: Optional[float] = None) -> None:
|
|
935
|
+
"""Block until the tunnel closes or `timeout` seconds elapse."""
|
|
936
|
+
if self._closed or self._loop.is_closed():
|
|
937
|
+
return
|
|
938
|
+
fut = asyncio.run_coroutine_threadsafe(self._tunnel.wait(), self._loop)
|
|
939
|
+
try:
|
|
940
|
+
fut.result(timeout=timeout)
|
|
941
|
+
except concurrent.futures.TimeoutError as exc:
|
|
942
|
+
raise TimeoutError("timed out waiting for tunnel to close") from exc
|
|
943
|
+
|
|
944
|
+
def close(self) -> None:
|
|
945
|
+
"""Close the tunnel and stop its background event loop thread (idempotent)."""
|
|
946
|
+
with self._closed_lock:
|
|
947
|
+
if self._closed:
|
|
948
|
+
return
|
|
949
|
+
self._closed = True
|
|
950
|
+
|
|
951
|
+
if not self._loop.is_closed():
|
|
952
|
+
try:
|
|
953
|
+
fut = asyncio.run_coroutine_threadsafe(self._tunnel.close(), self._loop)
|
|
954
|
+
fut.result(timeout=5.0)
|
|
955
|
+
except Exception:
|
|
956
|
+
pass
|
|
957
|
+
self._shutdown_loop()
|
|
958
|
+
|
|
959
|
+
def __enter__(self) -> SyncTunnel:
|
|
960
|
+
return self
|
|
961
|
+
|
|
962
|
+
def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
963
|
+
self.close()
|
|
964
|
+
|
|
965
|
+
|
|
966
|
+
def open_tunnel(
|
|
967
|
+
target: Optional[Union[int, str]] = None,
|
|
968
|
+
*,
|
|
969
|
+
url: Optional[str] = None,
|
|
970
|
+
server: Optional[str] = None,
|
|
971
|
+
token: Optional[str] = None,
|
|
972
|
+
subdomain: Optional[str] = None,
|
|
973
|
+
no_tls_verify: bool = False,
|
|
974
|
+
host_header: Optional[str] = None,
|
|
975
|
+
config_file: Optional[Union[str, Path]] = None,
|
|
976
|
+
reconnect: bool = True,
|
|
977
|
+
retry_initial: bool = False,
|
|
978
|
+
initial_backoff: float = 1.0,
|
|
979
|
+
max_backoff: float = 30.0,
|
|
980
|
+
handshake_timeout: float = 10.0,
|
|
981
|
+
ping_interval: Optional[float] = 20.0,
|
|
982
|
+
ping_timeout: Optional[float] = 20.0,
|
|
983
|
+
on_connect: Optional[ConnectCallback] = None,
|
|
984
|
+
on_disconnect: Optional[DisconnectCallback] = None,
|
|
985
|
+
on_reconnect: Optional[ReconnectCallback] = None,
|
|
986
|
+
on_request: Optional[RequestCallback] = None,
|
|
987
|
+
on_error: Optional[ErrorCallback] = None,
|
|
988
|
+
) -> SyncTunnel:
|
|
989
|
+
"""Open a synchronous Neruton tunnel (runs an asyncio loop in a daemon thread).
|
|
990
|
+
|
|
991
|
+
Usage:
|
|
992
|
+
with neruton.open(3000, server="...", token="ntk_...") as tunnel:
|
|
993
|
+
print(tunnel.public_url)
|
|
994
|
+
"""
|
|
995
|
+
tunnel = _build_tunnel(
|
|
996
|
+
target,
|
|
997
|
+
url=url,
|
|
998
|
+
server=server,
|
|
999
|
+
token=token,
|
|
1000
|
+
subdomain=subdomain,
|
|
1001
|
+
no_tls_verify=no_tls_verify,
|
|
1002
|
+
host_header=host_header,
|
|
1003
|
+
config_file=config_file,
|
|
1004
|
+
reconnect=reconnect,
|
|
1005
|
+
retry_initial=retry_initial,
|
|
1006
|
+
initial_backoff=initial_backoff,
|
|
1007
|
+
max_backoff=max_backoff,
|
|
1008
|
+
handshake_timeout=handshake_timeout,
|
|
1009
|
+
ping_interval=ping_interval,
|
|
1010
|
+
ping_timeout=ping_timeout,
|
|
1011
|
+
on_connect=on_connect,
|
|
1012
|
+
on_disconnect=on_disconnect,
|
|
1013
|
+
on_reconnect=on_reconnect,
|
|
1014
|
+
on_request=on_request,
|
|
1015
|
+
on_error=on_error,
|
|
1016
|
+
)
|
|
1017
|
+
return SyncTunnel(tunnel)
|