shellzapy 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- shellzapy-0.1.0.dist-info/METADATA +112 -0
- shellzapy-0.1.0.dist-info/RECORD +345 -0
- shellzapy-0.1.0.dist-info/WHEEL +4 -0
- shellzapy-0.1.0.dist-info/licenses/LICENSE +21 -0
- shellzapy-0.1.0.dist-info/licenses/NOTICE +9 -0
- zapy/__init__.py +58 -0
- zapy/_appstate/__init__.py +59 -0
- zapy/_appstate/constants.py +82 -0
- zapy/_appstate/crypto/__init__.py +17 -0
- zapy/_appstate/crypto/app_state_crypto.py +401 -0
- zapy/_appstate/parsers/__init__.py +23 -0
- zapy/_appstate/parsers/encoding.py +157 -0
- zapy/_appstate/parsers/response_parser.py +135 -0
- zapy/_appstate/sync/__init__.py +11 -0
- zapy/_appstate/sync/sync_client.py +1559 -0
- zapy/_appstate/types.py +137 -0
- zapy/_appstate/utils.py +100 -0
- zapy/_auth/__init__.py +3 -0
- zapy/_auth/auth_client.py +618 -0
- zapy/_auth/credentials_flow.py +290 -0
- zapy/_auth/pairing/__init__.py +3 -0
- zapy/_auth/pairing/companion_host.py +239 -0
- zapy/_auth/pairing/flow.py +808 -0
- zapy/_auth/pairing/pairing_code_crypto.py +143 -0
- zapy/_auth/pairing/qr_flow.py +123 -0
- zapy/_auth/pairing/shortcake_crypto.py +122 -0
- zapy/_auth/pairing/shortcake_flow.py +393 -0
- zapy/_auth/types.py +110 -0
- zapy/_client/__init__.py +26 -0
- zapy/_client/client.py +972 -0
- zapy/_client/connection/__init__.py +6 -0
- zapy/_client/connection/manager.py +525 -0
- zapy/_client/connection/receipt_queue.py +74 -0
- zapy/_client/coordinators/__init__.py +81 -0
- zapy/_client/coordinators/ab_props.py +260 -0
- zapy/_client/coordinators/app_state_mutation.py +2538 -0
- zapy/_client/coordinators/bot.py +830 -0
- zapy/_client/coordinators/broadcast_list.py +101 -0
- zapy/_client/coordinators/business.py +247 -0
- zapy/_client/coordinators/email.py +158 -0
- zapy/_client/coordinators/group.py +1478 -0
- zapy/_client/coordinators/incoming_node.py +758 -0
- zapy/_client/coordinators/low_level.py +119 -0
- zapy/_client/coordinators/message.py +1153 -0
- zapy/_client/coordinators/message_dispatch.py +1637 -0
- zapy/_client/coordinators/newsletter.py +110 -0
- zapy/_client/coordinators/offline_resume.py +271 -0
- zapy/_client/coordinators/passive_tasks.py +447 -0
- zapy/_client/coordinators/presence.py +103 -0
- zapy/_client/coordinators/privacy.py +623 -0
- zapy/_client/coordinators/profile.py +1024 -0
- zapy/_client/coordinators/retry.py +1878 -0
- zapy/_client/coordinators/status.py +132 -0
- zapy/_client/coordinators/stream_control.py +260 -0
- zapy/_client/coordinators/trusted_contact_token.py +417 -0
- zapy/_client/events/__init__.py +266 -0
- zapy/_client/events/abprops.py +58 -0
- zapy/_client/events/appstate_mutation.py +248 -0
- zapy/_client/events/business.py +565 -0
- zapy/_client/events/call.py +144 -0
- zapy/_client/events/chatstate.py +41 -0
- zapy/_client/events/devices.py +122 -0
- zapy/_client/events/dirty.py +384 -0
- zapy/_client/events/group.py +655 -0
- zapy/_client/events/identity.py +40 -0
- zapy/_client/events/incoming.py +1079 -0
- zapy/_client/events/mex_notification.py +317 -0
- zapy/_client/events/offline.py +123 -0
- zapy/_client/events/picture.py +67 -0
- zapy/_client/events/presence.py +74 -0
- zapy/_client/events/privacy.py +187 -0
- zapy/_client/events/privacy_token.py +72 -0
- zapy/_client/events/receipt.py +109 -0
- zapy/_client/events/registration.py +70 -0
- zapy/_client/events/username.py +76 -0
- zapy/_client/factory.py +2020 -0
- zapy/_client/media.py +829 -0
- zapy/_client/newsletter/__init__.py +90 -0
- zapy/_client/newsletter/admin.py +323 -0
- zapy/_client/newsletter/content.py +499 -0
- zapy/_client/newsletter/discovery.py +233 -0
- zapy/_client/newsletter/messaging.py +396 -0
- zapy/_client/newsletter/mex.py +99 -0
- zapy/_client/newsletter/parse.py +406 -0
- zapy/_client/newsletter/types.py +393 -0
- zapy/_client/persistence/__init__.py +89 -0
- zapy/_client/persistence/companion_host.py +133 -0
- zapy/_client/persistence/ephemeral_setting.py +245 -0
- zapy/_client/persistence/group_history.py +361 -0
- zapy/_client/persistence/history_blob.py +169 -0
- zapy/_client/persistence/history_sync.py +646 -0
- zapy/_client/persistence/mailbox.py +232 -0
- zapy/_client/persistence/write_behind_persistence.py +368 -0
- zapy/_client/plugins/__init__.py +23 -0
- zapy/_client/plugins/define.py +44 -0
- zapy/_client/plugins/install.py +254 -0
- zapy/_client/plugins/types.py +64 -0
- zapy/_client/tokens/__init__.py +21 -0
- zapy/_client/tokens/cs_token.py +47 -0
- zapy/_client/tokens/tc_token.py +43 -0
- zapy/_client/types.py +988 -0
- zapy/_crypto/__init__.py +65 -0
- zapy/_crypto/core/__init__.py +62 -0
- zapy/_crypto/core/hkdf.py +41 -0
- zapy/_crypto/core/keys.py +51 -0
- zapy/_crypto/core/nonce.py +25 -0
- zapy/_crypto/core/primitives.py +179 -0
- zapy/_crypto/core/random.py +32 -0
- zapy/_crypto/core/xeddsa.py +72 -0
- zapy/_crypto/curves/__init__.py +3 -0
- zapy/_crypto/curves/constants.py +10 -0
- zapy/_crypto/curves/ed25519.py +61 -0
- zapy/_crypto/curves/types.py +18 -0
- zapy/_crypto/curves/x25519.py +117 -0
- zapy/_crypto/math/__init__.py +3 -0
- zapy/_crypto/math/constants.py +35 -0
- zapy/_crypto/math/edwards.py +174 -0
- zapy/_crypto/math/fe.py +120 -0
- zapy/_crypto/math/le.py +13 -0
- zapy/_crypto/math/mod.py +15 -0
- zapy/_crypto/math/prime.py +11 -0
- zapy/_crypto/math/types.py +25 -0
- zapy/_crypto/native_backend.py +40 -0
- zapy/_infra/__init__.py +3 -0
- zapy/_infra/log.py +142 -0
- zapy/_infra/perf.py +77 -0
- zapy/_media/__init__.py +64 -0
- zapy/_media/constants.py +133 -0
- zapy/_media/container.py +110 -0
- zapy/_media/crypto/__init__.py +19 -0
- zapy/_media/crypto/crypto.py +633 -0
- zapy/_media/crypto/media_retry.py +107 -0
- zapy/_media/processor.py +100 -0
- zapy/_media/sticker/__init__.py +8 -0
- zapy/_media/sticker/pack.py +188 -0
- zapy/_media/transfer/__init__.py +15 -0
- zapy/_media/transfer/client.py +635 -0
- zapy/_media/transfer/conn.py +48 -0
- zapy/_media/types.py +169 -0
- zapy/_message/__init__.py +121 -0
- zapy/_message/addons/__init__.py +5 -0
- zapy/_message/addons/link_preview/__init__.py +54 -0
- zapy/_message/addons/link_preview/builder.py +56 -0
- zapy/_message/addons/link_preview/detect.py +72 -0
- zapy/_message/addons/link_preview/fetcher.py +553 -0
- zapy/_message/addons/link_preview/types.py +100 -0
- zapy/_message/client.py +486 -0
- zapy/_message/context_info.py +424 -0
- zapy/_message/crypto/__init__.py +71 -0
- zapy/_message/crypto/addon_crypto.py +656 -0
- zapy/_message/crypto/icdc.py +138 -0
- zapy/_message/crypto/phash.py +87 -0
- zapy/_message/crypto/reporting_token.py +498 -0
- zapy/_message/crypto/use_case_secret.py +113 -0
- zapy/_message/encode/__init__.py +84 -0
- zapy/_message/encode/content.py +636 -0
- zapy/_message/encode/device_sent.py +88 -0
- zapy/_message/encode/media_payload.py +122 -0
- zapy/_message/encode/padding.py +27 -0
- zapy/_message/kinds/__init__.py +1 -0
- zapy/_message/kinds/bot.py +179 -0
- zapy/_message/kinds/group_history.py +206 -0
- zapy/_message/kinds/newsletter.py +388 -0
- zapy/_message/kinds/sticker_pack.py +74 -0
- zapy/_message/messaging/__init__.py +336 -0
- zapy/_message/messaging/companion_host.py +117 -0
- zapy/_message/messaging/fanout.py +311 -0
- zapy/_message/messaging/group_metadata.py +444 -0
- zapy/_message/messaging/ignore_key.py +264 -0
- zapy/_message/messaging/key_protocol.py +217 -0
- zapy/_message/messaging/link_preview.py +448 -0
- zapy/_message/messaging/messages.py +1429 -0
- zapy/_message/primitives/__init__.py +1 -0
- zapy/_message/primitives/ack.py +232 -0
- zapy/_message/primitives/incoming.py +1141 -0
- zapy/_message/primitives/media_retry.py +451 -0
- zapy/_message/primitives/peer_data_operation.py +271 -0
- zapy/_message/types.py +434 -0
- zapy/_proto/WAProto_pb2.py +2584 -0
- zapy/_proto/__init__.py +1 -0
- zapy/_protocol/__init__.py +3 -0
- zapy/_protocol/abprops_spec.py +6216 -0
- zapy/_protocol/auth.py +17 -0
- zapy/_protocol/browser.py +57 -0
- zapy/_protocol/defaults.py +38 -0
- zapy/_protocol/device_identity.py +54 -0
- zapy/_protocol/jid.py +241 -0
- zapy/_protocol/message.py +127 -0
- zapy/_protocol/nodes.py +144 -0
- zapy/_protocol/notification.py +18 -0
- zapy/_retry/__init__.py +77 -0
- zapy/_retry/codec.py +209 -0
- zapy/_retry/constants.py +28 -0
- zapy/_retry/parse.py +132 -0
- zapy/_retry/reason.py +65 -0
- zapy/_retry/replay.py +483 -0
- zapy/_retry/tracker.py +161 -0
- zapy/_retry/types.py +122 -0
- zapy/_signal/__init__.py +171 -0
- zapy/_signal/api/__init__.py +133 -0
- zapy/_signal/api/codec.py +164 -0
- zapy/_signal/api/constants.py +14 -0
- zapy/_signal/api/device_sync.py +915 -0
- zapy/_signal/api/digest_sync.py +363 -0
- zapy/_signal/api/identity_sync.py +250 -0
- zapy/_signal/api/missing_pre_keys_sync.py +267 -0
- zapy/_signal/api/prekeys.py +191 -0
- zapy/_signal/api/result_map.py +40 -0
- zapy/_signal/api/rotate_key.py +111 -0
- zapy/_signal/api/session_sync.py +297 -0
- zapy/_signal/attestation.py +145 -0
- zapy/_signal/constants.py +22 -0
- zapy/_signal/encoding.py +78 -0
- zapy/_signal/group/__init__.py +35 -0
- zapy/_signal/group/chain.py +139 -0
- zapy/_signal/group/codec.py +78 -0
- zapy/_signal/group/encoding.py +166 -0
- zapy/_signal/group/manager.py +361 -0
- zapy/_signal/registration/__init__.py +44 -0
- zapy/_signal/registration/keygen.py +46 -0
- zapy/_signal/registration/reg_encoding.py +66 -0
- zapy/_signal/registration/reg_utils.py +52 -0
- zapy/_signal/session/__init__.py +114 -0
- zapy/_signal/session/encoding.py +385 -0
- zapy/_signal/session/protocol.py +590 -0
- zapy/_signal/session/ratchet.py +381 -0
- zapy/_signal/session/resolver.py +630 -0
- zapy/_signal/session/serializer.py +96 -0
- zapy/_signal/session/session.py +272 -0
- zapy/_signal/types.py +214 -0
- zapy/_store/__init__.py +118 -0
- zapy/_store/cache/__init__.py +166 -0
- zapy/_store/cache/identity.py +130 -0
- zapy/_store/cache/privacy_token.py +116 -0
- zapy/_store/cache/sender_key.py +168 -0
- zapy/_store/cache/session.py +142 -0
- zapy/_store/contracts/__init__.py +84 -0
- zapy/_store/contracts/appstate.py +82 -0
- zapy/_store/contracts/auth.py +16 -0
- zapy/_store/contracts/chat_metadata.py +29 -0
- zapy/_store/contracts/contact.py +31 -0
- zapy/_store/contracts/device_list.py +35 -0
- zapy/_store/contracts/group_metadata.py +33 -0
- zapy/_store/contracts/identity.py +18 -0
- zapy/_store/contracts/message.py +36 -0
- zapy/_store/contracts/message_secret.py +41 -0
- zapy/_store/contracts/pre_key.py +32 -0
- zapy/_store/contracts/privacy_token.py +32 -0
- zapy/_store/contracts/retry.py +47 -0
- zapy/_store/contracts/sender_key.py +37 -0
- zapy/_store/contracts/session.py +21 -0
- zapy/_store/contracts/signal.py +23 -0
- zapy/_store/contracts/thread.py +35 -0
- zapy/_store/create_store.py +890 -0
- zapy/_store/locks.py +1154 -0
- zapy/_store/memory/__init__.py +40 -0
- zapy/_store/memory/appstate.py +200 -0
- zapy/_store/memory/auth.py +24 -0
- zapy/_store/memory/chat_metadata.py +124 -0
- zapy/_store/memory/contact.py +125 -0
- zapy/_store/memory/device_list.py +161 -0
- zapy/_store/memory/group_metadata.py +125 -0
- zapy/_store/memory/identity.py +86 -0
- zapy/_store/memory/message.py +85 -0
- zapy/_store/memory/message_secret.py +145 -0
- zapy/_store/memory/pre_key.py +112 -0
- zapy/_store/memory/privacy_token.py +103 -0
- zapy/_store/memory/retry.py +250 -0
- zapy/_store/memory/sender_key.py +162 -0
- zapy/_store/memory/session.py +111 -0
- zapy/_store/memory/signal.py +45 -0
- zapy/_store/memory/thread.py +66 -0
- zapy/_store/noop.py +279 -0
- zapy/_transport/__init__.py +3 -0
- zapy/_transport/binary/__init__.py +77 -0
- zapy/_transport/binary/constants.py +80 -0
- zapy/_transport/binary/decoder.py +260 -0
- zapy/_transport/binary/encoder.py +279 -0
- zapy/_transport/binary/tokens.py +1289 -0
- zapy/_transport/comms.py +759 -0
- zapy/_transport/keepalive/__init__.py +3 -0
- zapy/_transport/keepalive/keep_alive.py +252 -0
- zapy/_transport/node/__init__.py +3 -0
- zapy/_transport/node/builders/__init__.py +9 -0
- zapy/_transport/node/builders/abprops.py +33 -0
- zapy/_transport/node/builders/account_sync.py +120 -0
- zapy/_transport/node/builders/bot.py +56 -0
- zapy/_transport/node/builders/business.py +261 -0
- zapy/_transport/node/builders/chatstate.py +74 -0
- zapy/_transport/node/builders/community.py +116 -0
- zapy/_transport/node/builders/device.py +30 -0
- zapy/_transport/node/builders/email.py +181 -0
- zapy/_transport/node/builders/global_.py +74 -0
- zapy/_transport/node/builders/group.py +279 -0
- zapy/_transport/node/builders/media.py +21 -0
- zapy/_transport/node/builders/message.py +436 -0
- zapy/_transport/node/builders/mobile.py +227 -0
- zapy/_transport/node/builders/newsletter.py +293 -0
- zapy/_transport/node/builders/offline.py +20 -0
- zapy/_transport/node/builders/pairing.py +130 -0
- zapy/_transport/node/builders/passive.py +28 -0
- zapy/_transport/node/builders/prekeys.py +215 -0
- zapy/_transport/node/builders/presence.py +100 -0
- zapy/_transport/node/builders/privacy.py +243 -0
- zapy/_transport/node/builders/privacy_token.py +94 -0
- zapy/_transport/node/builders/profile.py +176 -0
- zapy/_transport/node/builders/retry.py +156 -0
- zapy/_transport/node/builders/shortcake.py +87 -0
- zapy/_transport/node/builders/tos.py +92 -0
- zapy/_transport/node/builders/usync.py +185 -0
- zapy/_transport/node/helpers.py +201 -0
- zapy/_transport/node/orchestrator.py +210 -0
- zapy/_transport/node/query.py +82 -0
- zapy/_transport/node/transport.py +105 -0
- zapy/_transport/node/usync.py +33 -0
- zapy/_transport/node/xml.py +38 -0
- zapy/_transport/noise/__init__.py +7 -0
- zapy/_transport/noise/cert.py +85 -0
- zapy/_transport/noise/client_payload.py +344 -0
- zapy/_transport/noise/constants.py +12 -0
- zapy/_transport/noise/frame_codec.py +120 -0
- zapy/_transport/noise/handshake.py +92 -0
- zapy/_transport/noise/session.py +493 -0
- zapy/_transport/noise/socket.py +45 -0
- zapy/_transport/noise/types.py +66 -0
- zapy/_transport/noise/version.json +3 -0
- zapy/_transport/proxy.py +35 -0
- zapy/_transport/types.py +19 -0
- zapy/_transport/wa_version_fetcher.py +159 -0
- zapy/_transport/web_socket.py +602 -0
- zapy/_util/__init__.py +3 -0
- zapy/_util/bytes.py +131 -0
- zapy/_util/coercion.py +29 -0
- zapy/_util/collections.py +45 -0
- zapy/_util/primitives.py +49 -0
- zapy/client.py +840 -0
- zapy/errors.py +148 -0
- zapy/events.py +564 -0
- zapy/jid.py +140 -0
- zapy/py.typed +0 -0
- zapy/stores/__init__.py +50 -0
- zapy/stores/base.py +1627 -0
- zapy/stores/json_file.py +359 -0
- zapy/stores/memory.py +322 -0
- zapy/stores/sqlite.py +343 -0
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""Inbound mailbox persistence (mirrors ``src/client/persistence/mailbox.ts``).
|
|
2
|
+
|
|
3
|
+
The proto encoding of ``event.message`` goes through the injected
|
|
4
|
+
``message_encoder`` seam: the message layer works with ``MessageDict`` values
|
|
5
|
+
and ``WAProto_pb2`` objects but exposes no shared dict-to-bytes helper, so
|
|
6
|
+
production wiring passes its own encoder (tests inject a JSON encoder).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
from collections.abc import Callable, Coroutine
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from zapy._message.encode.content import MessageDict, needs_secret_persistence
|
|
17
|
+
from zapy._message.primitives.incoming import (
|
|
18
|
+
WaIncomingMessageEvent,
|
|
19
|
+
to_user_jid,
|
|
20
|
+
)
|
|
21
|
+
from zapy._protocol.defaults import HOST_DOMAIN, LID_SERVER
|
|
22
|
+
from zapy._store.contracts.contact import WaStoredContactRecord
|
|
23
|
+
from zapy._store.contracts.message import WaStoredMessageRecord
|
|
24
|
+
from zapy._store.contracts.message_secret import (
|
|
25
|
+
WaMessageSecretEntry,
|
|
26
|
+
WaMessageSecretStore,
|
|
27
|
+
)
|
|
28
|
+
from zapy._util.primitives import to_error
|
|
29
|
+
|
|
30
|
+
_logger = logging.getLogger("zapy._client.persistence.mailbox")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _is_jid_type(jid: str, server: str) -> bool:
|
|
34
|
+
at_index = len(jid) - len(server) - 1
|
|
35
|
+
return at_index >= 1 and jid.endswith(f"@{server}") and jid[at_index] == "@"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def is_lid_jid(jid: str) -> bool:
|
|
39
|
+
"""Return whether ``jid`` lives on the LID server."""
|
|
40
|
+
return _is_jid_type(jid, LID_SERVER)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def is_user_jid(jid: str) -> bool:
|
|
44
|
+
"""Return whether ``jid`` lives on the phone-number user server."""
|
|
45
|
+
return _is_jid_type(jid, HOST_DOMAIN)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True, slots=True)
|
|
49
|
+
class WaPersistIncomingMailboxOptions:
|
|
50
|
+
"""Mailbox persist inputs (mirrors ``WaPersistIncomingMailboxOptions``)."""
|
|
51
|
+
|
|
52
|
+
write_behind: Any
|
|
53
|
+
message_secret_store: WaMessageSecretStore
|
|
54
|
+
event: WaIncomingMessageEvent
|
|
55
|
+
logger: Any = None
|
|
56
|
+
persist_all_secrets: bool = False
|
|
57
|
+
message_encoder: Callable[[MessageDict], bytes] | None = None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _pair_lid_pn(first: str | None, second: str | None) -> tuple[str, str] | None:
|
|
61
|
+
if not first or not second:
|
|
62
|
+
return None
|
|
63
|
+
if is_lid_jid(first) and is_user_jid(second):
|
|
64
|
+
return (first, second)
|
|
65
|
+
if is_lid_jid(second) and is_user_jid(first):
|
|
66
|
+
return (second, first)
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _canonical_contact(
|
|
71
|
+
primary: str, alt: str | None, now_ms: int
|
|
72
|
+
) -> WaStoredContactRecord:
|
|
73
|
+
pair = _pair_lid_pn(primary, alt)
|
|
74
|
+
if pair is not None:
|
|
75
|
+
lid, phone_number = pair
|
|
76
|
+
return WaStoredContactRecord(
|
|
77
|
+
jid=lid,
|
|
78
|
+
phone_number=phone_number,
|
|
79
|
+
last_updated_ms=now_ms,
|
|
80
|
+
)
|
|
81
|
+
return WaStoredContactRecord(jid=primary, last_updated_ms=now_ms)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _persist_contacts(
|
|
85
|
+
write_behind: Any, event: WaIncomingMessageEvent, now_ms: int
|
|
86
|
+
) -> None:
|
|
87
|
+
key = event.key
|
|
88
|
+
if key is None:
|
|
89
|
+
return
|
|
90
|
+
raw_node = event.raw_node
|
|
91
|
+
raw_participant = (
|
|
92
|
+
raw_node.attrs.get("participant") if raw_node is not None else None
|
|
93
|
+
)
|
|
94
|
+
participant_jid = to_user_jid(raw_participant) if raw_participant else None
|
|
95
|
+
sender_primary = key.participant or raw_participant or key.remote_jid
|
|
96
|
+
if not sender_primary and not participant_jid:
|
|
97
|
+
return
|
|
98
|
+
|
|
99
|
+
written: set[str] = set()
|
|
100
|
+
if sender_primary:
|
|
101
|
+
alt = key.participant_alt
|
|
102
|
+
if not alt and not key.is_group and sender_primary == key.remote_jid:
|
|
103
|
+
alt = key.remote_jid_alt
|
|
104
|
+
record = _canonical_contact(sender_primary, alt, now_ms)
|
|
105
|
+
write_behind.persist_contact(record)
|
|
106
|
+
written.add(record.jid)
|
|
107
|
+
if record.phone_number:
|
|
108
|
+
written.add(record.phone_number)
|
|
109
|
+
if participant_jid and participant_jid not in written:
|
|
110
|
+
write_behind.persist_contact(
|
|
111
|
+
WaStoredContactRecord(jid=participant_jid, last_updated_ms=now_ms)
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def persist_incoming_mailbox_entities(
|
|
116
|
+
options: WaPersistIncomingMailboxOptions,
|
|
117
|
+
) -> None:
|
|
118
|
+
"""Persist one inbound message, its contacts and (maybe) its secret."""
|
|
119
|
+
import time
|
|
120
|
+
|
|
121
|
+
logger = options.logger
|
|
122
|
+
write_behind = options.write_behind
|
|
123
|
+
event = options.event
|
|
124
|
+
key = event.key
|
|
125
|
+
stanza_id = key.id if key is not None else ""
|
|
126
|
+
chat_jid = key.remote_jid if key is not None else ""
|
|
127
|
+
if not stanza_id or not chat_jid:
|
|
128
|
+
return
|
|
129
|
+
|
|
130
|
+
now_ms = int(time.time() * 1000)
|
|
131
|
+
try:
|
|
132
|
+
message_bytes: bytes | None = None
|
|
133
|
+
if event.message is not None and options.message_encoder is not None:
|
|
134
|
+
message_bytes = options.message_encoder(event.message)
|
|
135
|
+
raw_participant = (
|
|
136
|
+
event.raw_node.attrs.get("participant")
|
|
137
|
+
if event.raw_node is not None
|
|
138
|
+
else None
|
|
139
|
+
)
|
|
140
|
+
write_behind.persist_message(
|
|
141
|
+
WaStoredMessageRecord(
|
|
142
|
+
id=stanza_id,
|
|
143
|
+
thread_jid=chat_jid,
|
|
144
|
+
sender_jid=(key.participant or raw_participant or key.remote_jid)
|
|
145
|
+
if key is not None
|
|
146
|
+
else None,
|
|
147
|
+
participant_jid=raw_participant,
|
|
148
|
+
from_me=key.from_me if key is not None else False,
|
|
149
|
+
timestamp_ms=event.timestamp_seconds * 1000
|
|
150
|
+
if event.timestamp_seconds is not None
|
|
151
|
+
else None,
|
|
152
|
+
message_bytes=message_bytes,
|
|
153
|
+
)
|
|
154
|
+
)
|
|
155
|
+
_persist_contacts(write_behind, event, now_ms)
|
|
156
|
+
raw_secret = (
|
|
157
|
+
(event.message or {}).get("messageContextInfo", {}).get("messageSecret")
|
|
158
|
+
)
|
|
159
|
+
if (
|
|
160
|
+
raw_secret
|
|
161
|
+
and len(raw_secret) > 0
|
|
162
|
+
and event.message is not None
|
|
163
|
+
and (options.persist_all_secrets or needs_secret_persistence(event.message))
|
|
164
|
+
):
|
|
165
|
+
raw_sender = (
|
|
166
|
+
(key.participant or raw_participant or key.remote_jid)
|
|
167
|
+
if key is not None
|
|
168
|
+
else ""
|
|
169
|
+
)
|
|
170
|
+
sender_jid = to_user_jid(raw_sender) if raw_sender else ""
|
|
171
|
+
|
|
172
|
+
async def _store_secret() -> None:
|
|
173
|
+
try:
|
|
174
|
+
await options.message_secret_store.set(
|
|
175
|
+
stanza_id,
|
|
176
|
+
WaMessageSecretEntry(
|
|
177
|
+
secret=bytes(raw_secret), sender_jid=sender_jid
|
|
178
|
+
),
|
|
179
|
+
)
|
|
180
|
+
except Exception as error:
|
|
181
|
+
_log_warn(
|
|
182
|
+
logger,
|
|
183
|
+
"failed to persist message secret",
|
|
184
|
+
{"id": stanza_id, "message": str(to_error(error))},
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
_spawn(_store_secret())
|
|
188
|
+
except Exception as error:
|
|
189
|
+
_log_warn(
|
|
190
|
+
logger,
|
|
191
|
+
"failed to persist incoming mailbox entities",
|
|
192
|
+
{"id": stanza_id, "from": chat_jid, "message": str(to_error(error))},
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _log_warn(logger: Any, message: str, context: dict[str, Any]) -> None:
|
|
197
|
+
if logger is None:
|
|
198
|
+
_logger.warning("%s %s", message, context)
|
|
199
|
+
return
|
|
200
|
+
warn = getattr(logger, "warn", None)
|
|
201
|
+
if callable(warn):
|
|
202
|
+
try:
|
|
203
|
+
warn(message, context)
|
|
204
|
+
return
|
|
205
|
+
except TypeError:
|
|
206
|
+
pass
|
|
207
|
+
_logger.warning("%s %s", message, context)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _spawn(awaitable: Coroutine[Any, Any, None]) -> None:
|
|
211
|
+
import asyncio
|
|
212
|
+
|
|
213
|
+
try:
|
|
214
|
+
loop = asyncio.get_running_loop()
|
|
215
|
+
except RuntimeError:
|
|
216
|
+
asyncio.run(awaitable)
|
|
217
|
+
return
|
|
218
|
+
task: asyncio.Task[None] = loop.create_task(awaitable)
|
|
219
|
+
|
|
220
|
+
def _done(done_task: asyncio.Task[None]) -> None:
|
|
221
|
+
if not done_task.cancelled():
|
|
222
|
+
done_task.exception()
|
|
223
|
+
|
|
224
|
+
task.add_done_callback(_done)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
__all__: list[str] = [
|
|
228
|
+
"WaPersistIncomingMailboxOptions",
|
|
229
|
+
"is_lid_jid",
|
|
230
|
+
"is_user_jid",
|
|
231
|
+
"persist_incoming_mailbox_entities",
|
|
232
|
+
]
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
"""Write-behind persistence queues (mirrors ``persistence/WriteBehindPersistence.ts``).
|
|
2
|
+
|
|
3
|
+
# DEVIATION: the TS ``BackgroundQueue`` pumps writes in the background while
|
|
4
|
+
this port coalesces pending writes and drains them on ``flush``/``destroy``.
|
|
5
|
+
The merge behavior, batching, timeout accounting and destroy/restart semantics
|
|
6
|
+
are identical; only the pump timing differs (no background task is spawned
|
|
7
|
+
from the synchronous ``persist_*`` entry points).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import time
|
|
14
|
+
from collections.abc import Awaitable, Callable
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any, Generic, TypeVar
|
|
17
|
+
|
|
18
|
+
from zapy._infra.log import Logger
|
|
19
|
+
from zapy._store.contracts.contact import WaContactStore, WaStoredContactRecord
|
|
20
|
+
from zapy._store.contracts.message import WaMessageStore, WaStoredMessageRecord
|
|
21
|
+
from zapy._store.contracts.thread import WaThreadStore, WaStoredThreadRecord
|
|
22
|
+
from zapy._util.primitives import to_error
|
|
23
|
+
|
|
24
|
+
T = TypeVar("T")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True, slots=True)
|
|
28
|
+
class WaWriteBehindOptions:
|
|
29
|
+
"""Queue tuning (mirrors ``WaWriteBehindOptions``)."""
|
|
30
|
+
|
|
31
|
+
max_pending_keys: int = 4096
|
|
32
|
+
max_write_concurrency: int = 4
|
|
33
|
+
flush_timeout_ms: int = 5000
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, slots=True)
|
|
37
|
+
class BackgroundQueueFlushResult:
|
|
38
|
+
"""Per-domain drain outcome."""
|
|
39
|
+
|
|
40
|
+
flushed: int = 0
|
|
41
|
+
remaining: int = 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True, slots=True)
|
|
45
|
+
class WriteBehindDrainResult:
|
|
46
|
+
"""Combined drain outcome across messages/threads/contacts."""
|
|
47
|
+
|
|
48
|
+
messages: BackgroundQueueFlushResult = BackgroundQueueFlushResult()
|
|
49
|
+
threads: BackgroundQueueFlushResult = BackgroundQueueFlushResult()
|
|
50
|
+
contacts: BackgroundQueueFlushResult = BackgroundQueueFlushResult()
|
|
51
|
+
flushed: int = 0
|
|
52
|
+
remaining: int = 0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _merge_thread(
|
|
56
|
+
previous: WaStoredThreadRecord, incoming: WaStoredThreadRecord
|
|
57
|
+
) -> WaStoredThreadRecord:
|
|
58
|
+
def _pick(old: Any | None, new: Any | None) -> Any | None:
|
|
59
|
+
return new if new is not None else old
|
|
60
|
+
|
|
61
|
+
return WaStoredThreadRecord(
|
|
62
|
+
jid=incoming.jid,
|
|
63
|
+
name=_pick(previous.name, incoming.name),
|
|
64
|
+
unread_count=_pick(previous.unread_count, incoming.unread_count),
|
|
65
|
+
archived=_pick(previous.archived, incoming.archived),
|
|
66
|
+
pinned=_pick(previous.pinned, incoming.pinned),
|
|
67
|
+
mute_end_ms=_pick(previous.mute_end_ms, incoming.mute_end_ms),
|
|
68
|
+
marked_as_unread=_pick(previous.marked_as_unread, incoming.marked_as_unread),
|
|
69
|
+
ephemeral_expiration=_pick(
|
|
70
|
+
previous.ephemeral_expiration, incoming.ephemeral_expiration
|
|
71
|
+
),
|
|
72
|
+
ephemeral_setting_timestamp=_pick(
|
|
73
|
+
previous.ephemeral_setting_timestamp,
|
|
74
|
+
incoming.ephemeral_setting_timestamp,
|
|
75
|
+
),
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _merge_contact(
|
|
80
|
+
previous: WaStoredContactRecord, incoming: WaStoredContactRecord
|
|
81
|
+
) -> WaStoredContactRecord:
|
|
82
|
+
return WaStoredContactRecord(
|
|
83
|
+
jid=incoming.jid,
|
|
84
|
+
last_updated_ms=max(previous.last_updated_ms, incoming.last_updated_ms),
|
|
85
|
+
display_name=incoming.display_name
|
|
86
|
+
if incoming.display_name is not None
|
|
87
|
+
else previous.display_name,
|
|
88
|
+
push_name=incoming.push_name
|
|
89
|
+
if incoming.push_name is not None
|
|
90
|
+
else previous.push_name,
|
|
91
|
+
lid=incoming.lid if incoming.lid is not None else previous.lid,
|
|
92
|
+
phone_number=incoming.phone_number
|
|
93
|
+
if incoming.phone_number is not None
|
|
94
|
+
else previous.phone_number,
|
|
95
|
+
username=incoming.username
|
|
96
|
+
if incoming.username is not None
|
|
97
|
+
else previous.username,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class _PendingQueue(Generic[T]):
|
|
102
|
+
"""Coalescing pending-write map drained by ``flush``/``destroy``."""
|
|
103
|
+
|
|
104
|
+
def __init__(
|
|
105
|
+
self,
|
|
106
|
+
domain: str,
|
|
107
|
+
logger: Logger,
|
|
108
|
+
writer: Callable[[T], Awaitable[None]],
|
|
109
|
+
batch_writer: Callable[[list[T]], Awaitable[None]] | None,
|
|
110
|
+
coalesce: Callable[[T, T], T] | None,
|
|
111
|
+
options: WaWriteBehindOptions,
|
|
112
|
+
) -> None:
|
|
113
|
+
self._domain = domain
|
|
114
|
+
self._logger = logger
|
|
115
|
+
self._writer = writer
|
|
116
|
+
self._batch_writer = batch_writer
|
|
117
|
+
self._coalesce = coalesce
|
|
118
|
+
self._options = options
|
|
119
|
+
self._pending: dict[str, T] = {}
|
|
120
|
+
self._destroyed = False
|
|
121
|
+
self._discarded = 0
|
|
122
|
+
|
|
123
|
+
def _check_live(self) -> None:
|
|
124
|
+
if self._destroyed:
|
|
125
|
+
raise RuntimeError("background queue is destroyed")
|
|
126
|
+
|
|
127
|
+
def enqueue(self, key: str, value: T) -> None:
|
|
128
|
+
"""Stage ``value`` under ``key``, coalescing with a pending entry."""
|
|
129
|
+
self._check_live()
|
|
130
|
+
existing = self._pending.get(key)
|
|
131
|
+
if existing is not None and self._coalesce is not None:
|
|
132
|
+
self._pending[key] = self._coalesce(existing, value)
|
|
133
|
+
elif existing is not None:
|
|
134
|
+
self._pending[key] = value
|
|
135
|
+
else:
|
|
136
|
+
if len(self._pending) >= self._options.max_pending_keys:
|
|
137
|
+
self._logger.warn(
|
|
138
|
+
"write-behind discarded pending write",
|
|
139
|
+
{"domain": self._domain, "key": key},
|
|
140
|
+
)
|
|
141
|
+
self._discarded += 1
|
|
142
|
+
return
|
|
143
|
+
self._pending[key] = value
|
|
144
|
+
|
|
145
|
+
async def enqueue_async(self, key: str, value: T) -> None:
|
|
146
|
+
"""Async ``enqueue`` (mirrors ``enqueueAsync``; still drains on flush)."""
|
|
147
|
+
self.enqueue(key, value)
|
|
148
|
+
|
|
149
|
+
async def flush(self, timeout_ms: int) -> BackgroundQueueFlushResult:
|
|
150
|
+
"""Write every pending entry, honouring ``timeout_ms``."""
|
|
151
|
+
flushed = 0
|
|
152
|
+
deadline = time.monotonic() + timeout_ms / 1000.0
|
|
153
|
+
entries = list(self._pending.items())
|
|
154
|
+
self._pending.clear()
|
|
155
|
+
batch_writer = self._batch_writer
|
|
156
|
+
if len(entries) > 1 and batch_writer is not None:
|
|
157
|
+
try:
|
|
158
|
+
remaining_s = max(0.0, deadline - time.monotonic())
|
|
159
|
+
# Shielded: a flush timeout reports the entries as remaining
|
|
160
|
+
# without cancelling the in-flight store write.
|
|
161
|
+
await asyncio.wait_for(
|
|
162
|
+
asyncio.shield(batch_writer([value for _, value in entries])),
|
|
163
|
+
timeout=remaining_s,
|
|
164
|
+
)
|
|
165
|
+
return BackgroundQueueFlushResult(flushed=len(entries), remaining=0)
|
|
166
|
+
except (asyncio.TimeoutError, TimeoutError):
|
|
167
|
+
for key, value in entries:
|
|
168
|
+
self._pending.setdefault(key, value)
|
|
169
|
+
return BackgroundQueueFlushResult(
|
|
170
|
+
flushed=0, remaining=len(self._pending)
|
|
171
|
+
)
|
|
172
|
+
except Exception as error: # noqa: BLE001 - logged, like the TS onError
|
|
173
|
+
for key, value in entries:
|
|
174
|
+
self._on_error(key, value, error)
|
|
175
|
+
return BackgroundQueueFlushResult(flushed=0, remaining=0)
|
|
176
|
+
for index, (key, value) in enumerate(entries):
|
|
177
|
+
remaining_s = deadline - time.monotonic()
|
|
178
|
+
if remaining_s <= 0:
|
|
179
|
+
for rest_key, rest_value in entries[index:]:
|
|
180
|
+
self._pending.setdefault(rest_key, rest_value)
|
|
181
|
+
break
|
|
182
|
+
try:
|
|
183
|
+
await asyncio.wait_for(
|
|
184
|
+
asyncio.shield(self._writer(value)), timeout=remaining_s
|
|
185
|
+
)
|
|
186
|
+
flushed += 1
|
|
187
|
+
except (asyncio.TimeoutError, TimeoutError):
|
|
188
|
+
self._pending[key] = value
|
|
189
|
+
for rest_key, rest_value in entries[index + 1 :]:
|
|
190
|
+
self._pending.setdefault(rest_key, rest_value)
|
|
191
|
+
break
|
|
192
|
+
except Exception as error: # noqa: BLE001 - logged, like the TS onError
|
|
193
|
+
self._on_error(key, value, error)
|
|
194
|
+
return BackgroundQueueFlushResult(flushed=flushed, remaining=len(self._pending))
|
|
195
|
+
|
|
196
|
+
def _on_error(self, key: str, value: T, error: Exception) -> None:
|
|
197
|
+
self._logger.warn(
|
|
198
|
+
"write-behind error",
|
|
199
|
+
{"domain": self._domain, "key": key, "message": str(to_error(error))},
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
def mark_destroyed(self) -> None:
|
|
203
|
+
"""Refuse new enqueues while keeping pending entries for a later flush."""
|
|
204
|
+
self._destroyed = True
|
|
205
|
+
|
|
206
|
+
def destroy(self) -> dict[str, T]:
|
|
207
|
+
"""Mark destroyed; returns entries still pending."""
|
|
208
|
+
self._destroyed = True
|
|
209
|
+
pending = dict(self._pending)
|
|
210
|
+
self._pending.clear()
|
|
211
|
+
return pending
|
|
212
|
+
|
|
213
|
+
def restore(self, entries: dict[str, T]) -> None:
|
|
214
|
+
"""Re-arm after ``destroy``; used by ``restart``."""
|
|
215
|
+
self._destroyed = False
|
|
216
|
+
self._pending.update(entries)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@dataclass(frozen=True, slots=True)
|
|
220
|
+
class WriteBehindStores:
|
|
221
|
+
"""Backing stores drained by the write-behind queues."""
|
|
222
|
+
|
|
223
|
+
message_store: WaMessageStore
|
|
224
|
+
thread_store: WaThreadStore
|
|
225
|
+
contact_store: WaContactStore
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class WriteBehindPersistence:
|
|
229
|
+
"""Coalescing write-behind cache over the message/thread/contact stores."""
|
|
230
|
+
|
|
231
|
+
def __init__(
|
|
232
|
+
self,
|
|
233
|
+
stores: WriteBehindStores,
|
|
234
|
+
logger: Logger,
|
|
235
|
+
options: WaWriteBehindOptions | None = None,
|
|
236
|
+
) -> None:
|
|
237
|
+
self._logger = logger
|
|
238
|
+
self._stores = stores
|
|
239
|
+
self._options = options or WaWriteBehindOptions()
|
|
240
|
+
self._flush_timeout_ms = self._options.flush_timeout_ms
|
|
241
|
+
self._destroyed = False
|
|
242
|
+
self._queues = self._build_queues()
|
|
243
|
+
|
|
244
|
+
def _build_queues(
|
|
245
|
+
self,
|
|
246
|
+
) -> dict[str, _PendingQueue[Any]]:
|
|
247
|
+
options = self._options
|
|
248
|
+
return {
|
|
249
|
+
"messages": _PendingQueue[WaStoredMessageRecord](
|
|
250
|
+
"messages",
|
|
251
|
+
self._logger,
|
|
252
|
+
self._stores.message_store.upsert,
|
|
253
|
+
self._stores.message_store.upsert_batch,
|
|
254
|
+
None,
|
|
255
|
+
options,
|
|
256
|
+
),
|
|
257
|
+
"threads": _PendingQueue[WaStoredThreadRecord](
|
|
258
|
+
"threads",
|
|
259
|
+
self._logger,
|
|
260
|
+
self._stores.thread_store.upsert,
|
|
261
|
+
self._stores.thread_store.upsert_batch,
|
|
262
|
+
_merge_thread,
|
|
263
|
+
options,
|
|
264
|
+
),
|
|
265
|
+
"contacts": _PendingQueue[WaStoredContactRecord](
|
|
266
|
+
"contacts",
|
|
267
|
+
self._logger,
|
|
268
|
+
self._stores.contact_store.upsert,
|
|
269
|
+
self._stores.contact_store.upsert_batch,
|
|
270
|
+
_merge_contact,
|
|
271
|
+
options,
|
|
272
|
+
),
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
def restart(self) -> None:
|
|
276
|
+
"""Re-arm the queues after ``destroy``; no-op when already live."""
|
|
277
|
+
if not self._destroyed:
|
|
278
|
+
return
|
|
279
|
+
self._queues = self._build_queues()
|
|
280
|
+
self._destroyed = False
|
|
281
|
+
|
|
282
|
+
def persist_message(self, record: WaStoredMessageRecord) -> None:
|
|
283
|
+
"""Stage a message write."""
|
|
284
|
+
self._queues["messages"].enqueue(f"msg:{record.id}", record)
|
|
285
|
+
|
|
286
|
+
async def persist_message_async(self, record: WaStoredMessageRecord) -> None:
|
|
287
|
+
"""Stage a message write (async entry point)."""
|
|
288
|
+
await self._queues["messages"].enqueue_async(f"msg:{record.id}", record)
|
|
289
|
+
|
|
290
|
+
def persist_thread(self, record: WaStoredThreadRecord) -> None:
|
|
291
|
+
"""Stage a thread write."""
|
|
292
|
+
self._queues["threads"].enqueue(f"thread:{record.jid}", record)
|
|
293
|
+
|
|
294
|
+
async def persist_thread_async(self, record: WaStoredThreadRecord) -> None:
|
|
295
|
+
"""Stage a thread write (async entry point)."""
|
|
296
|
+
await self._queues["threads"].enqueue_async(f"thread:{record.jid}", record)
|
|
297
|
+
|
|
298
|
+
def persist_contact(self, record: WaStoredContactRecord) -> None:
|
|
299
|
+
"""Stage a contact write."""
|
|
300
|
+
self._queues["contacts"].enqueue(f"contact:{record.jid}", record)
|
|
301
|
+
|
|
302
|
+
async def persist_contact_async(self, record: WaStoredContactRecord) -> None:
|
|
303
|
+
"""Stage a contact write (async entry point)."""
|
|
304
|
+
await self._queues["contacts"].enqueue_async(f"contact:{record.jid}", record)
|
|
305
|
+
|
|
306
|
+
async def flush(self, timeout_ms: int | None = None) -> WriteBehindDrainResult:
|
|
307
|
+
"""Drain every domain; reports entries still pending on timeout."""
|
|
308
|
+
timeout = self._flush_timeout_ms if timeout_ms is None else timeout_ms
|
|
309
|
+
messages = await self._queues["messages"].flush(timeout)
|
|
310
|
+
threads = await self._queues["threads"].flush(timeout)
|
|
311
|
+
contacts = await self._queues["contacts"].flush(timeout)
|
|
312
|
+
result = self._to_drain_result(messages, threads, contacts)
|
|
313
|
+
if result.remaining > 0:
|
|
314
|
+
self._logger.warn(
|
|
315
|
+
"write-behind flush finished with pending writes",
|
|
316
|
+
{
|
|
317
|
+
"messagesRemaining": messages.remaining,
|
|
318
|
+
"threadsRemaining": threads.remaining,
|
|
319
|
+
"contactsRemaining": contacts.remaining,
|
|
320
|
+
},
|
|
321
|
+
)
|
|
322
|
+
return result
|
|
323
|
+
|
|
324
|
+
async def destroy(self, timeout_ms: int | None = None) -> WriteBehindDrainResult:
|
|
325
|
+
"""Drain then destroy the queues; ``restart`` re-arms them.
|
|
326
|
+
|
|
327
|
+
Entries still pending after the timeout are kept (not dropped) so a
|
|
328
|
+
later ``flush`` can complete them; only new enqueues are refused.
|
|
329
|
+
"""
|
|
330
|
+
result = await self.flush(
|
|
331
|
+
self._flush_timeout_ms if timeout_ms is None else timeout_ms
|
|
332
|
+
)
|
|
333
|
+
for queue in self._queues.values():
|
|
334
|
+
queue.mark_destroyed()
|
|
335
|
+
self._destroyed = True
|
|
336
|
+
if result.remaining > 0:
|
|
337
|
+
self._logger.warn(
|
|
338
|
+
"write-behind destroy finished with pending writes",
|
|
339
|
+
{
|
|
340
|
+
"messagesRemaining": result.messages.remaining,
|
|
341
|
+
"threadsRemaining": result.threads.remaining,
|
|
342
|
+
"contactsRemaining": result.contacts.remaining,
|
|
343
|
+
},
|
|
344
|
+
)
|
|
345
|
+
return result
|
|
346
|
+
|
|
347
|
+
def _to_drain_result(
|
|
348
|
+
self,
|
|
349
|
+
messages: BackgroundQueueFlushResult,
|
|
350
|
+
threads: BackgroundQueueFlushResult,
|
|
351
|
+
contacts: BackgroundQueueFlushResult,
|
|
352
|
+
) -> WriteBehindDrainResult:
|
|
353
|
+
return WriteBehindDrainResult(
|
|
354
|
+
messages=messages,
|
|
355
|
+
threads=threads,
|
|
356
|
+
contacts=contacts,
|
|
357
|
+
flushed=messages.flushed + threads.flushed + contacts.flushed,
|
|
358
|
+
remaining=messages.remaining + threads.remaining + contacts.remaining,
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
__all__: list[str] = [
|
|
363
|
+
"BackgroundQueueFlushResult",
|
|
364
|
+
"WaWriteBehindOptions",
|
|
365
|
+
"WriteBehindDrainResult",
|
|
366
|
+
"WriteBehindPersistence",
|
|
367
|
+
"WriteBehindStores",
|
|
368
|
+
]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Client plugin surface (mirrors ``src/client/plugins/``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from zapy._client.plugins.define import define_wa_client_plugin
|
|
6
|
+
from zapy._client.plugins.install import (
|
|
7
|
+
WaClientPluginInstallInput,
|
|
8
|
+
install_wa_client_plugins,
|
|
9
|
+
)
|
|
10
|
+
from zapy._client.plugins.types import (
|
|
11
|
+
WaClientPluginContext,
|
|
12
|
+
WaClientPluginDefinition,
|
|
13
|
+
is_wa_client_expose_plugin_definition,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__all__: list[str] = [
|
|
17
|
+
"WaClientPluginContext",
|
|
18
|
+
"WaClientPluginDefinition",
|
|
19
|
+
"WaClientPluginInstallInput",
|
|
20
|
+
"define_wa_client_plugin",
|
|
21
|
+
"install_wa_client_plugins",
|
|
22
|
+
"is_wa_client_expose_plugin_definition",
|
|
23
|
+
]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Plugin definition helper (mirrors ``src/client/plugins/define.ts``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Callable
|
|
6
|
+
|
|
7
|
+
from zapy._client.plugins.types import WaClientPluginContext, WaClientPluginDefinition
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def define_wa_client_plugin(
|
|
11
|
+
*,
|
|
12
|
+
id: str,
|
|
13
|
+
setup: Callable[[WaClientPluginContext], Any],
|
|
14
|
+
dispose: Callable[[Any, WaClientPluginContext], Any]
|
|
15
|
+
| Callable[[WaClientPluginContext], Any]
|
|
16
|
+
| None = None,
|
|
17
|
+
expose_as: str | None = None,
|
|
18
|
+
) -> WaClientPluginDefinition:
|
|
19
|
+
"""Type-safe helper for authoring plugin definitions.
|
|
20
|
+
|
|
21
|
+
Behavior plugins only run side effects; expose plugins (``expose_as`` set)
|
|
22
|
+
return the value published at ``client.<expose_as>``. A behavior-style
|
|
23
|
+
``dispose`` taking only the context is adapted to the two-argument form.
|
|
24
|
+
"""
|
|
25
|
+
adapted: Callable[[Any, WaClientPluginContext], Any] | None = None
|
|
26
|
+
if dispose is not None:
|
|
27
|
+
if expose_as is not None:
|
|
28
|
+
adapted = dispose # type: ignore[assignment]
|
|
29
|
+
else:
|
|
30
|
+
|
|
31
|
+
def _adapt(
|
|
32
|
+
_instance: Any,
|
|
33
|
+
ctx: WaClientPluginContext,
|
|
34
|
+
_dispose: Callable[[Any], Any] = dispose, # type: ignore[assignment]
|
|
35
|
+
) -> Any:
|
|
36
|
+
return _dispose(ctx)
|
|
37
|
+
|
|
38
|
+
adapted = _adapt
|
|
39
|
+
return WaClientPluginDefinition(
|
|
40
|
+
id=id, setup=setup, expose_as=expose_as, dispose=adapted
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
__all__: list[str] = ["define_wa_client_plugin"]
|