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.
Files changed (345) hide show
  1. shellzapy-0.1.0.dist-info/METADATA +112 -0
  2. shellzapy-0.1.0.dist-info/RECORD +345 -0
  3. shellzapy-0.1.0.dist-info/WHEEL +4 -0
  4. shellzapy-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. shellzapy-0.1.0.dist-info/licenses/NOTICE +9 -0
  6. zapy/__init__.py +58 -0
  7. zapy/_appstate/__init__.py +59 -0
  8. zapy/_appstate/constants.py +82 -0
  9. zapy/_appstate/crypto/__init__.py +17 -0
  10. zapy/_appstate/crypto/app_state_crypto.py +401 -0
  11. zapy/_appstate/parsers/__init__.py +23 -0
  12. zapy/_appstate/parsers/encoding.py +157 -0
  13. zapy/_appstate/parsers/response_parser.py +135 -0
  14. zapy/_appstate/sync/__init__.py +11 -0
  15. zapy/_appstate/sync/sync_client.py +1559 -0
  16. zapy/_appstate/types.py +137 -0
  17. zapy/_appstate/utils.py +100 -0
  18. zapy/_auth/__init__.py +3 -0
  19. zapy/_auth/auth_client.py +618 -0
  20. zapy/_auth/credentials_flow.py +290 -0
  21. zapy/_auth/pairing/__init__.py +3 -0
  22. zapy/_auth/pairing/companion_host.py +239 -0
  23. zapy/_auth/pairing/flow.py +808 -0
  24. zapy/_auth/pairing/pairing_code_crypto.py +143 -0
  25. zapy/_auth/pairing/qr_flow.py +123 -0
  26. zapy/_auth/pairing/shortcake_crypto.py +122 -0
  27. zapy/_auth/pairing/shortcake_flow.py +393 -0
  28. zapy/_auth/types.py +110 -0
  29. zapy/_client/__init__.py +26 -0
  30. zapy/_client/client.py +972 -0
  31. zapy/_client/connection/__init__.py +6 -0
  32. zapy/_client/connection/manager.py +525 -0
  33. zapy/_client/connection/receipt_queue.py +74 -0
  34. zapy/_client/coordinators/__init__.py +81 -0
  35. zapy/_client/coordinators/ab_props.py +260 -0
  36. zapy/_client/coordinators/app_state_mutation.py +2538 -0
  37. zapy/_client/coordinators/bot.py +830 -0
  38. zapy/_client/coordinators/broadcast_list.py +101 -0
  39. zapy/_client/coordinators/business.py +247 -0
  40. zapy/_client/coordinators/email.py +158 -0
  41. zapy/_client/coordinators/group.py +1478 -0
  42. zapy/_client/coordinators/incoming_node.py +758 -0
  43. zapy/_client/coordinators/low_level.py +119 -0
  44. zapy/_client/coordinators/message.py +1153 -0
  45. zapy/_client/coordinators/message_dispatch.py +1637 -0
  46. zapy/_client/coordinators/newsletter.py +110 -0
  47. zapy/_client/coordinators/offline_resume.py +271 -0
  48. zapy/_client/coordinators/passive_tasks.py +447 -0
  49. zapy/_client/coordinators/presence.py +103 -0
  50. zapy/_client/coordinators/privacy.py +623 -0
  51. zapy/_client/coordinators/profile.py +1024 -0
  52. zapy/_client/coordinators/retry.py +1878 -0
  53. zapy/_client/coordinators/status.py +132 -0
  54. zapy/_client/coordinators/stream_control.py +260 -0
  55. zapy/_client/coordinators/trusted_contact_token.py +417 -0
  56. zapy/_client/events/__init__.py +266 -0
  57. zapy/_client/events/abprops.py +58 -0
  58. zapy/_client/events/appstate_mutation.py +248 -0
  59. zapy/_client/events/business.py +565 -0
  60. zapy/_client/events/call.py +144 -0
  61. zapy/_client/events/chatstate.py +41 -0
  62. zapy/_client/events/devices.py +122 -0
  63. zapy/_client/events/dirty.py +384 -0
  64. zapy/_client/events/group.py +655 -0
  65. zapy/_client/events/identity.py +40 -0
  66. zapy/_client/events/incoming.py +1079 -0
  67. zapy/_client/events/mex_notification.py +317 -0
  68. zapy/_client/events/offline.py +123 -0
  69. zapy/_client/events/picture.py +67 -0
  70. zapy/_client/events/presence.py +74 -0
  71. zapy/_client/events/privacy.py +187 -0
  72. zapy/_client/events/privacy_token.py +72 -0
  73. zapy/_client/events/receipt.py +109 -0
  74. zapy/_client/events/registration.py +70 -0
  75. zapy/_client/events/username.py +76 -0
  76. zapy/_client/factory.py +2020 -0
  77. zapy/_client/media.py +829 -0
  78. zapy/_client/newsletter/__init__.py +90 -0
  79. zapy/_client/newsletter/admin.py +323 -0
  80. zapy/_client/newsletter/content.py +499 -0
  81. zapy/_client/newsletter/discovery.py +233 -0
  82. zapy/_client/newsletter/messaging.py +396 -0
  83. zapy/_client/newsletter/mex.py +99 -0
  84. zapy/_client/newsletter/parse.py +406 -0
  85. zapy/_client/newsletter/types.py +393 -0
  86. zapy/_client/persistence/__init__.py +89 -0
  87. zapy/_client/persistence/companion_host.py +133 -0
  88. zapy/_client/persistence/ephemeral_setting.py +245 -0
  89. zapy/_client/persistence/group_history.py +361 -0
  90. zapy/_client/persistence/history_blob.py +169 -0
  91. zapy/_client/persistence/history_sync.py +646 -0
  92. zapy/_client/persistence/mailbox.py +232 -0
  93. zapy/_client/persistence/write_behind_persistence.py +368 -0
  94. zapy/_client/plugins/__init__.py +23 -0
  95. zapy/_client/plugins/define.py +44 -0
  96. zapy/_client/plugins/install.py +254 -0
  97. zapy/_client/plugins/types.py +64 -0
  98. zapy/_client/tokens/__init__.py +21 -0
  99. zapy/_client/tokens/cs_token.py +47 -0
  100. zapy/_client/tokens/tc_token.py +43 -0
  101. zapy/_client/types.py +988 -0
  102. zapy/_crypto/__init__.py +65 -0
  103. zapy/_crypto/core/__init__.py +62 -0
  104. zapy/_crypto/core/hkdf.py +41 -0
  105. zapy/_crypto/core/keys.py +51 -0
  106. zapy/_crypto/core/nonce.py +25 -0
  107. zapy/_crypto/core/primitives.py +179 -0
  108. zapy/_crypto/core/random.py +32 -0
  109. zapy/_crypto/core/xeddsa.py +72 -0
  110. zapy/_crypto/curves/__init__.py +3 -0
  111. zapy/_crypto/curves/constants.py +10 -0
  112. zapy/_crypto/curves/ed25519.py +61 -0
  113. zapy/_crypto/curves/types.py +18 -0
  114. zapy/_crypto/curves/x25519.py +117 -0
  115. zapy/_crypto/math/__init__.py +3 -0
  116. zapy/_crypto/math/constants.py +35 -0
  117. zapy/_crypto/math/edwards.py +174 -0
  118. zapy/_crypto/math/fe.py +120 -0
  119. zapy/_crypto/math/le.py +13 -0
  120. zapy/_crypto/math/mod.py +15 -0
  121. zapy/_crypto/math/prime.py +11 -0
  122. zapy/_crypto/math/types.py +25 -0
  123. zapy/_crypto/native_backend.py +40 -0
  124. zapy/_infra/__init__.py +3 -0
  125. zapy/_infra/log.py +142 -0
  126. zapy/_infra/perf.py +77 -0
  127. zapy/_media/__init__.py +64 -0
  128. zapy/_media/constants.py +133 -0
  129. zapy/_media/container.py +110 -0
  130. zapy/_media/crypto/__init__.py +19 -0
  131. zapy/_media/crypto/crypto.py +633 -0
  132. zapy/_media/crypto/media_retry.py +107 -0
  133. zapy/_media/processor.py +100 -0
  134. zapy/_media/sticker/__init__.py +8 -0
  135. zapy/_media/sticker/pack.py +188 -0
  136. zapy/_media/transfer/__init__.py +15 -0
  137. zapy/_media/transfer/client.py +635 -0
  138. zapy/_media/transfer/conn.py +48 -0
  139. zapy/_media/types.py +169 -0
  140. zapy/_message/__init__.py +121 -0
  141. zapy/_message/addons/__init__.py +5 -0
  142. zapy/_message/addons/link_preview/__init__.py +54 -0
  143. zapy/_message/addons/link_preview/builder.py +56 -0
  144. zapy/_message/addons/link_preview/detect.py +72 -0
  145. zapy/_message/addons/link_preview/fetcher.py +553 -0
  146. zapy/_message/addons/link_preview/types.py +100 -0
  147. zapy/_message/client.py +486 -0
  148. zapy/_message/context_info.py +424 -0
  149. zapy/_message/crypto/__init__.py +71 -0
  150. zapy/_message/crypto/addon_crypto.py +656 -0
  151. zapy/_message/crypto/icdc.py +138 -0
  152. zapy/_message/crypto/phash.py +87 -0
  153. zapy/_message/crypto/reporting_token.py +498 -0
  154. zapy/_message/crypto/use_case_secret.py +113 -0
  155. zapy/_message/encode/__init__.py +84 -0
  156. zapy/_message/encode/content.py +636 -0
  157. zapy/_message/encode/device_sent.py +88 -0
  158. zapy/_message/encode/media_payload.py +122 -0
  159. zapy/_message/encode/padding.py +27 -0
  160. zapy/_message/kinds/__init__.py +1 -0
  161. zapy/_message/kinds/bot.py +179 -0
  162. zapy/_message/kinds/group_history.py +206 -0
  163. zapy/_message/kinds/newsletter.py +388 -0
  164. zapy/_message/kinds/sticker_pack.py +74 -0
  165. zapy/_message/messaging/__init__.py +336 -0
  166. zapy/_message/messaging/companion_host.py +117 -0
  167. zapy/_message/messaging/fanout.py +311 -0
  168. zapy/_message/messaging/group_metadata.py +444 -0
  169. zapy/_message/messaging/ignore_key.py +264 -0
  170. zapy/_message/messaging/key_protocol.py +217 -0
  171. zapy/_message/messaging/link_preview.py +448 -0
  172. zapy/_message/messaging/messages.py +1429 -0
  173. zapy/_message/primitives/__init__.py +1 -0
  174. zapy/_message/primitives/ack.py +232 -0
  175. zapy/_message/primitives/incoming.py +1141 -0
  176. zapy/_message/primitives/media_retry.py +451 -0
  177. zapy/_message/primitives/peer_data_operation.py +271 -0
  178. zapy/_message/types.py +434 -0
  179. zapy/_proto/WAProto_pb2.py +2584 -0
  180. zapy/_proto/__init__.py +1 -0
  181. zapy/_protocol/__init__.py +3 -0
  182. zapy/_protocol/abprops_spec.py +6216 -0
  183. zapy/_protocol/auth.py +17 -0
  184. zapy/_protocol/browser.py +57 -0
  185. zapy/_protocol/defaults.py +38 -0
  186. zapy/_protocol/device_identity.py +54 -0
  187. zapy/_protocol/jid.py +241 -0
  188. zapy/_protocol/message.py +127 -0
  189. zapy/_protocol/nodes.py +144 -0
  190. zapy/_protocol/notification.py +18 -0
  191. zapy/_retry/__init__.py +77 -0
  192. zapy/_retry/codec.py +209 -0
  193. zapy/_retry/constants.py +28 -0
  194. zapy/_retry/parse.py +132 -0
  195. zapy/_retry/reason.py +65 -0
  196. zapy/_retry/replay.py +483 -0
  197. zapy/_retry/tracker.py +161 -0
  198. zapy/_retry/types.py +122 -0
  199. zapy/_signal/__init__.py +171 -0
  200. zapy/_signal/api/__init__.py +133 -0
  201. zapy/_signal/api/codec.py +164 -0
  202. zapy/_signal/api/constants.py +14 -0
  203. zapy/_signal/api/device_sync.py +915 -0
  204. zapy/_signal/api/digest_sync.py +363 -0
  205. zapy/_signal/api/identity_sync.py +250 -0
  206. zapy/_signal/api/missing_pre_keys_sync.py +267 -0
  207. zapy/_signal/api/prekeys.py +191 -0
  208. zapy/_signal/api/result_map.py +40 -0
  209. zapy/_signal/api/rotate_key.py +111 -0
  210. zapy/_signal/api/session_sync.py +297 -0
  211. zapy/_signal/attestation.py +145 -0
  212. zapy/_signal/constants.py +22 -0
  213. zapy/_signal/encoding.py +78 -0
  214. zapy/_signal/group/__init__.py +35 -0
  215. zapy/_signal/group/chain.py +139 -0
  216. zapy/_signal/group/codec.py +78 -0
  217. zapy/_signal/group/encoding.py +166 -0
  218. zapy/_signal/group/manager.py +361 -0
  219. zapy/_signal/registration/__init__.py +44 -0
  220. zapy/_signal/registration/keygen.py +46 -0
  221. zapy/_signal/registration/reg_encoding.py +66 -0
  222. zapy/_signal/registration/reg_utils.py +52 -0
  223. zapy/_signal/session/__init__.py +114 -0
  224. zapy/_signal/session/encoding.py +385 -0
  225. zapy/_signal/session/protocol.py +590 -0
  226. zapy/_signal/session/ratchet.py +381 -0
  227. zapy/_signal/session/resolver.py +630 -0
  228. zapy/_signal/session/serializer.py +96 -0
  229. zapy/_signal/session/session.py +272 -0
  230. zapy/_signal/types.py +214 -0
  231. zapy/_store/__init__.py +118 -0
  232. zapy/_store/cache/__init__.py +166 -0
  233. zapy/_store/cache/identity.py +130 -0
  234. zapy/_store/cache/privacy_token.py +116 -0
  235. zapy/_store/cache/sender_key.py +168 -0
  236. zapy/_store/cache/session.py +142 -0
  237. zapy/_store/contracts/__init__.py +84 -0
  238. zapy/_store/contracts/appstate.py +82 -0
  239. zapy/_store/contracts/auth.py +16 -0
  240. zapy/_store/contracts/chat_metadata.py +29 -0
  241. zapy/_store/contracts/contact.py +31 -0
  242. zapy/_store/contracts/device_list.py +35 -0
  243. zapy/_store/contracts/group_metadata.py +33 -0
  244. zapy/_store/contracts/identity.py +18 -0
  245. zapy/_store/contracts/message.py +36 -0
  246. zapy/_store/contracts/message_secret.py +41 -0
  247. zapy/_store/contracts/pre_key.py +32 -0
  248. zapy/_store/contracts/privacy_token.py +32 -0
  249. zapy/_store/contracts/retry.py +47 -0
  250. zapy/_store/contracts/sender_key.py +37 -0
  251. zapy/_store/contracts/session.py +21 -0
  252. zapy/_store/contracts/signal.py +23 -0
  253. zapy/_store/contracts/thread.py +35 -0
  254. zapy/_store/create_store.py +890 -0
  255. zapy/_store/locks.py +1154 -0
  256. zapy/_store/memory/__init__.py +40 -0
  257. zapy/_store/memory/appstate.py +200 -0
  258. zapy/_store/memory/auth.py +24 -0
  259. zapy/_store/memory/chat_metadata.py +124 -0
  260. zapy/_store/memory/contact.py +125 -0
  261. zapy/_store/memory/device_list.py +161 -0
  262. zapy/_store/memory/group_metadata.py +125 -0
  263. zapy/_store/memory/identity.py +86 -0
  264. zapy/_store/memory/message.py +85 -0
  265. zapy/_store/memory/message_secret.py +145 -0
  266. zapy/_store/memory/pre_key.py +112 -0
  267. zapy/_store/memory/privacy_token.py +103 -0
  268. zapy/_store/memory/retry.py +250 -0
  269. zapy/_store/memory/sender_key.py +162 -0
  270. zapy/_store/memory/session.py +111 -0
  271. zapy/_store/memory/signal.py +45 -0
  272. zapy/_store/memory/thread.py +66 -0
  273. zapy/_store/noop.py +279 -0
  274. zapy/_transport/__init__.py +3 -0
  275. zapy/_transport/binary/__init__.py +77 -0
  276. zapy/_transport/binary/constants.py +80 -0
  277. zapy/_transport/binary/decoder.py +260 -0
  278. zapy/_transport/binary/encoder.py +279 -0
  279. zapy/_transport/binary/tokens.py +1289 -0
  280. zapy/_transport/comms.py +759 -0
  281. zapy/_transport/keepalive/__init__.py +3 -0
  282. zapy/_transport/keepalive/keep_alive.py +252 -0
  283. zapy/_transport/node/__init__.py +3 -0
  284. zapy/_transport/node/builders/__init__.py +9 -0
  285. zapy/_transport/node/builders/abprops.py +33 -0
  286. zapy/_transport/node/builders/account_sync.py +120 -0
  287. zapy/_transport/node/builders/bot.py +56 -0
  288. zapy/_transport/node/builders/business.py +261 -0
  289. zapy/_transport/node/builders/chatstate.py +74 -0
  290. zapy/_transport/node/builders/community.py +116 -0
  291. zapy/_transport/node/builders/device.py +30 -0
  292. zapy/_transport/node/builders/email.py +181 -0
  293. zapy/_transport/node/builders/global_.py +74 -0
  294. zapy/_transport/node/builders/group.py +279 -0
  295. zapy/_transport/node/builders/media.py +21 -0
  296. zapy/_transport/node/builders/message.py +436 -0
  297. zapy/_transport/node/builders/mobile.py +227 -0
  298. zapy/_transport/node/builders/newsletter.py +293 -0
  299. zapy/_transport/node/builders/offline.py +20 -0
  300. zapy/_transport/node/builders/pairing.py +130 -0
  301. zapy/_transport/node/builders/passive.py +28 -0
  302. zapy/_transport/node/builders/prekeys.py +215 -0
  303. zapy/_transport/node/builders/presence.py +100 -0
  304. zapy/_transport/node/builders/privacy.py +243 -0
  305. zapy/_transport/node/builders/privacy_token.py +94 -0
  306. zapy/_transport/node/builders/profile.py +176 -0
  307. zapy/_transport/node/builders/retry.py +156 -0
  308. zapy/_transport/node/builders/shortcake.py +87 -0
  309. zapy/_transport/node/builders/tos.py +92 -0
  310. zapy/_transport/node/builders/usync.py +185 -0
  311. zapy/_transport/node/helpers.py +201 -0
  312. zapy/_transport/node/orchestrator.py +210 -0
  313. zapy/_transport/node/query.py +82 -0
  314. zapy/_transport/node/transport.py +105 -0
  315. zapy/_transport/node/usync.py +33 -0
  316. zapy/_transport/node/xml.py +38 -0
  317. zapy/_transport/noise/__init__.py +7 -0
  318. zapy/_transport/noise/cert.py +85 -0
  319. zapy/_transport/noise/client_payload.py +344 -0
  320. zapy/_transport/noise/constants.py +12 -0
  321. zapy/_transport/noise/frame_codec.py +120 -0
  322. zapy/_transport/noise/handshake.py +92 -0
  323. zapy/_transport/noise/session.py +493 -0
  324. zapy/_transport/noise/socket.py +45 -0
  325. zapy/_transport/noise/types.py +66 -0
  326. zapy/_transport/noise/version.json +3 -0
  327. zapy/_transport/proxy.py +35 -0
  328. zapy/_transport/types.py +19 -0
  329. zapy/_transport/wa_version_fetcher.py +159 -0
  330. zapy/_transport/web_socket.py +602 -0
  331. zapy/_util/__init__.py +3 -0
  332. zapy/_util/bytes.py +131 -0
  333. zapy/_util/coercion.py +29 -0
  334. zapy/_util/collections.py +45 -0
  335. zapy/_util/primitives.py +49 -0
  336. zapy/client.py +840 -0
  337. zapy/errors.py +148 -0
  338. zapy/events.py +564 -0
  339. zapy/jid.py +140 -0
  340. zapy/py.typed +0 -0
  341. zapy/stores/__init__.py +50 -0
  342. zapy/stores/base.py +1627 -0
  343. zapy/stores/json_file.py +359 -0
  344. zapy/stores/memory.py +322 -0
  345. zapy/stores/sqlite.py +343 -0
@@ -0,0 +1,1878 @@
1
+ """Retry coordinator (mirrors ``src/client/coordinators/WaRetryCoordinator.ts``).
2
+
3
+ Record shapes and parse/reason helpers below intentionally mirror the
4
+ coordinator's own dialect from the oracle (defaults, ``stanza_from`` alias);
5
+ the canonical ``zapy._retry`` copies back them and are used at the resend
6
+ boundary (:func:`_to_retry_outbound_record`). Actual resends run through the
7
+ real :class:`zapy._retry.replay.WaRetryReplayService`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import base64
14
+ import time
15
+ from collections.abc import Awaitable, Callable, Mapping
16
+ from dataclasses import dataclass
17
+ from typing import Any, Literal, cast
18
+
19
+ from zapy._retry import types as _retry_types
20
+ from zapy._retry.replay import WaRetryReplayService, WaRetryReplayServiceOptions
21
+
22
+ from zapy._auth.types import WaAuthCredentials
23
+ from zapy._crypto.core.keys import to_raw_pub_key
24
+ from zapy._infra.log import Logger
25
+ from zapy._infra.perf import BoundedTaskQueue, BoundedTaskQueueFullError
26
+ from zapy._message.context_info import proto_message_to_dict
27
+ from zapy._message.primitives.ack import WA_MESSAGE_TAGS, WA_MESSAGE_TYPES
28
+ from zapy._message.primitives.incoming import (
29
+ WaIncomingMessageEvent,
30
+ build_recovered_incoming_event,
31
+ is_group_or_broadcast_jid,
32
+ resolve_unavailable_message_kind,
33
+ to_user_jid,
34
+ )
35
+ from zapy._message.primitives.peer_data_operation import PeerDataOperationRequester
36
+ from zapy._proto import WAProto_pb2
37
+ from zapy._signal.api.codec import (
38
+ decode_exact_length,
39
+ parse_signal_key_bundle_from_node,
40
+ parse_uint,
41
+ )
42
+ from zapy._signal.api.constants import SIGNAL_REGISTRATION_ID_LENGTH
43
+ from zapy._signal.api.missing_pre_keys_sync import SignalMissingPreKeysUserError
44
+ from zapy._signal.api.prekeys import (
45
+ MissingPreKeysDeviceTarget,
46
+ MissingPreKeysFetchTarget,
47
+ )
48
+ from zapy._signal.registration.keygen import generate_pre_key_pair
49
+ from zapy._signal.session import normalize_device_jid, parse_signal_address_from_jid
50
+ from zapy._signal.types import (
51
+ SignalAddress,
52
+ SignalPreKeyBundle,
53
+ SignalPreKeyBundleOneTimeKey,
54
+ SignalPreKeyBundleSignedKey,
55
+ )
56
+ from zapy._store.contracts.pre_key import WaPreKeyStore
57
+ from zapy._store.contracts.retry import WaRetryStore
58
+ from zapy._store.contracts.sender_key import WaSenderKeyStore
59
+ from zapy._store.contracts.session import WaSessionStore
60
+ from zapy._store.contracts.signal import WaSignalStore
61
+ from zapy._transport.node.builders.retry import (
62
+ RetryKey,
63
+ RetryKeyBundle,
64
+ RetryReceiptNodeInput,
65
+ build_retry_receipt_node,
66
+ )
67
+ from zapy._transport.node.helpers import find_node_children_by_tags
68
+ from zapy._transport.types import BinaryNode
69
+ from zapy._util.bytes import uint8_equal
70
+ from zapy._util.collections import set_bounded_map_entry
71
+ from zapy._util.primitives import parse_optional_int, to_error
72
+
73
+ # Verbatim ``src/retry/constants.ts``.
74
+ MAX_RETRY_ATTEMPTS: int = 5
75
+ RETRY_KEYS_MIN_COUNT: int = 2
76
+ RETRY_OUTBOUND_TTL_MS: int = 60 * 1000
77
+ RETRY_RECEIPT_VERSION: str = "1"
78
+
79
+ # Verbatim ``src/retry/constants.ts`` (``WaRetryReasonCode`` values).
80
+ RETRY_REASON: dict[str, int] = {
81
+ "UnknownError": 0,
82
+ "SignalErrorNoSession": 1,
83
+ "SignalErrorInvalidKey": 2,
84
+ "SignalErrorInvalidKeyId": 3,
85
+ "SignalErrorInvalidMessage": 4,
86
+ "SignalErrorInvalidSignature": 5,
87
+ "SignalErrorFutureMessage": 6,
88
+ "SignalErrorBadMac": 7,
89
+ "SignalErrorInvalidSession": 8,
90
+ "SignalErrorInvalidMsgKey": 9,
91
+ "BadBroadcastEphemeralSetting": 10,
92
+ "UnknownCompanionNoPrekey": 11,
93
+ "AdvFailure": 12,
94
+ "StatusRevokeDelay": 13,
95
+ }
96
+
97
+ # Verbatim ``src/protocol/defaults.ts`` (hosted-device id; the hosted servers
98
+ # already live in ``zapy._protocol.defaults``).
99
+ _HOSTED_DEVICE_ID: int = 99
100
+ _HOSTED_SERVER: str = "hosted"
101
+ _HOSTED_LID_SERVER: str = "hosted.lid"
102
+
103
+ # Coordinator-local tunables (verbatim ``WaRetryCoordinator.ts``).
104
+ _RETRY_CLEANUP_INTERVAL_MS = 30_000
105
+ _RETRY_SESSION_BASE_KEY_CACHE_MAX_ENTRIES = 8_192
106
+ _DECRYPT_FAILURE_QUEUE_MAX_SIZE = 1_024
107
+ _DECRYPT_FAILURE_QUEUE_MAX_CONCURRENCY = 8
108
+ _PLACEHOLDER_RESEND_RETRY_THRESHOLD = 4
109
+ _PLACEHOLDER_RESEND_BATCH_SIZE = 32
110
+ _PLACEHOLDER_RESEND_DEBOUNCE_SECONDS = 0.2
111
+ _PLACEHOLDER_RESEND_FALLBACK_MAX_AGE_DAYS = 14
112
+ _PLACEHOLDER_RESEND_IN_FLIGHT_MAX = 256
113
+ _PLACEHOLDER_RESEND_TIMEOUT_MS = 120_000
114
+ _DAY_SECONDS = 24 * 60 * 60
115
+ _PLACEHOLDER_RESEND_SKIP_SUBTYPE_BY_KIND: dict[str, str] = {
116
+ "bot": "bot_unavailable_fanout",
117
+ "hosted": "hosted_unavailable_fanout",
118
+ "view_once": "view_once_unavailable_fanout",
119
+ "sender_drop": "acp_unavailable_fanout",
120
+ }
121
+ _PLACEHOLDER_RESEND_SKIP_SUBTYPES = frozenset(
122
+ _PLACEHOLDER_RESEND_SKIP_SUBTYPE_BY_KIND.values()
123
+ )
124
+ # Verbatim ``PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND``.
125
+ _PLACEHOLDER_MESSAGE_RESEND_REQUEST_TYPE: int = (
126
+ WAProto_pb2.Message.PeerDataOperationRequestType.Value("PLACEHOLDER_MESSAGE_RESEND")
127
+ )
128
+
129
+ WaRetryOutboundState = Literal["pending", "delivered", "read", "played", "ineligible"]
130
+
131
+ _RETRY_STATE_RANK: dict[str, int] = {
132
+ "pending": 0,
133
+ "delivered": 1,
134
+ "read": 2,
135
+ "played": 3,
136
+ "ineligible": 4,
137
+ }
138
+
139
+
140
+ def pick_retry_state_max(
141
+ left: WaRetryOutboundState, right: WaRetryOutboundState
142
+ ) -> WaRetryOutboundState:
143
+ """Return whichever retry state is more advanced (verbatim ``retry/parse.ts``)."""
144
+ return left if _RETRY_STATE_RANK[left] >= _RETRY_STATE_RANK[right] else right
145
+
146
+
147
+ def _retry_reason_name(code: int | None) -> str | None:
148
+ """Reason name for a retry-reason code (verbatim ``WaRetryCoordinator.ts``)."""
149
+ if code is None:
150
+ return None
151
+ for name, value in RETRY_REASON.items():
152
+ if value == code:
153
+ return name
154
+ return "unknown"
155
+
156
+
157
+ def _remote_retry_reason_log_fields(reason: int | None) -> dict[str, Any]:
158
+ """Log fields describing a remote retry reason."""
159
+ return {
160
+ "hasRemoteRetryReason": reason is not None,
161
+ "remoteRetryReason": reason if reason is not None else None,
162
+ "remoteRetryReasonName": _retry_reason_name(reason)
163
+ or "missing_in_retry_receipt",
164
+ }
165
+
166
+
167
+ def is_hosted_device_jid(jid: str) -> bool:
168
+ """Whether the JID refers to a hosted device (verbatim ``protocol/jid.ts``)."""
169
+ at_index = jid.find("@")
170
+ if at_index < 1 or at_index >= len(jid) - 1:
171
+ return False
172
+ server = jid[at_index + 1 :]
173
+ if server == _HOSTED_SERVER or server == _HOSTED_LID_SERVER:
174
+ return True
175
+ colon_index = jid.find(":")
176
+ if colon_index < 0 or colon_index >= at_index - 1:
177
+ return False
178
+ device_segment = jid[colon_index + 1 : at_index]
179
+ if not device_segment or not device_segment.isdigit():
180
+ return False
181
+ device_id = int(device_segment)
182
+ if device_id > 2**53 - 1:
183
+ return False
184
+ return device_id == _HOSTED_DEVICE_ID
185
+
186
+
187
+ # Verbatim ``src/retry/reason.ts``.
188
+ _RETRY_REASON_MATCHER_LIST: list[tuple[list[str | list[str]], int]] = [
189
+ (
190
+ [
191
+ "no session",
192
+ "session not found",
193
+ ],
194
+ RETRY_REASON["SignalErrorNoSession"],
195
+ ),
196
+ (["invalid key id"], RETRY_REASON["SignalErrorInvalidKeyId"]),
197
+ (["invalid key"], RETRY_REASON["SignalErrorInvalidKey"]),
198
+ (
199
+ [
200
+ "invalid signal message",
201
+ "invalid prekey signal message",
202
+ "invalid sender key message",
203
+ ],
204
+ RETRY_REASON["SignalErrorInvalidMessage"],
205
+ ),
206
+ (["invalid signature"], RETRY_REASON["SignalErrorInvalidSignature"]),
207
+ (
208
+ ["too far in future", "too many messages in future", "future message"],
209
+ RETRY_REASON["SignalErrorFutureMessage"],
210
+ ),
211
+ (["invalid message mac", "invalid mac"], RETRY_REASON["SignalErrorBadMac"]),
212
+ (["invalid session"], RETRY_REASON["SignalErrorInvalidSession"]),
213
+ (["invalid message key"], RETRY_REASON["SignalErrorInvalidMsgKey"]),
214
+ (
215
+ [["broadcast", "ephemeral"]],
216
+ RETRY_REASON["BadBroadcastEphemeralSetting"],
217
+ ),
218
+ (
219
+ ["unknown companion", "unknown device"],
220
+ RETRY_REASON["UnknownCompanionNoPrekey"],
221
+ ),
222
+ (["adv"], RETRY_REASON["AdvFailure"]),
223
+ (
224
+ [["status", "revoke", "delay"]],
225
+ RETRY_REASON["StatusRevokeDelay"],
226
+ ),
227
+ ]
228
+
229
+
230
+ def map_retry_reason_from_error(error: object) -> int | None:
231
+ """Map a decrypt/Signal error to a retry-receipt reason code (verbatim)."""
232
+ message = str(to_error(error)).lower()
233
+ for candidates, code in _RETRY_REASON_MATCHER_LIST:
234
+ for candidate in candidates:
235
+ if isinstance(candidate, list):
236
+ if all(part in message for part in candidate):
237
+ return code
238
+ elif candidate in message:
239
+ return code
240
+ return None
241
+
242
+
243
+ @dataclass(frozen=True, slots=True)
244
+ class WaRetryParsedKey:
245
+ """One key entry of a parsed retry key bundle."""
246
+
247
+ id: int
248
+ public_key: bytes
249
+ signature: bytes | None = None
250
+
251
+
252
+ @dataclass(frozen=True, slots=True)
253
+ class WaRetryParsedKeyBundle:
254
+ """Key bundle parsed from a retry receipt."""
255
+
256
+ identity: bytes
257
+ skey: WaRetryParsedKey
258
+ key: WaRetryParsedKey | None = None
259
+ device_identity: bytes | None = None
260
+
261
+
262
+ @dataclass(frozen=True, slots=True)
263
+ class WaParsedRetryRequest:
264
+ """Parsed incoming retry/rekey-retry receipt (verbatim ``retry/types.ts``)."""
265
+
266
+ type: str
267
+ stanza_id: str
268
+ sender_jid: str
269
+ original_msg_id: str
270
+ retry_count: int
271
+ reg_id: int
272
+ participant: str | None = None
273
+ recipient: str | None = None
274
+ offline: bool = False
275
+ is_lid: bool = False
276
+ retry_reason: int | None = None
277
+ t: str | None = None
278
+ key_bundle: WaRetryParsedKeyBundle | None = None
279
+
280
+
281
+ @dataclass(frozen=True, slots=True)
282
+ class WaRetryDecryptFailureContext:
283
+ """Context for one undecryptable inbound stanza."""
284
+
285
+ message_node: BinaryNode
286
+ stanza_id: str
287
+ sender_jid: str
288
+ participant: str | None = None
289
+ recipient: str | None = None
290
+ t: str | None = None
291
+
292
+ @property
293
+ def stanza_from(self) -> str:
294
+ """Alias matching the oracle's ``context.from`` field name."""
295
+ return self.sender_jid
296
+
297
+
298
+ @dataclass(frozen=True, slots=True)
299
+ class WaRetryOutboundMessageRecord:
300
+ """Outbound message tracked for retry replay."""
301
+
302
+ message_id: str
303
+ to_jid: str
304
+ replay_mode: str
305
+ replay_payload: Any
306
+ state: WaRetryOutboundState
307
+ updated_at_ms: int
308
+ expires_at_ms: int
309
+ eligible_requester_device_jids: tuple[str, ...] | None = None
310
+ delivered_requester_device_jids: tuple[str, ...] | None = None
311
+
312
+
313
+ @dataclass(frozen=True, slots=True)
314
+ class WaRetryReplayPayload:
315
+ """Payload a retry resend replays (plaintext/encrypted/opaque-node)."""
316
+
317
+ mode: str
318
+ to: str
319
+ type: str
320
+ plaintext: bytes | None = None
321
+ ciphertext: bytes | None = None
322
+ node: bytes | None = None
323
+ enc_type: str | None = None
324
+ participant: str | None = None
325
+ status_setting: str | None = None
326
+
327
+
328
+ def _validate_retry_receipt_to_attr(
329
+ to: str | None, expected_to_jids: list[str] | None
330
+ ) -> None:
331
+ """Reject receipts not addressed to this device (verbatim ``retry/parse.ts``)."""
332
+ if not to or not expected_to_jids:
333
+ return
334
+ try:
335
+ normalized_to = normalize_device_jid(to)
336
+ except ValueError:
337
+ raise ValueError("retry receipt has invalid to attr")
338
+ for expected in expected_to_jids:
339
+ trimmed = expected.strip() if expected else ""
340
+ if not trimmed:
341
+ continue
342
+ try:
343
+ if normalize_device_jid(trimmed) == normalized_to:
344
+ return
345
+ except ValueError:
346
+ continue
347
+ raise ValueError("retry receipt to attr does not match local device")
348
+
349
+
350
+ def _parse_retry_key_bundle(node: BinaryNode | None) -> WaRetryParsedKeyBundle | None:
351
+ """Parse the ``<keys>`` bundle of a retry receipt."""
352
+ if node is None:
353
+ return None
354
+ parsed = parse_signal_key_bundle_from_node(node, "retry.keys")
355
+ one_time = parsed.one_time_key
356
+ return WaRetryParsedKeyBundle(
357
+ identity=parsed.identity,
358
+ device_identity=parsed.device_identity,
359
+ key=(
360
+ WaRetryParsedKey(id=one_time.id, public_key=one_time.public_key)
361
+ if one_time is not None
362
+ else None
363
+ ),
364
+ skey=WaRetryParsedKey(
365
+ id=parsed.signed_key.id,
366
+ public_key=parsed.signed_key.public_key,
367
+ signature=parsed.signed_key.signature,
368
+ ),
369
+ )
370
+
371
+
372
+ def parse_retry_receipt_request(
373
+ node: BinaryNode, expected_to_jids: list[str] | None = None
374
+ ) -> WaParsedRetryRequest | None:
375
+ """Parse an incoming retry/rekey-retry receipt (verbatim ``retry/parse.ts``).
376
+
377
+ Returns ``None`` when the stanza is not a retry receipt; raises when
378
+ required attrs/children are missing.
379
+ """
380
+ if node.tag != WA_MESSAGE_TAGS["RECEIPT"]:
381
+ return None
382
+ receipt_type = node.attrs.get("type")
383
+ if receipt_type not in (
384
+ WA_MESSAGE_TYPES["RECEIPT_TYPE_RETRY"],
385
+ WA_MESSAGE_TYPES["RECEIPT_TYPE_ENC_REKEY_RETRY"],
386
+ ):
387
+ return None
388
+ stanza_id = node.attrs.get("id")
389
+ sender_jid = node.attrs.get("from")
390
+ if not stanza_id or not sender_jid:
391
+ raise ValueError("retry receipt is missing id/from attrs")
392
+ _validate_retry_receipt_to_attr(node.attrs.get("to"), expected_to_jids)
393
+ retry_node, registration_node, keys_node = find_node_children_by_tags(
394
+ node, ["retry", "registration", "keys"]
395
+ )
396
+ if retry_node is None:
397
+ raise ValueError("retry receipt is missing retry child")
398
+ if registration_node is None:
399
+ raise ValueError("retry receipt is missing registration child")
400
+ original_msg_id = retry_node.attrs.get("id")
401
+ if not original_msg_id:
402
+ raise ValueError("retry receipt is missing retry.id")
403
+ registration = decode_exact_length(
404
+ registration_node.content, "retry.registration", SIGNAL_REGISTRATION_ID_LENGTH
405
+ )
406
+ retry_count = parse_optional_int(retry_node.attrs.get("count")) or 0
407
+ return WaParsedRetryRequest(
408
+ type=receipt_type,
409
+ stanza_id=stanza_id,
410
+ sender_jid=sender_jid,
411
+ participant=node.attrs.get("participant"),
412
+ recipient=node.attrs.get("recipient"),
413
+ offline="offline" in node.attrs,
414
+ is_lid=node.attrs.get("is_lid") == "true",
415
+ original_msg_id=original_msg_id,
416
+ retry_count=retry_count,
417
+ retry_reason=parse_optional_int(
418
+ retry_node.attrs.get("error") or node.attrs.get("error")
419
+ ),
420
+ t=retry_node.attrs.get("t") or node.attrs.get("t"),
421
+ reg_id=parse_uint(registration, "retry.registration"),
422
+ key_bundle=_parse_retry_key_bundle(keys_node),
423
+ )
424
+
425
+
426
+ def _to_retry_outbound_record(
427
+ outbound: WaRetryOutboundMessageRecord,
428
+ ) -> _retry_types.WaRetryOutboundMessageRecord:
429
+ """Convert the coordinator record to the canonical ``zapy._retry`` shape."""
430
+ payload = outbound.replay_payload
431
+ if isinstance(payload, (bytes, bytearray)):
432
+ stored: bytes | _retry_types.WaRetryReplayPayload = bytes(payload)
433
+ elif isinstance(
434
+ payload,
435
+ (
436
+ _retry_types.WaRetryPlaintextReplayPayload,
437
+ _retry_types.WaRetryEncryptedReplayPayload,
438
+ _retry_types.WaRetryOpaqueNodeReplayPayload,
439
+ ),
440
+ ):
441
+ stored = payload
442
+ elif isinstance(payload, dict):
443
+ stored = _payload_from_mapping(payload)
444
+ else:
445
+ stored = _payload_from_object(payload)
446
+ return _retry_types.WaRetryOutboundMessageRecord(
447
+ message_id=outbound.message_id,
448
+ to_jid=outbound.to_jid,
449
+ replay_mode=outbound.replay_mode,
450
+ replay_payload=stored,
451
+ state=outbound.state,
452
+ updated_at_ms=outbound.updated_at_ms,
453
+ expires_at_ms=outbound.expires_at_ms,
454
+ eligible_requester_device_jids=outbound.eligible_requester_device_jids,
455
+ delivered_requester_device_jids=outbound.delivered_requester_device_jids,
456
+ )
457
+
458
+
459
+ def _payload_from_mapping(
460
+ payload: Mapping[str, Any],
461
+ ) -> _retry_types.WaRetryReplayPayload:
462
+ mode = payload.get("mode")
463
+ if mode == "plaintext":
464
+ return _retry_types.WaRetryPlaintextReplayPayload(
465
+ mode="plaintext",
466
+ to=str(payload["to"]),
467
+ type=str(payload["type"]),
468
+ plaintext=bytes(payload["plaintext"]),
469
+ status_setting=payload.get("status_setting"),
470
+ )
471
+ if mode == "encrypted":
472
+ return _retry_types.WaRetryEncryptedReplayPayload(
473
+ mode="encrypted",
474
+ to=str(payload["to"]),
475
+ type=str(payload["type"]),
476
+ enc_type=str(payload["enc_type"]),
477
+ ciphertext=bytes(payload["ciphertext"]),
478
+ participant=payload.get("participant"),
479
+ )
480
+ if mode == "opaque_node":
481
+ return _retry_types.WaRetryOpaqueNodeReplayPayload(
482
+ mode="opaque_node", node=bytes(payload["node"])
483
+ )
484
+ raise ValueError(f"unsupported retry replay payload mode: {mode!r}")
485
+
486
+
487
+ def _payload_from_object(payload: Any) -> _retry_types.WaRetryReplayPayload:
488
+ mode = payload.mode
489
+ if mode == "plaintext":
490
+ return _retry_types.WaRetryPlaintextReplayPayload(
491
+ mode="plaintext",
492
+ to=str(payload.to),
493
+ type=str(payload.type),
494
+ plaintext=bytes(payload.plaintext),
495
+ status_setting=getattr(payload, "status_setting", None),
496
+ )
497
+ if mode == "encrypted":
498
+ return _retry_types.WaRetryEncryptedReplayPayload(
499
+ mode="encrypted",
500
+ to=str(payload.to),
501
+ type=str(payload.type),
502
+ enc_type=str(payload.enc_type),
503
+ ciphertext=bytes(payload.ciphertext),
504
+ participant=getattr(payload, "participant", None),
505
+ )
506
+ if mode == "opaque_node":
507
+ return _retry_types.WaRetryOpaqueNodeReplayPayload(
508
+ mode="opaque_node", node=bytes(payload.node)
509
+ )
510
+ raise ValueError(f"unsupported retry replay payload mode: {mode!r}")
511
+
512
+
513
+ @dataclass(frozen=True, slots=True)
514
+ class RetryAuthorization:
515
+ """Whether a retry request may trigger a resend."""
516
+
517
+ authorized: bool
518
+ reason: str | None = None
519
+
520
+
521
+ @dataclass(frozen=True, slots=True)
522
+ class RetryDecryptFailurePreparation:
523
+ """Prepared retry receipt for one decrypt failure."""
524
+
525
+ registration_id: int
526
+ retry_count: int
527
+ retry_reason: int | None
528
+ timestamp: str
529
+ retry_keys: RetryKeyBundle | None = None
530
+ delegated_to_placeholder_resend: bool = False
531
+
532
+
533
+ @dataclass(frozen=True, slots=True)
534
+ class RetryResendPreparation:
535
+ """Validated retry request ready to resend."""
536
+
537
+ requester_jid: str
538
+ requester_address: SignalAddress
539
+ requester_normalized_device_jid: str
540
+ outbound: WaRetryOutboundMessageRecord
541
+
542
+
543
+ @dataclass(frozen=True, slots=True)
544
+ class PlaceholderResendQueueItem:
545
+ """One queued placeholder-message resend request."""
546
+
547
+ remote_jid: str
548
+ id: str
549
+ from_me: bool
550
+ participant: str | None = None
551
+
552
+
553
+ @dataclass(frozen=True, slots=True)
554
+ class RetrySessionBaseKeySnapshot:
555
+ """Cached session base key used to detect resend loops."""
556
+
557
+ base_key: bytes
558
+ expires_at_ms: int
559
+
560
+
561
+ def resolve_placeholder_resend_skip_subtype(node: BinaryNode) -> str | None:
562
+ """Placeholder subtype the primary never resends, or ``None`` when recoverable."""
563
+ subtype = node.attrs.get("subtype")
564
+ if isinstance(subtype, str) and subtype in _PLACEHOLDER_RESEND_SKIP_SUBTYPES:
565
+ return subtype
566
+ kind = resolve_unavailable_message_kind(node)
567
+ if kind is None or kind == "other":
568
+ return None
569
+ return _PLACEHOLDER_RESEND_SKIP_SUBTYPE_BY_KIND.get(kind)
570
+
571
+
572
+ def _now_ms() -> int:
573
+ """Current time in milliseconds (mirrors ``Date.now()``)."""
574
+ return int(time.time() * 1000)
575
+
576
+
577
+ def _now_seconds() -> float:
578
+ """Current time in seconds (mirrors ``Date.now() / 1000``)."""
579
+ return time.time()
580
+
581
+
582
+ def _try_as_number(value: Any) -> float | int | None:
583
+ """Return ``value`` as a number, else ``None`` (verbatim ``tryAsNumber``)."""
584
+ if isinstance(value, bool):
585
+ return None
586
+ if isinstance(value, (int, float)):
587
+ finite = value == value and value not in (float("inf"), float("-inf"))
588
+ return value if finite else None
589
+ if isinstance(value, str):
590
+ normalized = value.strip()
591
+ if not normalized:
592
+ return None
593
+ try:
594
+ parsed = float(normalized)
595
+ except ValueError:
596
+ return None
597
+ finite = parsed == parsed and parsed not in (float("inf"), float("-inf"))
598
+ return parsed if finite else None
599
+ return None
600
+
601
+
602
+ def _build_retry_ack_node(receipt_node: BinaryNode) -> BinaryNode:
603
+ """Build the ack for a consumed retry receipt.
604
+
605
+ Mirrors the fallthrough receipt branch of ``buildAckNode``; moves to
606
+ ``zapy._transport.node.builders.global_`` once that ports the branch.
607
+ """
608
+ attrs: dict[str, str] = {"class": WA_MESSAGE_TAGS["RECEIPT"]}
609
+ attrs["type"] = WA_MESSAGE_TYPES["RECEIPT_TYPE_RETRY"]
610
+ if receipt_node.attrs.get("id"):
611
+ attrs["id"] = receipt_node.attrs["id"]
612
+ if receipt_node.attrs.get("from"):
613
+ attrs["to"] = receipt_node.attrs["from"]
614
+ if receipt_node.attrs.get("participant"):
615
+ attrs["participant"] = receipt_node.attrs["participant"]
616
+ return BinaryNode(tag="ack", attrs=attrs)
617
+
618
+
619
+ def _build_message_ack_node(
620
+ *,
621
+ node: BinaryNode,
622
+ stanza_id: str,
623
+ to: str,
624
+ sender: str | None,
625
+ participant: str | None,
626
+ error: int,
627
+ ) -> BinaryNode:
628
+ """Build ``<ack class=message error=…/>`` echoing a stanza.
629
+
630
+ Mirrors the ``message`` branch of ``buildAckNode``; moves to
631
+ ``zapy._transport.node.builders.global_`` once that ports the branch.
632
+ """
633
+ attrs: dict[str, str] = {
634
+ "id": stanza_id,
635
+ "to": to,
636
+ "class": WA_MESSAGE_TYPES["ACK_CLASS_MESSAGE"],
637
+ "error": str(error),
638
+ }
639
+ stanza_type = node.attrs.get("type")
640
+ if stanza_type:
641
+ attrs["type"] = stanza_type
642
+ resolved_participant = (
643
+ participant if participant is not None else node.attrs.get("participant")
644
+ )
645
+ if resolved_participant:
646
+ attrs["participant"] = resolved_participant
647
+ if sender:
648
+ attrs["from"] = sender
649
+ return BinaryNode(tag="ack", attrs=attrs)
650
+
651
+
652
+ @dataclass
653
+ class WaRetryCoordinatorOptions:
654
+ """Injected dependencies of :class:`WaRetryCoordinator`."""
655
+
656
+ logger: Logger
657
+ retry_store: WaRetryStore
658
+ signal_store: WaSignalStore
659
+ pre_key_store: WaPreKeyStore
660
+ session_store: WaSessionStore
661
+ sender_key_store: WaSenderKeyStore
662
+ signal_protocol: Any
663
+ session_resolver: Any
664
+ signal_device_sync: Any
665
+ signal_missing_pre_keys_sync: Any
666
+ message_client: Any
667
+ send_node: Callable[[BinaryNode], Awaitable[None]]
668
+ get_current_credentials: Callable[[], WaAuthCredentials | None]
669
+ resolve_user_icdc: Callable[[str], Awaitable[Any | None]] | None = None
670
+ peer_data_operation: PeerDataOperationRequester | None = None
671
+ emit_incoming_message: Callable[[WaIncomingMessageEvent], None] | None = None
672
+ is_mobile_primary: Callable[[], bool] | None = None
673
+ resolve_privacy_token_node: Callable[[str], Awaitable[BinaryNode | None]] | None = (
674
+ None
675
+ )
676
+ get_ab_prop_number: Callable[[str], float | int | None] | None = None
677
+
678
+
679
+ class WaRetryCoordinator:
680
+ """Handles decrypt-failure retry receipts and incoming retry requests."""
681
+
682
+ def __init__(self, options: WaRetryCoordinatorOptions) -> None:
683
+ self._deps = options
684
+ self._retry_ttl_ms: int | None = None
685
+ self._replay = WaRetryReplayService(
686
+ WaRetryReplayServiceOptions(
687
+ logger=options.logger,
688
+ message_client=options.message_client,
689
+ signal_protocol=options.signal_protocol,
690
+ session_resolver=options.session_resolver,
691
+ get_current_credentials=options.get_current_credentials,
692
+ is_mobile_primary=options.is_mobile_primary,
693
+ resolve_user_icdc=options.resolve_user_icdc,
694
+ resolve_privacy_token_node=options.resolve_privacy_token_node,
695
+ )
696
+ )
697
+ self._retry_processing_by_message_id: dict[str, asyncio.Task[None]] = {}
698
+ self._retry_session_base_keys: dict[str, RetrySessionBaseKeySnapshot] = {}
699
+ self._next_retry_cleanup_at_ms = 0
700
+ self._placeholder_in_flight: set[str] = set()
701
+ self._placeholder_queue: list[PlaceholderResendQueueItem] = []
702
+ self._placeholder_timer: asyncio.TimerHandle | None = None
703
+ self._decrypt_failure_queue = BoundedTaskQueue(
704
+ _DECRYPT_FAILURE_QUEUE_MAX_SIZE, _DECRYPT_FAILURE_QUEUE_MAX_CONCURRENCY
705
+ )
706
+
707
+ async def _get_retry_ttl_ms(self) -> int:
708
+ if self._retry_ttl_ms is None:
709
+ # DEVIATION: the zapy store contract is async while the TS one is
710
+ # sync; test fakes may also return the value directly.
711
+ raw: Any = self._deps.retry_store.get_ttl_ms()
712
+ if asyncio.iscoroutine(raw) or asyncio.isfuture(raw):
713
+ raw = await raw
714
+ self._retry_ttl_ms = raw if raw is not None else RETRY_OUTBOUND_TTL_MS
715
+ return self._retry_ttl_ms
716
+
717
+ async def on_decrypt_failure(
718
+ self, context: WaRetryDecryptFailureContext, error: object
719
+ ) -> bool:
720
+ """Schedule retry handling for one decrypt failure; always ``True``."""
721
+ # Deferred to the bounded queue: building the receipt inline would stall
722
+ # the inbound node pipeline.
723
+ future = self._decrypt_failure_queue.enqueue(
724
+ lambda: self._handle_decrypt_failure(context, error)
725
+ )
726
+
727
+ def _on_done(done: asyncio.Future[object]) -> None:
728
+ try:
729
+ exception = done.exception()
730
+ except asyncio.CancelledError:
731
+ return
732
+ if exception is None:
733
+ return
734
+ if isinstance(exception, BoundedTaskQueueFullError):
735
+ self._deps.logger.warn(
736
+ "decrypt-failure retry dropped: queue saturated",
737
+ {
738
+ "id": context.stanza_id,
739
+ "from": context.sender_jid,
740
+ "participant": context.participant,
741
+ },
742
+ )
743
+ return
744
+ self._deps.logger.warn(
745
+ "failed to schedule decrypt-failure retry",
746
+ {
747
+ "id": context.stanza_id,
748
+ "from": context.sender_jid,
749
+ "participant": context.participant,
750
+ "message": str(to_error(exception)),
751
+ },
752
+ )
753
+
754
+ future.add_done_callback(_on_done)
755
+ return True
756
+
757
+ async def _handle_decrypt_failure(
758
+ self, context: WaRetryDecryptFailureContext, error: object
759
+ ) -> None:
760
+ try:
761
+ prepared = await self._prepare_decrypt_failure_retry(context, error)
762
+ if prepared is not None and not prepared.delegated_to_placeholder_resend:
763
+ await self._send_decrypt_failure_retry_receipt(context, prepared)
764
+ # Ack the failed stanza even on the give-up path: the retry receipt
765
+ # asks for a resend but does not consume the message, so without the
766
+ # ack it is redelivered on every offline resume.
767
+ await self._send_decrypt_failure_ack(context)
768
+ except Exception as send_error:
769
+ self._deps.logger.warn(
770
+ "failed to send retry receipt for decrypt failure",
771
+ {
772
+ "id": context.stanza_id,
773
+ "from": context.sender_jid,
774
+ "participant": context.participant,
775
+ "message": str(to_error(send_error)),
776
+ },
777
+ )
778
+
779
+ async def handle_incoming_retry_receipt(self, receipt_node: BinaryNode) -> None:
780
+ """Handle one incoming retry/rekey-retry receipt stanza."""
781
+ if not self._is_retry_receipt_node(receipt_node):
782
+ return
783
+ should_ack = False
784
+ try:
785
+ await self._maybe_cleanup_retry_store(_now_ms())
786
+ expected_to_jids: list[str] = []
787
+ credentials = self._deps.get_current_credentials()
788
+ me_jid = (credentials.me_jid or "").strip() if credentials else ""
789
+ me_lid = (credentials.me_lid or "").strip() if credentials else ""
790
+ if me_jid:
791
+ expected_to_jids.append(me_jid)
792
+ if me_lid:
793
+ expected_to_jids.append(me_lid)
794
+ request = parse_retry_receipt_request(
795
+ receipt_node, expected_to_jids or None
796
+ )
797
+ if request is None:
798
+ return
799
+ should_ack = True
800
+ await self._handle_parsed_retry_request(receipt_node, request)
801
+ except Exception as error:
802
+ self._deps.logger.warn(
803
+ "failed handling incoming retry request",
804
+ {
805
+ "id": receipt_node.attrs.get("id"),
806
+ "from": receipt_node.attrs.get("from"),
807
+ "participant": receipt_node.attrs.get("participant"),
808
+ "message": str(to_error(error)),
809
+ },
810
+ )
811
+ finally:
812
+ if should_ack:
813
+ await self._send_retry_ack_safe(receipt_node)
814
+
815
+ def _is_retry_receipt_node(self, node: BinaryNode) -> bool:
816
+ return node.tag == WA_MESSAGE_TAGS["RECEIPT"] and node.attrs.get("type") in (
817
+ WA_MESSAGE_TYPES["RECEIPT_TYPE_RETRY"],
818
+ WA_MESSAGE_TYPES["RECEIPT_TYPE_ENC_REKEY_RETRY"],
819
+ )
820
+
821
+ async def _prepare_decrypt_failure_retry(
822
+ self, context: WaRetryDecryptFailureContext, error: object
823
+ ) -> RetryDecryptFailurePreparation | None:
824
+ now_ms = _now_ms()
825
+ registration_info = await self._deps.signal_store.get_registration_info()
826
+ if registration_info is None:
827
+ self._deps.logger.warn(
828
+ "retry receipt skipped: missing local registration info",
829
+ {"id": context.stanza_id, "from": context.sender_jid},
830
+ )
831
+ return None
832
+ requester = context.participant or context.sender_jid
833
+ ttl_ms = await self._get_retry_ttl_ms()
834
+ expires_at_ms = now_ms + ttl_ms
835
+ retry_count = await self._deps.retry_store.increment_inbound_counter(
836
+ context.stanza_id, requester, now_ms, expires_at_ms
837
+ )
838
+ if retry_count > MAX_RETRY_ATTEMPTS:
839
+ # Give up past the ceiling: each attempt rebuilds an expensive keys
840
+ # section, so an uncapped retry on redelivered backlog hammers the store.
841
+ self._deps.logger.debug(
842
+ "retry receipt skipped: inbound retry limit exceeded",
843
+ {
844
+ "id": context.stanza_id,
845
+ "from": context.sender_jid,
846
+ "participant": context.participant,
847
+ "retryCount": retry_count,
848
+ },
849
+ )
850
+ return None
851
+ delegated_to_placeholder_resend = (
852
+ retry_count >= _PLACEHOLDER_RESEND_RETRY_THRESHOLD
853
+ and self._enqueue_placeholder_resend(context)
854
+ )
855
+ if delegated_to_placeholder_resend:
856
+ return RetryDecryptFailurePreparation(
857
+ registration_id=registration_info.registration_id,
858
+ retry_count=retry_count,
859
+ retry_reason=map_retry_reason_from_error(error),
860
+ timestamp=context.t or str(now_ms // 1000),
861
+ delegated_to_placeholder_resend=True,
862
+ )
863
+ sender_device_jid = context.participant or context.sender_jid
864
+ force_keys_for_hosted = bool(sender_device_jid) and is_hosted_device_jid(
865
+ sender_device_jid
866
+ )
867
+ keys: RetryKeyBundle | None = None
868
+ if force_keys_for_hosted or retry_count >= RETRY_KEYS_MIN_COUNT:
869
+ keys = await self._build_retry_keys_section(
870
+ bytes(registration_info.identity_key_pair.pub_key),
871
+ stanza_id=context.stanza_id,
872
+ sender_jid=context.sender_jid,
873
+ )
874
+ return RetryDecryptFailurePreparation(
875
+ registration_id=registration_info.registration_id,
876
+ retry_count=retry_count,
877
+ retry_reason=map_retry_reason_from_error(error),
878
+ timestamp=context.t or str(now_ms // 1000),
879
+ retry_keys=keys,
880
+ delegated_to_placeholder_resend=False,
881
+ )
882
+
883
+ async def _send_decrypt_failure_retry_receipt(
884
+ self,
885
+ context: WaRetryDecryptFailureContext,
886
+ prepared: RetryDecryptFailurePreparation,
887
+ ) -> None:
888
+ receipt_node = build_retry_receipt_node(
889
+ RetryReceiptNodeInput(
890
+ stanza_id=context.stanza_id,
891
+ to=context.sender_jid,
892
+ participant=context.participant,
893
+ recipient=context.recipient,
894
+ original_msg_id=context.stanza_id,
895
+ retry_count=prepared.retry_count,
896
+ t=prepared.timestamp,
897
+ registration_id=prepared.registration_id,
898
+ error=prepared.retry_reason,
899
+ category_peer=context.message_node.attrs.get("category") == "peer",
900
+ keys=prepared.retry_keys,
901
+ )
902
+ )
903
+ await self._deps.send_node(receipt_node)
904
+ self._deps.logger.trace(
905
+ "sent retry receipt for decrypt failure",
906
+ {
907
+ "id": context.stanza_id,
908
+ "to": context.sender_jid,
909
+ "participant": context.participant,
910
+ "recipient": context.recipient,
911
+ "retryCount": prepared.retry_count,
912
+ "reason": prepared.retry_reason,
913
+ "withKeys": prepared.retry_keys is not None,
914
+ },
915
+ )
916
+
917
+ async def _send_decrypt_failure_ack(
918
+ self, context: WaRetryDecryptFailureContext
919
+ ) -> None:
920
+ if not context.stanza_id or not context.sender_jid:
921
+ return
922
+ try:
923
+ credentials = self._deps.get_current_credentials()
924
+ await self._deps.send_node(
925
+ _build_message_ack_node(
926
+ node=context.message_node,
927
+ stanza_id=context.stanza_id,
928
+ to=context.sender_jid,
929
+ sender=credentials.me_jid if credentials else None,
930
+ participant=context.participant,
931
+ error=500,
932
+ )
933
+ )
934
+ self._deps.logger.trace(
935
+ "acked undecryptable stanza",
936
+ {
937
+ "id": context.stanza_id,
938
+ "from": context.sender_jid,
939
+ "participant": context.participant,
940
+ },
941
+ )
942
+ except Exception as error:
943
+ self._deps.logger.warn(
944
+ "failed to ack undecryptable stanza",
945
+ {
946
+ "id": context.stanza_id,
947
+ "from": context.sender_jid,
948
+ "participant": context.participant,
949
+ "message": str(to_error(error)),
950
+ },
951
+ )
952
+
953
+ async def _handle_parsed_retry_request(
954
+ self, receipt_node: BinaryNode, request: WaParsedRetryRequest
955
+ ) -> None:
956
+ if request.type == WA_MESSAGE_TYPES["RECEIPT_TYPE_ENC_REKEY_RETRY"]:
957
+ self._deps.logger.debug(
958
+ "received enc_rekey_retry request (voip path deferred)",
959
+ {
960
+ "id": request.stanza_id,
961
+ "originalMsgId": request.original_msg_id,
962
+ "from": request.sender_jid,
963
+ "participant": request.participant,
964
+ "remoteRetryCount": request.retry_count,
965
+ **_remote_retry_reason_log_fields(request.retry_reason),
966
+ },
967
+ )
968
+ return
969
+ await self._run_retry_task_serialized(
970
+ request.original_msg_id,
971
+ lambda: self._process_retry_request(request),
972
+ )
973
+
974
+ async def _process_retry_request(self, request: WaParsedRetryRequest) -> None:
975
+ prepared = await self._prepare_retry_resend(request)
976
+ if prepared is None:
977
+ return
978
+ request_logger_extra = {
979
+ "id": request.stanza_id,
980
+ "originalMsgId": request.original_msg_id,
981
+ "requester": prepared.requester_jid,
982
+ }
983
+ resend_result = await self._replay.resend_outbound_message(
984
+ _to_retry_outbound_record(prepared.outbound),
985
+ prepared.requester_jid,
986
+ request.retry_count,
987
+ )
988
+ if resend_result == "ineligible":
989
+ self._deps.logger.debug(
990
+ "retry request marked ineligible for resend",
991
+ {**request_logger_extra, "mode": prepared.outbound.replay_mode},
992
+ )
993
+ return
994
+ self._deps.logger.debug(
995
+ "retry request processed and resent",
996
+ {
997
+ **request_logger_extra,
998
+ "mode": prepared.outbound.replay_mode,
999
+ "remoteRetryCount": request.retry_count,
1000
+ **_remote_retry_reason_log_fields(request.retry_reason),
1001
+ },
1002
+ )
1003
+
1004
+ async def _prepare_retry_resend(
1005
+ self, request: WaParsedRetryRequest
1006
+ ) -> RetryResendPreparation | None:
1007
+ requester_jid = request.participant or request.sender_jid or None
1008
+ if not requester_jid:
1009
+ self._deps.logger.warn(
1010
+ "retry request ignored: missing requester jid",
1011
+ {
1012
+ "id": request.stanza_id,
1013
+ "originalMsgId": request.original_msg_id,
1014
+ },
1015
+ )
1016
+ return None
1017
+ try:
1018
+ parsed = parse_signal_address_from_jid(requester_jid)
1019
+ requester_address = parsed
1020
+ requester_normalized_device_jid = normalize_device_jid(requester_jid)
1021
+ except ValueError as error:
1022
+ self._deps.logger.debug(
1023
+ "retry request rejected: invalid requester jid",
1024
+ {
1025
+ "id": request.stanza_id,
1026
+ "originalMsgId": request.original_msg_id,
1027
+ "requester": requester_jid,
1028
+ "message": str(to_error(error)),
1029
+ },
1030
+ )
1031
+ return None
1032
+ if request.retry_count >= MAX_RETRY_ATTEMPTS:
1033
+ self._deps.logger.debug(
1034
+ "retry request rejected: retry count exceeded",
1035
+ {
1036
+ "id": request.stanza_id,
1037
+ "originalMsgId": request.original_msg_id,
1038
+ "requester": requester_jid,
1039
+ "remoteRetryCount": request.retry_count,
1040
+ **_remote_retry_reason_log_fields(request.retry_reason),
1041
+ },
1042
+ )
1043
+ return None
1044
+ raw_outbound = await self._deps.retry_store.get_outbound_message(
1045
+ request.original_msg_id
1046
+ )
1047
+ if raw_outbound is None:
1048
+ self._deps.logger.debug(
1049
+ "retry request ignored: outbound message not found",
1050
+ {
1051
+ "id": request.stanza_id,
1052
+ "originalMsgId": request.original_msg_id,
1053
+ "requester": requester_jid,
1054
+ },
1055
+ )
1056
+ return None
1057
+ outbound = _coerce_outbound_record(raw_outbound)
1058
+ session_ready = await self._update_local_session_from_retry_request(
1059
+ request, requester_jid, requester_address, requester_normalized_device_jid
1060
+ )
1061
+ if not session_ready:
1062
+ self._deps.logger.debug(
1063
+ "retry request rejected: missing compatible session",
1064
+ {
1065
+ "id": request.stanza_id,
1066
+ "originalMsgId": request.original_msg_id,
1067
+ "requester": requester_jid,
1068
+ "remoteRetryCount": request.retry_count,
1069
+ **_remote_retry_reason_log_fields(request.retry_reason),
1070
+ },
1071
+ )
1072
+ return None
1073
+ authorization = await self._authorize_retry_request(
1074
+ request,
1075
+ outbound,
1076
+ requester_jid,
1077
+ requester_address,
1078
+ requester_normalized_device_jid,
1079
+ )
1080
+ if not authorization.authorized:
1081
+ self._deps.logger.debug(
1082
+ "retry request rejected",
1083
+ {
1084
+ "id": request.stanza_id,
1085
+ "originalMsgId": request.original_msg_id,
1086
+ "requester": requester_jid,
1087
+ "reason": authorization.reason,
1088
+ "remoteRetryCount": request.retry_count,
1089
+ **_remote_retry_reason_log_fields(request.retry_reason),
1090
+ },
1091
+ )
1092
+ return None
1093
+ return RetryResendPreparation(
1094
+ requester_jid=requester_jid,
1095
+ requester_address=requester_address,
1096
+ requester_normalized_device_jid=requester_normalized_device_jid,
1097
+ outbound=outbound,
1098
+ )
1099
+
1100
+ async def track_outbound_receipt(self, receipt_node: BinaryNode) -> None:
1101
+ """Advance outbound retry state from a non-retry receipt."""
1102
+ if receipt_node.tag != WA_MESSAGE_TAGS["RECEIPT"]:
1103
+ return
1104
+ message_id = receipt_node.attrs.get("id")
1105
+ if not message_id:
1106
+ return
1107
+ receipt_type = receipt_node.attrs.get("type")
1108
+ if receipt_type in (
1109
+ WA_MESSAGE_TYPES["RECEIPT_TYPE_RETRY"],
1110
+ WA_MESSAGE_TYPES["RECEIPT_TYPE_ENC_REKEY_RETRY"],
1111
+ ):
1112
+ return
1113
+ next_state = self._map_outbound_state_from_receipt_type(receipt_type)
1114
+ if next_state is None:
1115
+ return
1116
+
1117
+ async def _track() -> None:
1118
+ raw_current = await self._deps.retry_store.get_outbound_message(message_id)
1119
+ if raw_current is None:
1120
+ return
1121
+ current = _coerce_outbound_record(raw_current)
1122
+ now_ms = _now_ms()
1123
+ ttl_ms = await self._get_retry_ttl_ms()
1124
+ expires_at_ms = now_ms + ttl_ms
1125
+ merged = pick_retry_state_max(current.state, next_state)
1126
+ if merged != current.state:
1127
+ await self._deps.retry_store.update_outbound_message_state(
1128
+ message_id, merged, now_ms, expires_at_ms
1129
+ )
1130
+ requester_jid = receipt_node.attrs.get(
1131
+ "participant"
1132
+ ) or receipt_node.attrs.get("from")
1133
+ if not requester_jid:
1134
+ return
1135
+ try:
1136
+ await self._deps.retry_store.mark_outbound_requester_delivered(
1137
+ message_id,
1138
+ normalize_device_jid(requester_jid),
1139
+ now_ms,
1140
+ expires_at_ms,
1141
+ )
1142
+ except Exception as error:
1143
+ self._deps.logger.warn(
1144
+ "failed to update outbound requester delivery state",
1145
+ {
1146
+ "id": message_id,
1147
+ "requester": requester_jid,
1148
+ "message": str(to_error(error)),
1149
+ },
1150
+ )
1151
+
1152
+ await self._run_retry_task_serialized(message_id, _track)
1153
+
1154
+ async def _run_retry_task_serialized(
1155
+ self, message_id: str, task: Callable[[], Awaitable[None]]
1156
+ ) -> None:
1157
+ previous = self._retry_processing_by_message_id.get(message_id)
1158
+
1159
+ async def _run() -> None:
1160
+ if previous is not None:
1161
+ try:
1162
+ await previous
1163
+ except Exception:
1164
+ pass
1165
+ await task()
1166
+
1167
+ current = asyncio.ensure_future(_run())
1168
+
1169
+ async def _guarded() -> None:
1170
+ try:
1171
+ await current
1172
+ except Exception:
1173
+ pass
1174
+
1175
+ tracker = asyncio.ensure_future(_guarded())
1176
+ self._retry_processing_by_message_id[message_id] = tracker
1177
+ try:
1178
+ await current
1179
+ finally:
1180
+ if self._retry_processing_by_message_id.get(message_id) is tracker:
1181
+ del self._retry_processing_by_message_id[message_id]
1182
+
1183
+ async def _build_retry_keys_section(
1184
+ self, identity: bytes, *, stanza_id: str, sender_jid: str
1185
+ ) -> RetryKeyBundle | None:
1186
+ signed_pre_key = await self._deps.signal_store.get_signed_pre_key()
1187
+ pre_key = await self._deps.pre_key_store.get_or_gen_single_pre_key(
1188
+ generate_pre_key_pair
1189
+ )
1190
+ if signed_pre_key is None:
1191
+ self._deps.logger.warn(
1192
+ "retry keys section skipped: signed prekey unavailable",
1193
+ {"id": stanza_id, "from": sender_jid},
1194
+ )
1195
+ return None
1196
+ await self._deps.pre_key_store.mark_key_as_uploaded(pre_key.key_id)
1197
+ credentials = self._deps.get_current_credentials()
1198
+ signed_identity = credentials.signed_pre_identity if credentials else None
1199
+ device_identity: bytes | None = None
1200
+ if signed_identity is not None:
1201
+ if isinstance(signed_identity, (bytes, bytearray)):
1202
+ device_identity = bytes(signed_identity)
1203
+ else:
1204
+ serialize = getattr(signed_identity, "SerializeToString", None)
1205
+ if callable(serialize):
1206
+ device_identity = bytes(serialize())
1207
+ return RetryKeyBundle(
1208
+ identity=to_raw_pub_key(identity),
1209
+ key=RetryKey(
1210
+ id=pre_key.key_id,
1211
+ public_key=to_raw_pub_key(bytes(pre_key.key_pair.pub_key)),
1212
+ ),
1213
+ skey=RetryKey(
1214
+ id=signed_pre_key.key_id,
1215
+ public_key=to_raw_pub_key(bytes(signed_pre_key.key_pair.pub_key)),
1216
+ signature=bytes(signed_pre_key.signature),
1217
+ ),
1218
+ device_identity=device_identity,
1219
+ )
1220
+
1221
+ async def _update_local_session_from_retry_request(
1222
+ self,
1223
+ request: WaParsedRetryRequest,
1224
+ requester_jid: str,
1225
+ requester_address: SignalAddress,
1226
+ requester_normalized_device_jid: str,
1227
+ ) -> bool:
1228
+ await self._mark_retry_requester_sender_key_as_stale(
1229
+ request, requester_jid, requester_address
1230
+ )
1231
+ current_session = await self._deps.session_store.get_session(requester_address)
1232
+ reg_id_mismatch = (
1233
+ current_session is not None
1234
+ and request.reg_id > 0
1235
+ and current_session.remote.reg_id != request.reg_id
1236
+ )
1237
+ if reg_id_mismatch and request.key_bundle is None:
1238
+ await self._deps.session_store.delete_session(requester_address)
1239
+ if request.key_bundle is not None:
1240
+ bundle = request.key_bundle
1241
+ if bundle.key is None or not bundle.skey.signature:
1242
+ return False
1243
+ if request.offline:
1244
+ if current_session is None:
1245
+ self._deps.logger.debug(
1246
+ "retry request rejected: offline retry missing session",
1247
+ {
1248
+ "id": request.stanza_id,
1249
+ "originalMsgId": request.original_msg_id,
1250
+ "requester": requester_jid,
1251
+ "remoteRetryCount": request.retry_count,
1252
+ **_remote_retry_reason_log_fields(request.retry_reason),
1253
+ },
1254
+ )
1255
+ await self._deps.session_store.delete_session(requester_address)
1256
+ return False
1257
+ if reg_id_mismatch:
1258
+ self._deps.logger.debug(
1259
+ "retry request rejected: offline retry reg id mismatch",
1260
+ {
1261
+ "id": request.stanza_id,
1262
+ "originalMsgId": request.original_msg_id,
1263
+ "requester": requester_jid,
1264
+ "remoteRetryCount": request.retry_count,
1265
+ **_remote_retry_reason_log_fields(request.retry_reason),
1266
+ },
1267
+ )
1268
+ await self._deps.session_store.delete_session(requester_address)
1269
+ return False
1270
+ elif reg_id_mismatch:
1271
+ await self._deps.session_store.delete_session(requester_address)
1272
+ await self._deps.signal_protocol.establish_outgoing_session(
1273
+ requester_address,
1274
+ SignalPreKeyBundle(
1275
+ reg_id=request.reg_id,
1276
+ identity=bytes(bundle.identity),
1277
+ signed_key=SignalPreKeyBundleSignedKey(
1278
+ id=bundle.skey.id,
1279
+ public_key=bytes(bundle.skey.public_key),
1280
+ signature=bytes(bundle.skey.signature or b""),
1281
+ ),
1282
+ one_time_key=(
1283
+ SignalPreKeyBundleOneTimeKey(
1284
+ id=bundle.key.id,
1285
+ public_key=bytes(bundle.key.public_key),
1286
+ )
1287
+ if bundle.key is not None
1288
+ else None
1289
+ ),
1290
+ ),
1291
+ reuse_existing=True,
1292
+ )
1293
+ return await self._apply_session_base_key_policy(
1294
+ request,
1295
+ requester_jid,
1296
+ requester_address,
1297
+ requester_normalized_device_jid,
1298
+ )
1299
+ session_still_exists = current_session is not None and not reg_id_mismatch
1300
+ if session_still_exists:
1301
+ return await self._apply_session_base_key_policy(
1302
+ request,
1303
+ requester_jid,
1304
+ requester_address,
1305
+ requester_normalized_device_jid,
1306
+ )
1307
+ fetched = await self._fetch_missing_pre_keys_session(
1308
+ requester_jid,
1309
+ requester_address,
1310
+ requester_normalized_device_jid,
1311
+ request.reg_id,
1312
+ )
1313
+ if fetched is None:
1314
+ return False
1315
+ await self._deps.signal_protocol.establish_outgoing_session(
1316
+ requester_address, fetched
1317
+ )
1318
+ return await self._apply_session_base_key_policy(
1319
+ request, requester_jid, requester_address, requester_normalized_device_jid
1320
+ )
1321
+
1322
+ async def _apply_session_base_key_policy(
1323
+ self,
1324
+ request: WaParsedRetryRequest,
1325
+ requester_jid: str,
1326
+ requester_address: SignalAddress,
1327
+ requester_normalized_device_jid: str,
1328
+ ) -> bool:
1329
+ if request.retry_count < 2:
1330
+ return True
1331
+ current_session = await self._deps.session_store.get_session(requester_address)
1332
+ session_base_key = (
1333
+ current_session.alice_base_key if current_session is not None else None
1334
+ )
1335
+ if not session_base_key:
1336
+ return True
1337
+ ttl_ms = await self._get_retry_ttl_ms()
1338
+ expires_at_ms = _now_ms() + ttl_ms
1339
+ if request.retry_count == 2:
1340
+ self._set_retry_session_base_key(
1341
+ request.original_msg_id,
1342
+ requester_normalized_device_jid,
1343
+ bytes(session_base_key),
1344
+ expires_at_ms,
1345
+ )
1346
+ return True
1347
+ saved = self._get_retry_session_base_key(
1348
+ request.original_msg_id, requester_normalized_device_jid
1349
+ )
1350
+ if saved is None or not uint8_equal(saved.base_key, bytes(session_base_key)):
1351
+ return True
1352
+ await self._deps.session_store.delete_session(requester_address)
1353
+ self._deps.logger.debug(
1354
+ "retry request forcing session refresh due to repeated base key",
1355
+ {
1356
+ "id": request.stanza_id,
1357
+ "originalMsgId": request.original_msg_id,
1358
+ "requester": requester_jid,
1359
+ "remoteRetryCount": request.retry_count,
1360
+ **_remote_retry_reason_log_fields(request.retry_reason),
1361
+ },
1362
+ )
1363
+ fetched = await self._fetch_missing_pre_keys_session(
1364
+ requester_jid,
1365
+ requester_address,
1366
+ requester_normalized_device_jid,
1367
+ request.reg_id,
1368
+ )
1369
+ if fetched is None:
1370
+ return False
1371
+ await self._deps.signal_protocol.establish_outgoing_session(
1372
+ requester_address, fetched
1373
+ )
1374
+ return True
1375
+
1376
+ async def _mark_retry_requester_sender_key_as_stale(
1377
+ self,
1378
+ request: WaParsedRetryRequest,
1379
+ requester_jid: str,
1380
+ requester_address: SignalAddress,
1381
+ ) -> None:
1382
+ if not is_group_or_broadcast_jid(request.sender_jid):
1383
+ return
1384
+ try:
1385
+ deleted = await self._deps.sender_key_store.mark_forget_sender_key(
1386
+ request.sender_jid, [requester_address]
1387
+ )
1388
+ self._deps.logger.debug(
1389
+ "marked sender key as stale for group retry requester",
1390
+ {
1391
+ "groupJid": request.sender_jid,
1392
+ "requester": requester_jid,
1393
+ "deleted": deleted,
1394
+ },
1395
+ )
1396
+ except Exception as error:
1397
+ self._deps.logger.warn(
1398
+ "failed to mark sender key as stale for group retry requester",
1399
+ {
1400
+ "groupJid": request.sender_jid,
1401
+ "requester": requester_jid,
1402
+ "message": str(to_error(error)),
1403
+ },
1404
+ )
1405
+
1406
+ async def _fetch_missing_pre_keys_session(
1407
+ self,
1408
+ requester_jid: str,
1409
+ requester_address: SignalAddress,
1410
+ requester_normalized_device_jid: str,
1411
+ requester_registration_id: int,
1412
+ ) -> SignalPreKeyBundle | None:
1413
+ try:
1414
+ missing_pre_keys = self._deps.signal_missing_pre_keys_sync
1415
+ results = await missing_pre_keys.fetch_missing_pre_keys(
1416
+ [
1417
+ MissingPreKeysFetchTarget(
1418
+ user_jid=f"{requester_address.user}@{requester_address.server}",
1419
+ devices=(
1420
+ MissingPreKeysDeviceTarget(
1421
+ device_id=requester_address.device,
1422
+ registration_id=requester_registration_id,
1423
+ ),
1424
+ ),
1425
+ )
1426
+ ]
1427
+ )
1428
+ first = results[0] if results else None
1429
+ if first is None or isinstance(first, SignalMissingPreKeysUserError):
1430
+ self._deps.logger.debug(
1431
+ "missing prekeys fetch returned user error",
1432
+ {
1433
+ "requester": requester_jid,
1434
+ "errorText": first.error_text
1435
+ if isinstance(first, SignalMissingPreKeysUserError)
1436
+ else "unknown",
1437
+ },
1438
+ )
1439
+ return None
1440
+ matched = next(
1441
+ (
1442
+ device
1443
+ for device in first.devices
1444
+ if normalize_device_jid(device.device_jid)
1445
+ == requester_normalized_device_jid
1446
+ ),
1447
+ None,
1448
+ )
1449
+ if matched is None:
1450
+ self._deps.logger.debug(
1451
+ "missing prekeys fetch did not return requested device",
1452
+ {
1453
+ "requester": requester_jid,
1454
+ "devices": len(first.devices),
1455
+ },
1456
+ )
1457
+ return None
1458
+ return cast("SignalPreKeyBundle", matched.bundle)
1459
+ except Exception as error:
1460
+ self._deps.logger.debug(
1461
+ "failed to fetch missing prekeys for retry requester",
1462
+ {"requester": requester_jid, "message": str(to_error(error))},
1463
+ )
1464
+ return None
1465
+
1466
+ async def _authorize_retry_request(
1467
+ self,
1468
+ request: WaParsedRetryRequest,
1469
+ outbound: WaRetryOutboundMessageRecord,
1470
+ requester_jid: str,
1471
+ requester_address: SignalAddress,
1472
+ requester_normalized_device_jid: str,
1473
+ ) -> RetryAuthorization:
1474
+ if outbound.state == "ineligible":
1475
+ return RetryAuthorization(
1476
+ authorized=False, reason=f"state_{outbound.state}"
1477
+ )
1478
+ requester_status = None
1479
+ try:
1480
+ status_fn = self._deps.retry_store.get_outbound_requester_status
1481
+ requester_status = await status_fn(
1482
+ outbound.message_id, to_user_jid(requester_normalized_device_jid)
1483
+ )
1484
+ except Exception as error:
1485
+ self._deps.logger.warn(
1486
+ "failed to resolve outbound requester status from retry store",
1487
+ {
1488
+ "id": request.stanza_id,
1489
+ "originalMsgId": request.original_msg_id,
1490
+ "requester": requester_jid,
1491
+ "message": str(to_error(error)),
1492
+ },
1493
+ )
1494
+ if requester_status is not None:
1495
+ if not requester_status.eligible:
1496
+ return RetryAuthorization(
1497
+ authorized=False, reason="requester_device_not_eligible"
1498
+ )
1499
+ if requester_status.delivered:
1500
+ return RetryAuthorization(
1501
+ authorized=False, reason="requester_already_delivered"
1502
+ )
1503
+ is_group_outbound = is_group_or_broadcast_jid(outbound.to_jid)
1504
+ if not is_group_outbound and outbound.state in ("read", "played"):
1505
+ return RetryAuthorization(
1506
+ authorized=False, reason=f"state_{outbound.state}"
1507
+ )
1508
+ if requester_status is None:
1509
+ requester_authorized = await self._is_requester_authorized_device(
1510
+ requester_jid, requester_address, requester_normalized_device_jid
1511
+ )
1512
+ if not requester_authorized:
1513
+ return RetryAuthorization(
1514
+ authorized=False, reason="requester_device_not_authorized"
1515
+ )
1516
+ return RetryAuthorization(authorized=True)
1517
+
1518
+ async def _is_requester_authorized_device(
1519
+ self,
1520
+ requester_jid: str,
1521
+ requester_address: SignalAddress,
1522
+ requester_normalized_device_jid: str,
1523
+ ) -> bool:
1524
+ try:
1525
+ requester_user = f"{requester_address.user}@{requester_address.server}"
1526
+ if requester_normalized_device_jid == normalize_device_jid(requester_user):
1527
+ return True
1528
+ synced = await self._deps.signal_device_sync.sync_device_list(
1529
+ [requester_user]
1530
+ )
1531
+ target = next(
1532
+ (entry for entry in synced if entry.jid == requester_user), None
1533
+ )
1534
+ if target is None:
1535
+ return False
1536
+ for device_jid in target.device_jids:
1537
+ if normalize_device_jid(device_jid) == requester_normalized_device_jid:
1538
+ return True
1539
+ return False
1540
+ except Exception as error:
1541
+ self._deps.logger.warn(
1542
+ "retry authorization failed while syncing requester device list",
1543
+ {"requester": requester_jid, "message": str(to_error(error))},
1544
+ )
1545
+ return False
1546
+
1547
+ def _map_outbound_state_from_receipt_type(
1548
+ self, receipt_type: str | None
1549
+ ) -> WaRetryOutboundState | None:
1550
+ if receipt_type == WA_MESSAGE_TYPES["RECEIPT_TYPE_READ"]:
1551
+ return "read"
1552
+ if receipt_type == WA_MESSAGE_TYPES["RECEIPT_TYPE_PLAYED"]:
1553
+ return "played"
1554
+ if (
1555
+ receipt_type is None
1556
+ or receipt_type == ""
1557
+ or receipt_type == WA_MESSAGE_TYPES["RECEIPT_TYPE_DELIVERY"]
1558
+ or receipt_type == WA_MESSAGE_TYPES["RECEIPT_TYPE_SENDER"]
1559
+ or receipt_type == WA_MESSAGE_TYPES["RECEIPT_TYPE_INACTIVE"]
1560
+ or receipt_type == WA_MESSAGE_TYPES["RECEIPT_TYPE_PEER"]
1561
+ ):
1562
+ return "delivered"
1563
+ return None
1564
+
1565
+ async def _send_retry_ack_safe(self, receipt_node: BinaryNode) -> None:
1566
+ if not receipt_node.attrs.get("id") or not receipt_node.attrs.get("from"):
1567
+ self._deps.logger.warn(
1568
+ "retry ack skipped: missing receipt id/from",
1569
+ {
1570
+ "hasId": receipt_node.attrs.get("id") is not None,
1571
+ "hasFrom": receipt_node.attrs.get("from") is not None,
1572
+ "participant": receipt_node.attrs.get("participant"),
1573
+ "type": receipt_node.attrs.get("type"),
1574
+ },
1575
+ )
1576
+ return
1577
+ try:
1578
+ await self._deps.send_node(_build_retry_ack_node(receipt_node))
1579
+ except Exception as error:
1580
+ self._deps.logger.warn(
1581
+ "failed to send retry ack",
1582
+ {
1583
+ "id": receipt_node.attrs.get("id"),
1584
+ "from": receipt_node.attrs.get("from"),
1585
+ "participant": receipt_node.attrs.get("participant"),
1586
+ "message": str(to_error(error)),
1587
+ },
1588
+ )
1589
+
1590
+ async def _maybe_cleanup_retry_store(self, now_ms: int) -> None:
1591
+ if now_ms < self._next_retry_cleanup_at_ms:
1592
+ return
1593
+ self._next_retry_cleanup_at_ms = now_ms + _RETRY_CLEANUP_INTERVAL_MS
1594
+ self._cleanup_retry_session_base_keys(now_ms)
1595
+ try:
1596
+ await self._deps.retry_store.cleanup_expired(now_ms)
1597
+ except Exception as error:
1598
+ self._deps.logger.warn(
1599
+ "retry store cleanup failed", {"message": str(to_error(error))}
1600
+ )
1601
+
1602
+ def _retry_session_base_key_map_key(
1603
+ self, original_msg_id: str, requester_normalized_device_jid: str
1604
+ ) -> str:
1605
+ return f"{original_msg_id}|{requester_normalized_device_jid}"
1606
+
1607
+ def _set_retry_session_base_key(
1608
+ self,
1609
+ original_msg_id: str,
1610
+ requester_normalized_device_jid: str,
1611
+ base_key: bytes,
1612
+ expires_at_ms: int,
1613
+ ) -> None:
1614
+ set_bounded_map_entry(
1615
+ self._retry_session_base_keys,
1616
+ self._retry_session_base_key_map_key(
1617
+ original_msg_id, requester_normalized_device_jid
1618
+ ),
1619
+ RetrySessionBaseKeySnapshot(
1620
+ base_key=bytes(base_key), expires_at_ms=expires_at_ms
1621
+ ),
1622
+ _RETRY_SESSION_BASE_KEY_CACHE_MAX_ENTRIES,
1623
+ )
1624
+
1625
+ def _get_retry_session_base_key(
1626
+ self, original_msg_id: str, requester_normalized_device_jid: str
1627
+ ) -> RetrySessionBaseKeySnapshot | None:
1628
+ key = self._retry_session_base_key_map_key(
1629
+ original_msg_id, requester_normalized_device_jid
1630
+ )
1631
+ entry = self._retry_session_base_keys.get(key)
1632
+ if entry is None:
1633
+ return None
1634
+ if entry.expires_at_ms <= _now_ms():
1635
+ del self._retry_session_base_keys[key]
1636
+ return None
1637
+ return entry
1638
+
1639
+ def _cleanup_retry_session_base_keys(self, now_ms: int) -> None:
1640
+ for key, entry in list(self._retry_session_base_keys.items()):
1641
+ if entry.expires_at_ms <= now_ms:
1642
+ del self._retry_session_base_keys[key]
1643
+
1644
+ def _is_sender_from_own_account(
1645
+ self, context: WaRetryDecryptFailureContext
1646
+ ) -> bool:
1647
+ sender_user = parse_signal_address_from_jid(
1648
+ context.participant or context.sender_jid
1649
+ ).user
1650
+ credentials = self._deps.get_current_credentials()
1651
+ me_lid = credentials.me_lid if credentials else None
1652
+ if me_lid:
1653
+ try:
1654
+ if parse_signal_address_from_jid(me_lid).user == sender_user:
1655
+ return True
1656
+ except ValueError:
1657
+ pass
1658
+ me_jid = credentials.me_jid if credentials else None
1659
+ if not me_jid:
1660
+ return False
1661
+ try:
1662
+ return parse_signal_address_from_jid(me_jid).user == sender_user
1663
+ except ValueError:
1664
+ return False
1665
+
1666
+ def on_unavailable_message(self, context: WaRetryDecryptFailureContext) -> bool:
1667
+ """Queue a placeholder resend for a server-delivered ``<unavailable/>``."""
1668
+ return self._enqueue_placeholder_resend(context)
1669
+
1670
+ def _get_placeholder_resend_max_age_seconds(self) -> float:
1671
+ days = (
1672
+ _try_as_number(
1673
+ self._deps.get_ab_prop_number(
1674
+ "placeholder_message_resend_maximum_days_limit"
1675
+ )
1676
+ )
1677
+ if self._deps.get_ab_prop_number is not None
1678
+ else None
1679
+ )
1680
+ window_days = (
1681
+ days
1682
+ if days is not None and days > 0
1683
+ else _PLACEHOLDER_RESEND_FALLBACK_MAX_AGE_DAYS
1684
+ )
1685
+ return window_days * _DAY_SECONDS
1686
+
1687
+ def _build_placeholder_resend_key(
1688
+ self, context: WaRetryDecryptFailureContext
1689
+ ) -> PlaceholderResendQueueItem:
1690
+ from_me = self._is_sender_from_own_account(context)
1691
+ is_group_or_broadcast = is_group_or_broadcast_jid(context.sender_jid)
1692
+ chat_jid = (
1693
+ (context.message_node.attrs.get("recipient") or context.sender_jid)
1694
+ if from_me and not is_group_or_broadcast
1695
+ else context.sender_jid
1696
+ )
1697
+ participant: str | None = None
1698
+ if not from_me and is_group_or_broadcast and context.participant:
1699
+ participant = to_user_jid(context.participant)
1700
+ return PlaceholderResendQueueItem(
1701
+ remote_jid=to_user_jid(chat_jid),
1702
+ id=context.stanza_id,
1703
+ from_me=from_me,
1704
+ participant=participant,
1705
+ )
1706
+
1707
+ def _enqueue_placeholder_resend(
1708
+ self, context: WaRetryDecryptFailureContext
1709
+ ) -> bool:
1710
+ peer_data = self._deps.peer_data_operation
1711
+ emit = self._deps.emit_incoming_message
1712
+ if peer_data is None or emit is None:
1713
+ return False
1714
+ if self._deps.is_mobile_primary is not None and self._deps.is_mobile_primary():
1715
+ return False
1716
+ skip_subtype = resolve_placeholder_resend_skip_subtype(context.message_node)
1717
+ if skip_subtype is not None:
1718
+ self._deps.logger.trace(
1719
+ "placeholder resend skipped: unrecoverable placeholder",
1720
+ {"id": context.stanza_id, "subtype": skip_subtype},
1721
+ )
1722
+ return False
1723
+ timestamp_seconds: float | None = None
1724
+ if context.t:
1725
+ try:
1726
+ timestamp_seconds = float(context.t)
1727
+ except ValueError:
1728
+ timestamp_seconds = None
1729
+ if timestamp_seconds is not None and timestamp_seconds == timestamp_seconds:
1730
+ age_seconds = _now_seconds() - timestamp_seconds
1731
+ if age_seconds > self._get_placeholder_resend_max_age_seconds():
1732
+ return False
1733
+ if context.stanza_id in self._placeholder_in_flight:
1734
+ return True
1735
+ if len(self._placeholder_in_flight) >= _PLACEHOLDER_RESEND_IN_FLIGHT_MAX:
1736
+ self._deps.logger.warn(
1737
+ "placeholder resend: in-flight set saturated, dropping enqueue",
1738
+ {
1739
+ "id": context.stanza_id,
1740
+ "maxInFlight": _PLACEHOLDER_RESEND_IN_FLIGHT_MAX,
1741
+ },
1742
+ )
1743
+ return False
1744
+ self._placeholder_in_flight.add(context.stanza_id)
1745
+ self._placeholder_queue.append(self._build_placeholder_resend_key(context))
1746
+ if self._placeholder_timer is None:
1747
+ loop = asyncio.get_running_loop()
1748
+ self._placeholder_timer = loop.call_later(
1749
+ _PLACEHOLDER_RESEND_DEBOUNCE_SECONDS, self._on_placeholder_timer
1750
+ )
1751
+ return True
1752
+
1753
+ def _on_placeholder_timer(self) -> None:
1754
+ self._placeholder_timer = None
1755
+ task = asyncio.ensure_future(self._flush_placeholder_batch())
1756
+
1757
+ def _log_failure(done: asyncio.Task[None]) -> None:
1758
+ try:
1759
+ done.result()
1760
+ except Exception as error:
1761
+ self._deps.logger.warn(
1762
+ "placeholder resend: background flush failed",
1763
+ {"message": str(to_error(error))},
1764
+ )
1765
+
1766
+ task.add_done_callback(_log_failure)
1767
+
1768
+ async def _flush_placeholder_batch(self) -> None:
1769
+ peer_data_operation = self._deps.peer_data_operation
1770
+ emit_incoming_message = self._deps.emit_incoming_message
1771
+ if peer_data_operation is None or emit_incoming_message is None:
1772
+ self._placeholder_queue = []
1773
+ self._placeholder_in_flight.clear()
1774
+ return
1775
+ me_jid = None
1776
+ credentials = self._deps.get_current_credentials()
1777
+ if credentials is not None:
1778
+ me_jid = credentials.me_jid
1779
+ while self._placeholder_queue:
1780
+ batch = self._placeholder_queue[:_PLACEHOLDER_RESEND_BATCH_SIZE]
1781
+ del self._placeholder_queue[:_PLACEHOLDER_RESEND_BATCH_SIZE]
1782
+ try:
1783
+ results = await peer_data_operation.request(
1784
+ _PLACEHOLDER_MESSAGE_RESEND_REQUEST_TYPE,
1785
+ {
1786
+ "placeholderMessageResendRequest": [
1787
+ {
1788
+ "messageKey": {
1789
+ "remoteJid": item.remote_jid,
1790
+ "id": item.id,
1791
+ "fromMe": item.from_me,
1792
+ **(
1793
+ {"participant": item.participant}
1794
+ if item.participant is not None
1795
+ else {}
1796
+ ),
1797
+ }
1798
+ }
1799
+ for item in batch
1800
+ ]
1801
+ },
1802
+ _PLACEHOLDER_RESEND_TIMEOUT_MS,
1803
+ )
1804
+ for result in results:
1805
+ response = result.get("placeholderMessageResendResponse")
1806
+ raw_bytes = (
1807
+ response.get("webMessageInfoBytes")
1808
+ if isinstance(response, dict)
1809
+ else None
1810
+ )
1811
+ if raw_bytes is None:
1812
+ continue
1813
+ try:
1814
+ if isinstance(raw_bytes, str):
1815
+ raw_bytes = base64.b64decode(raw_bytes)
1816
+ recovered = WAProto_pb2.WebMessageInfo.FromString(
1817
+ bytes(raw_bytes)
1818
+ )
1819
+ emit_incoming_message(
1820
+ build_recovered_incoming_event(
1821
+ proto_message_to_dict(recovered), me_jid
1822
+ )
1823
+ )
1824
+ except Exception as error:
1825
+ self._deps.logger.warn(
1826
+ "placeholder resend: failed to decode WebMessageInfo",
1827
+ {"message": str(to_error(error))},
1828
+ )
1829
+ except Exception as error:
1830
+ self._deps.logger.warn(
1831
+ "placeholder resend: request failed",
1832
+ {
1833
+ "batchSize": len(batch),
1834
+ "message": str(to_error(error)),
1835
+ },
1836
+ )
1837
+ finally:
1838
+ for item in batch:
1839
+ self._placeholder_in_flight.discard(item.id)
1840
+
1841
+
1842
+ def _coerce_outbound_record(raw: Any) -> WaRetryOutboundMessageRecord:
1843
+ """Coerce a store outbound record to :class:`WaRetryOutboundMessageRecord`."""
1844
+ if isinstance(raw, WaRetryOutboundMessageRecord):
1845
+ return raw
1846
+ if isinstance(raw, dict):
1847
+ eligible = raw.get("eligibleRequesterDeviceJids")
1848
+ delivered = raw.get("deliveredRequesterDeviceJids")
1849
+ return WaRetryOutboundMessageRecord(
1850
+ message_id=raw["messageId"],
1851
+ to_jid=raw["toJid"],
1852
+ replay_mode=raw["replayMode"],
1853
+ replay_payload=raw.get("replayPayload"),
1854
+ state=raw["state"],
1855
+ updated_at_ms=raw.get("updatedAtMs", 0),
1856
+ expires_at_ms=raw.get("expiresAtMs", 0),
1857
+ eligible_requester_device_jids=(
1858
+ tuple(eligible) if eligible is not None else None
1859
+ ),
1860
+ delivered_requester_device_jids=(
1861
+ tuple(delivered) if delivered is not None else None
1862
+ ),
1863
+ )
1864
+ return WaRetryOutboundMessageRecord(
1865
+ message_id=raw.message_id,
1866
+ to_jid=raw.to_jid,
1867
+ replay_mode=raw.replay_mode,
1868
+ replay_payload=raw.replay_payload,
1869
+ state=raw.state,
1870
+ updated_at_ms=raw.updated_at_ms,
1871
+ expires_at_ms=raw.expires_at_ms,
1872
+ eligible_requester_device_jids=getattr(
1873
+ raw, "eligible_requester_device_jids", None
1874
+ ),
1875
+ delivered_requester_device_jids=getattr(
1876
+ raw, "delivered_requester_device_jids", None
1877
+ ),
1878
+ )