shellzapy 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.
- shellzapy-0.1.0.dist-info/METADATA +112 -0
- shellzapy-0.1.0.dist-info/RECORD +345 -0
- shellzapy-0.1.0.dist-info/WHEEL +4 -0
- shellzapy-0.1.0.dist-info/licenses/LICENSE +21 -0
- shellzapy-0.1.0.dist-info/licenses/NOTICE +9 -0
- zapy/__init__.py +58 -0
- zapy/_appstate/__init__.py +59 -0
- zapy/_appstate/constants.py +82 -0
- zapy/_appstate/crypto/__init__.py +17 -0
- zapy/_appstate/crypto/app_state_crypto.py +401 -0
- zapy/_appstate/parsers/__init__.py +23 -0
- zapy/_appstate/parsers/encoding.py +157 -0
- zapy/_appstate/parsers/response_parser.py +135 -0
- zapy/_appstate/sync/__init__.py +11 -0
- zapy/_appstate/sync/sync_client.py +1559 -0
- zapy/_appstate/types.py +137 -0
- zapy/_appstate/utils.py +100 -0
- zapy/_auth/__init__.py +3 -0
- zapy/_auth/auth_client.py +618 -0
- zapy/_auth/credentials_flow.py +290 -0
- zapy/_auth/pairing/__init__.py +3 -0
- zapy/_auth/pairing/companion_host.py +239 -0
- zapy/_auth/pairing/flow.py +808 -0
- zapy/_auth/pairing/pairing_code_crypto.py +143 -0
- zapy/_auth/pairing/qr_flow.py +123 -0
- zapy/_auth/pairing/shortcake_crypto.py +122 -0
- zapy/_auth/pairing/shortcake_flow.py +393 -0
- zapy/_auth/types.py +110 -0
- zapy/_client/__init__.py +26 -0
- zapy/_client/client.py +972 -0
- zapy/_client/connection/__init__.py +6 -0
- zapy/_client/connection/manager.py +525 -0
- zapy/_client/connection/receipt_queue.py +74 -0
- zapy/_client/coordinators/__init__.py +81 -0
- zapy/_client/coordinators/ab_props.py +260 -0
- zapy/_client/coordinators/app_state_mutation.py +2538 -0
- zapy/_client/coordinators/bot.py +830 -0
- zapy/_client/coordinators/broadcast_list.py +101 -0
- zapy/_client/coordinators/business.py +247 -0
- zapy/_client/coordinators/email.py +158 -0
- zapy/_client/coordinators/group.py +1478 -0
- zapy/_client/coordinators/incoming_node.py +758 -0
- zapy/_client/coordinators/low_level.py +119 -0
- zapy/_client/coordinators/message.py +1153 -0
- zapy/_client/coordinators/message_dispatch.py +1637 -0
- zapy/_client/coordinators/newsletter.py +110 -0
- zapy/_client/coordinators/offline_resume.py +271 -0
- zapy/_client/coordinators/passive_tasks.py +447 -0
- zapy/_client/coordinators/presence.py +103 -0
- zapy/_client/coordinators/privacy.py +623 -0
- zapy/_client/coordinators/profile.py +1024 -0
- zapy/_client/coordinators/retry.py +1878 -0
- zapy/_client/coordinators/status.py +132 -0
- zapy/_client/coordinators/stream_control.py +260 -0
- zapy/_client/coordinators/trusted_contact_token.py +417 -0
- zapy/_client/events/__init__.py +266 -0
- zapy/_client/events/abprops.py +58 -0
- zapy/_client/events/appstate_mutation.py +248 -0
- zapy/_client/events/business.py +565 -0
- zapy/_client/events/call.py +144 -0
- zapy/_client/events/chatstate.py +41 -0
- zapy/_client/events/devices.py +122 -0
- zapy/_client/events/dirty.py +384 -0
- zapy/_client/events/group.py +655 -0
- zapy/_client/events/identity.py +40 -0
- zapy/_client/events/incoming.py +1079 -0
- zapy/_client/events/mex_notification.py +317 -0
- zapy/_client/events/offline.py +123 -0
- zapy/_client/events/picture.py +67 -0
- zapy/_client/events/presence.py +74 -0
- zapy/_client/events/privacy.py +187 -0
- zapy/_client/events/privacy_token.py +72 -0
- zapy/_client/events/receipt.py +109 -0
- zapy/_client/events/registration.py +70 -0
- zapy/_client/events/username.py +76 -0
- zapy/_client/factory.py +2020 -0
- zapy/_client/media.py +829 -0
- zapy/_client/newsletter/__init__.py +90 -0
- zapy/_client/newsletter/admin.py +323 -0
- zapy/_client/newsletter/content.py +499 -0
- zapy/_client/newsletter/discovery.py +233 -0
- zapy/_client/newsletter/messaging.py +396 -0
- zapy/_client/newsletter/mex.py +99 -0
- zapy/_client/newsletter/parse.py +406 -0
- zapy/_client/newsletter/types.py +393 -0
- zapy/_client/persistence/__init__.py +89 -0
- zapy/_client/persistence/companion_host.py +133 -0
- zapy/_client/persistence/ephemeral_setting.py +245 -0
- zapy/_client/persistence/group_history.py +361 -0
- zapy/_client/persistence/history_blob.py +169 -0
- zapy/_client/persistence/history_sync.py +646 -0
- zapy/_client/persistence/mailbox.py +232 -0
- zapy/_client/persistence/write_behind_persistence.py +368 -0
- zapy/_client/plugins/__init__.py +23 -0
- zapy/_client/plugins/define.py +44 -0
- zapy/_client/plugins/install.py +254 -0
- zapy/_client/plugins/types.py +64 -0
- zapy/_client/tokens/__init__.py +21 -0
- zapy/_client/tokens/cs_token.py +47 -0
- zapy/_client/tokens/tc_token.py +43 -0
- zapy/_client/types.py +988 -0
- zapy/_crypto/__init__.py +65 -0
- zapy/_crypto/core/__init__.py +62 -0
- zapy/_crypto/core/hkdf.py +41 -0
- zapy/_crypto/core/keys.py +51 -0
- zapy/_crypto/core/nonce.py +25 -0
- zapy/_crypto/core/primitives.py +179 -0
- zapy/_crypto/core/random.py +32 -0
- zapy/_crypto/core/xeddsa.py +72 -0
- zapy/_crypto/curves/__init__.py +3 -0
- zapy/_crypto/curves/constants.py +10 -0
- zapy/_crypto/curves/ed25519.py +61 -0
- zapy/_crypto/curves/types.py +18 -0
- zapy/_crypto/curves/x25519.py +117 -0
- zapy/_crypto/math/__init__.py +3 -0
- zapy/_crypto/math/constants.py +35 -0
- zapy/_crypto/math/edwards.py +174 -0
- zapy/_crypto/math/fe.py +120 -0
- zapy/_crypto/math/le.py +13 -0
- zapy/_crypto/math/mod.py +15 -0
- zapy/_crypto/math/prime.py +11 -0
- zapy/_crypto/math/types.py +25 -0
- zapy/_crypto/native_backend.py +40 -0
- zapy/_infra/__init__.py +3 -0
- zapy/_infra/log.py +142 -0
- zapy/_infra/perf.py +77 -0
- zapy/_media/__init__.py +64 -0
- zapy/_media/constants.py +133 -0
- zapy/_media/container.py +110 -0
- zapy/_media/crypto/__init__.py +19 -0
- zapy/_media/crypto/crypto.py +633 -0
- zapy/_media/crypto/media_retry.py +107 -0
- zapy/_media/processor.py +100 -0
- zapy/_media/sticker/__init__.py +8 -0
- zapy/_media/sticker/pack.py +188 -0
- zapy/_media/transfer/__init__.py +15 -0
- zapy/_media/transfer/client.py +635 -0
- zapy/_media/transfer/conn.py +48 -0
- zapy/_media/types.py +169 -0
- zapy/_message/__init__.py +121 -0
- zapy/_message/addons/__init__.py +5 -0
- zapy/_message/addons/link_preview/__init__.py +54 -0
- zapy/_message/addons/link_preview/builder.py +56 -0
- zapy/_message/addons/link_preview/detect.py +72 -0
- zapy/_message/addons/link_preview/fetcher.py +553 -0
- zapy/_message/addons/link_preview/types.py +100 -0
- zapy/_message/client.py +486 -0
- zapy/_message/context_info.py +424 -0
- zapy/_message/crypto/__init__.py +71 -0
- zapy/_message/crypto/addon_crypto.py +656 -0
- zapy/_message/crypto/icdc.py +138 -0
- zapy/_message/crypto/phash.py +87 -0
- zapy/_message/crypto/reporting_token.py +498 -0
- zapy/_message/crypto/use_case_secret.py +113 -0
- zapy/_message/encode/__init__.py +84 -0
- zapy/_message/encode/content.py +636 -0
- zapy/_message/encode/device_sent.py +88 -0
- zapy/_message/encode/media_payload.py +122 -0
- zapy/_message/encode/padding.py +27 -0
- zapy/_message/kinds/__init__.py +1 -0
- zapy/_message/kinds/bot.py +179 -0
- zapy/_message/kinds/group_history.py +206 -0
- zapy/_message/kinds/newsletter.py +388 -0
- zapy/_message/kinds/sticker_pack.py +74 -0
- zapy/_message/messaging/__init__.py +336 -0
- zapy/_message/messaging/companion_host.py +117 -0
- zapy/_message/messaging/fanout.py +311 -0
- zapy/_message/messaging/group_metadata.py +444 -0
- zapy/_message/messaging/ignore_key.py +264 -0
- zapy/_message/messaging/key_protocol.py +217 -0
- zapy/_message/messaging/link_preview.py +448 -0
- zapy/_message/messaging/messages.py +1429 -0
- zapy/_message/primitives/__init__.py +1 -0
- zapy/_message/primitives/ack.py +232 -0
- zapy/_message/primitives/incoming.py +1141 -0
- zapy/_message/primitives/media_retry.py +451 -0
- zapy/_message/primitives/peer_data_operation.py +271 -0
- zapy/_message/types.py +434 -0
- zapy/_proto/WAProto_pb2.py +2584 -0
- zapy/_proto/__init__.py +1 -0
- zapy/_protocol/__init__.py +3 -0
- zapy/_protocol/abprops_spec.py +6216 -0
- zapy/_protocol/auth.py +17 -0
- zapy/_protocol/browser.py +57 -0
- zapy/_protocol/defaults.py +38 -0
- zapy/_protocol/device_identity.py +54 -0
- zapy/_protocol/jid.py +241 -0
- zapy/_protocol/message.py +127 -0
- zapy/_protocol/nodes.py +144 -0
- zapy/_protocol/notification.py +18 -0
- zapy/_retry/__init__.py +77 -0
- zapy/_retry/codec.py +209 -0
- zapy/_retry/constants.py +28 -0
- zapy/_retry/parse.py +132 -0
- zapy/_retry/reason.py +65 -0
- zapy/_retry/replay.py +483 -0
- zapy/_retry/tracker.py +161 -0
- zapy/_retry/types.py +122 -0
- zapy/_signal/__init__.py +171 -0
- zapy/_signal/api/__init__.py +133 -0
- zapy/_signal/api/codec.py +164 -0
- zapy/_signal/api/constants.py +14 -0
- zapy/_signal/api/device_sync.py +915 -0
- zapy/_signal/api/digest_sync.py +363 -0
- zapy/_signal/api/identity_sync.py +250 -0
- zapy/_signal/api/missing_pre_keys_sync.py +267 -0
- zapy/_signal/api/prekeys.py +191 -0
- zapy/_signal/api/result_map.py +40 -0
- zapy/_signal/api/rotate_key.py +111 -0
- zapy/_signal/api/session_sync.py +297 -0
- zapy/_signal/attestation.py +145 -0
- zapy/_signal/constants.py +22 -0
- zapy/_signal/encoding.py +78 -0
- zapy/_signal/group/__init__.py +35 -0
- zapy/_signal/group/chain.py +139 -0
- zapy/_signal/group/codec.py +78 -0
- zapy/_signal/group/encoding.py +166 -0
- zapy/_signal/group/manager.py +361 -0
- zapy/_signal/registration/__init__.py +44 -0
- zapy/_signal/registration/keygen.py +46 -0
- zapy/_signal/registration/reg_encoding.py +66 -0
- zapy/_signal/registration/reg_utils.py +52 -0
- zapy/_signal/session/__init__.py +114 -0
- zapy/_signal/session/encoding.py +385 -0
- zapy/_signal/session/protocol.py +590 -0
- zapy/_signal/session/ratchet.py +381 -0
- zapy/_signal/session/resolver.py +630 -0
- zapy/_signal/session/serializer.py +96 -0
- zapy/_signal/session/session.py +272 -0
- zapy/_signal/types.py +214 -0
- zapy/_store/__init__.py +118 -0
- zapy/_store/cache/__init__.py +166 -0
- zapy/_store/cache/identity.py +130 -0
- zapy/_store/cache/privacy_token.py +116 -0
- zapy/_store/cache/sender_key.py +168 -0
- zapy/_store/cache/session.py +142 -0
- zapy/_store/contracts/__init__.py +84 -0
- zapy/_store/contracts/appstate.py +82 -0
- zapy/_store/contracts/auth.py +16 -0
- zapy/_store/contracts/chat_metadata.py +29 -0
- zapy/_store/contracts/contact.py +31 -0
- zapy/_store/contracts/device_list.py +35 -0
- zapy/_store/contracts/group_metadata.py +33 -0
- zapy/_store/contracts/identity.py +18 -0
- zapy/_store/contracts/message.py +36 -0
- zapy/_store/contracts/message_secret.py +41 -0
- zapy/_store/contracts/pre_key.py +32 -0
- zapy/_store/contracts/privacy_token.py +32 -0
- zapy/_store/contracts/retry.py +47 -0
- zapy/_store/contracts/sender_key.py +37 -0
- zapy/_store/contracts/session.py +21 -0
- zapy/_store/contracts/signal.py +23 -0
- zapy/_store/contracts/thread.py +35 -0
- zapy/_store/create_store.py +890 -0
- zapy/_store/locks.py +1154 -0
- zapy/_store/memory/__init__.py +40 -0
- zapy/_store/memory/appstate.py +200 -0
- zapy/_store/memory/auth.py +24 -0
- zapy/_store/memory/chat_metadata.py +124 -0
- zapy/_store/memory/contact.py +125 -0
- zapy/_store/memory/device_list.py +161 -0
- zapy/_store/memory/group_metadata.py +125 -0
- zapy/_store/memory/identity.py +86 -0
- zapy/_store/memory/message.py +85 -0
- zapy/_store/memory/message_secret.py +145 -0
- zapy/_store/memory/pre_key.py +112 -0
- zapy/_store/memory/privacy_token.py +103 -0
- zapy/_store/memory/retry.py +250 -0
- zapy/_store/memory/sender_key.py +162 -0
- zapy/_store/memory/session.py +111 -0
- zapy/_store/memory/signal.py +45 -0
- zapy/_store/memory/thread.py +66 -0
- zapy/_store/noop.py +279 -0
- zapy/_transport/__init__.py +3 -0
- zapy/_transport/binary/__init__.py +77 -0
- zapy/_transport/binary/constants.py +80 -0
- zapy/_transport/binary/decoder.py +260 -0
- zapy/_transport/binary/encoder.py +279 -0
- zapy/_transport/binary/tokens.py +1289 -0
- zapy/_transport/comms.py +759 -0
- zapy/_transport/keepalive/__init__.py +3 -0
- zapy/_transport/keepalive/keep_alive.py +252 -0
- zapy/_transport/node/__init__.py +3 -0
- zapy/_transport/node/builders/__init__.py +9 -0
- zapy/_transport/node/builders/abprops.py +33 -0
- zapy/_transport/node/builders/account_sync.py +120 -0
- zapy/_transport/node/builders/bot.py +56 -0
- zapy/_transport/node/builders/business.py +261 -0
- zapy/_transport/node/builders/chatstate.py +74 -0
- zapy/_transport/node/builders/community.py +116 -0
- zapy/_transport/node/builders/device.py +30 -0
- zapy/_transport/node/builders/email.py +181 -0
- zapy/_transport/node/builders/global_.py +74 -0
- zapy/_transport/node/builders/group.py +279 -0
- zapy/_transport/node/builders/media.py +21 -0
- zapy/_transport/node/builders/message.py +436 -0
- zapy/_transport/node/builders/mobile.py +227 -0
- zapy/_transport/node/builders/newsletter.py +293 -0
- zapy/_transport/node/builders/offline.py +20 -0
- zapy/_transport/node/builders/pairing.py +130 -0
- zapy/_transport/node/builders/passive.py +28 -0
- zapy/_transport/node/builders/prekeys.py +215 -0
- zapy/_transport/node/builders/presence.py +100 -0
- zapy/_transport/node/builders/privacy.py +243 -0
- zapy/_transport/node/builders/privacy_token.py +94 -0
- zapy/_transport/node/builders/profile.py +176 -0
- zapy/_transport/node/builders/retry.py +156 -0
- zapy/_transport/node/builders/shortcake.py +87 -0
- zapy/_transport/node/builders/tos.py +92 -0
- zapy/_transport/node/builders/usync.py +185 -0
- zapy/_transport/node/helpers.py +201 -0
- zapy/_transport/node/orchestrator.py +210 -0
- zapy/_transport/node/query.py +82 -0
- zapy/_transport/node/transport.py +105 -0
- zapy/_transport/node/usync.py +33 -0
- zapy/_transport/node/xml.py +38 -0
- zapy/_transport/noise/__init__.py +7 -0
- zapy/_transport/noise/cert.py +85 -0
- zapy/_transport/noise/client_payload.py +344 -0
- zapy/_transport/noise/constants.py +12 -0
- zapy/_transport/noise/frame_codec.py +120 -0
- zapy/_transport/noise/handshake.py +92 -0
- zapy/_transport/noise/session.py +493 -0
- zapy/_transport/noise/socket.py +45 -0
- zapy/_transport/noise/types.py +66 -0
- zapy/_transport/noise/version.json +3 -0
- zapy/_transport/proxy.py +35 -0
- zapy/_transport/types.py +19 -0
- zapy/_transport/wa_version_fetcher.py +159 -0
- zapy/_transport/web_socket.py +602 -0
- zapy/_util/__init__.py +3 -0
- zapy/_util/bytes.py +131 -0
- zapy/_util/coercion.py +29 -0
- zapy/_util/collections.py +45 -0
- zapy/_util/primitives.py +49 -0
- zapy/client.py +840 -0
- zapy/errors.py +148 -0
- zapy/events.py +564 -0
- zapy/jid.py +140 -0
- zapy/py.typed +0 -0
- zapy/stores/__init__.py +50 -0
- zapy/stores/base.py +1627 -0
- zapy/stores/json_file.py +359 -0
- zapy/stores/memory.py +322 -0
- zapy/stores/sqlite.py +343 -0
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
"""WebSocket wrapper with failover, timeouts and stale-socket guards.
|
|
2
|
+
|
|
3
|
+
Mirrors ``src/transport/WaWebSocket.ts``. The underlying socket is created by
|
|
4
|
+
an injectable async factory (the default uses the ``websockets`` package);
|
|
5
|
+
tests inject fakes through the same seam.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import inspect
|
|
12
|
+
import time
|
|
13
|
+
from collections.abc import Awaitable, Callable
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Any, Protocol
|
|
16
|
+
|
|
17
|
+
from zapy._infra.log import Logger, get_logger
|
|
18
|
+
from zapy._protocol.defaults import CHAT_SOCKET_URLS
|
|
19
|
+
from zapy._protocol.nodes import WA_READY_STATES
|
|
20
|
+
from zapy._util.primitives import to_error
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class SocketOpenInfo:
|
|
25
|
+
"""When the socket opened (``Date.now()`` ms at success)."""
|
|
26
|
+
|
|
27
|
+
opened_at: float
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class SocketCloseInfo:
|
|
32
|
+
"""How a socket closed."""
|
|
33
|
+
|
|
34
|
+
code: int
|
|
35
|
+
reason: str
|
|
36
|
+
was_clean: bool
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class RawWebSocket(Protocol):
|
|
40
|
+
"""The surface WaWebSocket needs from any socket implementation."""
|
|
41
|
+
|
|
42
|
+
binary_type: str
|
|
43
|
+
onopen: Callable[..., Any] | None
|
|
44
|
+
onclose: Callable[..., Any] | None
|
|
45
|
+
onerror: Callable[..., Any] | None
|
|
46
|
+
onmessage: Callable[..., Any] | None
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def ready_state(self) -> int: ...
|
|
50
|
+
|
|
51
|
+
def close(self, code: int = 1000, reason: str = "") -> Any: ...
|
|
52
|
+
def send(self, data: bytes | str) -> Any: ...
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
RawWebSocketFactory = Callable[..., Awaitable[RawWebSocket]]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class WaSocketHandlers:
|
|
60
|
+
"""Lifecycle callbacks owned by ``WaComms``."""
|
|
61
|
+
|
|
62
|
+
on_open: Callable[[SocketOpenInfo], Awaitable[None] | None] | None = None
|
|
63
|
+
on_close: Callable[[SocketCloseInfo], Awaitable[None] | None] | None = None
|
|
64
|
+
on_error: Callable[[Exception], Awaitable[None] | None] | None = None
|
|
65
|
+
on_message: Callable[[bytes], Awaitable[None] | None] | None = None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass
|
|
69
|
+
class WaSocketConfig:
|
|
70
|
+
"""Connection settings (mirrors ``WaSocketConfig``)."""
|
|
71
|
+
|
|
72
|
+
url: str | None = None
|
|
73
|
+
urls: list[str] | None = None
|
|
74
|
+
protocols: list[str] | None = None
|
|
75
|
+
headers: dict[str, str] | None = None
|
|
76
|
+
dispatcher: Any | None = None
|
|
77
|
+
agent: Any | None = None
|
|
78
|
+
timeout_interval_ms: float = 10_000
|
|
79
|
+
raw_websocket_constructor: RawWebSocketFactory | None = None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _resolve_socket_urls(config: WaSocketConfig) -> list[str]:
|
|
83
|
+
if config.urls:
|
|
84
|
+
unique: list[str] = []
|
|
85
|
+
for url in config.urls:
|
|
86
|
+
if url not in unique:
|
|
87
|
+
unique.append(url)
|
|
88
|
+
return unique
|
|
89
|
+
if config.url:
|
|
90
|
+
return [config.url]
|
|
91
|
+
return list(CHAT_SOCKET_URLS)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class _PendingSocket:
|
|
95
|
+
def __init__(self, url: str, socket: RawWebSocket) -> None:
|
|
96
|
+
self.url = url
|
|
97
|
+
self.socket = socket
|
|
98
|
+
self.timer: asyncio.TimerHandle | None = None
|
|
99
|
+
self.settled = False
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class WaWebSocket:
|
|
103
|
+
"""Owns one logical socket across failover, timeouts and reconnects."""
|
|
104
|
+
|
|
105
|
+
def __init__(self, config: WaSocketConfig, logger: Logger | None = None) -> None:
|
|
106
|
+
self._config = config
|
|
107
|
+
self._socket_urls = _resolve_socket_urls(config)
|
|
108
|
+
self._logger = logger if logger is not None else get_logger(__name__)
|
|
109
|
+
self._factory = config.raw_websocket_constructor or _default_raw_socket_factory
|
|
110
|
+
self._handlers = WaSocketHandlers()
|
|
111
|
+
self._connecting_sockets: set[RawWebSocket] = set()
|
|
112
|
+
self._close_waiters: dict[int, list[Callable[[SocketCloseInfo], None]]] = {}
|
|
113
|
+
self._socket: RawWebSocket | None = None
|
|
114
|
+
self._socket_closing = False
|
|
115
|
+
|
|
116
|
+
def set_handlers(self, handlers: WaSocketHandlers) -> None:
|
|
117
|
+
self._handlers = handlers
|
|
118
|
+
|
|
119
|
+
def is_open(self) -> bool:
|
|
120
|
+
if self._socket is None:
|
|
121
|
+
return False
|
|
122
|
+
return self._socket.ready_state == WA_READY_STATES["OPEN"]
|
|
123
|
+
|
|
124
|
+
def is_connecting(self) -> bool:
|
|
125
|
+
if self._connecting_sockets:
|
|
126
|
+
return True
|
|
127
|
+
return (
|
|
128
|
+
self._socket is not None
|
|
129
|
+
and self._socket.ready_state == WA_READY_STATES["CONNECTING"]
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
async def open(self) -> SocketOpenInfo:
|
|
133
|
+
"""Connect; tries URLs in order (failover list races, first win stands)."""
|
|
134
|
+
if self.is_open():
|
|
135
|
+
self._logger.trace("socket open skipped: already open")
|
|
136
|
+
return SocketOpenInfo(opened_at=time.time() * 1000)
|
|
137
|
+
if self.is_connecting():
|
|
138
|
+
raise ValueError("websocket is already connecting")
|
|
139
|
+
self._logger.info("socket open start", {"urls": len(self._socket_urls)})
|
|
140
|
+
if len(self._socket_urls) == 1:
|
|
141
|
+
return await self._open_single(self._socket_urls[0])
|
|
142
|
+
return await self._open_concurrently(self._socket_urls)
|
|
143
|
+
|
|
144
|
+
async def close(self, code: int = 1000, reason: str = "") -> SocketCloseInfo | None:
|
|
145
|
+
"""Close the socket, resolving once the close handshake (or timeout) lands."""
|
|
146
|
+
self._logger.debug("socket close requested", {"code": code, "reason": reason})
|
|
147
|
+
socket = self._socket
|
|
148
|
+
if socket is None:
|
|
149
|
+
if self._connecting_sockets:
|
|
150
|
+
for pending in list(self._connecting_sockets):
|
|
151
|
+
self._close_socket_safe(pending, code, reason)
|
|
152
|
+
self._connecting_sockets.clear()
|
|
153
|
+
return SocketCloseInfo(code=code, reason=reason, was_clean=True)
|
|
154
|
+
return None
|
|
155
|
+
if socket.ready_state == WA_READY_STATES["CLOSED"]:
|
|
156
|
+
self._socket = None
|
|
157
|
+
return SocketCloseInfo(code=code, reason=reason, was_clean=True)
|
|
158
|
+
|
|
159
|
+
already_closing = self._socket_closing
|
|
160
|
+
self._socket_closing = True
|
|
161
|
+
loop = asyncio.get_running_loop()
|
|
162
|
+
future: asyncio.Future[SocketCloseInfo] = loop.create_future()
|
|
163
|
+
|
|
164
|
+
key = id(socket)
|
|
165
|
+
|
|
166
|
+
def waiter(info: SocketCloseInfo) -> None:
|
|
167
|
+
if not future.done():
|
|
168
|
+
future.set_result(info)
|
|
169
|
+
|
|
170
|
+
self._close_waiters.setdefault(key, []).append(waiter)
|
|
171
|
+
|
|
172
|
+
def on_timeout() -> None:
|
|
173
|
+
waiters = self._close_waiters.get(key)
|
|
174
|
+
if waiters and waiter in waiters:
|
|
175
|
+
waiters.remove(waiter)
|
|
176
|
+
if not waiters:
|
|
177
|
+
del self._close_waiters[key]
|
|
178
|
+
if not future.done():
|
|
179
|
+
future.set_result(
|
|
180
|
+
SocketCloseInfo(code=code, reason=reason, was_clean=False)
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
timer = loop.call_later(self._config.timeout_interval_ms / 1000, on_timeout)
|
|
184
|
+
|
|
185
|
+
def _done(_future: asyncio.Future[SocketCloseInfo]) -> None:
|
|
186
|
+
timer.cancel()
|
|
187
|
+
if self._socket is socket:
|
|
188
|
+
self._socket = None
|
|
189
|
+
|
|
190
|
+
future.add_done_callback(_done)
|
|
191
|
+
if already_closing:
|
|
192
|
+
return await future
|
|
193
|
+
try:
|
|
194
|
+
result = socket.close(code, reason)
|
|
195
|
+
if inspect.isawaitable(result):
|
|
196
|
+
await result
|
|
197
|
+
except Exception as error:
|
|
198
|
+
self._settle_close_waiters(
|
|
199
|
+
socket, SocketCloseInfo(code=code, reason=reason, was_clean=False)
|
|
200
|
+
)
|
|
201
|
+
handler = self._handlers.on_error
|
|
202
|
+
if handler is not None:
|
|
203
|
+
self._fire_handler(handler(to_error(error)))
|
|
204
|
+
return await future
|
|
205
|
+
|
|
206
|
+
async def send(self, data: bytes | str) -> None:
|
|
207
|
+
"""Send binary (or text) on the open socket."""
|
|
208
|
+
socket = self._socket
|
|
209
|
+
if socket is None or socket.ready_state != WA_READY_STATES["OPEN"]:
|
|
210
|
+
raise ValueError("websocket is not connected")
|
|
211
|
+
result = socket.send(data)
|
|
212
|
+
if inspect.isawaitable(result):
|
|
213
|
+
await result
|
|
214
|
+
|
|
215
|
+
async def _open_single(self, url: str) -> SocketOpenInfo:
|
|
216
|
+
pending = await self._create_pending_socket(url)
|
|
217
|
+
loop = asyncio.get_running_loop()
|
|
218
|
+
future: asyncio.Future[SocketOpenInfo] = loop.create_future()
|
|
219
|
+
|
|
220
|
+
def on_open() -> None:
|
|
221
|
+
if not self._settle_pending_socket(pending):
|
|
222
|
+
return
|
|
223
|
+
future_settled = future.done()
|
|
224
|
+
info = self._activate_pending_socket(pending, "socket open success")
|
|
225
|
+
if not future_settled:
|
|
226
|
+
future.set_result(info)
|
|
227
|
+
|
|
228
|
+
def on_fail(error: Exception) -> None:
|
|
229
|
+
if not self._settle_pending_socket(pending):
|
|
230
|
+
return
|
|
231
|
+
if self._socket is pending.socket:
|
|
232
|
+
self._socket = None
|
|
233
|
+
if not future.done():
|
|
234
|
+
future.set_exception(error)
|
|
235
|
+
|
|
236
|
+
self._bind_pending_socket(pending, on_open, on_fail)
|
|
237
|
+
self._maybe_fire_open(pending, on_open)
|
|
238
|
+
return await future
|
|
239
|
+
|
|
240
|
+
async def _open_concurrently(self, urls: list[str]) -> SocketOpenInfo:
|
|
241
|
+
results = await asyncio.gather(
|
|
242
|
+
*(self._create_pending_socket(url) for url in urls), return_exceptions=True
|
|
243
|
+
)
|
|
244
|
+
pending_sockets: list[_PendingSocket] = []
|
|
245
|
+
setup_error: Exception | None = None
|
|
246
|
+
for result in results:
|
|
247
|
+
if isinstance(result, BaseException):
|
|
248
|
+
if setup_error is None:
|
|
249
|
+
setup_error = to_error(result)
|
|
250
|
+
continue
|
|
251
|
+
pending_sockets.append(result)
|
|
252
|
+
if setup_error is not None:
|
|
253
|
+
for entry in pending_sockets:
|
|
254
|
+
if self._settle_pending_socket(entry):
|
|
255
|
+
self._close_socket_safe(entry.socket, 1000, "connect_setup_failed")
|
|
256
|
+
raise setup_error
|
|
257
|
+
|
|
258
|
+
loop = asyncio.get_running_loop()
|
|
259
|
+
future: asyncio.Future[SocketOpenInfo] = loop.create_future()
|
|
260
|
+
done = False
|
|
261
|
+
failed_count = 0
|
|
262
|
+
last_error: Exception | None = None
|
|
263
|
+
|
|
264
|
+
def fail(entry: _PendingSocket, error: Exception) -> None:
|
|
265
|
+
nonlocal done, failed_count, last_error
|
|
266
|
+
if done or not self._settle_pending_socket(entry):
|
|
267
|
+
return
|
|
268
|
+
failed_count += 1
|
|
269
|
+
last_error = error
|
|
270
|
+
if failed_count == len(pending_sockets) and not future.done():
|
|
271
|
+
done = True
|
|
272
|
+
if last_error is not None:
|
|
273
|
+
future.set_exception(last_error)
|
|
274
|
+
else:
|
|
275
|
+
future.set_exception(ValueError("websocket connect error"))
|
|
276
|
+
|
|
277
|
+
def win(entry: _PendingSocket) -> None:
|
|
278
|
+
nonlocal done
|
|
279
|
+
if not self._settle_pending_socket(entry):
|
|
280
|
+
return
|
|
281
|
+
if done:
|
|
282
|
+
self._close_socket_safe(entry.socket, 1000, "loser_socket")
|
|
283
|
+
return
|
|
284
|
+
done = True
|
|
285
|
+
for other in pending_sockets:
|
|
286
|
+
if other.socket is entry.socket:
|
|
287
|
+
continue
|
|
288
|
+
if self._settle_pending_socket(other):
|
|
289
|
+
self._close_socket_safe(other.socket, 1000, "loser_socket")
|
|
290
|
+
info = self._activate_pending_socket(
|
|
291
|
+
entry, "socket open success (race winner)"
|
|
292
|
+
)
|
|
293
|
+
if not future.done():
|
|
294
|
+
future.set_result(info)
|
|
295
|
+
|
|
296
|
+
for entry in pending_sockets:
|
|
297
|
+
def _win(entry: _PendingSocket = entry) -> None:
|
|
298
|
+
win(entry)
|
|
299
|
+
|
|
300
|
+
def _fail(error: Exception, entry: _PendingSocket = entry) -> None:
|
|
301
|
+
fail(entry, error)
|
|
302
|
+
|
|
303
|
+
self._bind_pending_socket(entry, on_open=_win, on_fail=_fail)
|
|
304
|
+
self._maybe_fire_open(entry, _win)
|
|
305
|
+
return await future
|
|
306
|
+
|
|
307
|
+
async def _create_pending_socket(self, url: str) -> _PendingSocket:
|
|
308
|
+
socket = await self._factory(
|
|
309
|
+
url,
|
|
310
|
+
protocols=self._config.protocols,
|
|
311
|
+
headers=self._config.headers,
|
|
312
|
+
dispatcher=self._config.dispatcher,
|
|
313
|
+
agent=self._config.agent,
|
|
314
|
+
)
|
|
315
|
+
socket.binary_type = "arraybuffer"
|
|
316
|
+
self._connecting_sockets.add(socket)
|
|
317
|
+
return _PendingSocket(url=url, socket=socket)
|
|
318
|
+
|
|
319
|
+
def _maybe_fire_open(
|
|
320
|
+
self, entry: _PendingSocket, on_open: Callable[[], None]
|
|
321
|
+
) -> None:
|
|
322
|
+
if entry.settled:
|
|
323
|
+
return
|
|
324
|
+
if entry.socket.ready_state == WA_READY_STATES["OPEN"]:
|
|
325
|
+
on_open()
|
|
326
|
+
|
|
327
|
+
def _bind_pending_socket(
|
|
328
|
+
self,
|
|
329
|
+
entry: _PendingSocket,
|
|
330
|
+
on_open: Callable[[], None],
|
|
331
|
+
on_fail: Callable[[Exception], None],
|
|
332
|
+
) -> None:
|
|
333
|
+
loop = asyncio.get_running_loop()
|
|
334
|
+
|
|
335
|
+
def on_timeout() -> None:
|
|
336
|
+
self._logger.warn("socket connect timeout", {"url": entry.url})
|
|
337
|
+
self._close_socket_safe(entry.socket, 4000, "connect_timeout")
|
|
338
|
+
on_fail(ValueError(f"websocket connect timeout for {entry.url}"))
|
|
339
|
+
|
|
340
|
+
entry.timer = loop.call_later(
|
|
341
|
+
self._config.timeout_interval_ms / 1000, on_timeout
|
|
342
|
+
)
|
|
343
|
+
entry.socket.onopen = on_open
|
|
344
|
+
|
|
345
|
+
def _on_error() -> None:
|
|
346
|
+
self._handle_pending_error(entry, on_fail)
|
|
347
|
+
|
|
348
|
+
entry.socket.onerror = _on_error
|
|
349
|
+
def _on_close(event: object) -> None:
|
|
350
|
+
self._handle_pending_close(entry, event, on_fail)
|
|
351
|
+
|
|
352
|
+
entry.socket.onclose = _on_close
|
|
353
|
+
|
|
354
|
+
def _handle_pending_error(
|
|
355
|
+
self, entry: _PendingSocket, on_fail: Callable[[Exception], None]
|
|
356
|
+
) -> None:
|
|
357
|
+
if entry.settled:
|
|
358
|
+
self._logger.trace("settled pending socket error", {"url": entry.url})
|
|
359
|
+
else:
|
|
360
|
+
self._logger.warn("socket open error", {"url": entry.url})
|
|
361
|
+
on_fail(ValueError(f"websocket connect error for {entry.url}"))
|
|
362
|
+
|
|
363
|
+
def _handle_pending_close(
|
|
364
|
+
self, entry: _PendingSocket, event: Any, on_fail: Callable[[Exception], None]
|
|
365
|
+
) -> None:
|
|
366
|
+
info = self._to_close_info(event)
|
|
367
|
+
if entry.settled:
|
|
368
|
+
self._logger.trace(
|
|
369
|
+
"settled pending socket closed",
|
|
370
|
+
{"url": entry.url, "code": info.code, "reason": info.reason},
|
|
371
|
+
)
|
|
372
|
+
else:
|
|
373
|
+
self._logger.warn(
|
|
374
|
+
"socket closed before open",
|
|
375
|
+
{"url": entry.url, "code": info.code, "reason": info.reason},
|
|
376
|
+
)
|
|
377
|
+
on_fail(
|
|
378
|
+
ValueError(
|
|
379
|
+
f"websocket closed before open ({info.code}:{info.reason})"
|
|
380
|
+
f" for {entry.url}"
|
|
381
|
+
)
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
def _settle_pending_socket(self, entry: _PendingSocket) -> bool:
|
|
385
|
+
if entry.settled:
|
|
386
|
+
return False
|
|
387
|
+
entry.settled = True
|
|
388
|
+
if entry.timer is not None:
|
|
389
|
+
entry.timer.cancel()
|
|
390
|
+
entry.timer = None
|
|
391
|
+
self._connecting_sockets.discard(entry.socket)
|
|
392
|
+
return True
|
|
393
|
+
|
|
394
|
+
def _activate_pending_socket(
|
|
395
|
+
self, entry: _PendingSocket, message: str
|
|
396
|
+
) -> SocketOpenInfo:
|
|
397
|
+
info = SocketOpenInfo(opened_at=time.time() * 1000)
|
|
398
|
+
self._socket = entry.socket
|
|
399
|
+
self._socket_closing = False
|
|
400
|
+
self._bind_runtime_handlers(entry.socket)
|
|
401
|
+
self._logger.info(message, {"url": entry.url})
|
|
402
|
+
handler = self._handlers.on_open
|
|
403
|
+
if handler is not None:
|
|
404
|
+
self._fire_handler(handler(info))
|
|
405
|
+
return info
|
|
406
|
+
|
|
407
|
+
def _bind_runtime_handlers(self, socket: RawWebSocket) -> None:
|
|
408
|
+
def _on_message(data: object) -> None:
|
|
409
|
+
self._fire_handler(self._handle_message(socket, data))
|
|
410
|
+
|
|
411
|
+
def _on_error(_event: object) -> None:
|
|
412
|
+
self._handle_runtime_error(socket)
|
|
413
|
+
|
|
414
|
+
def _on_close(event: object) -> None:
|
|
415
|
+
self._handle_runtime_close(socket, event)
|
|
416
|
+
|
|
417
|
+
socket.onmessage = _on_message
|
|
418
|
+
socket.onerror = _on_error
|
|
419
|
+
socket.onclose = _on_close
|
|
420
|
+
|
|
421
|
+
def _is_deliverable(self, socket: RawWebSocket) -> bool:
|
|
422
|
+
return self._socket is socket and not self._socket_closing
|
|
423
|
+
|
|
424
|
+
async def _handle_message(self, socket: RawWebSocket, data: Any) -> None:
|
|
425
|
+
try:
|
|
426
|
+
payload = await self._normalize_payload(data)
|
|
427
|
+
if payload is None:
|
|
428
|
+
self._logger.trace("socket message ignored: unsupported payload shape")
|
|
429
|
+
return
|
|
430
|
+
if not self._is_deliverable(socket):
|
|
431
|
+
self._logger.trace("socket message ignored: stale or closing socket")
|
|
432
|
+
return
|
|
433
|
+
on_message = self._handlers.on_message
|
|
434
|
+
if on_message is not None:
|
|
435
|
+
await _maybe_await(on_message(payload))
|
|
436
|
+
except Exception as error:
|
|
437
|
+
normalized = to_error(error)
|
|
438
|
+
self._logger.error(
|
|
439
|
+
"socket message handling failed", {"message": str(normalized)}
|
|
440
|
+
)
|
|
441
|
+
on_error = self._handlers.on_error
|
|
442
|
+
if on_error is not None:
|
|
443
|
+
self._fire_handler(on_error(normalized))
|
|
444
|
+
|
|
445
|
+
async def _normalize_payload(self, data: Any) -> bytes | None:
|
|
446
|
+
if isinstance(data, bytes):
|
|
447
|
+
return data
|
|
448
|
+
if isinstance(data, bytearray):
|
|
449
|
+
return bytes(data)
|
|
450
|
+
if isinstance(data, memoryview):
|
|
451
|
+
return data.tobytes()
|
|
452
|
+
if isinstance(data, str):
|
|
453
|
+
return data.encode("utf-8")
|
|
454
|
+
if hasattr(data, "array_buffer") and callable(data.array_buffer):
|
|
455
|
+
buffer = await data.array_buffer()
|
|
456
|
+
if isinstance(buffer, (bytes, bytearray, memoryview)):
|
|
457
|
+
return bytes(buffer)
|
|
458
|
+
return None
|
|
459
|
+
return None
|
|
460
|
+
|
|
461
|
+
def _handle_runtime_error(self, socket: RawWebSocket) -> None:
|
|
462
|
+
if socket is not self._socket:
|
|
463
|
+
self._logger.trace("socket runtime error ignored: stale socket")
|
|
464
|
+
return
|
|
465
|
+
self._logger.warn("socket runtime error event")
|
|
466
|
+
handler = self._handlers.on_error
|
|
467
|
+
if handler is not None:
|
|
468
|
+
self._fire_handler(handler(ValueError("websocket runtime error")))
|
|
469
|
+
|
|
470
|
+
def _handle_runtime_close(self, socket: RawWebSocket, event: Any) -> None:
|
|
471
|
+
info = self._to_close_info(event)
|
|
472
|
+
if socket is not self._socket:
|
|
473
|
+
self._logger.debug(
|
|
474
|
+
"stale socket closed",
|
|
475
|
+
{"code": info.code, "reason": info.reason, "wasClean": info.was_clean},
|
|
476
|
+
)
|
|
477
|
+
self._settle_close_waiters(socket, info)
|
|
478
|
+
return
|
|
479
|
+
self._logger.info(
|
|
480
|
+
"socket runtime closed",
|
|
481
|
+
{"code": info.code, "reason": info.reason, "wasClean": info.was_clean},
|
|
482
|
+
)
|
|
483
|
+
self._socket = None
|
|
484
|
+
self._settle_close_waiters(socket, info)
|
|
485
|
+
handler = self._handlers.on_close
|
|
486
|
+
if handler is not None:
|
|
487
|
+
self._fire_handler(handler(info))
|
|
488
|
+
|
|
489
|
+
def _to_close_info(self, event: Any) -> SocketCloseInfo:
|
|
490
|
+
if isinstance(event, dict):
|
|
491
|
+
code = event.get("code")
|
|
492
|
+
reason = event.get("reason")
|
|
493
|
+
was_clean = event.get("was_clean", event.get("wasClean", False))
|
|
494
|
+
else:
|
|
495
|
+
code = getattr(event, "code", None)
|
|
496
|
+
reason = getattr(event, "reason", None)
|
|
497
|
+
was_clean = getattr(event, "was_clean", getattr(event, "wasClean", False))
|
|
498
|
+
return SocketCloseInfo(
|
|
499
|
+
code=code if isinstance(code, int) else 1000,
|
|
500
|
+
reason=reason if isinstance(reason, str) else "",
|
|
501
|
+
was_clean=was_clean is True,
|
|
502
|
+
)
|
|
503
|
+
|
|
504
|
+
def _settle_close_waiters(
|
|
505
|
+
self, socket: RawWebSocket, info: SocketCloseInfo
|
|
506
|
+
) -> None:
|
|
507
|
+
waiters = self._close_waiters.pop(id(socket), None)
|
|
508
|
+
if not waiters:
|
|
509
|
+
return
|
|
510
|
+
for waiter in waiters:
|
|
511
|
+
waiter(info)
|
|
512
|
+
|
|
513
|
+
def _close_socket_safe(self, socket: RawWebSocket, code: int, reason: str) -> None:
|
|
514
|
+
try:
|
|
515
|
+
result = socket.close(code, reason)
|
|
516
|
+
if inspect.isawaitable(result):
|
|
517
|
+
asyncio.ensure_future(result)
|
|
518
|
+
except Exception as error:
|
|
519
|
+
self._logger.trace(
|
|
520
|
+
"socket close ignored",
|
|
521
|
+
{"code": code, "reason": reason, "message": str(to_error(error))},
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
def _fire_handler(self, awaitable: Any) -> None:
|
|
525
|
+
if inspect.isawaitable(awaitable):
|
|
526
|
+
asyncio.ensure_future(awaitable)
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
async def _maybe_await(value: Any) -> Any:
|
|
530
|
+
if inspect.isawaitable(value):
|
|
531
|
+
return await value
|
|
532
|
+
return value
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
async def _default_raw_socket_factory(
|
|
536
|
+
url: str,
|
|
537
|
+
protocols: list[str] | None = None,
|
|
538
|
+
headers: dict[str, str] | None = None,
|
|
539
|
+
dispatcher: Any = None,
|
|
540
|
+
agent: Any = None,
|
|
541
|
+
) -> RawWebSocket:
|
|
542
|
+
"""Open a real socket with the ``websockets`` package."""
|
|
543
|
+
from websockets.asyncio.client import connect
|
|
544
|
+
|
|
545
|
+
extra: dict[str, Any] = {}
|
|
546
|
+
if protocols:
|
|
547
|
+
extra["subprotocols"] = protocols
|
|
548
|
+
if headers:
|
|
549
|
+
extra["additional_headers"] = headers
|
|
550
|
+
connection = await connect(url, **extra)
|
|
551
|
+
return _WebsocketsAdapter(connection)
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
class _WebsocketsAdapter:
|
|
555
|
+
"""Adapts a ``websockets`` client connection to the raw-socket surface."""
|
|
556
|
+
|
|
557
|
+
def __init__(self, connection: Any) -> None:
|
|
558
|
+
self._connection = connection
|
|
559
|
+
self.binary_type = "arraybuffer"
|
|
560
|
+
self.onopen: Callable[[], None] | None = None
|
|
561
|
+
self.onclose: Callable[[dict[str, Any]], None] | None = None
|
|
562
|
+
self.onerror: Callable[[], None] | None = None
|
|
563
|
+
self.onmessage: Callable[[Any], None] | None = None
|
|
564
|
+
self._recv_task: asyncio.Task[None] | None = None
|
|
565
|
+
|
|
566
|
+
@property
|
|
567
|
+
def ready_state(self) -> int:
|
|
568
|
+
return int(self._connection.state.value)
|
|
569
|
+
|
|
570
|
+
def _ensure_recv_loop(self) -> None:
|
|
571
|
+
if self._recv_task is None:
|
|
572
|
+
self._recv_task = asyncio.ensure_future(self._recv_loop())
|
|
573
|
+
|
|
574
|
+
async def _recv_loop(self) -> None:
|
|
575
|
+
try:
|
|
576
|
+
async for message in self._connection:
|
|
577
|
+
on_message = self.onmessage
|
|
578
|
+
if on_message is not None:
|
|
579
|
+
on_message(message)
|
|
580
|
+
except Exception:
|
|
581
|
+
on_error = self.onerror
|
|
582
|
+
if on_error is not None:
|
|
583
|
+
on_error()
|
|
584
|
+
finally:
|
|
585
|
+
code = getattr(self._connection, "close_code", None)
|
|
586
|
+
reason = getattr(self._connection, "close_reason", None) or ""
|
|
587
|
+
on_close = self.onclose
|
|
588
|
+
if on_close is not None:
|
|
589
|
+
on_close(
|
|
590
|
+
{"code": code, "reason": reason, "was_clean": code == 1000}
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
def close(self, code: int = 1000, reason: str = "") -> Any:
|
|
594
|
+
return self._connection.close(code, reason)
|
|
595
|
+
|
|
596
|
+
def send(self, data: bytes | str) -> Any:
|
|
597
|
+
return self._connection.send(data)
|
|
598
|
+
|
|
599
|
+
def __setattr__(self, name: str, value: Any) -> None:
|
|
600
|
+
object.__setattr__(self, name, value)
|
|
601
|
+
if name in ("onmessage", "onclose", "onerror") and value is not None:
|
|
602
|
+
self._ensure_recv_loop()
|
zapy/_util/__init__.py
ADDED