Skip to content

Commit 262f2c6

Browse files
committed
Rename Message to ResultPayload
1 parent 043248b commit 262f2c6

File tree

11 files changed

+59
-75
lines changed

11 files changed

+59
-75
lines changed

trinity/protocol/common/exchanges.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,13 @@
1414
from .managers import ExchangeManager
1515
from .normalizers import BaseNormalizer
1616
from .types import (
17-
TMsg,
17+
TResponsePayload,
1818
TResult,
1919
)
2020
from .validators import BaseValidator
2121

2222

23-
class BaseExchange(ABC, Generic[TRequestPayload, TMsg, TResult]):
23+
class BaseExchange(ABC, Generic[TRequestPayload, TResponsePayload, TResult]):
2424
"""
2525
The exchange object handles a few things, in rough order:
2626
@@ -34,19 +34,19 @@ class BaseExchange(ABC, Generic[TRequestPayload, TMsg, TResult]):
3434
- await the normalized & validated response, and return it
3535
3636
TRequestPayload is the data as passed directly to the p2p command
37-
TMsg is the data as received directly from the p2p command response
37+
TResponsePayload is the data as received directly from the p2p command response
3838
TResult is the response data after normalization
3939
"""
4040

41-
def __init__(self, manager: ExchangeManager[TRequestPayload, TMsg, TResult]) -> None:
42-
self._manager = manager
41+
def __init__(self, mgr: ExchangeManager[TRequestPayload, TResponsePayload, TResult]) -> None:
42+
self._manager = mgr
4343

4444
async def get_result(
4545
self,
4646
request: BaseRequest[TRequestPayload],
47-
normalizer: BaseNormalizer[TMsg, TResult],
47+
normalizer: BaseNormalizer[TResponsePayload, TResult],
4848
result_validator: BaseValidator[TResult],
49-
payload_validator: Callable[[TRequestPayload, TMsg], None],
49+
payload_validator: Callable[[TRequestPayload, TResponsePayload], None],
5050
timeout: int = None) -> TResult:
5151
"""
5252
This is a light convenience wrapper around the ExchangeManager's get_result() method.

trinity/protocol/common/managers.py

Lines changed: 35 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929

3030
from .normalizers import BaseNormalizer
3131
from .types import (
32-
TMsg,
32+
TResponsePayload,
3333
TResult,
3434
)
3535

@@ -59,7 +59,10 @@ def add(self, time: float, size: int) -> None:
5959
self.total_response_time += time
6060

6161

62-
class MessageManager(PeerSubscriber, BaseService, Generic[TRequestPayload, TMsg]):
62+
class ResponseCandidateStream(
63+
PeerSubscriber,
64+
BaseService,
65+
Generic[TRequestPayload, TResponsePayload]):
6366

6467
#
6568
# PeerSubscriber
@@ -72,7 +75,7 @@ def subscription_msg_types(self) -> Set[Type[Command]]:
7275

7376
response_timout: int = 60
7477

75-
pending_request: Tuple[float, 'asyncio.Future[TMsg]'] = None
78+
pending_request: Tuple[float, 'asyncio.Future[TResponsePayload]'] = None
7679

7780
_peer: BasePeer
7881

@@ -86,19 +89,19 @@ def __init__(
8689
self.response_times = ResponseTimeTracker()
8790
self._response_msg_type = response_msg_type
8891

89-
async def message_candidates(
92+
async def payload_candidates(
9093
self,
9194
request: BaseRequest[TRequestPayload],
92-
timeout: int) -> 'AsyncGenerator[TMsg, None]':
95+
timeout: int) -> 'AsyncGenerator[TResponsePayload, None]':
9396
"""
9497
Make a request and iterate through candidates for a valid response.
9598
96-
To mark a response as valid, use `complete_request`. After that call, message
99+
To mark a response as valid, use `complete_request`. After that call, payload
97100
candidates will stop arriving.
98101
"""
99102
self._request(request)
100103
while self._is_pending():
101-
yield await self._get_message(timeout)
104+
yield await self._get_payload(timeout)
102105

103106
@property
104107
def response_msg_name(self) -> str:
@@ -121,35 +124,35 @@ async def _run(self) -> None:
121124
self.logger.error("Unexpected peer: %s expected: %s", peer, self._peer)
122125
continue
123126
elif isinstance(cmd, self._response_msg_type):
124-
await self._handle_msg(cast(TMsg, msg))
127+
await self._handle_msg(cast(TResponsePayload, msg))
125128
else:
126-
self.logger.warning("Unexpected message type: %s", cmd.__class__.__name__)
129+
self.logger.warning("Unexpected payload type: %s", cmd.__class__.__name__)
127130

128-
async def _handle_msg(self, msg: TMsg) -> None:
131+
async def _handle_msg(self, msg: TResponsePayload) -> None:
129132
if self.pending_request is None:
130133
self.logger.debug(
131-
"Got unexpected %s message from %", self.response_msg_name, self._peer
134+
"Got unexpected %s payload from %", self.response_msg_name, self._peer
132135
)
133136
return
134137

135138
send_time, future = self.pending_request
136139
self.last_response_time = time.perf_counter() - send_time
137140
future.set_result(msg)
138141

139-
async def _get_message(self, timeout: int) -> TMsg:
142+
async def _get_payload(self, timeout: int) -> TResponsePayload:
140143
send_time, future = self.pending_request
141144
try:
142-
message = await self.wait(future, timeout=timeout)
145+
payload = await self.wait(future, timeout=timeout)
143146
except TimeoutError:
144147
self.response_times.total_timeouts += 1
145148
raise
146149
finally:
147150
self.pending_request = None
148151

149-
# message might be invalid, so prepare for another call to _get_message()
152+
# payload might be invalid, so prepare for another call to _get_payload()
150153
self.pending_request = (send_time, asyncio.Future())
151154

152-
return message
155+
return payload
153156

154157
def _request(self, request: BaseRequest[TRequestPayload]) -> None:
155158
if self.pending_request is not None:
@@ -167,7 +170,7 @@ def _request(self, request: BaseRequest[TRequestPayload]) -> None:
167170

168171
self._peer.sub_proto.send_request(request)
169172

170-
future: 'asyncio.Future[TMsg]' = asyncio.Future()
173+
future: 'asyncio.Future[TResponsePayload]' = asyncio.Future()
171174
self.pending_request = (time.perf_counter(), future)
172175

173176
def _is_pending(self) -> bool:
@@ -177,8 +180,8 @@ def get_stats(self) -> str:
177180
return '%s: %s' % (self.response_msg_name, self.response_times.get_stats())
178181

179182

180-
class ExchangeManager(Generic[TRequestPayload, TMsg, TResult]):
181-
_message_manager: MessageManager[TRequestPayload, TMsg] = None
183+
class ExchangeManager(Generic[TRequestPayload, TResponsePayload, TResult]):
184+
_response_stream: ResponseCandidateStream[TRequestPayload, TResponsePayload] = None
182185

183186
def __init__(
184187
self,
@@ -188,13 +191,13 @@ def __init__(
188191
self._cancel_token = cancel_token
189192

190193
async def launch_service(self, listening_for: Type[Command]) -> None:
191-
self._message_manager = MessageManager(
194+
self._response_stream = ResponseCandidateStream(
192195
self._peer,
193196
listening_for,
194197
self._cancel_token,
195198
)
196-
self._peer.run_daemon(self._message_manager)
197-
await self._message_manager.events.started.wait()
199+
self._peer.run_daemon(self._response_stream)
200+
await self._response_stream.events.started.wait()
198201

199202
@property
200203
def is_running(self) -> bool:
@@ -203,38 +206,37 @@ def is_running(self) -> bool:
203206
async def get_result(
204207
self,
205208
request: BaseRequest[TRequestPayload],
206-
normalizer: BaseNormalizer[TMsg, TResult],
209+
normalizer: BaseNormalizer[TResponsePayload, TResult],
207210
validate_result: Callable[[TResult], None],
208-
message_validator: Callable[[TMsg], None] = None,
211+
payload_validator: Callable[[TResponsePayload], None],
209212
timeout: int = None) -> TResult:
210213

211214
if not self.is_running:
212215
raise ValidationError("You must call `launch_service` before initiating a peer request")
213216

214-
manager = self._message_manager
217+
stream = self._response_stream
215218

216-
async for message in manager.message_candidates(request, timeout):
219+
async for payload in stream.payload_candidates(request, timeout):
217220
try:
218-
if message_validator is not None:
219-
message_validator(message)
221+
payload_validator(payload)
220222

221223
if normalizer.is_normalization_slow:
222-
result = await manager._run_in_executor(normalizer.normalize_result, message)
224+
result = await stream._run_in_executor(normalizer.normalize_result, payload)
223225
else:
224-
result = normalizer.normalize_result(message)
226+
result = normalizer.normalize_result(payload)
225227

226228
validate_result(result)
227229
except ValidationError as err:
228230
self.service.logger.debug(
229231
"Response validation failed for pending %s request from peer %s: %s",
230-
manager.response_msg_name,
232+
stream.response_msg_name,
231233
self._peer,
232234
err,
233235
)
234236
continue
235237
else:
236238
num_items = normalizer.get_num_results(result)
237-
manager.complete_request(num_items)
239+
stream.complete_request(num_items)
238240
return result
239241

240242
raise ValidationError("Manager is not pending a response, but no valid response received")
@@ -244,7 +246,7 @@ def service(self) -> BaseService:
244246
"""
245247
This service that needs to be running for calls to execute properly
246248
"""
247-
return self._message_manager
249+
return self._response_stream
248250

249251
def get_stats(self) -> str:
250-
return self._message_manager.get_stats()
252+
return self._response_stream.get_stats()

trinity/protocol/common/normalizers.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
from abc import abstractmethod, ABC
2-
32
from typing import (
43
Generic,
5-
Sized,
64
TypeVar,
75
)
86

7+
from p2p.protocol import PayloadType
8+
99
from .types import (
10-
TMsg,
10+
TResponsePayload,
1111
TResult,
1212
)
1313

1414

15-
class BaseNormalizer(ABC, Generic[TMsg, TResult]):
15+
class BaseNormalizer(ABC, Generic[TResponsePayload, TResult]):
1616
is_normalization_slow = False
1717
"""
1818
This variable indicates how slow normalization is. If normalization requires
@@ -22,7 +22,7 @@ class BaseNormalizer(ABC, Generic[TMsg, TResult]):
2222

2323
@staticmethod
2424
@abstractmethod
25-
def normalize_result(message: TMsg) -> TResult:
25+
def normalize_result(message: TResponsePayload) -> TResult:
2626
"""
2727
Convert underlying peer message to final result
2828
"""
@@ -37,7 +37,7 @@ def get_num_results(result: TResult) -> int:
3737
raise NotImplementedError()
3838

3939

40-
TPassthrough = TypeVar('TPassthrough', bound=Sized)
40+
TPassthrough = TypeVar('TPassthrough', bound=PayloadType)
4141

4242

4343
class NoopNormalizer(BaseNormalizer[TPassthrough, TPassthrough]):

trinity/protocol/common/requests.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,6 @@
66

77
from eth_typing import BlockIdentifier, BlockNumber
88

9-
from eth_utils import (
10-
ValidationError,
11-
)
12-
139
from trinity.utils.headers import sequence_builder
1410

1511

trinity/protocol/common/types.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,6 @@
1818
# A payload delivered by a responding command
1919
TResponsePayload = TypeVar('TResponsePayload', bound=PayloadType)
2020

21-
TMsg = TypeVar('TMsg')
22-
2321
# The returned value at the end of an exchange
2422
TResult = TypeVar('TResult')
2523

trinity/protocol/common/validators.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,10 @@
1212
BlockIdentifier,
1313
BlockNumber,
1414
)
15-
from eth_utils import encode_hex
16-
from p2p.exceptions import ValidationError
15+
from eth_utils import (
16+
ValidationError,
17+
encode_hex,
18+
)
1719

1820
from trinity.utils.headers import sequence_builder
1921

trinity/protocol/eth/exchanges.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,13 @@
22
Any,
33
Dict,
44
Tuple,
5-
TypeVar,
65
)
76

87
from eth_typing import (
98
BlockIdentifier,
109
Hash32,
1110
)
1211
from eth.rlp.headers import BlockHeader
13-
from p2p.protocol import (
14-
TRequestPayload,
15-
)
1612

1713
from trinity.protocol.common.exchanges import (
1814
BaseExchange,
@@ -49,13 +45,11 @@
4945
ReceiptsValidator,
5046
)
5147

52-
# when the message equals the result
53-
TMsgResult = TypeVar('TMsgResult')
54-
55-
# For when the result type is the same as the message type
56-
EthExchangePassthrough = BaseExchange[TRequestPayload, TMsgResult, TMsgResult]
57-
58-
BaseGetBlockHeadersExchange = EthExchangePassthrough[Dict[str, Any], Tuple[BlockHeader, ...]]
48+
BaseGetBlockHeadersExchange = BaseExchange[
49+
Dict[str, Any],
50+
Tuple[BlockHeader, ...],
51+
Tuple[BlockHeader, ...],
52+
]
5953

6054

6155
class GetBlockHeadersExchange(BaseGetBlockHeadersExchange):

trinity/protocol/eth/requests.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,6 @@
1010
)
1111
from p2p.protocol import BaseRequest
1212

13-
from eth_utils import (
14-
ValidationError,
15-
)
16-
1713
from trinity.protocol.eth.constants import MAX_HEADERS_FETCH
1814
from trinity.protocol.common.requests import (
1915
BaseHeaderRequest,

trinity/protocol/eth/validators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from eth_typing import (
77
Hash32,
88
)
9-
from p2p.exceptions import (
9+
from eth_utils import (
1010
ValidationError,
1111
)
1212

trinity/protocol/les/requests.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,6 @@
55

66
from eth_typing import BlockIdentifier
77

8-
from eth_utils import (
9-
ValidationError,
10-
)
11-
128
from p2p.protocol import BaseRequest
139

1410
from trinity.protocol.common.requests import (

0 commit comments

Comments
 (0)