Edit on GitHub

communex.module.client

Client for Commune modules.

 1"""
 2Client for Commune modules.
 3"""
 4
 5import asyncio
 6import json
 7from typing import Any
 8
 9import aiohttp
10import aiohttp.client_exceptions
11import aiohttp.web_exceptions
12from substrateinterface import Keypair  # type: ignore
13
14from communex.errors import NetworkTimeoutError
15from communex.key import check_ss58_address
16from communex.types import Ss58Address
17
18from ._protocol import create_method_endpoint, create_request_data
19from ._signer import TESTING_MNEMONIC
20
21
22class ModuleClient:
23    host: str
24    port: int
25    key: Keypair
26
27    def __init__(self, host: str, port: int, key: Keypair):
28        self.host = host
29        self.port = port
30        self.key = key
31
32    async def call(
33            self,
34            fn: str,
35            target_key: Ss58Address,
36            params: Any = {},
37            timeout: int = 16,
38    ) -> Any:
39        serialized_data, headers = create_request_data(self.key, target_key, params)
40
41        out = aiohttp.ClientTimeout(total=timeout)
42        try:
43            async with aiohttp.ClientSession(timeout=out) as session:
44                async with session.post(
45                    create_method_endpoint(self.host, self.port, fn),
46                    json=json.loads(serialized_data),
47                    headers=headers,
48                ) as response:
49                    match response.status:
50                        case 200:
51                            pass
52                        case status_code:
53                            response_j = await response.json()
54                            raise Exception(
55                                f"Unexpected status code: {status_code}, response: {response_j}")
56                    match response.content_type:
57                        case 'application/json':
58                            result = await asyncio.wait_for(response.json(), timeout=timeout)
59                            # TODO: deserialize result
60                            return result
61                        case _:
62                            raise Exception(
63                                f"Unknown content type: {response.content_type}")
64        except asyncio.exceptions.TimeoutError as e:
65            raise NetworkTimeoutError(
66                f"The call took longer than the timeout of {timeout} second(s)").with_traceback(e.__traceback__)
67
68
69if __name__ == "__main__":
70    keypair = Keypair.create_from_mnemonic(
71        TESTING_MNEMONIC
72    )
73    client = ModuleClient("localhost", 8000, keypair)
74    ss58_address = check_ss58_address(keypair.ss58_address)
75    result = asyncio.run(client.call("do_the_thing", ss58_address, {
76                         "awesomness": 45, "extra": "hi"}))
77    print(result)
class ModuleClient:
23class ModuleClient:
24    host: str
25    port: int
26    key: Keypair
27
28    def __init__(self, host: str, port: int, key: Keypair):
29        self.host = host
30        self.port = port
31        self.key = key
32
33    async def call(
34            self,
35            fn: str,
36            target_key: Ss58Address,
37            params: Any = {},
38            timeout: int = 16,
39    ) -> Any:
40        serialized_data, headers = create_request_data(self.key, target_key, params)
41
42        out = aiohttp.ClientTimeout(total=timeout)
43        try:
44            async with aiohttp.ClientSession(timeout=out) as session:
45                async with session.post(
46                    create_method_endpoint(self.host, self.port, fn),
47                    json=json.loads(serialized_data),
48                    headers=headers,
49                ) as response:
50                    match response.status:
51                        case 200:
52                            pass
53                        case status_code:
54                            response_j = await response.json()
55                            raise Exception(
56                                f"Unexpected status code: {status_code}, response: {response_j}")
57                    match response.content_type:
58                        case 'application/json':
59                            result = await asyncio.wait_for(response.json(), timeout=timeout)
60                            # TODO: deserialize result
61                            return result
62                        case _:
63                            raise Exception(
64                                f"Unknown content type: {response.content_type}")
65        except asyncio.exceptions.TimeoutError as e:
66            raise NetworkTimeoutError(
67                f"The call took longer than the timeout of {timeout} second(s)").with_traceback(e.__traceback__)
ModuleClient(host: str, port: int, key: substrateinterface.keypair.Keypair)
28    def __init__(self, host: str, port: int, key: Keypair):
29        self.host = host
30        self.port = port
31        self.key = key
host: str
port: int
key: substrateinterface.keypair.Keypair
async def call( self, fn: str, target_key: communex.types.Ss58Address, params: Any = {}, timeout: int = 16) -> Any:
33    async def call(
34            self,
35            fn: str,
36            target_key: Ss58Address,
37            params: Any = {},
38            timeout: int = 16,
39    ) -> Any:
40        serialized_data, headers = create_request_data(self.key, target_key, params)
41
42        out = aiohttp.ClientTimeout(total=timeout)
43        try:
44            async with aiohttp.ClientSession(timeout=out) as session:
45                async with session.post(
46                    create_method_endpoint(self.host, self.port, fn),
47                    json=json.loads(serialized_data),
48                    headers=headers,
49                ) as response:
50                    match response.status:
51                        case 200:
52                            pass
53                        case status_code:
54                            response_j = await response.json()
55                            raise Exception(
56                                f"Unexpected status code: {status_code}, response: {response_j}")
57                    match response.content_type:
58                        case 'application/json':
59                            result = await asyncio.wait_for(response.json(), timeout=timeout)
60                            # TODO: deserialize result
61                            return result
62                        case _:
63                            raise Exception(
64                                f"Unknown content type: {response.content_type}")
65        except asyncio.exceptions.TimeoutError as e:
66            raise NetworkTimeoutError(
67                f"The call took longer than the timeout of {timeout} second(s)").with_traceback(e.__traceback__)