Skip to content

Infrastructure API

Configuration

config

ExtraConfig

Bases: BaseConfig

model_config class-attribute instance-attribute

model_config = ConfigDict(arbitrary_types_allowed=True)

transport class-attribute instance-attribute

transport: BaseTransportConfig = Field(
    default_factory=DefaultTransportConfig
)

encoding class-attribute instance-attribute

encoding: BaseEncodingConfig = DefaultEncodingConfig()

protocol class-attribute instance-attribute

protocol: BaseProtocolConfig = Field(
    default_factory=DefaultProtocolConfig
)

mapper class-attribute instance-attribute

mapper: BaseMapperConfig = Field(
    default_factory=DefaultMapperConfig
)

session_storage class-attribute instance-attribute

session_storage: BaseSessionStorage | None = None

auth_interactor class-attribute instance-attribute

auth_interactor: AuthInteractor | None = None

work_dir class-attribute instance-attribute

work_dir: str = '.'

session_name class-attribute instance-attribute

session_name: str = 'session.db'

session_id class-attribute instance-attribute

session_id: str | None = None

app_version class-attribute instance-attribute

app_version: str | None = None

app_fingerprint class-attribute instance-attribute

app_fingerprint: ApkBuildFingerprint | None = None

version_api class-attribute instance-attribute

version_api: VersionApi | None = None

catalog class-attribute instance-attribute

catalog: VersionApi | None = None

restore_user_agent_from_session class-attribute instance-attribute

restore_user_agent_from_session: bool = True

auto_connect_after_init class-attribute instance-attribute

auto_connect_after_init: bool = True

strict_fingerprint_pair class-attribute instance-attribute

strict_fingerprint_pair: bool = False

reconnect class-attribute instance-attribute

reconnect: bool = True

reconnect_delay class-attribute instance-attribute

reconnect_delay: float = 1.0

relogin class-attribute instance-attribute

relogin: bool = True

autochange_app_version_if_current_unsupported class-attribute instance-attribute

autochange_app_version_if_current_unsupported: bool = True

sync class-attribute instance-attribute

sync: SyncOverrides = Field(default_factory=SyncOverrides)

resolved_version_api property

resolved_version_api: VersionApi | None

validate_version_api_aliases

validate_version_api_aliases() -> Self
Source code in src/pyromax/config.py
559
560
561
562
563
@model_validator(mode="after")
def validate_version_api_aliases(self) -> Self:
    if self.version_api is not None and self.catalog is not None:
        raise ValueError("version_api and catalog cannot be used together")
    return self

resolve_app_version

resolve_app_version() -> None

Apply an explicit app version to a compatible user agent.

Source code in src/pyromax/config.py
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
def resolve_app_version(self) -> None:
    """Apply an explicit app version to a compatible user agent."""

    if self.app_version is None:
        return
    user_agent_config = self.mapper.user_agent_config
    if not user_agent_config.supports_versioning:
        self._logger.warning(
            "The selected user-agent configuration does not support app versions"
        )
        return

    self.mapper.user_agent_config = user_agent_config.model_copy(
        update={"app_version": self.app_version}
    )

resolve_app_fingerprint async

resolve_app_fingerprint() -> None

Resolve and apply an Android APK fingerprint when requested.

Source code in src/pyromax/config.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
async def resolve_app_fingerprint(self) -> None:
    """Resolve and apply an Android APK fingerprint when requested."""

    user_agent_config = self.mapper.user_agent_config
    if not user_agent_config.supports_app_fingerprint:
        return

    fingerprint_requested = any(
        value is not None
        for value in (
            self.app_version,
            self.app_fingerprint,
            self.resolved_version_api,
        )
    )
    if not fingerprint_requested:
        return

    app_version = cast(str, getattr(user_agent_config, "app_version"))
    app_fingerprint = self.app_fingerprint
    if app_fingerprint is None:
        version_api = self.resolved_version_api or VersionApi()
        await version_api.load()
        if self.strict_fingerprint_pair:
            app_fingerprint = version_api.resolve(app_version)
        else:
            app_fingerprint = version_api.versions.get(app_version)
            if app_fingerprint is None:
                return

    self.app_fingerprint = app_fingerprint
    self.mapper.user_agent_config = user_agent_config.model_copy(
        update={"build_number": app_fingerprint.build_number}
    )

validate_transport classmethod

validate_transport(data: Any) -> Any
Source code in src/pyromax/config.py
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
@model_validator(mode="before")
@classmethod
def validate_transport(self, data: Any) -> Any:
    if isinstance(data, dict):
        extra_config_device_type = data.get("device_type", DeviceType.Web)
    elif isinstance(data, BaseModel):
        extra_config_device_type = data.model_dump().get(
            "device_type", DeviceType.Web
        )
    else:
        extra_config_device_type = DeviceType.Web

    if isinstance(data, dict):
        if "mapper" in data and "transport" not in data:
            mapper = data["mapper"]
            if isinstance(mapper, dict):
                device_type = mapper.get("device_type", extra_config_device_type)
            elif isinstance(mapper, BaseModel):
                device_type = mapper.model_dump().get(
                    "device_type", extra_config_device_type
                )
            else:
                return data
            data["transport"] = (
                WebSocketTransportConfig()
                if device_type == DeviceType.Web
                else SocketTransportConfig()
            )
        return data
    else:
        return data

config_rebuild

config_rebuild(
    transport: TransportRegistry | None,
    encoding: EncodingRegistry | None,
    protocol: ProtocolRegistry | None,
    mapper: MapperRegistry | None,
) -> ExtraConfig
Source code in src/pyromax/config.py
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
def config_rebuild(
    self,
    transport: TransportRegistry | None,
    encoding: EncodingRegistry | None,
    protocol: ProtocolRegistry | None,
    mapper: MapperRegistry | None,
) -> "ExtraConfig":

    device_type = self.mapper.device_type

    config_presets = CONFIG_SETS.get(device_type) or (
        (
            from_config_to_registry(default_transport_config),
            from_config_to_registry(default_encoding_config),
            from_config_to_registry(default_protocol_config),
            from_config_to_registry(default_mapper_config),
        ),
    )
    config_mask = config_presets[0]

    transport_config = (
        from_registry_to_config(TransportRegistry, transport)
        or (
            type(self.transport)
            if not issubclass(type(self.transport), Default)
            else None
        )
        or from_registry_to_config(TransportRegistry, config_mask[0])
        or default_transport_config
    )
    encoding_config = (
        from_registry_to_config(EncodingRegistry, encoding)
        or (
            type(self.encoding)
            if not issubclass(type(self.encoding), Default)
            else None
        )
        or from_registry_to_config(EncodingRegistry, config_mask[1])
        or default_encoding_config
    )
    protocol_config = (
        from_registry_to_config(ProtocolRegistry, protocol)
        or (
            type(self.protocol)
            if not issubclass(type(self.protocol), Default)
            else None
        )
        or from_registry_to_config(ProtocolRegistry, config_mask[2])
        or default_protocol_config
    )
    mapper_config = (
        from_registry_to_config(MapperRegistry, mapper)
        or (
            type(self.mapper)
            if not issubclass(type(self.mapper), Default)
            else None
        )
        or from_registry_to_config(MapperRegistry, config_mask[3])
        or default_mapper_config
    )

    user_preset = (
        from_config_to_registry(transport_config),
        from_config_to_registry(encoding_config),
        from_config_to_registry(protocol_config),
        from_config_to_registry(mapper_config),
    )
    if user_preset not in config_presets:
        self._logger.warning(
            "Your chosen settings not found in presets, a big chance for errors."
        )

    mapper_user_agent_config = self.mapper.user_agent_config

    mapper_dump = self.mapper.model_dump()
    for key in mapper_dump.copy():
        if key not in self.mapper.model_fields_set:
            del mapper_dump[key]
    if not self.mapper.is_custom_user_agent_config:
        mapper_dump.pop("user_agent_config", None)
    else:
        mapper_dump["user_agent_config"] = mapper_user_agent_config

    other_params = self.model_dump()
    other_params.pop("transport")
    other_params.pop("encoding")
    other_params.pop("protocol")
    other_params.pop("mapper")

    config_updated = ExtraConfig(
        transport=cast(
            BaseTransportConfig,
            transport_config.model_validate(self.transport.model_dump()),
        ),
        encoding=cast(
            BaseEncodingConfig,
            encoding_config.model_validate(self.encoding.model_dump()),
        ),
        protocol=cast(
            BaseProtocolConfig,
            protocol_config.model_validate(self.protocol.model_dump()),
        ),
        mapper=cast(BaseMapperConfig, mapper_config.model_validate(mapper_dump)),
        **other_params,
    )
    return config_updated

SocketTransportConfig

Bases: BaseTransportConfig

host class-attribute instance-attribute

host: str = 'api.oneme.ru'

port class-attribute instance-attribute

port: int = 443

proxy class-attribute instance-attribute

proxy: str | None = None

use_ssl class-attribute instance-attribute

use_ssl: bool = True

WebSocketTransportConfig

Bases: BaseTransportConfig

url class-attribute instance-attribute

url: str = 'wss://ws-api.oneme.ru/websocket'

proxy class-attribute instance-attribute

proxy: str | None = None

origin class-attribute instance-attribute

origin: str = 'https://web.max.ru'

user_agent_header class-attribute instance-attribute

user_agent_header: str = DEFAULT_WEB_HEADER_USER_AGENT

max_size class-attribute instance-attribute

max_size: int = 1024 * 1024 * 10

JsonEncodingConfig

Bases: BaseEncodingConfig

MsgPackDictEncodingConfig

Bases: BaseEncodingConfig

EnvelopeProtocolConfig

Bases: BaseProtocolConfig

EnvelopeMapperConfigV11

Bases: BaseMapperConfig

token class-attribute instance-attribute

token: str | None = None

protocol_version class-attribute instance-attribute

protocol_version: int = 11

device_type class-attribute instance-attribute

device_type: DeviceType = Web

password class-attribute instance-attribute

password: str | None = None

phone class-attribute instance-attribute

phone: str | None = None

sms_auth class-attribute instance-attribute

sms_auth: bool = False

interactive class-attribute instance-attribute

interactive: bool = True

keepalive_ping_interval class-attribute instance-attribute

keepalive_ping_interval: int = 30

connect_timeout class-attribute instance-attribute

connect_timeout: int | None = None

user_agent_config class-attribute instance-attribute

user_agent_config: BaseEnvelopeMappingUserAgentConfigV11 = (
    WebEnvelopeMappingUserAgentConfigV11()
)

registration_config class-attribute instance-attribute

registration_config: RegistrationConfig | None = None

use_mobile_fingerprint class-attribute instance-attribute

use_mobile_fingerprint: bool = True

use_telemetry class-attribute instance-attribute

use_telemetry: bool = True

request_timeout class-attribute instance-attribute

request_timeout: float = 30.0

circuit_breakers class-attribute instance-attribute

circuit_breakers: MappingCircuitBreakersConfig = Field(
    default_factory=MappingCircuitBreakersConfig
)

mapper_logger class-attribute instance-attribute

mapper_logger: Logger | None = None

validate_config

validate_config() -> Self
Source code in src/pyromax/config.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def validate_config(self) -> Self:
    original_fields_set = self.model_fields_set.copy()

    device_type = self.device_type
    if "sms_auth" not in original_fields_set:
        self.sms_auth = False if device_type == DeviceType.Web else True
    if "user_agent_config" not in original_fields_set:
        user_agent_config_per_device_type = USER_AGENTS_V11_PER_DEVICE_TYPE.get(
            device_type
        )
        user_agent_config = (
            user_agent_config_per_device_type
            or WebEnvelopeMappingUserAgentConfigV11
        )
        self.user_agent_config = user_agent_config()
    self.__pydantic_fields_set__ = original_fields_set
    return self

CircuitBreakerConfig

Bases: BaseConfig

Failure policy for one category of operations.

enabled class-attribute instance-attribute

enabled: bool = True

failure_threshold class-attribute instance-attribute

failure_threshold: int = Field(default=1, ge=1)

recovery_timeout class-attribute instance-attribute

recovery_timeout: float = Field(default=1.0, ge=0)

max_cycles class-attribute instance-attribute

max_cycles: int = Field(default=5, ge=0)

backoff_factor class-attribute instance-attribute

backoff_factor: float = Field(default=2.75, ge=1)

max_recovery_timeout class-attribute instance-attribute

max_recovery_timeout: float = Field(default=30.0, ge=0)

wait_when_open class-attribute instance-attribute

wait_when_open: bool = True

validate_recovery_timeouts

validate_recovery_timeouts() -> Self
Source code in src/pyromax/config.py
338
339
340
341
342
343
344
@model_validator(mode="after")
def validate_recovery_timeouts(self) -> Self:
    if self.max_recovery_timeout < self.recovery_timeout:
        raise ValueError(
            "max_recovery_timeout cannot be less than recovery_timeout"
        )
    return self

MappingCircuitBreakersConfig

Bases: BaseConfig

Independent failure policies for mapper transport and API errors.

transport class-attribute instance-attribute

transport: CircuitBreakerConfig = Field(
    default_factory=CircuitBreakerConfig
)

api class-attribute instance-attribute

api: CircuitBreakerConfig = Field(
    default_factory=CircuitBreakerConfig
)

WebEnvelopeMappingUserAgentConfigV11

Bases: BaseEnvelopeMappingUserAgentConfigV11

device_type class-attribute instance-attribute

device_type: str = Web

device_id class-attribute instance-attribute

device_id: str = Field(default_factory=get_random_device_id)

header_user_agent class-attribute instance-attribute

header_user_agent: str = DEFAULT_WEB_HEADER_USER_AGENT

app_version class-attribute instance-attribute

app_version: str = WEB_APP_VERSION

screen class-attribute instance-attribute

screen: str = WEB_SCREEN

client_session_id class-attribute instance-attribute

client_session_id: int = Field(
    default_factory=lambda: round(time() * 1000)
)

DesktopEnvelopeMappingUserAgentConfigV11

Bases: BaseEnvelopeMappingUserAgentConfigV11

device_type class-attribute instance-attribute

device_type: str = Desktop

screen class-attribute instance-attribute

screen: str = '2.0x'

device_id class-attribute instance-attribute

device_id: str = Field(
    default_factory=get_random_device_id_numeric
)

build_number class-attribute instance-attribute

build_number: int = default_build_number

app_version class-attribute instance-attribute

app_version: str = default_app_version

AndroidEnvelopeMappingUserAgentConfigV11

Bases: BaseEnvelopeMappingUserAgentConfigV11

device_type class-attribute instance-attribute

device_type: str = Android

os_version class-attribute instance-attribute

os_version: str = 'Android 13'

arch class-attribute instance-attribute

arch: str = 'arm64-v8a'

device_name class-attribute instance-attribute

device_name: str = 'Samsung SM-A525F'

push_device_type class-attribute instance-attribute

push_device_type: str = 'GCM'

app_version class-attribute instance-attribute

app_version: str = default_app_version

build_number class-attribute instance-attribute

build_number: int = default_build_number

device_id class-attribute instance-attribute

device_id: str = Field(default_factory=lambda: str(uuid4()))

mt_instance_id class-attribute instance-attribute

mt_instance_id: str = Field(
    default_factory=lambda: str(uuid4())
)

supports_app_fingerprint property

supports_app_fingerprint: bool

session_info_params property

session_info_params: dict[str, Any]

from_session_info classmethod

from_session_info(
    session_info: SessionInfo, *args: Any, **kwargs: Any
) -> Self
Source code in src/pyromax/config.py
292
293
294
295
296
297
298
299
300
301
302
303
304
@classmethod
def from_session_info(
    cls: type[Self],
    session_info: SessionInfo,
    *args: Any,
    **kwargs: Any,
) -> Self:
    return super().from_session_info(
        session_info,
        *args,
        mt_instance_id=session_info.mt_instance_id,
        **kwargs,
    )

Sessions

session

__all__ module-attribute

__all__ = ['BaseSessionStorage', 'AioSqLiteSessionStorage']

BaseSessionStorage

Bases: ABC

save_session async

save_session(
    session_info: SessionInfo, session_key: SessionKey
) -> None
Source code in src/pyromax/session/base.py
13
14
15
async def save_session(
    self, session_info: SessionInfo, session_key: SessionKey
) -> None: ...

load_session async

load_session(session_key: SessionKey) -> SessionInfo | None
Source code in src/pyromax/session/base.py
16
async def load_session(self, session_key: SessionKey) -> SessionInfo | None: ...

update_session async

update_session(
    session_key: SessionKey, session_info: SessionInfo
) -> None
Source code in src/pyromax/session/base.py
17
18
19
async def update_session(
    self, session_key: SessionKey, session_info: SessionInfo
) -> None: ...

delete_session async

delete_session(session_key: SessionKey) -> None
Source code in src/pyromax/session/base.py
20
async def delete_session(self, session_key: SessionKey) -> None: ...

close async

close() -> None
Source code in src/pyromax/session/base.py
21
async def close(self) -> None: ...

AioSqLiteSessionStorage

AioSqLiteSessionStorage(
    work_dir: str, db_name: str | None = "session.db"
)

Bases: BaseSessionStorage

Source code in src/pyromax/session/aiosqlite.py
27
28
29
30
31
32
33
34
35
def __init__(self, work_dir: str, db_name: str | None = "session.db") -> None:
    if db_name is None:
        db_name = "session.db"
    self.work_dir = Path(work_dir)
    self.work_dir.mkdir(parents=True, exist_ok=True)
    self.db_path = str(self.work_dir / db_name)
    self.conn: asq.Connection | None = None
    self._logger = logging.getLogger("AioSlqLiteSessionStorage")
    self._logger.debug("Session storage initialized db=%s", self.db_path)

work_dir instance-attribute

work_dir = Path(work_dir)

db_path instance-attribute

db_path = str(work_dir / db_name)

conn instance-attribute

conn: Connection | None = None

save_session async

save_session(
    session_info: SessionInfo, session_key: SessionKey
) -> None
Source code in src/pyromax/session/aiosqlite.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
async def save_session(
    self, session_info: SessionInfo, session_key: SessionKey
) -> None:
    session_id = session_key.session_id
    session_name = session_key.session_name
    serialized_session_info = session_info.to_string()
    conn = await self._get_connection()
    self._logger.debug(
        "Saving session device_id=%s phone_set=%s mt_instance_id_set=%s",
        session_info.device_id,
        bool(session_info.phone),
        bool(session_info.mt_instance_id),
    )
    await conn.execute(
        f"""
        INSERT OR REPLACE INTO sessions (
            {SESSION_COLUMNS}
        )
        VALUES (?, ?, ?, ?)
        """,
        (
            session_id,
            session_name,
            serialized_session_info,
            session_key.device_type,
        ),
    )
    await conn.commit()
    self._logger.info("Session saved")

load_session async

load_session(session_key: SessionKey) -> SessionInfo | None
Source code in src/pyromax/session/aiosqlite.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
async def load_session(self, session_key: SessionKey) -> SessionInfo | None:
    conn = await self._get_connection()
    sql_req = f"""
        SELECT {SESSION_COLUMNS}
        FROM sessions
        """

    sql_req, values = self._prepare_session_spicies_by_session_key(
        session_key, sql_req
    )

    self._logger.debug("loading first session")
    async with conn.execute(
        sql_req,
        values,
    ) as cursor:
        rows = await cursor.fetchall()
        filtered_rows = self._validate_session_info_by_session_key(
            session_key, list(rows)
        )

        if filtered_rows:
            session_info = filtered_rows[0]
        else:
            self._logger.debug("Session not found")
            return None

    self._logger.debug(
        "session loaded device_id=%s phone_set=%s",
        session_info.device_id,
        bool(session_info.phone),
    )
    return session_info

update_session async

update_session(
    session_key: SessionKey, session_info: SessionInfo
) -> None
Source code in src/pyromax/session/aiosqlite.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
async def update_session(
    self, session_key: SessionKey, session_info: SessionInfo
) -> None:
    self._logger.debug("Updating session session_id=%s", session_info.session_id)
    new_session_id = session_info.session_id
    if new_session_id is None:
        self._logger.warning(
            "Trying to update session without session_id, session_info=%s, session_key=%s",
            session_info,
            session_key,
        )
        return

    serialized_session = session_info.to_string()
    conn = await self._get_connection()

    if (
        session_key.session_id is not None
        and session_key.session_id != new_session_id
    ):

        sql_req = """
            UPDATE sessions
            SET session_id=?, session_name=?, session_value=?, device_type=?
            """
        values = [
            new_session_id,
            session_key.session_name,
            serialized_session,
            session_key.device_type,
        ]

        sql_req, values = self._prepare_session_spicies_by_session_key(
            session_key, sql_req, values
        )
        cursor = await conn.execute(sql_req, values)

        if cursor.rowcount == 0:
            self._logger.warning(
                "Session to rename was not found old_session_id=%s",
                session_key.session_id,
            )
    else:
        await conn.execute(
            """
            INSERT INTO sessions (
                session_id, session_name, session_value, device_type
            )
            VALUES (?, ?, ?, ?)
            ON CONFLICT(session_id) DO UPDATE SET
                session_name=excluded.session_name,
                session_value=excluded.session_value,
                device_type=excluded.device_type
            """,
            (
                new_session_id,
                session_key.session_name,
                serialized_session,
                session_key.device_type,
            ),
        )

    await conn.commit()
    self._logger.debug("Session updated")

delete_session async

delete_session(session_key: SessionKey) -> None
Source code in src/pyromax/session/aiosqlite.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
async def delete_session(self, session_key: SessionKey) -> None:
    session_info = await self.load_session(session_key)
    if session_info is None:
        self._logger.warning("Deleting session not found")
        return None

    conn = await self._get_connection()
    sql_req = """
        DELETE FROM sessions
        """

    sql_req, values = self._prepare_session_spicies_by_session_key(
        session_key, sql_req, session_info=session_info
    )

    self._logger.warning("Deleting session token_set=%s", bool(session_info.token))
    await conn.execute(
        sql_req,
        values,
    )
    await conn.commit()
    self._logger.info("Session deleted")

delete_all_sessions async

delete_all_sessions() -> None
Source code in src/pyromax/session/aiosqlite.py
305
306
307
308
309
310
311
312
async def delete_all_sessions(self) -> None:
    conn = await self._get_connection()
    self._logger.warning("Deleting all sessions")
    await conn.execute("""
        DELETE FROM sessions
        """)
    await conn.commit()
    self._logger.info("All sessions deleted")

close async

close() -> None
Source code in src/pyromax/session/aiosqlite.py
314
315
316
317
318
319
320
321
322
323
324
325
326
async def close(self) -> None:
    if self.conn is not None:
        self._logger.debug("Closing session database")
        conn = self.conn
        self.conn = None
        try:
            await conn.close()
        except asyncio.CancelledError:
            stop_future = conn.stop()
            if stop_future is not None:
                with suppress(asyncio.CancelledError):
                    await stop_future
            raise

Authentication interaction

interaction

__all__ module-attribute

__all__ = [
    "BaseInteractor",
    "AuthInteractor",
    "TerminalAuthInteractor",
    "AuthCallbacks",
    "PasswordRequest",
]

AuthCallbacks dataclass

AuthCallbacks(
    qr_url: Callable[[str], Awaitable[None]] | None = None,
    sms_code: (
        Callable[[str], Awaitable[str | int]] | None
    ) = None,
    password: (
        Callable[[PasswordRequest], Awaitable[str]] | None
    ) = None,
)

Optional overrides for the standard authentication interaction.

qr_url class-attribute instance-attribute

qr_url: Callable[[str], Awaitable[None]] | None = None

sms_code class-attribute instance-attribute

sms_code: Callable[[str], Awaitable[str | int]] | None = (
    None
)

password class-attribute instance-attribute

password: (
    Callable[[PasswordRequest], Awaitable[str]] | None
) = None

AuthInteractor

Bases: BaseInteractor

Interaction contract required by the built-in authentication flow.

show_qr abstractmethod async

show_qr(url: str) -> None
Source code in src/pyromax/interaction/auth.py
30
31
@abstractmethod
async def show_qr(self, url: str) -> None: ...

request_sms_code abstractmethod async

request_sms_code(phone: str) -> str
Source code in src/pyromax/interaction/auth.py
33
34
@abstractmethod
async def request_sms_code(self, phone: str) -> str: ...

request_password abstractmethod async

request_password(request: PasswordRequest) -> str
Source code in src/pyromax/interaction/auth.py
36
37
@abstractmethod
async def request_password(self, request: PasswordRequest) -> str: ...

PasswordRequest dataclass

PasswordRequest(track_id: str, phone: str | None = None)

Context supplied when a two-factor password is requested.

track_id instance-attribute

track_id: str

phone class-attribute instance-attribute

phone: str | None = None

BaseInteractor

Bases: ABC

Base class for user interaction implementations.

The class intentionally has no domain-specific methods. Authentication and future interaction areas extend it with their own contracts.

TerminalAuthInteractor

TerminalAuthInteractor(
    callbacks: AuthCallbacks | None = None,
)

Bases: AuthInteractor

Default auth interaction using callbacks with terminal fallbacks.

Source code in src/pyromax/interaction/terminal.py
16
17
def __init__(self, callbacks: AuthCallbacks | None = None) -> None:
    self.callbacks = callbacks or AuthCallbacks()

callbacks instance-attribute

callbacks = callbacks or AuthCallbacks()

can_prompt property

can_prompt: bool

show_qr async

show_qr(url: str) -> None
Source code in src/pyromax/interaction/terminal.py
23
24
25
26
27
28
29
30
31
async def show_qr(self, url: str) -> None:
    if self.callbacks.qr_url is not None:
        await self.callbacks.qr_url(url)
        return

    qr = qrcode.QRCode()
    qr.add_data(url)
    qr.make(fit=True)
    qr.print_ascii(invert=True)

request_sms_code async

request_sms_code(phone: str) -> str
Source code in src/pyromax/interaction/terminal.py
33
34
35
36
37
38
39
40
41
42
43
44
45
async def request_sms_code(self, phone: str) -> str:
    if self.callbacks.sms_code is not None:
        return str(await self.callbacks.sms_code(phone))
    if not self.can_prompt:
        raise AuthInputRequired(
            "SMS code is required: provide an AuthInteractor or run in a terminal."
        )
    try:
        return await asyncio.to_thread(input, "Write a SMS code: ")
    except EOFError as error:
        raise AuthInputRequired(
            "SMS code is required: provide an AuthInteractor or run in a terminal."
        ) from error

request_password async

request_password(request: PasswordRequest) -> str
Source code in src/pyromax/interaction/terminal.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
async def request_password(self, request: PasswordRequest) -> str:
    if self.callbacks.password is not None:
        return await self.callbacks.password(request)
    if not self.can_prompt:
        raise AuthInputRequired(
            "Account has 2FA enabled: pass password=..., provide an "
            "AuthInteractor, or run in a terminal."
        )
    try:
        return await asyncio.to_thread(getpass.getpass, "2FA password: ")
    except EOFError as error:
        raise AuthInputRequired(
            "Account has 2FA enabled: pass password=..., provide an "
            "AuthInteractor, or run in a terminal."
        ) from error

Encodings

encoding

__all__ module-attribute

__all__ = [
    "BaseEncoding",
    "BaseSymmetricEncoding",
    "DictAndBytesEncoding",
    "SocketEncoding",
    "JsonEncoding",
    "NoEncoding",
    "MsgPackDictEncoding",
]

BaseEncoding

BaseEncoding(extra_config: ExtraConfig)

Bases: ABC, Generic[ENCODE_IN_TYPE, ENCODE_OUT_TYPE, DECODE_IN_TYPE, DECODE_OUT_TYPE]

Source code in src/pyromax/encoding/base.py
19
20
def __init__(self, extra_config: ExtraConfig) -> None:
    self.extra_config = extra_config

extra_config instance-attribute

extra_config = extra_config

encode abstractmethod

encode(
    data: ENCODE_IN_TYPE, *args: Any, **kwargs: Any
) -> ENCODE_OUT_TYPE

Encode the given data to the given encoding type.

Parameters:

Name Type Description Default
data ENCODE_IN_TYPE

The data to encode.

required
Source code in src/pyromax/encoding/base.py
22
23
24
25
26
27
28
29
30
31
@abstractmethod
def encode(
    self, data: ENCODE_IN_TYPE, *args: Any, **kwargs: Any
) -> ENCODE_OUT_TYPE:
    """
    Encode the given data to the given encoding type.

    :param data: The data to encode.
    :type data: Any
    """

decode abstractmethod

decode(
    data: DECODE_IN_TYPE, *args: Any, **kwargs: Any
) -> DECODE_OUT_TYPE

Decode the given data to the given decoded type.

Parameters:

Name Type Description Default
data DECODE_IN_TYPE

The data to decode.

required

Returns:

Type Description
DECODE_OUT_TYPE
Source code in src/pyromax/encoding/base.py
33
34
35
36
37
38
39
40
41
42
43
@abstractmethod
def decode(
    self, data: DECODE_IN_TYPE, *args: Any, **kwargs: Any
) -> DECODE_OUT_TYPE:
    """
    Decode the given data to the given decoded type.

    :param data: The data to decode.
    :type data: Any
    :return:
    """

BaseSymmetricEncoding

BaseSymmetricEncoding(extra_config: ExtraConfig)

Bases: BaseEncoding[DECODED_TYPE, ENCODED_TYPE, ENCODED_TYPE, DECODED_TYPE], Generic[ENCODED_TYPE, DECODED_TYPE]

a subtype of the basic encoding, for encodings that work symmetrically, i.e. they accept one type of data for encoding and return another, and for decoding the same data types are used, but in the opposite way, i.e. the data type returned from encoding is accepted, and the data type that was originally encoded is returned

Source code in src/pyromax/encoding/base.py
19
20
def __init__(self, extra_config: ExtraConfig) -> None:
    self.extra_config = extra_config

DictAndBytesEncoding

DictAndBytesEncoding(extra_config: ExtraConfig)

Bases: SocketEncoding[bytes, dict[Any, Any]]

Replacement of JsonAndBytesEncoding since, due to architectural changes, EnvelopeProtocol is no longer tied to Json and now the encoding does not need to specifically serialize data in Json.

Source code in src/pyromax/encoding/base.py
19
20
def __init__(self, extra_config: ExtraConfig) -> None:
    self.extra_config = extra_config

SocketEncoding

SocketEncoding(extra_config: ExtraConfig)

Bases: BaseSymmetricEncoding[ENCODED_TYPE, DECODED_TYPE]

Encoding for Socket transport, it is assumed that the socket transport will expect a subtype of this class, and with its help understand how many bytes to read from the bus. This is done to avoid mixing abstraction levels, and the "dumb" transport is not responsible for the message structure, but simply reads bytes from the bus. Simply put, the socket transport delegates the work with the message size to it.

Source code in src/pyromax/encoding/base.py
19
20
def __init__(self, extra_config: ExtraConfig) -> None:
    self.extra_config = extra_config

HEADER_SIZE abstractmethod property

HEADER_SIZE: int

Get the minimum size to read from the bus (i.e., the header size) to further understand how many more bytes need to be read from the bus.

Returns:

Type Description
int

Header size (number of bytes).

unpack_header_to_get_payload_length abstractmethod

unpack_header_to_get_payload_length(data: bytes) -> int

Unpack the bytes header, obtained using HEADER_SIZE

Parameters:

Name Type Description Default
data bytes

bytes of header

required

Returns:

Type Description
int

the length of the remaining message(payload)

Source code in src/pyromax/encoding/base.py
87
88
89
90
91
92
93
94
95
96
97
@abstractmethod
def unpack_header_to_get_payload_length(self, data: bytes) -> int:
    """
    Unpack the bytes header, obtained using HEADER_SIZE

    :param data: bytes of header
    :type data: bytes

    :returns: the length of the remaining message(payload)
    :rtype: int
    """

MsgPackDictEncoding

MsgPackDictEncoding(extra_config: ExtraConfig)

Bases: DictAndBytesEncoding

An encoding implementation suitable for use with the Envelope protocol and socket transport determines the size of the socket message header and provides an implementation for obtaining the message length from the header. Serializes Json data into bytes and deserializes bytes into Json.

Source code in src/pyromax/encoding/MsgPack.py
32
33
34
def __init__(self, extra_config: ExtraConfig) -> None:
    super().__init__(extra_config)
    self._logger = logging.getLogger("MsgPackDictEncoding")

HEADER_STRUCT class-attribute instance-attribute

HEADER_STRUCT = Struct('>BBHHI')

HEADER_SIZE property

HEADER_SIZE: int

encode

encode(
    data: str | dict[Any, Any], *args: Any, **kwargs: Any
) -> bytes
Source code in src/pyromax/encoding/MsgPack.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def encode(self, data: str | dict[Any, Any], *args: Any, **kwargs: Any) -> bytes:
    request: dict[Any, Any]
    if isinstance(data, str):
        request = json.loads(data)
    else:
        request = data

    seq = int(request.get("seq", 0))
    opcode = int(request.get("opcode", 1))
    cmd = int(request.get("cmd", 0))
    ver = int(request.get("ver", 11))
    del request["seq"]
    del request["opcode"]
    del request["cmd"]
    if "ver" in request:
        del request["ver"]
    if not ver:
        ver = 11
    packet = self._create_packet(
        seq, opcode, cmd, ver, payload=request.get("payload")
    )

    return packet

unpack_header_to_get_payload_length

unpack_header_to_get_payload_length(data: bytes) -> int
Source code in src/pyromax/encoding/MsgPack.py
76
77
78
def unpack_header_to_get_payload_length(self, data: bytes) -> int:
    _, _, _, _, _, payload_len = self._unpack_header(data)
    return payload_len

decode

decode(
    data: bytes, *args: Any, **kwargs: Any
) -> dict[Any, Any]
Source code in src/pyromax/encoding/MsgPack.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def decode(self, data: bytes, *args: Any, **kwargs: Any) -> dict[Any, Any]:
    header_raw = data[: self.HEADER_SIZE]

    ver, cmd, seq, opcode, flags, payload_length = self._unpack_header(header_raw)
    if payload_length > 0:
        payload_raw = data[10:]
        if len(payload_raw) != payload_length:
            raise ValueError("payload length does not match")
    else:
        payload_raw = b""

    payload_uncompressed: bytes
    if len(payload_raw) > 0:
        try:
            decompressed = self._safe_decompress(
                payload_raw,
                flags=flags,
                start_uncompressed_size=payload_length,
            )
            if decompressed is None:
                # decompressed = b""
                raise ValueError("Uncompressed return None")
            payload_uncompressed = decompressed

        except ValueError as e:
            raise e
        except Exception as e:
            logging.error(f"uncompressed error: {e}")
            raise ValueError(f"uncompressed error: {e}")
    else:
        payload_uncompressed = payload_raw

    if len(payload_uncompressed) > 0:
        try:
            decoded_payload = msgpack.unpackb(
                payload_uncompressed, strict_map_key=False
            )
        except Exception as e:
            logging.error(f"unpack error: {e}")
            raise ValueError(f"unpack error: {e}")
    else:
        decoded_payload = {}

    return {
        "opcode": opcode,
        "cmd": cmd,
        "seq": seq,
        "ver": ver,
        "payload": decoded_payload,
    }

Transports

transport

BaseTransport

BaseTransport(
    encoding: ENCODING_TYPE,
    extra_config: ExtraConfig,
    *args: Any,
    **kwargs: Any
)

Bases: AsyncInitializerMixin, Generic[ENCODING_TYPE]

Source code in src/pyromax/transport/bases/base.py
30
31
32
33
34
35
36
37
@abstractmethod
def __init__(
    self,
    encoding: ENCODING_TYPE,
    extra_config: ExtraConfig,
    *args: Any,
    **kwargs: Any,
) -> None: ...

WebSocketTransport

WebSocketTransport(
    encoding: BaseEncoding[Any, Any, Any, Any],
    extra_config: ExtraConfig,
    *args: Any,
    **kwargs: Any
)

Bases: StreamTransport[BaseEncoding[Any, Any, Any, Any]]

Initialize the web socket transport.

Parameters:

Name Type Description Default
url str

Resource URL.

required
origin str

The origin value.

required
user_agent_header str

The user agent header value.

required
Source code in src/pyromax/transport/websocket.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def __init__(
    self,
    encoding: BaseEncoding[Any, Any, Any, Any],
    extra_config: ExtraConfig,
    *args: Any,
    **kwargs: Any,
) -> None:
    # from ..config import DEFAULT_WEB_HEADER_USER_AGENT
    # if user_agent_header is None:
    #     user_agent_header = DEFAULT_WEB_HEADER_USER_AGENT
    """Initialize the web socket transport.

    :param url: Resource URL.
    :type url: str
    :param origin: The origin value.
    :type origin: str
    :param user_agent_header: The user agent header value.
    :type user_agent_header: str
    """
    self._encoding = encoding

    self.extra_config = extra_config
    transport_config = self.extra_config.transport
    from ..config import WebSocketTransportConfig
    if not isinstance(transport_config, WebSocketTransportConfig):
        raise TypeError(
            "transport config must be an instance of WebSocketTransportConfig for this transport"
        )
    self.transport_config = transport_config

    self.url = self.transport_config.url
    self.proxy = self.transport_config.proxy
    self.origin = Origin(self.transport_config.origin)
    self.user_agent_header = self.transport_config.user_agent_header
    self.max_size = transport_config.max_size


    self.ws: ClientConnection | None = None
    self.__logger = logging.getLogger("WebSocketTransport")

extra_config instance-attribute

extra_config = extra_config

transport_config instance-attribute

transport_config = transport_config

url instance-attribute

url = url

proxy instance-attribute

proxy = proxy

origin instance-attribute

origin = Origin(origin)

user_agent_header instance-attribute

user_agent_header = user_agent_header

max_size instance-attribute

max_size = max_size

ws instance-attribute

ws: ClientConnection | None = None

__logger instance-attribute

__logger = getLogger('WebSocketTransport')

connected property

connected: bool

connect async

connect(**kwargs: Any) -> None

Connect.

Parameters:

Name Type Description Default
kwargs Any

Keyword arguments forwarded to the wrapped callable.

{}

Raises:

Type Description
ConnectTransportError

If connection handshake timed out or handle unknown error.

Source code in src/pyromax/transport/websocket.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
async def connect(self, **kwargs: Any) -> None:
    """Connect.

    :param kwargs: Keyword arguments forwarded to the wrapped callable.
    :type kwargs: Any
    :raises ConnectTransportError: If connection handshake timed out or handle unknown error.
    """
    if self.ws:
        self.__logger.info("WebSocket already connected to %s", self.url)
        await self.close()
        self.__logger.info("WebSocket was close")
    self.__logger.info("Connecting to %s", self.url)
    try:
        if self.proxy:
            self.ws = await connect(
                self.url,
                origin=self.origin,
                proxy=self.proxy,
                user_agent_header=self.user_agent_header,
                max_size=self.max_size,
            )
        else:
            self.ws = await connect(
                self.url,
                origin=self.origin,
                user_agent_header=self.user_agent_header,
                max_size=self.max_size,
                # ping_interval=1,
                # ping_timeout=0.01,
                # just a for tests
            )
    except asyncio.TimeoutError as e:
        self.__logger.warning("Websocket url=%s connection handshake timed out", self.url)
        raise ConnectTransportError("Websocket connection handshake timed out") from e
    except Exception as e:
        self.__logger.error("Handler unknown exception while connecting to websocket url=%s: %s",self.url, e)
        raise ConnectTransportError("Websocket connection unknown exception") from e
    self.__logger.info("WebSocket connected to %s", self.url)

close async

close() -> None

Close.

Source code in src/pyromax/transport/websocket.py
132
133
134
135
136
137
138
139
140
141
async def close(self) -> None:
    """Close."""
    if self.ws is not None:
        ws = self.ws
        await ws.close()
        await ws.wait_closed()
        self.ws = None
        self.__logger.info("Websocket closed")
    else:
        self.__logger.info("Websocket already closed")

send async

send(data: str | bytes) -> None

Send.

Parameters:

Name Type Description Default
data str | bytes

Contextual data passed through the processing pipeline.

required

Raises:

Type Description
TypeError

If data must be str or bytes.

SendingTransportError

If you try to send before initialization connection.

Source code in src/pyromax/transport/websocket.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
async def send(self, data: str | bytes) -> None:
    """Send.

    :param data: Contextual data passed through the processing pipeline.
    :type data: str | bytes
    :raises TypeError: If data must be str or bytes.
    :raises SendingTransportError: If you try to send before initialization connection.
    """
    if not isinstance(data, (str, bytes)):
        raise TypeError("data must be str or bytes")

    if self.ws is None:
        raise SendingTransportError("You try to send before initialization connection")

    if not self.connected:
        raise SendingTransportError("You try to send before initialization connection")

    self.__logger.debug("Sending data: %s", data)
    await self.ws.send(data)

recv async

recv() -> Any

Recv.

Returns:

Type Description
Any

The value returned by backend.

Raises:

Type Description
ConnectionTransportError

If you try to recv before initialization connection.

Source code in src/pyromax/transport/websocket.py
163
164
165
166
167
168
169
170
171
172
173
async def recv(self) -> Any:
    """Recv.

    :returns: The value returned by backend.
    :rtype: Any
    :raises ConnectionTransportError: If you try to recv before initialization connection.
    """
    if self.ws is None or not self.connected:
        raise ConnectionTransportError("You try to recv before initialization connection")
    response = await self.ws.recv()
    return response

SocketTransport

SocketTransport(
    encoding: SocketEncoding[Any, Any],
    extra_config: ExtraConfig,
    *args: Any,
    **kwargs: Any
)

Bases: StreamTransport[SocketEncoding[Any, Any]]

Initialize the socket transport.

Source code in src/pyromax/transport/socket.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def __init__(
    self,
    encoding: SocketEncoding[Any, Any],
    extra_config: ExtraConfig,
    *args: Any,
    **kwargs: Any,
) -> None:
    """Initialize the socket transport."""

    from ..config import SocketTransportConfig

    self.extra_config = extra_config
    transport_config = self.extra_config.transport
    if not isinstance(transport_config, SocketTransportConfig):
        raise TypeError(
            "transport config must be an instance of SocketTransportConfig for this transport"
        )
    self.transport_config = transport_config

    self.host = self.transport_config.host
    self.port = self.transport_config.port
    self._proxy = self.transport_config.proxy
    self._use_ssl = self.transport_config.use_ssl

    self._encoding = encoding
    self.__buffer = bytearray()
    self.__logger = logging.getLogger("SocketTransport")
    self.__reader = None
    self.__writer = None
    self._ssl_context = ssl.create_default_context()
    self._ssl_context.load_verify_locations(
        str(resources.files("pyromax._data") / "rootca_ssl_rsa2022.crt")
    )

BASE_EXCEPTION_FOR_TRANSPORT class-attribute instance-attribute

BASE_EXCEPTION_FOR_TRANSPORT = BaseTransportError

OTHER_EXCEPTIONS_FOR_TRANSPORT class-attribute instance-attribute

OTHER_EXCEPTIONS_FOR_TRANSPORT = [
    ConnectionTransportError,
    SendingTransportError,
]

__reader instance-attribute

__reader: StreamReader | None = None

__writer instance-attribute

__writer: StreamWriter | None = None

__buffer instance-attribute

__buffer: bytearray = bytearray()

__logger instance-attribute

__logger: Logger = getLogger('SocketTransport')

url instance-attribute

url: str

port instance-attribute

port: int = port

extra_config instance-attribute

extra_config = extra_config

transport_config instance-attribute

transport_config = transport_config

host instance-attribute

host = host

connected property

connected: bool

send async

send(request: bytes) -> None

Send.

Parameters:

Name Type Description Default
request bytes

Protocol request envelope to populate or send.

required
Source code in src/pyromax/transport/socket.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
async def send(self, request: bytes) -> None:
    """Send.

    :param request: Protocol request envelope to populate or send.
    :type request: bytes
    """
    # assert self.__writer is not None, "Writer is not initialized"
    if self.__writer is None or not self.connected:
        self.__logger.error("Socket send failed: transport is not connected")
        raise SendingTransportError("Not connected to socket")
    self.__logger.debug("Socket send bytes=%s", len(request))
    self.__writer.write(request)
    await self.__writer.drain()
    self.__logger.debug("socket request bytes=%s was send", len(request))

recv async

recv() -> Any

Recv.

Returns:

Type Description
Any

The bytes of one message returned by backend.

Raises:

Type Description
ConnectionTransportError

If connection broken/shutdown while receiving.

Source code in src/pyromax/transport/socket.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
async def recv(self) -> Any:
    """Recv.

    :returns: The bytes of one message returned by backend.
    :rtype: Any
    :raises ConnectionTransportError: If connection broken/shutdown while receiving.
    """
    try:
        header_raw = await self._recv_raw(self._encoding.HEADER_SIZE)
    except ConnectionTransportError as e:
        self.__logger.error("Socket recv failed while try recv message header: %s", e)
        raise ConnectionTransportError("Socket recv") from e
    payload_length = self._encoding.unpack_header_to_get_payload_length(header_raw)
    if payload_length > 0:
        try:
            payload_raw = await self._recv_raw(payload_length)
        except ConnectionTransportError as e:
            self.__logger.error("Socket recv failed while try recv message payload: %s", e)
            raise ConnectionTransportError("Socket recv") from e
    else:
        payload_raw = b""

    return header_raw + payload_raw

connect async

connect(**kwargs: Any) -> None

Connect.

:param kwargs: Keyword arguments forwarded to the wrapped callable.
:type kwargs: Any

Raises:

Type Description
ConnectTransportError

If handler unknown error.

Source code in src/pyromax/transport/socket.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
async def connect(self, **kwargs: Any) -> None:
    """Connect.

    # :param kwargs: Keyword arguments forwarded to the wrapped callable.
    # :type kwargs: Any
    :raises ConnectTransportError: If handler unknown error.
    """

    self.__logger.debug("Connecting to socket host=%s port=%s ssl=%s", self.host, self.port, self._use_ssl)
    try:

        if self._proxy:
            self.__logger.debug("Connecting to socket with proxy %s.", self._proxy)
            proxy = Proxy.from_url(self._proxy)
            sock = await proxy.connect(
                dest_host=self.host,
                dest_port=self.port,
            )

            ssl_context = self._ssl_context if self._use_ssl else None
            server_hostname = self.host if ssl_context is not None else None

            self.__reader, self.__writer = await asyncio.open_connection(
                sock=sock,
                ssl=ssl_context,
                server_hostname=server_hostname
            )

            self.__logger.debug("Connected to socket host=%s port=%s ssl=%s with proxy=%s", self._proxy)
        else:
            self.__reader, self.__writer = await asyncio.open_connection(
                self.host,
                self.port,
                ssl=self._ssl_context if self._use_ssl else None,
            )


    except ConnectionError as e:
        self.__logger.error("OS connection error while connecting to socket host=%s port=%s: %s",self.host, self.port, e)
        raise ConnectTransportError(f"Socket os connection error: {e}") from e
    except gaierror as e:
        self.__logger.error("Socket hanndle gaierror: %s", e)
        raise ConnectTransportError(f"Socket gaierror error: {e}") from e
    except OSError as e:
        self.__logger.error("Handle unknown OSerror while connecting to socket host=%s port=%s: %s",self.host, self.port, e)
    except Exception as e:
        self.__logger.error("Socket connection error: %s", e)
        raise ConnectTransportError(f"Socket connection error: {e}") from e
    self.__logger.info("Socket connected")
    self.__logger.info(
        "Socket connected host=%s port=%s ssl=%s",
        self.host,
        self.port,
        self._use_ssl,
    )

close async

close() -> None

Close.

Source code in src/pyromax/transport/socket.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
async def close(self) -> None:
    """Close."""
    self.__logger.debug("Closing socket connection.")
    if self.__writer:
        try:
            self.__writer.close()
            await asyncio.wait_for(self.__writer.wait_closed(), timeout=CLOSE_TIMEOUT)
        except (OSError, TimeoutError) as e:
            self.__logger.error("socket close without graceful shutdown(cleanly): %s", e)
            self.__writer.transport.abort()
        finally:
            self.__writer = None
            self.__reader = None
            self.__buffer.clear()
    else:
        self.__logger.debug("Socket connection already closed(socket writer already None).")
    self.__logger.info("Socket closed")

Protocols

protocol

BaseMaxProtocol

BaseMaxProtocol(
    transport: BaseTransport[Any],
    encoding: BaseEncoding[Any, Any, Any, Any],
    extra_config: ExtraConfig,
    *args: Any,
    **kwargs: Any
)

Bases: AsyncInitializerMixin, Generic[T, R, TRANSPORT_TYPE]

Source code in src/pyromax/protocol/bases/base.py
35
36
37
38
39
40
41
42
43
@abstractmethod
def __init__(
    self,
    transport: BaseTransport[Any],
    encoding: BaseEncoding[Any, Any, Any, Any],
    extra_config: ExtraConfig,
    *args: Any,
    **kwargs: Any,
) -> None: ...

transport abstractmethod property

transport: BaseTransport[Any]

Transport.

Returns:

Type Description
BaseTransport

The resulting BaseTransport value.

send abstractmethod async

send(
    method: BaseMaxProtocolMethod[T],
    data: Any | None = None,
) -> Awaitable[R]

Send.

Parameters:

Name Type Description Default
method BaseMaxProtocolMethod[T]

BaseMaxProtocolMethod[T] instance to process.

required
data Any | None

Contextual data passed through the processing pipeline.

None

Returns:

Type Description
Awaitable[R]

The resulting Awaitable[R] value.

Source code in src/pyromax/protocol/bases/base.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
@abstractmethod
async def send(
    self, method: BaseMaxProtocolMethod[T], data: Any | None = None
) -> Awaitable[R]:
    """Send.

    :param method: BaseMaxProtocolMethod[T] instance to process.
    :type method: BaseMaxProtocolMethod[T]
    :param data: Contextual data passed through the processing pipeline.
    :type data: Any | None
    :returns: The resulting Awaitable[R] value.
    :rtype: Awaitable[R]
    """
    pass

get_updates abstractmethod async

get_updates() -> Iterable[Any]

Retrieve updates.

Returns:

Type Description
Iterable[Any]

The resulting collection.

Source code in src/pyromax/protocol/bases/base.py
60
61
62
63
64
65
66
67
@abstractmethod
async def get_updates(self) -> Iterable[Any]:
    """Retrieve updates.

    :returns: The resulting collection.
    :rtype: Iterable[Any]
    """
    pass

StreamMaxProtocol

StreamMaxProtocol(
    transport: BaseTransport[Any],
    encoding: BaseEncoding[Any, Any, Any, Any],
    extra_config: ExtraConfig,
    *args: Any,
    **kwargs: Any
)

Bases: BaseMaxProtocol[T, R, TRANSPORT_TYPE], Generic[T, R, TRANSPORT_TYPE]

Source code in src/pyromax/protocol/bases/base.py
35
36
37
38
39
40
41
42
43
@abstractmethod
def __init__(
    self,
    transport: BaseTransport[Any],
    encoding: BaseEncoding[Any, Any, Any, Any],
    extra_config: ExtraConfig,
    *args: Any,
    **kwargs: Any,
) -> None: ...

transport abstractmethod property

transport: TRANSPORT_TYPE

Transport.

Returns:

Type Description
StreamTransport

The resulting StreamTransport value.

connect abstractmethod async

connect(gen: int) -> None

Connect the protocol transport and start its response reader.

Parameters:

Name Type Description Default
gen int

The current error gen.

required

Raises:

Type Description
ConnectProtocolError

If the transport cannot be connected.

Source code in src/pyromax/protocol/bases/StreamProtocol.py
11
12
13
14
15
16
17
18
19
20
21
@abstractmethod
async def connect(self, gen: int) -> None:
    """Connect the protocol transport and start its response reader.

    :raises ConnectProtocolError: If the transport cannot be connected.


    :param gen: The current error gen.
    :type gen: int
    """
    pass

close abstractmethod async

close() -> None

Close.

Source code in src/pyromax/protocol/bases/StreamProtocol.py
23
24
25
26
@abstractmethod
async def close(self) -> None:
    """Close."""
    pass

EnvelopeProtocol

EnvelopeProtocol(
    transport: StreamTransport[
        BaseEncoding[Any, Any, Any, Any]
    ],
    encoding: BaseEncoding[Any, Any, Any, Any],
    extra_config: ExtraConfig,
)

Bases: StreamMaxProtocol[Envelope, Envelope, StreamTransport[BaseEncoding[Any, Any, Any, Any]]]

Initialize the envelope protocol.

Parameters:

Name Type Description Default
transport StreamTransport[BaseEncoding[Any, Any, Any, Any]]

Transport instance.

required

Raises:

Type Description
TypeError

If transport must be StreamTransport.

Source code in src/pyromax/protocol/envelope/envelope.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def __init__(
    self,
    transport: StreamTransport[BaseEncoding[Any, Any, Any, Any]],
    encoding: BaseEncoding[Any, Any, Any, Any],
    extra_config: ExtraConfig,
) -> None:
    """Initialize the envelope protocol.

    :param transport: Transport instance.
    :type transport: StreamTransport
    # :param ping_interval: The ping interval value.
    # :type ping_interval: int
    :raises TypeError: If transport must be StreamTransport.
    """
    if not isinstance(transport, StreamTransport):
        raise TypeError("transport must be StreamTransport")
    self.event_router_lock = asyncio.Lock()
    self.exceptions_callback: Callable[[Exception, int, str], Any] | None = None
    self._network_lock = asyncio.Lock()
    self.event_router: EventRouter[Envelope, Envelope] | None = None
    self.__logger = logging.getLogger("EnvelopeProtocol")
    self.__transport = transport
    self._reader_task: asyncio.Task[Any] | None = None
    # self._ping_interval = ping_interval
    self._generation_getter: Callable[..., Awaitable[int]] | None = None
    self._current_generation: int | None = None
    self._encoding = encoding

event_router_lock instance-attribute

event_router_lock = Lock()

exceptions_callback instance-attribute

exceptions_callback: (
    Callable[[Exception, int, str], Any] | None
) = None

event_router instance-attribute

event_router: EventRouter[Envelope, Envelope] | None = None

__logger instance-attribute

__logger = getLogger('EnvelopeProtocol')

__transport instance-attribute

__transport = transport

transport property

transport: StreamTransport[BaseEncoding[Any, Any, Any, Any]]

Transport.

Returns:

Type Description
StreamTransport

The using transport.

set_generation_getter

set_generation_getter(
    generation_getter: Callable[..., Awaitable[int]] | None,
) -> None

Set generation getter.

Parameters:

Name Type Description Default
generation_getter Callable[..., Awaitable[int]] | None

Callable to invoke.

required
Source code in src/pyromax/protocol/envelope/envelope.py
115
116
117
118
119
120
121
122
123
def set_generation_getter(
    self, generation_getter: Callable[..., Awaitable[int]] | None
) -> None:
    """Set generation getter.

    :param generation_getter: Callable to invoke.
    :type generation_getter: Callable[..., Awaitable[int]]
    """
    self._generation_getter = generation_getter

set_exceptions_callback

set_exceptions_callback(
    exceptions_callback: (
        Callable[[Exception, int, str], Any] | None
    ),
) -> None

Set exceptions callback.

Parameters:

Name Type Description Default
exceptions_callback Callable[[Exception, int, str], Any] | None

Callable to invoke.

required
Source code in src/pyromax/protocol/envelope/envelope.py
125
126
127
128
129
130
131
132
133
def set_exceptions_callback(
    self, exceptions_callback: Callable[[Exception, int, str], Any] | None
) -> None:
    """Set exceptions callback.

    :param exceptions_callback: Callable to invoke.
    :type exceptions_callback: Callable[[Exception, int, str], Any]
    """
    self.exceptions_callback = exceptions_callback

connect async

connect(current_gen: int) -> None

Connect the protocol transport and start its response reader.

Parameters:

Name Type Description Default
current_gen int

The current gen value.

required

Raises:

Type Description
ConnectProtocolError

If the transport cannot be connected.

Source code in src/pyromax/protocol/envelope/envelope.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
async def connect(self, current_gen: int) -> None:
    """Connect the protocol transport and start its response reader.

    :raises ConnectProtocolError: If the transport cannot be connected.


    :param current_gen: The current gen value.
    :type current_gen: int
    """
    async with self._network_lock:
        self._current_generation = current_gen
        self.__logger.info(f"Protocol generation updated, current: {current_gen}")

        await self._close()
        # reader_task = self._reader_task
        # self._reader_task = None
        # if reader_task:
        #     self.__logger.info("Find another reader, closing it...")
        #     try:
        #         reader_task.cancel()
        #         await asyncio.wait_for(reader_task, timeout=5)
        #     except asyncio.CancelledError:
        #         self.__logger.debug("reader already cancelled in another place")
        #     except asyncio.TimeoutError:
        #         self.__logger.warning("reader task got stop stop timeout(in connect)")
        #     except Exception as e:
        #         self.__logger.error("reader task ended with exception=%s", e)
        #         await self._close()
        #         raise ConnectProtocolError(
        #             "reader task ended with exception"
        #         ) from e

        try:
            await asyncio.wait_for(self.__transport.connect(), timeout=30)
        except asyncio.TimeoutError as e:
            self.__logger.error("connection timeout")
            await self._close()
            raise ConnectProtocolError("timeout to connect") from e
        except Exception as e:
            await self._close()
            raise ConnectProtocolError("connect error") from e

        try:
            # router = await self.get_event_router()
            router = self.event_router
            if router:
                # await self.set_event_router(None)
                self.event_router = None
                await router.cancel_all()

            # await self.set_event_router(EventRouter())
            self.event_router = EventRouter()
            reader_task = asyncio.create_task(self.receive_reader(gen=current_gen))

            def reader_done_callback_wrapper(
                t: asyncio.Task[Any], gen: int = current_gen
            ) -> None:
                """Wrap additional args in wrapper.

                :param t: asyncio.Task[Any] instance to process.
                :type t: asyncio.Task[Any]
                :param gen: The gen value.
                :type gen: int
                """
                self._reader_done(t, gen)

            reader_task.add_done_callback(reader_done_callback_wrapper)
            self._reader_task = reader_task
            self.__logger.info("Background tasks started")

        except Exception as e:
            self.__logger.error("start background tasks error")
            await self._close()
            raise ConnectProtocolError("start background tasks error") from e

close async

close(
    pending_requests_exc: Exception | None = None,
) -> None

Close.

Source code in src/pyromax/protocol/envelope/envelope.py
310
311
312
313
314
315
316
async def close(
    self,
    pending_requests_exc: Exception | None = None,
) -> None:
    """Close."""
    async with self._network_lock:
        await self._close(pending_requests_exc)

send async

send(
    method: BaseMaxProtocolMethod[Envelope],
    data: Any | None = None,
) -> Future[Envelope]

send a envelope

Parameters:

Name Type Description Default
method BaseMaxProtocolMethod[Envelope]

BaseMaxProtocolMethod[Envelope] instance to process.

required
data Any | None

Contextual data passed through the processing pipeline.

None

Returns:

Type Description
Future[Envelope]

The envelope populated with the request opcode and payload.

Raises:

Type Description
SendingProtocolError

If the operation fails.

:raises AlreadyCancelledError: If the operation fails.
SendingProtocolError

If you try to send something before protocol init(event router is None).

TypeError

If data must be dict instance.

Source code in src/pyromax/protocol/envelope/envelope.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
async def send(
    self, method: BaseMaxProtocolMethod[Envelope], data: Any | None = None
) -> Future[Envelope]:
    """send a envelope

    :raises SendingProtocolError: If the operation fails.
    # :raises AlreadyCancelledError: If the operation fails.
    :raises SendingProtocolError: If you try to send something before protocol init(event router is None).

    :param method: BaseMaxProtocolMethod[Envelope] instance to process.
    :type method: BaseMaxProtocolMethod[Envelope]
    :param data: Contextual data passed through the processing pipeline.
    :type data: Any | None
    :returns: The envelope populated with the request opcode and payload.
    :rtype: Future[Envelope]
    :raises TypeError: If data must be dict instance.
    """

    if data is None:
        data = {}

    if not isinstance(data, dict):
        raise TypeError("data must be dict instance")
    envelope = await self.from_request(request_data=data)
    try:
        request = await method(request=envelope)
    except Exception as e:
        self.__logger.exception(
            "failed to create envelope, method: %s", method.__class__.__name__
        )
        raise SendingProtocolError("failed to create envelope") from e
    # event_router = await self.get_event_router()
    event_router = self.event_router
    if not event_router:
        raise SendingProtocolError("no event router while send")
    gen = self._current_generation
    if gen is None:
        raise SendingProtocolError("protocol not connected")
    try:
        record = event_router.create_record(request, gen=gen)
    except AlreadyCancelledError:
        raise SendingProtocolError("event router already cancelled")

    try:
        encoded_frame = self._encoding.encode(request.model_dump(by_alias=True))
        await self.__transport.send(encoded_frame)
    except BaseTransportError as e:
        self.__logger.error("transport sending error: %s", e, exc_info=True)
        try:
            if self.exceptions_callback is not None:
                self.exceptions_callback(e, gen, "send")
        except Exception:
            self.__logger.exception("exceptions_callback failed")
        event_router.cancel_request(request, gen=gen)
        raise SendingProtocolError("transport sending error") from e
    except Exception as e:
        self.__logger.error("sending error: %s", e, exc_info=True)
        try:
            if self.exceptions_callback is not None:
                self.exceptions_callback(e, gen, "send")
        except Exception:
            self.__logger.exception("exceptions_callback failed")
        event_router.cancel_request(request, gen=gen)
        raise SendingProtocolError("sending error") from e
    self.__logger.debug("send request: %s", envelope.model_dump(by_alias=True))

    return record

receive_reader async

receive_reader(gen: int) -> None

Receive reader.

Parameters:

Name Type Description Default
gen int

The gen value.

required

Raises:

Type Description
RuntimeError

If no event router while receive.

Source code in src/pyromax/protocol/envelope/envelope.py
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
async def receive_reader(self, gen: int) -> None:
    """Receive reader.

    :param gen: The gen value.
    :type gen: int
    :raises RuntimeError: If no event router while receive.
    """
    # event_router = await self.get_event_router()
    event_router = self.event_router
    if event_router is None:
        raise RuntimeError("no event router while receive")
    while True:
        raw_data = await self.__transport.recv()
        response = self._encoding.decode(raw_data)

        # from random import random
        #
        # rnd = random()
        #
        # if rnd > 0.5:
        #     print("raise")
        #     print(f"raise {str(response)[0:100]}...")
        #     raise BaseTransportError("test")

        response = self.from_response(response)
        self.__logger.debug("fetched response %s", response)
        response_resolved = await event_router.resolve_response(response, gen=gen)
        if response_resolved:
            # Let the request coroutine consume a delivered response before
            # reading again.  Some API errors are immediately followed by a
            # server-side socket close; without this hand-off the lifecycle
            # observer can cancel the request and mask the domain error with
            # a generic transport failure.
            await asyncio.sleep(0)

get_updates async

get_updates() -> Iterable[Envelope]

get updates from event router

Returns:

Type Description
Iterable[Envelope]

The envelope populated with the request opcode and payload.

Raises:

Type Description
GetUpdatesProtocolError

If the operation fails.

Source code in src/pyromax/protocol/envelope/envelope.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
async def get_updates(self) -> Iterable[Envelope]:
    """get updates from event router

    :raises GetUpdatesProtocolError: If the operation fails.

    :returns: The envelope populated with the request opcode and payload.
    :rtype: Iterable[Envelope]
    """
    try:
        # event_router = await self.get_event_router()
        event_router = self.event_router
        if event_router is None:
            raise GetUpdatesProtocolError("no event router while receive")
        updates = await event_router.pop_all_updates()
    except (AlreadyCancelledError, RoutingError) as e:
        self.__logger.error(
            "get_all_updates end with exception=%s", e, exc_info=True
        )
        raise GetUpdatesProtocolError(
            "get_all_updates end with exception while getting updates"
        ) from e
    return updates

from_request async

from_request(request_data: dict[str, Any]) -> Envelope

From request.

Parameters:

Name Type Description Default
request_data dict[str, Any]

dict[str, Any] instance to process.

required

Returns:

Type Description
Envelope

The envelope populated with the request opcode and payload.

Raises:

Type Description
BaseProtocolError

If no event router while parse request.

Source code in src/pyromax/protocol/envelope/envelope.py
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
async def from_request(self, request_data: dict[str, Any]) -> Envelope:
    """From request.

    :param request_data: dict[str, Any] instance to process.
    :type request_data: dict[str, Any]
    :returns: The envelope populated with the request opcode and payload.
    :rtype: Envelope
    :raises BaseProtocolError: If no event router while parse request.
    """
    envelope_data = dict(request_data)
    if "seq" not in envelope_data:
        # event_router = await self.get_event_router()
        event_router = self.event_router
        if not event_router:
            raise BaseProtocolError("no event router while parse request")
        envelope_data["seq"] = await event_router.correlator.next_counter()
    envelope_data.setdefault("payload", None)
    return Envelope(**envelope_data)

from_response

from_response(data: dict[str, Any]) -> Envelope

From response.

Parameters:

Name Type Description Default
data dict[str, Any]

Contextual data passed through the processing pipeline.

required

Returns:

Type Description
Envelope

The envelope populated with the request opcode and payload.

Source code in src/pyromax/protocol/envelope/envelope.py
505
506
507
508
509
510
511
512
513
def from_response(self, data: dict[str, Any]) -> Envelope:
    """From response.

    :param data: Contextual data passed through the processing pipeline.
    :type data: dict[str, Any]
    :returns: The envelope populated with the request opcode and payload.
    :rtype: Envelope
    """
    return Envelope(**data)

Request

Bases: ABC, Generic[T_response]

is_my_response abstractmethod

is_my_response(response: T_response) -> bool

Return whether my response.

Parameters:

Name Type Description Default
response T_response

Protocol response to process.

required

Returns:

Type Description
bool

True when the requested condition is satisfied; otherwise False.

Source code in src/pyromax/protocol/bases/request_response.py
24
25
26
27
28
29
30
31
32
33
@abstractmethod
def is_my_response(self, response: T_response) -> bool:
    """Return whether my response.

    :param response: Protocol response to process.
    :type response: T_response
    :returns: True when the requested condition is satisfied; otherwise False.
    :rtype: bool
    """
    pass

__hash__ abstractmethod

__hash__() -> int

Hash.

Returns:

Type Description
int

The resulting int value.

Source code in src/pyromax/protocol/bases/request_response.py
35
36
37
38
39
40
41
42
@abstractmethod
def __hash__(self) -> int:
    """Hash.

    :returns: The resulting int value.
    :rtype: int
    """
    pass

Response

Bases: ABC

Mappers

mapping

EnvelopeMapperV11

EnvelopeMapperV11(
    protocol: EnvelopeProtocol, extra_config: ExtraConfig
)

Bases: FullMixin

Source code in src/pyromax/mapping/envelope/v11/mixins/construct.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def __init__(
    self,
    protocol: EnvelopeProtocol,
    extra_config: ExtraConfig,
) -> None:
    """Initialize the constructor mixin.

    :param protocol: Protocol backend or protocol instance.
    :type protocol: EnvelopeProtocol
    :param keepalive_ping_interval: The keepalive ping interval value.
    :type keepalive_ping_interval: int
    """
    mapper_config = extra_config.mapper
    if not isinstance(mapper_config, EnvelopeMapperConfigV11):
        raise TypeError(
            "mapper config must be an instance of EnvelopeMappingConfigV11 for this mapper"
        )
    self.extra_config = extra_config
    self.mapper_config: EnvelopeMapperConfigV11 = mapper_config

    if self.mapper_config.device_type not in self.DEVICE_TYPE_TO_USERAGENT_MODEL:
        raise RuntimeError(f"Unknown device type: {self.mapper_config.device_type}")

    self.protocol: EnvelopeProtocol
    self.protocol_version: int

    self.max_api = cast("MaxApi", None)
    # self.token: str | None = self.mapper_config.token

    self.password: str | None = self.mapper_config.password
    if not isinstance(extra_config.auth_interactor, AuthInteractor):
        raise TypeError(
            "EnvelopeV11 mapper requires an AuthInteractor-compatible auth_interactor"
        )
    self.phone: str | None = self.mapper_config.phone
    self.sms_auth = self.mapper_config.sms_auth
    self.request_timeout: float = self.mapper_config.request_timeout
    circuit_breakers_config = self.mapper_config.circuit_breakers
    transport_config = circuit_breakers_config.transport
    api_config = circuit_breakers_config.api
    self._transport_circuit_breaker = (
        CircuitBreaker(
            failure_threshold=transport_config.failure_threshold,
            recovery_timeout=transport_config.recovery_timeout,
            max_cycles=transport_config.max_cycles,
            backoff_factor=transport_config.backoff_factor,
            max_recovery_timeout=transport_config.max_recovery_timeout,
            wait_when_open=transport_config.wait_when_open,
            name="transport",
        )
        if transport_config.enabled
        else None
    )
    self._api_circuit_breaker = (
        CircuitBreaker(
            failure_threshold=api_config.failure_threshold,
            recovery_timeout=api_config.recovery_timeout,
            max_cycles=api_config.max_cycles,
            backoff_factor=api_config.backoff_factor,
            max_recovery_timeout=api_config.max_recovery_timeout,
            wait_when_open=api_config.wait_when_open,
            name="api",
        )
        if api_config.enabled
        else None
    )
    self.use_telemetry: bool = self.mapper_config.use_telemetry
    self.keep_alive_interactive: bool = self.mapper_config.interactive
    self.connect_timeout = self.mapper_config.connect_timeout

    user_agent_params = self.mapper_config.user_agent_config.model_dump()
    user_agent_model = self.DEVICE_TYPE_TO_USERAGENT_MODEL[
        self.mapper_config.device_type
    ]
    user_agent = user_agent_model.get_random_user_agent(**user_agent_params)
    self.user_agent = user_agent

    # self.TOKEN_NAME: str

    fingerprint_overrides = None
    app_version = getattr(self.mapper_config.user_agent_config, "app_version", None)
    if (
        self.mapper_config.user_agent_config.supports_app_fingerprint
        and app_version is not None
        and extra_config.app_fingerprint is not None
    ):
        fingerprint_overrides = {
            app_version: extra_config.app_fingerprint,
        }
    self.fingerprint_generator = FingerprintGenerator(fingerprint_overrides)
    self.logged: bool = False
    self.calls_seed: int | None = None
    self._previous_cid = 0
    self._cid_lock = threading.Lock()

    # self._update_listener_task: Task[Any] | None = None

    self._update_listener_lock: Lock = Lock()
    self._authorized = asyncio.Event()

    self._keepalive_task: Task[Any] | None = None
    self._keepalive_ping_interval = self.mapper_config.keepalive_ping_interval

    self._mapper_connected: asyncio.Event = Event()
    self._protocol_connected: asyncio.Event = Event()

    self._lifecycle_manager: LifecycleManager | None = None
    self._lifecycle_manager_inited: asyncio.Event = Event()

    self._telemetry: TelemetryManager | None = None
    self._logger = self.mapper_config.mapper_logger or logging.getLogger(
        "MapperV11"
    )

listen_updates

listen_updates(
    context: Any,
) -> tuple[
    Callable[[Response], Response | BaseMaxObject],
    AsyncGenerator[Response, None],
]

Listen for updates.

Parameters:

Name Type Description Default
context Any

Runtime context used while processing the request.

required

Returns:

Type Description
tuple[Callable[[Response], Response | BaseMaxObject], AsyncGenerator[Response, None]]

Items produced by the iterator.

Source code in src/pyromax/mapping/envelope/v11/Mapper.py
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def listen_updates(
    self, context: Any
) -> tuple[
    Callable[[Response], Response | BaseMaxObject], AsyncGenerator[Response, None]
]:
    """Listen for updates.

    :param context: Runtime context used while processing the request.
    :type context: Any
    :returns: Items produced by the iterator.
    :rtype: tuple[Callable[[Response], Response | BaseMaxObject], AsyncGenerator[Response, None]]
    """
    return partial(update_translate, context=context), self._listen_updates(
        context=context
    )

High-level methods

BaseMaxApiMethod

Bases: ContextController, BaseModel, Generic[T], ABC

__call__ abstractmethod async

__call__(*args: Any, **kwargs: Any) -> T | Any

Execute the base max api MAX API method.

Parameters:

Name Type Description Default
args Any

Positional arguments forwarded to the wrapped callable.

()
kwargs Any

Keyword arguments forwarded to the wrapped callable.

{}

Returns:

Type Description
T | Any

The resulting T | Any value.

Source code in src/pyromax/methods/Base.py
13
14
15
16
17
18
19
20
21
22
23
24
@abc.abstractmethod
async def __call__(self, *args: Any, **kwargs: Any) -> T | Any:
    """Execute the base max api MAX API method.

    :param args: Positional arguments forwarded to the wrapped callable.
    :type args: Any
    :param kwargs: Keyword arguments forwarded to the wrapped callable.
    :type kwargs: Any
    :returns: The resulting T | Any value.
    :rtype: T | Any
    """
    pass

Versions

versions

VersionCatalog module-attribute

VersionCatalog = VersionApi

__all__ module-attribute

__all__ = [
    "ApkBuildFingerprint",
    "VersionAlreadyExistsError",
    "VersionApi",
    "VersionCatalog",
    "VersionNotFoundError",
]

ApkBuildFingerprint

Bases: BaseModel

Hashes and build metadata for one Android MAX release.

signature_scheme instance-attribute

signature_scheme: str

certificate_count instance-attribute

certificate_count: int

certificate_meta_sha256 instance-attribute

certificate_meta_sha256: str

certificate_sha256 instance-attribute

certificate_sha256: list[str]

dex_meta_sha256 instance-attribute

dex_meta_sha256: str

so_meta_sha256_arm64_v8a class-attribute instance-attribute

so_meta_sha256_arm64_v8a: str | None = None

so_meta_sha256 instance-attribute

so_meta_sha256: dict[str, str]

build_number instance-attribute

build_number: int

VersionAlreadyExistsError

VersionAlreadyExistsError(version: str)

Bases: ValueError

Raised when adding a version that is already in the catalog.

Source code in src/pyromax/exceptions/VersionError.py
11
12
def __init__(self, version: str) -> None:
    super().__init__(f"Version {version} already exists in registry")

VersionNotFoundError

VersionNotFoundError(version: str)

Bases: ValueError

Raised when an application version is absent from the catalog.

Source code in src/pyromax/exceptions/VersionError.py
4
5
def __init__(self, version: str) -> None:
    super().__init__(f"Could not find version {version} in registry")

VersionApi

VersionApi(remote_url: str | None = None)

Catalog of Android MAX versions and their APK fingerprints.

Built-in versions are available immediately. When remote_url is set, :meth:load merges that remote catalog over the bundled data. Network, HTTP, JSON, and validation errors are intentionally propagated.

Parameters:

Name Type Description Default
remote_url str | None

Optional URL fetched when :meth:load is called.

None
Source code in src/pyromax/versions/catalog.py
23
24
25
26
def __init__(self, remote_url: str | None = None) -> None:
    self.path = resources.files("pyromax._data") / "apk_fingerprints.json"
    self.remote_url = remote_url
    self.versions = self._convert_data(self._load_fingerprints())

RECOMMENDED_APP_VERSION class-attribute instance-attribute

RECOMMENDED_APP_VERSION = '26.25.0'

path instance-attribute

path = files('pyromax._data') / 'apk_fingerprints.json'

remote_url instance-attribute

remote_url = remote_url

versions instance-attribute

versions = _convert_data(_load_fingerprints())

recommended staticmethod

recommended() -> str

Return the application version used by mobile clients by default.

Source code in src/pyromax/versions/catalog.py
28
29
30
31
32
@staticmethod
def recommended() -> str:
    """Return the application version used by mobile clients by default."""

    return VersionApi.RECOMMENDED_APP_VERSION

recommended_pair

recommended_pair() -> tuple[str, int]

Return the recommended app version and its build number.

Source code in src/pyromax/versions/catalog.py
34
35
36
37
38
def recommended_pair(self) -> tuple[str, int]:
    """Return the recommended app version and its build number."""

    version = self.recommended()
    return version, self.resolve(version).build_number

load async

load() -> VersionApi

Load and merge remote versions when remote loading is enabled.

Source code in src/pyromax/versions/catalog.py
40
41
42
43
44
45
async def load(self) -> "VersionApi":
    """Load and merge remote versions when remote loading is enabled."""

    if self.remote_url is not None:
        self.versions.update(await self.fetch())
    return self

add

add(
    version: str,
    fingerprint: ApkBuildFingerprint,
    override: bool = False,
) -> None

Add a version to this catalog.

Source code in src/pyromax/versions/catalog.py
47
48
49
50
51
52
53
54
55
56
57
def add(
    self,
    version: str,
    fingerprint: ApkBuildFingerprint,
    override: bool = False,
) -> None:
    """Add a version to this catalog."""

    if version in self.versions and not override:
        raise VersionAlreadyExistsError(version)
    self.versions[version] = fingerprint

resolve

resolve(version: str) -> ApkBuildFingerprint

Resolve a version or raise :class:VersionNotFoundError.

Source code in src/pyromax/versions/catalog.py
59
60
61
62
63
64
65
def resolve(self, version: str) -> ApkBuildFingerprint:
    """Resolve a version or raise :class:`VersionNotFoundError`."""

    try:
        return self.versions[version]
    except KeyError as error:
        raise VersionNotFoundError(version) from error

fetch async

fetch() -> dict[str, ApkBuildFingerprint]
Source code in src/pyromax/versions/catalog.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
async def fetch(self) -> dict[str, ApkBuildFingerprint]:
    if self.remote_url is None:
        raise ValueError("remote_url must be configured before fetching versions")

    async with (
        aiohttp.ClientSession() as session,
        session.get(self.remote_url) as response,
    ):
        response.raise_for_status()
        data = await response.json()

    if not isinstance(data, dict):
        raise ValueError("Version catalog response must be an object")
    return self._convert_data(data)

Dispatcher modes

RawUpdateMode

RawUpdateMode

Bases: StrEnum

Control which protocol responses reach update outer middlewares.

TRANSLATED_ONLY class-attribute instance-attribute

TRANSLATED_ONLY = 'translated_only'

ALL_RESPONSES class-attribute instance-attribute

ALL_RESPONSES = 'all_responses'

UpdateTranslationFailure dataclass

UpdateTranslationFailure(exception: Exception)

Translation failure exposed to raw update middlewares through data.

exception instance-attribute

exception: Exception

UpdateTranslationFailure dataclass

UpdateTranslationFailure(exception: Exception)

Translation failure exposed to raw update middlewares through data.

exception instance-attribute

exception: Exception

Circuit breaker

circuit_breaker

__all__ module-attribute

__all__ = ['CircuitBreaker', 'CircuitBreakerState']

CircuitBreakerState

Bases: str, Enum

Possible states of a circuit breaker.

CLOSED class-attribute instance-attribute

CLOSED = 'closed'

OPEN class-attribute instance-attribute

OPEN = 'open'

HALF_OPEN class-attribute instance-attribute

HALF_OPEN = 'half_open'

CircuitBreaker

CircuitBreaker(
    failure_threshold: int = 1,
    recovery_timeout: float = 1.0,
    *,
    max_cycles: int = 5,
    backoff_factor: float = 2.0,
    max_recovery_timeout: float = 30.0,
    wait_when_open: bool = True,
    name: str | None = None,
    time_func: Callable[[], float] = time.monotonic
)

Async circuit breaker for logical operations.

Failures are counted consecutively. Once failure_threshold is reached, calls fail fast until recovery_timeout has elapsed. Exactly one call is then admitted as a half-open probe. Failed probes increase the recovery timeout by backoff_factor up to max_recovery_timeout.

Source code in src/pyromax/utils/circuit_breaker.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def __init__(
    self,
    failure_threshold: int = 1,
    recovery_timeout: float = 1.0,
    *,
    max_cycles: int = 5,
    backoff_factor: float = 2.0,
    max_recovery_timeout: float = 30.0,
    wait_when_open: bool = True,
    name: str | None = None,
    time_func: Callable[[], float] = time.monotonic,
) -> None:
    if failure_threshold < 1:
        raise ValueError("failure_threshold must be at least 1")
    if recovery_timeout < 0:
        raise ValueError("recovery_timeout cannot be negative")
    if max_cycles < 0:
        raise ValueError("max_cycles cannot be negative")
    if backoff_factor < 1:
        raise ValueError("backoff_factor must be at least 1")
    if max_recovery_timeout < recovery_timeout:
        raise ValueError(
            "max_recovery_timeout cannot be less than recovery_timeout"
        )

    self.failure_threshold = failure_threshold
    self.recovery_timeout = recovery_timeout
    self.max_cycles = max_cycles
    self.backoff_factor = backoff_factor
    self.max_recovery_timeout = max_recovery_timeout
    self.wait_when_open = wait_when_open
    self.name = name
    self._time = time_func
    self._current_recovery_timeout = recovery_timeout
    self._state = CircuitBreakerState.CLOSED
    self._failure_count = 0
    self._opened_at: float | None = None
    self._generation = 0
    self._lock = asyncio.Lock()
    self._state_changed = asyncio.Event()

failure_threshold instance-attribute

failure_threshold = failure_threshold

recovery_timeout instance-attribute

recovery_timeout = recovery_timeout

max_cycles instance-attribute

max_cycles = max_cycles

backoff_factor instance-attribute

backoff_factor = backoff_factor

max_recovery_timeout instance-attribute

max_recovery_timeout = max_recovery_timeout

wait_when_open instance-attribute

wait_when_open = wait_when_open

name instance-attribute

name = name

state property

state: CircuitBreakerState

failure_count property

failure_count: int

retry_after property

retry_after: float

Return seconds before another probe may be attempted.

before_call async

before_call() -> _CircuitBreakerPermit

Admit a call or raise when the circuit is not ready.

Source code in src/pyromax/utils/circuit_breaker.py
 98
 99
100
101
102
103
104
105
106
107
108
109
async def before_call(self) -> _CircuitBreakerPermit:
    """Admit a call or raise when the circuit is not ready."""
    async with self._lock:
        if self._state is CircuitBreakerState.CLOSED:
            return _CircuitBreakerPermit(self._generation)

        if self._state is CircuitBreakerState.OPEN and self.retry_after <= 0:
            self._state = CircuitBreakerState.HALF_OPEN
            self._notify_state_changed()
            return _CircuitBreakerPermit(self._generation, probe=True)

        raise CircuitBreakerOpenError(self.retry_after, circuit=self.name)

wait_for_call async

wait_for_call() -> _CircuitBreakerPermit

Wait for the cooldown and acquire the next available call permit.

Source code in src/pyromax/utils/circuit_breaker.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
async def wait_for_call(self) -> _CircuitBreakerPermit:
    """Wait for the cooldown and acquire the next available call permit."""
    while True:
        async with self._lock:
            if self._state is CircuitBreakerState.CLOSED:
                return _CircuitBreakerPermit(self._generation)

            retry_after = self.retry_after
            if self._state is CircuitBreakerState.OPEN and retry_after <= 0:
                self._state = CircuitBreakerState.HALF_OPEN
                self._notify_state_changed()
                return _CircuitBreakerPermit(self._generation, probe=True)

            state_changed = self._state_changed
            wait_timeout = (
                retry_after
                if self._state is CircuitBreakerState.OPEN
                else None
            )

        if wait_timeout is None:
            await state_changed.wait()
            continue
        try:
            await asyncio.wait_for(state_changed.wait(), timeout=wait_timeout)
        except asyncio.TimeoutError:
            pass

wait_until_available async

wait_until_available() -> None

Wait until a call may attempt to acquire the circuit.

Source code in src/pyromax/utils/circuit_breaker.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
async def wait_until_available(self) -> None:
    """Wait until a call may attempt to acquire the circuit."""
    while True:
        async with self._lock:
            if self._state is CircuitBreakerState.CLOSED:
                return

            retry_after = self.retry_after
            if self._state is CircuitBreakerState.OPEN and retry_after <= 0:
                return

            state_changed = self._state_changed
            wait_timeout = (
                retry_after
                if self._state is CircuitBreakerState.OPEN
                else None
            )

        if wait_timeout is None:
            await state_changed.wait()
            continue
        try:
            await asyncio.wait_for(state_changed.wait(), timeout=wait_timeout)
        except asyncio.TimeoutError:
            pass

record_success async

record_success(permit: _CircuitBreakerPermit) -> None

Record a successful admitted call.

Source code in src/pyromax/utils/circuit_breaker.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
async def record_success(self, permit: _CircuitBreakerPermit) -> None:
    """Record a successful admitted call."""
    async with self._lock:
        if permit.generation != self._generation:
            return

        if permit.probe:
            if self._state is not CircuitBreakerState.HALF_OPEN:
                return
            self._state = CircuitBreakerState.CLOSED
            self._opened_at = None
            self._current_recovery_timeout = self.recovery_timeout
            self._generation += 1
            self._notify_state_changed()

        if self._state is CircuitBreakerState.CLOSED:
            self._failure_count = 0

record_failure async

record_failure(permit: _CircuitBreakerPermit) -> None

Record a dependency failure for an admitted call.

Source code in src/pyromax/utils/circuit_breaker.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
async def record_failure(self, permit: _CircuitBreakerPermit) -> None:
    """Record a dependency failure for an admitted call."""
    async with self._lock:
        if permit.generation != self._generation:
            return

        if permit.probe:
            if self._state is CircuitBreakerState.HALF_OPEN:
                self._open(increase_timeout=True)
            return

        if self._state is not CircuitBreakerState.CLOSED:
            return

        self._failure_count += 1
        if self._failure_count >= self.failure_threshold:
            self._open(increase_timeout=False)

record_ignored async

record_ignored(permit: _CircuitBreakerPermit) -> None

Release a cancelled half-open probe without counting a failure.

Source code in src/pyromax/utils/circuit_breaker.py
201
202
203
204
205
206
207
208
209
async def record_ignored(self, permit: _CircuitBreakerPermit) -> None:
    """Release a cancelled half-open probe without counting a failure."""
    async with self._lock:
        if permit.generation != self._generation or not permit.probe:
            return
        if self._state is CircuitBreakerState.HALF_OPEN:
            self._state = CircuitBreakerState.OPEN
            self._generation += 1
            self._notify_state_changed()

reset async

reset() -> None

Close the circuit and clear its failure history.

Source code in src/pyromax/utils/circuit_breaker.py
211
212
213
214
215
216
217
218
219
async def reset(self) -> None:
    """Close the circuit and clear its failure history."""
    async with self._lock:
        self._state = CircuitBreakerState.CLOSED
        self._failure_count = 0
        self._opened_at = None
        self._current_recovery_timeout = self.recovery_timeout
        self._generation += 1
        self._notify_state_changed()

Registry decorators

register_transport

register_transport(
    transport: str,
) -> Callable[
    [type[BaseTransport[Any]]], type[BaseTransport[Any]]
]

Register transport.

Parameters:

Name Type Description Default
transport str

name of the transport.

required

Returns:

Type Description
Callable[[type[BaseTransport]], type[BaseTransport]]

The decorator Callable[[type[BaseTransport]], type[BaseTransport]].

Source code in src/pyromax/transport/registry.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def register_transport(
    transport: str,
) -> Callable[[type[BaseTransport[Any]]], type[BaseTransport[Any]]]:
    """Register transport.

    :param transport: name of the transport.
    :type transport: str
    :returns: The decorator Callable[[type[BaseTransport]], type[BaseTransport]].
    :rtype: Callable[[type[BaseTransport]], type[BaseTransport]]
    """
    global TRANSPORTS

    def wrapper(cls: type[BaseTransport[Any]]) -> type[BaseTransport[Any]]:
        """Wrapper.

        :param cls: transport class
        :type cls: type[BaseTransport]
        :returns: The resulting type[BaseTransport].
        :rtype: type[BaseTransport]
        """
        TRANSPORTS[transport] = cls
        return cls

    return wrapper

register_encoding

register_encoding(
    encoding: str,
) -> Callable[
    [type[BaseEncoding[Any, Any, Any, Any]]],
    type[BaseEncoding[Any, Any, Any, Any]],
]

Register protocol.

Parameters:

Name Type Description Default
encoding str

name of protocol.

required

Returns:

Type Description
Callable[[type[BaseMaxProtocol[Any, Any]]], type[BaseMaxProtocol[Any, Any]]]

The resulting Callable[[type[BaseMaxProtocol[Any, Any]]], type[BaseMaxProtocol[Any, Any]]] value.

Source code in src/pyromax/encoding/registry.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def register_encoding(
    encoding: str,
) -> Callable[
    [type[BaseEncoding[Any, Any, Any, Any]]], type[BaseEncoding[Any, Any, Any, Any]]
]:
    """Register protocol.

    :param encoding: name of protocol.
    :type encoding: str
    :returns: The resulting Callable[[type[BaseMaxProtocol[Any, Any]]], type[BaseMaxProtocol[Any, Any]]] value.
    :rtype: Callable[[type[BaseMaxProtocol[Any, Any]]], type[BaseMaxProtocol[Any, Any]]]
    """
    global ENCODINGS

    def wrapper(
        cls: type[BaseEncoding[Any, Any, Any, Any]],
    ) -> type[BaseEncoding[Any, Any, Any, Any]]:
        """Wrapper.

        :returns: The resulting type[BaseMaxProtocol[Any, Any]] value.
        :rtype: type[BaseMaxProtocol[Any, Any]]
        """
        ENCODINGS[encoding] = cls
        return cls

    return wrapper

register_protocol

register_protocol(
    protocol: str,
) -> Callable[
    [type[BaseMaxProtocol[Any, Any]]],
    type[BaseMaxProtocol[Any, Any]],
]

Register protocol.

Parameters:

Name Type Description Default
protocol str

name of protocol.

required

Returns:

Type Description
Callable[[type[BaseMaxProtocol[Any, Any]]], type[BaseMaxProtocol[Any, Any]]]

The resulting Callable[[type[BaseMaxProtocol[Any, Any]]], type[BaseMaxProtocol[Any, Any]]] value.

Source code in src/pyromax/protocol/registry.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def register_protocol(
    protocol: str,
) -> Callable[[type[BaseMaxProtocol[Any, Any]]], type[BaseMaxProtocol[Any, Any]]]:
    """Register protocol.

    :param protocol: name of protocol.
    :type protocol: str
    :returns: The resulting Callable[[type[BaseMaxProtocol[Any, Any]]], type[BaseMaxProtocol[Any, Any]]] value.
    :rtype: Callable[[type[BaseMaxProtocol[Any, Any]]], type[BaseMaxProtocol[Any, Any]]]
    """
    global PROTOCOLS

    def wrapper(
        cls: type[BaseMaxProtocol[Any, Any]],
    ) -> type[BaseMaxProtocol[Any, Any]]:
        """Wrapper.

        :returns: The resulting type[BaseMaxProtocol[Any, Any]] value.
        :rtype: type[BaseMaxProtocol[Any, Any]]
        """
        PROTOCOLS[protocol] = cls
        return cls

    return wrapper

register_mapper

register_mapper(
    mapper: str,
) -> Callable[
    [type[BaseMapper[Any, Any]]], type[BaseMapper[Any, Any]]
]

Register mapper.

Parameters:

Name Type Description Default
mapper str

Mapper backend or mapper instance.

required

Returns:

Type Description
Callable[[type[BaseMapper[Any, Any]]], type[BaseMapper[Any, Any]]]

The resulting Callable[[type[BaseMapper[Any, Any]]], type[BaseMapper[Any, Any]]] value.

Source code in src/pyromax/mapping/registry.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def register_mapper(
    mapper: str,
) -> Callable[[type[BaseMapper[Any, Any]]], type[BaseMapper[Any, Any]]]:
    """Register mapper.

    :param mapper: Mapper backend or mapper instance.
    :type mapper: str
    :returns: The resulting Callable[[type[BaseMapper[Any, Any]]], type[BaseMapper[Any, Any]]] value.
    :rtype: Callable[[type[BaseMapper[Any, Any]]], type[BaseMapper[Any, Any]]]
    """
    global MAPPERS

    def wrapper(cls: type[BaseMapper[Any, Any]]) -> type[BaseMapper[Any, Any]]:
        """Wrapper.

        :returns: The resulting type[BaseMapper[Any, Any]] value.
        :rtype: type[BaseMapper[Any, Any]]
        """
        MAPPERS[mapper] = cls
        return cls

    return wrapper