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
zapy/_transport/comms.py
ADDED
|
@@ -0,0 +1,759 @@
|
|
|
1
|
+
"""WebSocket + Noise handshake lifecycle (mirrors ``src/transport/WaComms.ts``).
|
|
2
|
+
|
|
3
|
+
Owns the socket, drives the Noise pairing/login exchange, persists
|
|
4
|
+
routing-info/server-static updates, and delivers post-handshake binary
|
|
5
|
+
frames to the stanza handler.
|
|
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
|
|
16
|
+
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
|
|
17
|
+
|
|
18
|
+
from zapy._infra.log import Logger, get_logger
|
|
19
|
+
from zapy._infra.perf import BoundedTaskQueue, BoundedTaskQueueFullError
|
|
20
|
+
from zapy._protocol import defaults as _defaults
|
|
21
|
+
from zapy._transport.noise.session import WaNoiseSession
|
|
22
|
+
from zapy._transport.noise.types import WaNoiseConfig
|
|
23
|
+
from zapy._transport.web_socket import (
|
|
24
|
+
SocketCloseInfo,
|
|
25
|
+
SocketOpenInfo,
|
|
26
|
+
WaSocketConfig,
|
|
27
|
+
WaSocketHandlers,
|
|
28
|
+
WaWebSocket,
|
|
29
|
+
)
|
|
30
|
+
from zapy._util.bytes import bytes_to_base64_urlsafe
|
|
31
|
+
from zapy._util.primitives import to_error
|
|
32
|
+
|
|
33
|
+
_FRAME_HANDLER_QUEUE_MAX_SIZE = 4096
|
|
34
|
+
_FRAME_HANDLER_MAX_CONCURRENCY = 8
|
|
35
|
+
_PENDING_FRAMES_MAX_COUNT = 2048
|
|
36
|
+
_PENDING_FRAMES_MAX_BYTES = 16 * 1024 * 1024
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class WaCommsState:
|
|
41
|
+
"""Snapshot of the connection state."""
|
|
42
|
+
|
|
43
|
+
started: bool = False
|
|
44
|
+
connected: bool = False
|
|
45
|
+
handling_requests: bool = False
|
|
46
|
+
reconnect_attempts: int = 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class WaCommsConfig:
|
|
51
|
+
"""Comms configuration (mirrors ``WaCommsConfig``)."""
|
|
52
|
+
|
|
53
|
+
noise: WaNoiseConfig
|
|
54
|
+
url: str | None = None
|
|
55
|
+
urls: list[str] | None = None
|
|
56
|
+
protocols: list[str] | None = None
|
|
57
|
+
headers: dict[str, str] | None = None
|
|
58
|
+
dispatcher: Any | None = None
|
|
59
|
+
agent: Any | None = None
|
|
60
|
+
timeout_interval_ms: float = 10_000
|
|
61
|
+
connect_timeout_ms: float = 10_000
|
|
62
|
+
reconnect_interval_ms: float = 2_000
|
|
63
|
+
max_reconnect_attempts: int | None = None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
StanzaHandler = Callable[[bytes], Awaitable[None] | None]
|
|
67
|
+
InflateFrame = Callable[[bytes], Awaitable[bytes] | bytes]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class _ConnectionWaiter:
|
|
72
|
+
future: asyncio.Future[None]
|
|
73
|
+
timer: asyncio.TimerHandle
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class WaComms:
|
|
77
|
+
"""Manages one logical WhatsApp Web connection over Noise+WebSocket."""
|
|
78
|
+
|
|
79
|
+
def __init__(self, config: WaCommsConfig, logger: Logger | None = None) -> None:
|
|
80
|
+
if config.noise is None:
|
|
81
|
+
raise ValueError("WaComms requires noise config")
|
|
82
|
+
self._config = self._apply_routing_info_to_socket_config(config)
|
|
83
|
+
self._logger = (
|
|
84
|
+
logger if logger is not None else get_logger("zapy._transport.comms")
|
|
85
|
+
)
|
|
86
|
+
self._socket = WaWebSocket(
|
|
87
|
+
WaSocketConfig(
|
|
88
|
+
url=self._config.url,
|
|
89
|
+
urls=self._config.urls,
|
|
90
|
+
protocols=self._config.protocols,
|
|
91
|
+
dispatcher=self._config.dispatcher,
|
|
92
|
+
agent=self._config.agent,
|
|
93
|
+
headers=self._config.headers,
|
|
94
|
+
timeout_interval_ms=self._config.timeout_interval_ms,
|
|
95
|
+
raw_websocket_constructor=None,
|
|
96
|
+
),
|
|
97
|
+
self._logger,
|
|
98
|
+
)
|
|
99
|
+
self._socket.set_handlers(
|
|
100
|
+
WaSocketHandlers(
|
|
101
|
+
on_open=self._handle_open_wrapper,
|
|
102
|
+
on_close=self._on_socket_closed,
|
|
103
|
+
on_error=self._on_socket_error,
|
|
104
|
+
on_message=self._on_socket_message,
|
|
105
|
+
)
|
|
106
|
+
)
|
|
107
|
+
self._started = False
|
|
108
|
+
self._connected = False
|
|
109
|
+
self._handling_requests = False
|
|
110
|
+
self._prevent_retry = False
|
|
111
|
+
self._reconnect_attempts = 0
|
|
112
|
+
self._reconnect_timer: asyncio.TimerHandle | None = None
|
|
113
|
+
self._waiters: list[_ConnectionWaiter] = []
|
|
114
|
+
self._stanza_handler: StanzaHandler | None = None
|
|
115
|
+
self._inflate_frame: InflateFrame | None = None
|
|
116
|
+
self._pending_frames: list[bytes] = []
|
|
117
|
+
self._pending_frames_byte_length = 0
|
|
118
|
+
self._pending_frames_overflow_closing = False
|
|
119
|
+
self._resume_in_flight = False
|
|
120
|
+
self._resume_handshake_failures = 0
|
|
121
|
+
self._server_restart_hold: Callable[[], None] | None = None
|
|
122
|
+
self._connection_generation = 0
|
|
123
|
+
self._noise_session: WaNoiseSession | None = None
|
|
124
|
+
self._last_server_static_key: bytes | None = None
|
|
125
|
+
self._last_inbound_at_ms = 0.0
|
|
126
|
+
self._frame_lock = asyncio.Lock()
|
|
127
|
+
self._frame_handler_queue = BoundedTaskQueue(
|
|
128
|
+
_FRAME_HANDLER_QUEUE_MAX_SIZE, _FRAME_HANDLER_MAX_CONCURRENCY
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def _apply_routing_info_to_socket_config(config: WaCommsConfig) -> WaCommsConfig:
|
|
133
|
+
routing_info = config.noise.routing_info if config.noise else None
|
|
134
|
+
if not routing_info:
|
|
135
|
+
return config
|
|
136
|
+
ed_value = bytes_to_base64_urlsafe(bytes(routing_info))
|
|
137
|
+
|
|
138
|
+
def append_ed(url: str) -> str:
|
|
139
|
+
try:
|
|
140
|
+
parsed = urlparse(url)
|
|
141
|
+
query = dict(parse_qsl(parsed.query, keep_blank_values=True))
|
|
142
|
+
if "ED" not in query:
|
|
143
|
+
query["ED"] = ed_value
|
|
144
|
+
parsed = parsed._replace(query=urlencode(query))
|
|
145
|
+
return urlunparse(parsed)
|
|
146
|
+
except ValueError:
|
|
147
|
+
if "ED=" in url:
|
|
148
|
+
return url
|
|
149
|
+
separator = "&" if "?" in url else "?"
|
|
150
|
+
return f"{url}{separator}ED={ed_value}"
|
|
151
|
+
|
|
152
|
+
headers = dict(config.headers) if config.headers else {}
|
|
153
|
+
sticky = headers.get("Cookie", headers.get("cookie", ""))
|
|
154
|
+
headers.pop("cookie", None)
|
|
155
|
+
if "sticky_routing=" not in sticky:
|
|
156
|
+
if sticky:
|
|
157
|
+
headers["Cookie"] = f"{sticky}; sticky_routing="
|
|
158
|
+
else:
|
|
159
|
+
headers["Cookie"] = "sticky_routing="
|
|
160
|
+
if config.urls:
|
|
161
|
+
urls: list[str] | None = [append_ed(entry) for entry in config.urls]
|
|
162
|
+
elif config.url is None:
|
|
163
|
+
urls = [append_ed(entry) for entry in _defaults.CHAT_SOCKET_URLS]
|
|
164
|
+
else:
|
|
165
|
+
urls = None
|
|
166
|
+
return WaCommsConfig(
|
|
167
|
+
noise=config.noise,
|
|
168
|
+
url=append_ed(config.url) if config.url else config.url,
|
|
169
|
+
urls=urls,
|
|
170
|
+
protocols=config.protocols,
|
|
171
|
+
headers=headers,
|
|
172
|
+
dispatcher=config.dispatcher,
|
|
173
|
+
agent=config.agent,
|
|
174
|
+
timeout_interval_ms=config.timeout_interval_ms,
|
|
175
|
+
connect_timeout_ms=config.connect_timeout_ms,
|
|
176
|
+
reconnect_interval_ms=config.reconnect_interval_ms,
|
|
177
|
+
max_reconnect_attempts=config.max_reconnect_attempts,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
def start_comms(
|
|
181
|
+
self, handle_stanza: StanzaHandler, inflate_frame: InflateFrame | None = None
|
|
182
|
+
) -> None:
|
|
183
|
+
"""Begin connecting; frames flow to ``handle_stanza`` once requested."""
|
|
184
|
+
self._logger.debug("comms start requested")
|
|
185
|
+
self._stanza_handler = handle_stanza
|
|
186
|
+
self._inflate_frame = inflate_frame
|
|
187
|
+
self.clear_pending_frames()
|
|
188
|
+
self._pending_frames_overflow_closing = False
|
|
189
|
+
self._started = True
|
|
190
|
+
self._prevent_retry = False
|
|
191
|
+
self._connected = self._socket.is_open()
|
|
192
|
+
self._handling_requests = False
|
|
193
|
+
self._clear_reconnect_timer()
|
|
194
|
+
asyncio.ensure_future(self._open_socket(False))
|
|
195
|
+
|
|
196
|
+
async def wait_for_connection(self, timeout_ms: float | None = None) -> None:
|
|
197
|
+
"""Wait until the noise session is established (or time out)."""
|
|
198
|
+
wait_ms = (
|
|
199
|
+
timeout_ms if timeout_ms is not None else self._config.connect_timeout_ms
|
|
200
|
+
)
|
|
201
|
+
if not self._started:
|
|
202
|
+
raise ValueError("comms not started")
|
|
203
|
+
if self._connected:
|
|
204
|
+
self._logger.trace("comms waitForConnection immediate success")
|
|
205
|
+
return
|
|
206
|
+
self._logger.debug("comms waiting for connection", {"timeoutMs": wait_ms})
|
|
207
|
+
loop = asyncio.get_running_loop()
|
|
208
|
+
future: asyncio.Future[None] = loop.create_future()
|
|
209
|
+
|
|
210
|
+
def on_timeout() -> None:
|
|
211
|
+
self._remove_waiter(future)
|
|
212
|
+
if not future.done():
|
|
213
|
+
future.set_exception(
|
|
214
|
+
TimeoutError(f"comms connection timeout after {wait_ms}ms")
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
timer = loop.call_later(wait_ms / 1000, on_timeout)
|
|
218
|
+
self._waiters.append(_ConnectionWaiter(future=future, timer=timer))
|
|
219
|
+
await future
|
|
220
|
+
|
|
221
|
+
def start_handling_requests(self) -> None:
|
|
222
|
+
"""Start delivering queued + live frames to the stanza handler."""
|
|
223
|
+
self._handling_requests = True
|
|
224
|
+
self._logger.debug("comms request handling enabled")
|
|
225
|
+
asyncio.ensure_future(self._flush_pending_frames())
|
|
226
|
+
|
|
227
|
+
async def stop_comms(self) -> None:
|
|
228
|
+
"""Stop everything; pending waiters are rejected."""
|
|
229
|
+
self._logger.debug("comms stop requested")
|
|
230
|
+
self._reset_connection_state(
|
|
231
|
+
started=False,
|
|
232
|
+
connected=False,
|
|
233
|
+
handling_requests=False,
|
|
234
|
+
prevent_retry=True,
|
|
235
|
+
resume_in_flight=False,
|
|
236
|
+
clear_handlers=True,
|
|
237
|
+
reject_waiters_error=ConnectionError("comms stopped"),
|
|
238
|
+
)
|
|
239
|
+
await self._socket.close(1000, "stop_comms")
|
|
240
|
+
|
|
241
|
+
def hold_for_server_restart(self, on_closed: Callable[[], None]) -> None:
|
|
242
|
+
"""Hand the next close to ``on_closed`` instead of scheduling a reconnect."""
|
|
243
|
+
self._server_restart_hold = on_closed
|
|
244
|
+
|
|
245
|
+
async def close_socket_and_resume(self) -> None:
|
|
246
|
+
"""Close the socket and reopen it, preserving the request state."""
|
|
247
|
+
if not self._started or self._prevent_retry:
|
|
248
|
+
self._logger.debug("comms resume skipped: comms stopped or retry disabled")
|
|
249
|
+
return
|
|
250
|
+
if self._resume_in_flight:
|
|
251
|
+
self._logger.debug("comms resume skipped: already in flight")
|
|
252
|
+
return
|
|
253
|
+
self._logger.debug("comms close socket and resume requested")
|
|
254
|
+
self._reset_connection_state(
|
|
255
|
+
started=True,
|
|
256
|
+
connected=False,
|
|
257
|
+
handling_requests=self._handling_requests,
|
|
258
|
+
prevent_retry=False,
|
|
259
|
+
resume_in_flight=True,
|
|
260
|
+
)
|
|
261
|
+
await self._socket.close(1000, "resume_socket")
|
|
262
|
+
if not self._resume_in_flight:
|
|
263
|
+
self._logger.debug("comms resume cancelled while closing socket")
|
|
264
|
+
return
|
|
265
|
+
self._resume_in_flight = False
|
|
266
|
+
asyncio.ensure_future(self._open_socket(True))
|
|
267
|
+
|
|
268
|
+
async def close_socket_and_prevent_retry(self) -> None:
|
|
269
|
+
"""Close the socket and stop reconnecting."""
|
|
270
|
+
self._logger.warn("comms close socket and prevent retry requested")
|
|
271
|
+
self._reset_connection_state(
|
|
272
|
+
started=False,
|
|
273
|
+
connected=False,
|
|
274
|
+
handling_requests=False,
|
|
275
|
+
prevent_retry=True,
|
|
276
|
+
resume_in_flight=False,
|
|
277
|
+
reject_waiters_error=ConnectionError("socket closed and retry disabled"),
|
|
278
|
+
)
|
|
279
|
+
await self._socket.close(1000, "prevent_retry")
|
|
280
|
+
|
|
281
|
+
async def send_frame(self, payload: bytes | bytearray) -> None:
|
|
282
|
+
"""Encrypt ``payload`` through the Noise session and write it to the socket."""
|
|
283
|
+
session = self._noise_session
|
|
284
|
+
if session is None:
|
|
285
|
+
raise ValueError("noise session not ready")
|
|
286
|
+
wire = await session.encrypt_frame(bytes(payload))
|
|
287
|
+
if session is not self._noise_session:
|
|
288
|
+
raise ValueError("noise session replaced during send")
|
|
289
|
+
await self._socket.send(wire)
|
|
290
|
+
|
|
291
|
+
def get_last_inbound_at_ms(self) -> float:
|
|
292
|
+
"""Timestamp (ms) of the last raw payload received from the socket."""
|
|
293
|
+
return self._last_inbound_at_ms
|
|
294
|
+
|
|
295
|
+
def get_comms_state(self) -> WaCommsState:
|
|
296
|
+
"""Snapshot of the connection state."""
|
|
297
|
+
return WaCommsState(
|
|
298
|
+
started=self._started,
|
|
299
|
+
connected=self._connected,
|
|
300
|
+
handling_requests=self._handling_requests,
|
|
301
|
+
reconnect_attempts=self._reconnect_attempts,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
def get_server_static_key(self) -> bytes | None:
|
|
305
|
+
"""Latest server static key, cached across reconnects."""
|
|
306
|
+
if self._noise_session is not None:
|
|
307
|
+
current = self._noise_session.get_server_static_key()
|
|
308
|
+
if current is not None:
|
|
309
|
+
self._last_server_static_key = current
|
|
310
|
+
return current
|
|
311
|
+
return self._last_server_static_key
|
|
312
|
+
|
|
313
|
+
async def _open_socket(self, is_reconnect: bool) -> None:
|
|
314
|
+
if not self._started or self._prevent_retry:
|
|
315
|
+
self._logger.trace(
|
|
316
|
+
"comms openSocket skipped",
|
|
317
|
+
{"started": self._started, "preventRetry": self._prevent_retry},
|
|
318
|
+
)
|
|
319
|
+
return
|
|
320
|
+
if self._socket.is_open() or self._socket.is_connecting():
|
|
321
|
+
self._logger.trace(
|
|
322
|
+
"comms openSocket skipped: socket already open/connecting"
|
|
323
|
+
)
|
|
324
|
+
return
|
|
325
|
+
if is_reconnect:
|
|
326
|
+
self._reconnect_attempts += 1
|
|
327
|
+
max_attempts = self._config.max_reconnect_attempts
|
|
328
|
+
if max_attempts is not None and self._reconnect_attempts > max_attempts:
|
|
329
|
+
self._prevent_retry = True
|
|
330
|
+
self._started = False
|
|
331
|
+
self._drain_waiters(
|
|
332
|
+
lambda waiter: waiter.set_exception(
|
|
333
|
+
ValueError("max reconnect attempts reached")
|
|
334
|
+
)
|
|
335
|
+
if not waiter.done()
|
|
336
|
+
else None
|
|
337
|
+
)
|
|
338
|
+
return
|
|
339
|
+
try:
|
|
340
|
+
self._logger.debug("comms opening websocket", {"isReconnect": is_reconnect})
|
|
341
|
+
await self._socket.open()
|
|
342
|
+
except Exception as error:
|
|
343
|
+
self._connected = False
|
|
344
|
+
if not self._prevent_retry and self._started:
|
|
345
|
+
self._schedule_reconnect()
|
|
346
|
+
self._logger.warn(
|
|
347
|
+
"socket open failed", {"message": str(to_error(error))}
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
async def _on_socket_opened(self, _info: SocketOpenInfo) -> None:
|
|
351
|
+
self._logger.debug("comms socket opened, starting noise session")
|
|
352
|
+
noise_config, used_resume = self._build_noise_config_for_attempt()
|
|
353
|
+
generation = self._connection_generation + 1
|
|
354
|
+
self._connection_generation = generation
|
|
355
|
+
|
|
356
|
+
async def send_wire(payload: bytes) -> None:
|
|
357
|
+
if generation != self._connection_generation:
|
|
358
|
+
raise ValueError("noise session replaced")
|
|
359
|
+
await self._socket.send(payload)
|
|
360
|
+
|
|
361
|
+
session = WaNoiseSession(send_wire, self._logger)
|
|
362
|
+
self._noise_session = session
|
|
363
|
+
try:
|
|
364
|
+
await session.start(noise_config)
|
|
365
|
+
except Exception as error:
|
|
366
|
+
if generation != self._connection_generation:
|
|
367
|
+
self._logger.debug(
|
|
368
|
+
"noise handshake of a replaced session ended",
|
|
369
|
+
{"message": str(to_error(error))},
|
|
370
|
+
)
|
|
371
|
+
return
|
|
372
|
+
if used_resume:
|
|
373
|
+
self._resume_handshake_failures += 1
|
|
374
|
+
self._logger.warn(
|
|
375
|
+
"noise resume handshake failed, next attempt may fallback to full",
|
|
376
|
+
{
|
|
377
|
+
"failures": self._resume_handshake_failures,
|
|
378
|
+
"threshold": _defaults.NOISE_RESUME_FAILURES_BEFORE_FULL_HANDSHAKE, # noqa: E501
|
|
379
|
+
},
|
|
380
|
+
)
|
|
381
|
+
self._noise_session = None
|
|
382
|
+
raise error
|
|
383
|
+
buffered = session.push_wire_chunk(b"")
|
|
384
|
+
if generation != self._connection_generation:
|
|
385
|
+
self._logger.debug("noise session replaced before it was established")
|
|
386
|
+
return
|
|
387
|
+
self._route_decoded_frames(buffered)
|
|
388
|
+
self._resume_handshake_failures = 0
|
|
389
|
+
self._last_server_static_key = session.get_server_static_key()
|
|
390
|
+
self._connected = True
|
|
391
|
+
self._reconnect_attempts = 0
|
|
392
|
+
self._logger.debug("comms connected and noise session established")
|
|
393
|
+
def _resolve(waiter: asyncio.Future[None]) -> None:
|
|
394
|
+
if not waiter.done():
|
|
395
|
+
waiter.set_result(None)
|
|
396
|
+
|
|
397
|
+
self._drain_waiters(_resolve)
|
|
398
|
+
|
|
399
|
+
async def _on_socket_closed(self, info: SocketCloseInfo) -> None:
|
|
400
|
+
self._connected = False
|
|
401
|
+
if self._noise_session is not None:
|
|
402
|
+
self._noise_session.on_socket_closed(
|
|
403
|
+
ConnectionError(f"socket closed ({info.code}:{info.reason})")
|
|
404
|
+
)
|
|
405
|
+
self._noise_session = None
|
|
406
|
+
self.clear_pending_frames()
|
|
407
|
+
self._pending_frames_overflow_closing = False
|
|
408
|
+
if not self._started or self._prevent_retry:
|
|
409
|
+
self._logger.trace("comms socket close ignored for reconnect")
|
|
410
|
+
return
|
|
411
|
+
if self._resume_in_flight:
|
|
412
|
+
self._logger.trace("comms socket close while resume in flight")
|
|
413
|
+
return
|
|
414
|
+
on_restart = self._server_restart_hold
|
|
415
|
+
if on_restart is not None:
|
|
416
|
+
self._server_restart_hold = None
|
|
417
|
+
self._logger.debug(
|
|
418
|
+
"comms socket closed by server while held for restart",
|
|
419
|
+
{"code": info.code, "reason": info.reason},
|
|
420
|
+
)
|
|
421
|
+
on_restart()
|
|
422
|
+
return
|
|
423
|
+
self._schedule_reconnect()
|
|
424
|
+
self._logger.info(
|
|
425
|
+
"socket closed, scheduling reconnect",
|
|
426
|
+
{
|
|
427
|
+
"code": info.code,
|
|
428
|
+
"reason": info.reason,
|
|
429
|
+
"reconnectAfterMs": self._config.reconnect_interval_ms,
|
|
430
|
+
"reconnectAttempts": self._reconnect_attempts,
|
|
431
|
+
},
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
async def _on_socket_error(self, error: Exception) -> None:
|
|
435
|
+
self._logger.warn("socket runtime error", {"message": str(to_error(error))})
|
|
436
|
+
|
|
437
|
+
def _on_socket_message(self, payload: bytes) -> None:
|
|
438
|
+
self._last_inbound_at_ms = time.time() * 1000
|
|
439
|
+
session = self._noise_session
|
|
440
|
+
raw = bytes(payload)
|
|
441
|
+
asyncio.ensure_future(self._run_chained(session, raw))
|
|
442
|
+
|
|
443
|
+
async def _run_chained(
|
|
444
|
+
self, session: WaNoiseSession | None, payload: bytes
|
|
445
|
+
) -> None:
|
|
446
|
+
async with self._frame_lock:
|
|
447
|
+
await self._process_socket_payload(session, payload)
|
|
448
|
+
|
|
449
|
+
async def _handle_open_wrapper(self, _info: SocketOpenInfo) -> None:
|
|
450
|
+
try:
|
|
451
|
+
await self._on_socket_opened(_info)
|
|
452
|
+
except Exception as error:
|
|
453
|
+
self._connected = False
|
|
454
|
+
self._logger.error(
|
|
455
|
+
"noise handshake failed", {"message": str(to_error(error))}
|
|
456
|
+
)
|
|
457
|
+
await self._socket.close(4003, "noise_handshake_failed")
|
|
458
|
+
|
|
459
|
+
async def _process_socket_payload(
|
|
460
|
+
self, session: WaNoiseSession | None, payload: bytes
|
|
461
|
+
) -> None:
|
|
462
|
+
if session is not self._noise_session:
|
|
463
|
+
self._logger.trace(
|
|
464
|
+
"socket payload dropped: noise session replaced",
|
|
465
|
+
{"byteLength": len(payload)},
|
|
466
|
+
)
|
|
467
|
+
return
|
|
468
|
+
if session is None:
|
|
469
|
+
context = {
|
|
470
|
+
"byteLength": len(payload),
|
|
471
|
+
"started": self._started,
|
|
472
|
+
"preventRetry": self._prevent_retry,
|
|
473
|
+
"resumeInFlight": self._resume_in_flight,
|
|
474
|
+
}
|
|
475
|
+
if not self._started or self._prevent_retry or self._resume_in_flight:
|
|
476
|
+
self._logger.debug(
|
|
477
|
+
"socket payload dropped: comms is tearing down", context
|
|
478
|
+
)
|
|
479
|
+
else:
|
|
480
|
+
self._logger.warn(
|
|
481
|
+
"socket payload dropped: no active noise session", context
|
|
482
|
+
)
|
|
483
|
+
return
|
|
484
|
+
try:
|
|
485
|
+
frames = session.push_wire_chunk(payload)
|
|
486
|
+
self._route_decoded_frames(frames)
|
|
487
|
+
except Exception as error:
|
|
488
|
+
if session is not self._noise_session:
|
|
489
|
+
self._logger.trace(
|
|
490
|
+
"noise decode failure ignored: noise session replaced"
|
|
491
|
+
)
|
|
492
|
+
return
|
|
493
|
+
normalized = to_error(error)
|
|
494
|
+
self._logger.error(
|
|
495
|
+
"failed to decode noise frame", {"message": str(normalized)}
|
|
496
|
+
)
|
|
497
|
+
if not self._started or self._prevent_retry or self._resume_in_flight:
|
|
498
|
+
return
|
|
499
|
+
self._logger.warn("resuming socket after noise decode failure")
|
|
500
|
+
|
|
501
|
+
async def _resume() -> None:
|
|
502
|
+
try:
|
|
503
|
+
await self.close_socket_and_resume()
|
|
504
|
+
except Exception as resume_error:
|
|
505
|
+
self._logger.warn(
|
|
506
|
+
"failed to resume socket after noise decode failure",
|
|
507
|
+
{"message": str(to_error(resume_error))},
|
|
508
|
+
)
|
|
509
|
+
|
|
510
|
+
asyncio.ensure_future(_resume())
|
|
511
|
+
|
|
512
|
+
async def _on_decoded_frame(self, payload: bytes) -> None:
|
|
513
|
+
if self._stanza_handler is None:
|
|
514
|
+
return
|
|
515
|
+
if not self._handling_requests:
|
|
516
|
+
self._logger.trace(
|
|
517
|
+
"comms frame queued until request handling starts",
|
|
518
|
+
{"byteLength": len(payload)},
|
|
519
|
+
)
|
|
520
|
+
self._try_queue_pending_frames([payload], "decoded_frame")
|
|
521
|
+
return
|
|
522
|
+
try:
|
|
523
|
+
frame = payload
|
|
524
|
+
if self._inflate_frame is not None:
|
|
525
|
+
inflated = self._inflate_frame(payload)
|
|
526
|
+
if inspect.isawaitable(inflated):
|
|
527
|
+
inflated = await inflated
|
|
528
|
+
frame = bytes(inflated)
|
|
529
|
+
result = self._stanza_handler(frame)
|
|
530
|
+
if inspect.isawaitable(result):
|
|
531
|
+
await result
|
|
532
|
+
except Exception as error:
|
|
533
|
+
self._logger.error(
|
|
534
|
+
"failed to handle incoming frame", {"message": str(to_error(error))}
|
|
535
|
+
)
|
|
536
|
+
|
|
537
|
+
async def _flush_pending_frames(self) -> None:
|
|
538
|
+
if (
|
|
539
|
+
not self._handling_requests
|
|
540
|
+
or self._stanza_handler is None
|
|
541
|
+
or not self._pending_frames
|
|
542
|
+
):
|
|
543
|
+
return
|
|
544
|
+
self._logger.debug(
|
|
545
|
+
"flushing pending comms frames", {"count": len(self._pending_frames)}
|
|
546
|
+
)
|
|
547
|
+
buffered = self._pending_frames
|
|
548
|
+
self._pending_frames = []
|
|
549
|
+
self._pending_frames_byte_length = 0
|
|
550
|
+
self._route_decoded_frames(buffered)
|
|
551
|
+
|
|
552
|
+
def _route_decoded_frames(self, frames: list[bytes] | tuple[bytes, ...]) -> None:
|
|
553
|
+
if not frames:
|
|
554
|
+
return
|
|
555
|
+
if not self._handling_requests or self._stanza_handler is None:
|
|
556
|
+
self._logger.trace(
|
|
557
|
+
"comms frame queued until request handling starts",
|
|
558
|
+
{"count": len(frames)},
|
|
559
|
+
)
|
|
560
|
+
self._try_queue_pending_frames(list(frames), "decoded_batch")
|
|
561
|
+
return
|
|
562
|
+
for frame in frames:
|
|
563
|
+
self._schedule_decoded_frame(frame)
|
|
564
|
+
|
|
565
|
+
def clear_pending_frames(self) -> None:
|
|
566
|
+
"""Drop queued pre-request frames and reset the byte accounting."""
|
|
567
|
+
self._pending_frames = []
|
|
568
|
+
self._pending_frames_byte_length = 0
|
|
569
|
+
|
|
570
|
+
def _try_queue_pending_frames(self, frames: list[bytes], source: str) -> bool:
|
|
571
|
+
if not frames:
|
|
572
|
+
return True
|
|
573
|
+
incoming_bytes = sum(len(frame) for frame in frames)
|
|
574
|
+
next_count = len(self._pending_frames) + len(frames)
|
|
575
|
+
next_bytes = self._pending_frames_byte_length + incoming_bytes
|
|
576
|
+
over_count = next_count > _PENDING_FRAMES_MAX_COUNT
|
|
577
|
+
over_bytes = next_bytes > _PENDING_FRAMES_MAX_BYTES
|
|
578
|
+
if over_count or over_bytes:
|
|
579
|
+
self._logger.error(
|
|
580
|
+
"pending comms frame buffer overflow",
|
|
581
|
+
{
|
|
582
|
+
"source": source,
|
|
583
|
+
"currentCount": len(self._pending_frames),
|
|
584
|
+
"currentBytes": self._pending_frames_byte_length,
|
|
585
|
+
"incomingCount": len(frames),
|
|
586
|
+
"incomingBytes": incoming_bytes,
|
|
587
|
+
"maxCount": _PENDING_FRAMES_MAX_COUNT,
|
|
588
|
+
"maxBytes": _PENDING_FRAMES_MAX_BYTES,
|
|
589
|
+
},
|
|
590
|
+
)
|
|
591
|
+
self.clear_pending_frames()
|
|
592
|
+
self._schedule_pending_frames_overflow_close()
|
|
593
|
+
return False
|
|
594
|
+
self._pending_frames.extend(frames)
|
|
595
|
+
self._pending_frames_byte_length = next_bytes
|
|
596
|
+
return True
|
|
597
|
+
|
|
598
|
+
def _schedule_pending_frames_overflow_close(self) -> None:
|
|
599
|
+
if self._pending_frames_overflow_closing or self._prevent_retry:
|
|
600
|
+
return
|
|
601
|
+
self._pending_frames_overflow_closing = True
|
|
602
|
+
|
|
603
|
+
async def _close() -> None:
|
|
604
|
+
try:
|
|
605
|
+
await self.close_socket_and_prevent_retry()
|
|
606
|
+
except Exception as error:
|
|
607
|
+
self._logger.warn(
|
|
608
|
+
"failed to close socket after pending frame overflow",
|
|
609
|
+
{"message": str(to_error(error))},
|
|
610
|
+
)
|
|
611
|
+
finally:
|
|
612
|
+
self._pending_frames_overflow_closing = False
|
|
613
|
+
|
|
614
|
+
asyncio.ensure_future(_close())
|
|
615
|
+
|
|
616
|
+
def _schedule_decoded_frame(self, frame: bytes) -> None:
|
|
617
|
+
async def _handle() -> None:
|
|
618
|
+
await self._on_decoded_frame(frame)
|
|
619
|
+
|
|
620
|
+
future = self._frame_handler_queue.enqueue(_handle)
|
|
621
|
+
|
|
622
|
+
def _done(future: asyncio.Future[object]) -> None:
|
|
623
|
+
if future.cancelled():
|
|
624
|
+
return
|
|
625
|
+
error = future.exception()
|
|
626
|
+
if error is None:
|
|
627
|
+
return
|
|
628
|
+
if isinstance(error, BoundedTaskQueueFullError):
|
|
629
|
+
if self._resume_in_flight:
|
|
630
|
+
self._logger.trace(
|
|
631
|
+
"frame handler queue is full, resume already in flight"
|
|
632
|
+
)
|
|
633
|
+
return
|
|
634
|
+
self._logger.warn(
|
|
635
|
+
"frame handler queue is full, resuming socket to preserve bounds",
|
|
636
|
+
{
|
|
637
|
+
"pending": self._frame_handler_queue.pending(),
|
|
638
|
+
"inFlight": self._frame_handler_queue.in_flight(),
|
|
639
|
+
},
|
|
640
|
+
)
|
|
641
|
+
asyncio.ensure_future(self.close_socket_and_resume())
|
|
642
|
+
return
|
|
643
|
+
self._logger.error(
|
|
644
|
+
"failed to enqueue decoded frame handler",
|
|
645
|
+
{"message": str(to_error(error))},
|
|
646
|
+
)
|
|
647
|
+
|
|
648
|
+
future.add_done_callback(_done)
|
|
649
|
+
|
|
650
|
+
def _schedule_reconnect(self) -> None:
|
|
651
|
+
if self._reconnect_timer is not None:
|
|
652
|
+
self._logger.trace("reconnect already scheduled")
|
|
653
|
+
return
|
|
654
|
+
self._logger.debug(
|
|
655
|
+
"scheduling reconnect timer",
|
|
656
|
+
{"intervalMs": self._config.reconnect_interval_ms},
|
|
657
|
+
)
|
|
658
|
+
loop = asyncio.get_running_loop()
|
|
659
|
+
self._reconnect_timer = loop.call_later(
|
|
660
|
+
self._config.reconnect_interval_ms / 1000, self._fire_reconnect
|
|
661
|
+
)
|
|
662
|
+
|
|
663
|
+
def _fire_reconnect(self) -> None:
|
|
664
|
+
self._reconnect_timer = None
|
|
665
|
+
asyncio.ensure_future(self._open_socket(True))
|
|
666
|
+
|
|
667
|
+
def _clear_reconnect_timer(self) -> None:
|
|
668
|
+
if self._reconnect_timer is None:
|
|
669
|
+
return
|
|
670
|
+
self._reconnect_timer.cancel()
|
|
671
|
+
self._reconnect_timer = None
|
|
672
|
+
|
|
673
|
+
def _remove_waiter(self, future: asyncio.Future[None]) -> None:
|
|
674
|
+
for index, waiter in enumerate(self._waiters):
|
|
675
|
+
if waiter.future is future:
|
|
676
|
+
waiter.timer.cancel()
|
|
677
|
+
del self._waiters[index]
|
|
678
|
+
return
|
|
679
|
+
|
|
680
|
+
def _drain_waiters(self, drain: Callable[[asyncio.Future[None]], None]) -> None:
|
|
681
|
+
waiters = self._waiters
|
|
682
|
+
self._waiters = []
|
|
683
|
+
for waiter in reversed(waiters):
|
|
684
|
+
waiter.timer.cancel()
|
|
685
|
+
drain(waiter.future)
|
|
686
|
+
|
|
687
|
+
def _build_noise_config_for_attempt(
|
|
688
|
+
self,
|
|
689
|
+
) -> tuple[WaNoiseConfig, bool]:
|
|
690
|
+
has_server_key = (
|
|
691
|
+
self._config.noise.server_static_key is not None
|
|
692
|
+
and len(self._config.noise.server_static_key) == 32
|
|
693
|
+
)
|
|
694
|
+
failures_before_full = _defaults.NOISE_RESUME_FAILURES_BEFORE_FULL_HANDSHAKE
|
|
695
|
+
if has_server_key and self._resume_handshake_failures < failures_before_full:
|
|
696
|
+
return self._config.noise, True
|
|
697
|
+
if has_server_key:
|
|
698
|
+
self._logger.info(
|
|
699
|
+
"noise resume temporarily disabled after previous failure(s)",
|
|
700
|
+
{"failures": self._resume_handshake_failures},
|
|
701
|
+
)
|
|
702
|
+
base = self._config.noise
|
|
703
|
+
return (
|
|
704
|
+
WaNoiseConfig(
|
|
705
|
+
client_static_key_pair=base.client_static_key_pair,
|
|
706
|
+
is_registered=base.is_registered,
|
|
707
|
+
login_payload=base.login_payload,
|
|
708
|
+
registration_payload=base.registration_payload,
|
|
709
|
+
login_payload_config=base.login_payload_config,
|
|
710
|
+
registration_payload_config=base.registration_payload_config,
|
|
711
|
+
server_static_key=None,
|
|
712
|
+
routing_info=base.routing_info,
|
|
713
|
+
protocol_header=base.protocol_header,
|
|
714
|
+
verify_certificate_chain=base.verify_certificate_chain,
|
|
715
|
+
trusted_root_ca=base.trusted_root_ca,
|
|
716
|
+
),
|
|
717
|
+
False,
|
|
718
|
+
)
|
|
719
|
+
|
|
720
|
+
def _reset_connection_state(
|
|
721
|
+
self,
|
|
722
|
+
*,
|
|
723
|
+
started: bool,
|
|
724
|
+
connected: bool,
|
|
725
|
+
handling_requests: bool,
|
|
726
|
+
prevent_retry: bool,
|
|
727
|
+
resume_in_flight: bool,
|
|
728
|
+
clear_handlers: bool = False,
|
|
729
|
+
reject_waiters_error: Exception | None = None,
|
|
730
|
+
reset_resume_handshake_failures: bool = True,
|
|
731
|
+
) -> None:
|
|
732
|
+
self._started = started
|
|
733
|
+
self._connected = connected
|
|
734
|
+
self._handling_requests = handling_requests
|
|
735
|
+
self._prevent_retry = prevent_retry
|
|
736
|
+
self._resume_in_flight = resume_in_flight
|
|
737
|
+
self._server_restart_hold = None
|
|
738
|
+
if reset_resume_handshake_failures:
|
|
739
|
+
self._resume_handshake_failures = 0
|
|
740
|
+
discarded = self._noise_session
|
|
741
|
+
self._noise_session = None
|
|
742
|
+
self._connection_generation += 1
|
|
743
|
+
if discarded is not None:
|
|
744
|
+
discarded.on_socket_closed(ConnectionError("comms connection state reset"))
|
|
745
|
+
self._last_inbound_at_ms = 0.0
|
|
746
|
+
self.clear_pending_frames()
|
|
747
|
+
self._pending_frames_overflow_closing = False
|
|
748
|
+
if clear_handlers:
|
|
749
|
+
self._stanza_handler = None
|
|
750
|
+
self._inflate_frame = None
|
|
751
|
+
self._clear_reconnect_timer()
|
|
752
|
+
if reject_waiters_error is not None:
|
|
753
|
+
error = reject_waiters_error
|
|
754
|
+
|
|
755
|
+
def _reject(waiter: asyncio.Future[None]) -> None:
|
|
756
|
+
if not waiter.done():
|
|
757
|
+
waiter.set_exception(error)
|
|
758
|
+
|
|
759
|
+
self._drain_waiters(_reject)
|