Encode a message dict to binary format. Supports the old dict-based API for backwards compatibility. Args: message: Message dict with 'type', 'id', and payload fields Returns: bytes: Complete encoded message
(message: dict)
| 574 | |
| 575 | @staticmethod |
| 576 | def _encode_from_dict(message: dict) -> bytes: # pylint: disable=too-many-return-statements |
| 577 | """ |
| 578 | Encode a message dict to binary format. |
| 579 | |
| 580 | Supports the old dict-based API for backwards compatibility. |
| 581 | |
| 582 | Args: |
| 583 | message: Message dict with 'type', 'id', and payload fields |
| 584 | |
| 585 | Returns: |
| 586 | bytes: Complete encoded message |
| 587 | """ |
| 588 | msg_type_str = message.get("type") |
| 589 | request_id = message.get("id", 0) |
| 590 | |
| 591 | # Handle string or int request IDs |
| 592 | if isinstance(request_id, str): |
| 593 | # For backwards compat with UUID strings, hash to int |
| 594 | request_id = hash(request_id) & 0xFFFFFFFFFFFFFFFF |
| 595 | |
| 596 | msg_type = MSG_TYPE_FROM_STR.get(msg_type_str) |
| 597 | if msg_type is None: |
| 598 | raise DirtyProtocolError(f"Unknown message type: {msg_type_str}") |
| 599 | |
| 600 | if msg_type == MSG_TYPE_REQUEST: |
| 601 | return BinaryProtocol.encode_request( |
| 602 | request_id, |
| 603 | message.get("app_path", ""), |
| 604 | message.get("action", ""), |
| 605 | message.get("args"), |
| 606 | message.get("kwargs") |
| 607 | ) |
| 608 | elif msg_type == MSG_TYPE_RESPONSE: |
| 609 | return BinaryProtocol.encode_response( |
| 610 | request_id, |
| 611 | message.get("result") |
| 612 | ) |
| 613 | elif msg_type == MSG_TYPE_ERROR: |
| 614 | return BinaryProtocol.encode_error( |
| 615 | request_id, |
| 616 | message.get("error", {}) |
| 617 | ) |
| 618 | elif msg_type == MSG_TYPE_CHUNK: |
| 619 | return BinaryProtocol.encode_chunk( |
| 620 | request_id, |
| 621 | message.get("data") |
| 622 | ) |
| 623 | elif msg_type == MSG_TYPE_END: |
| 624 | return BinaryProtocol.encode_end(request_id) |
| 625 | elif msg_type == MSG_TYPE_STASH: |
| 626 | return BinaryProtocol.encode_stash( |
| 627 | request_id, |
| 628 | message.get("op"), |
| 629 | message.get("table", ""), |
| 630 | message.get("key"), |
| 631 | message.get("value"), |
| 632 | message.get("pattern") |
| 633 | ) |