fjagepy 2.0.2__tar.gz → 2.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {fjagepy-2.0.2 → fjagepy-2.1.0}/PKG-INFO +27 -1
- {fjagepy-2.0.2 → fjagepy-2.1.0}/README.md +25 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy/AgentID.py +7 -3
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy/Connector.py +9 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy/Gateway.py +17 -11
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy/JSONMessage.py +4 -4
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy/Message.py +215 -49
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy/Performative.py +3 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy/TCPConnector.py +18 -14
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy/__init__.py +2 -1
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy.egg-info/PKG-INFO +27 -1
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy.egg-info/requires.txt +1 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/pyproject.toml +6 -3
- fjagepy-2.1.0/test/test_message.py +182 -0
- fjagepy-2.0.2/test/test_message.py +0 -87
- {fjagepy-2.0.2 → fjagepy-2.1.0}/LICENSE +0 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy/Services.py +0 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy/Utils.py +0 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy.egg-info/SOURCES.txt +0 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy.egg-info/dependency_links.txt +0 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/fjagepy.egg-info/top_level.txt +0 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/setup.cfg +0 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/test/test_agentid.py +0 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/test/test_gateway.py +0 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/test/test_jsonmessage.py +0 -0
- {fjagepy-2.0.2 → fjagepy-2.1.0}/test/test_shellreqs.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fjagepy
|
|
3
|
-
Version: 2.0
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: fjage Gateway in Python
|
|
5
5
|
Author-email: Chinmay Pendharkar <chinmay@subnero.com>
|
|
6
6
|
License: BSD-3-Clause
|
|
@@ -14,6 +14,7 @@ License-File: LICENSE
|
|
|
14
14
|
Provides-Extra: dev
|
|
15
15
|
Requires-Dist: pytest==8.3.5; extra == "dev"
|
|
16
16
|
Requires-Dist: numpy==2.3.0; extra == "dev"
|
|
17
|
+
Requires-Dist: mypy==1.19.0; extra == "dev"
|
|
17
18
|
Provides-Extra: docs
|
|
18
19
|
Requires-Dist: sphinx==8.2.3; extra == "docs"
|
|
19
20
|
Requires-Dist: sphinx-rtd-theme==3.0.2; extra == "docs"
|
|
@@ -128,6 +129,31 @@ important_msg = gw.receive(my_filter, timeout=1000)
|
|
|
128
129
|
|
|
129
130
|
gw.close()
|
|
130
131
|
```
|
|
132
|
+
|
|
133
|
+
### User-Defined Message Classes
|
|
134
|
+
|
|
135
|
+
Use `@message` to register your own message subclasses so incoming JSON can be inflated back into the right Python type.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
from fjagepy import Message, message
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@message('org.example.CustomReq')
|
|
142
|
+
class CustomReq(Message):
|
|
143
|
+
def __init__(self, text=None):
|
|
144
|
+
super().__init__()
|
|
145
|
+
self.text = text
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
outgoing = CustomReq('hello')
|
|
149
|
+
payload = outgoing.to_json()
|
|
150
|
+
|
|
151
|
+
# Later, when a message with the same clazz arrives from fjage:
|
|
152
|
+
incoming = Message.from_json(payload)
|
|
153
|
+
assert isinstance(incoming, CustomReq)
|
|
154
|
+
assert incoming.text == 'hello'
|
|
155
|
+
```
|
|
156
|
+
|
|
131
157
|
## Advanced Usage
|
|
132
158
|
|
|
133
159
|
### Custom Connectors
|
|
@@ -106,6 +106,31 @@ important_msg = gw.receive(my_filter, timeout=1000)
|
|
|
106
106
|
|
|
107
107
|
gw.close()
|
|
108
108
|
```
|
|
109
|
+
|
|
110
|
+
### User-Defined Message Classes
|
|
111
|
+
|
|
112
|
+
Use `@message` to register your own message subclasses so incoming JSON can be inflated back into the right Python type.
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from fjagepy import Message, message
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@message('org.example.CustomReq')
|
|
119
|
+
class CustomReq(Message):
|
|
120
|
+
def __init__(self, text=None):
|
|
121
|
+
super().__init__()
|
|
122
|
+
self.text = text
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
outgoing = CustomReq('hello')
|
|
126
|
+
payload = outgoing.to_json()
|
|
127
|
+
|
|
128
|
+
# Later, when a message with the same clazz arrives from fjage:
|
|
129
|
+
incoming = Message.from_json(payload)
|
|
130
|
+
assert isinstance(incoming, CustomReq)
|
|
131
|
+
assert incoming.text == 'hello'
|
|
132
|
+
```
|
|
133
|
+
|
|
109
134
|
## Advanced Usage
|
|
110
135
|
|
|
111
136
|
### Custom Connectors
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import logging
|
|
4
|
-
from typing import Optional, Any
|
|
4
|
+
from typing import Optional, Any, TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from .Gateway import Gateway
|
|
8
|
+
from .Message import Message
|
|
5
9
|
|
|
6
10
|
logger = logging.getLogger(__name__)
|
|
7
11
|
logger.addHandler(logging.NullHandler())
|
|
@@ -162,7 +166,7 @@ class AgentID:
|
|
|
162
166
|
Returns:
|
|
163
167
|
str: string representation of the agent id
|
|
164
168
|
"""
|
|
165
|
-
owner_str = f"Gateway({self.owner.
|
|
169
|
+
owner_str = f"Gateway({self.owner.__details__()})" if self.owner else 'none'
|
|
166
170
|
return f"AgentID(name={self.name}, topic={self.topic}, owner={owner_str})"
|
|
167
171
|
|
|
168
172
|
def _repr_pretty_(self, p, cycle) -> None:
|
|
@@ -198,7 +202,7 @@ class AgentID:
|
|
|
198
202
|
|
|
199
203
|
# Then we split them into lists based on the prefix. Everything before the
|
|
200
204
|
# final dot is considered a section.
|
|
201
|
-
sections = {}
|
|
205
|
+
sections: dict = {}
|
|
202
206
|
for param in param_names:
|
|
203
207
|
if '.' in param:
|
|
204
208
|
section, subparam = param.rsplit('.', 1)
|
|
@@ -5,6 +5,10 @@ from typing import Any, Callable, List, Optional
|
|
|
5
5
|
class Connector(ABC):
|
|
6
6
|
"""Abstract base class for fjåge transport connectors."""
|
|
7
7
|
|
|
8
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
9
|
+
""" Initialize the connector with any necessary parameters. Subclasses can define their own parameters as needed. """
|
|
10
|
+
pass
|
|
11
|
+
|
|
8
12
|
@abstractmethod
|
|
9
13
|
def connect(self) -> None:
|
|
10
14
|
"""Establish the transport connection."""
|
|
@@ -39,3 +43,8 @@ class Connector(ABC):
|
|
|
39
43
|
callback: Function that receives a list of messages whenever new data arrives.
|
|
40
44
|
"""
|
|
41
45
|
pass
|
|
46
|
+
|
|
47
|
+
@abstractmethod
|
|
48
|
+
def __details__(self) -> str:
|
|
49
|
+
"""Return a string with details about the connector (e.g., host and port)."""
|
|
50
|
+
pass
|
|
@@ -16,7 +16,6 @@ from .JSONMessage import JSONMessage, Actions
|
|
|
16
16
|
from .Message import Message
|
|
17
17
|
from .Utils import UUID7
|
|
18
18
|
|
|
19
|
-
DEFAULT_RECONNECT_DELAY = 2.0 # seconds
|
|
20
19
|
DEFAULT_MAX_QUEUE_SIZE = 512
|
|
21
20
|
|
|
22
21
|
logger = logging.getLogger(__name__)
|
|
@@ -66,10 +65,10 @@ class Gateway:
|
|
|
66
65
|
self._pending_actions = ThreadSafeDict()
|
|
67
66
|
self._pending_requests = ThreadSafeDict()
|
|
68
67
|
self._queue = ThreadSafeDeque(maxlen=DEFAULT_MAX_QUEUE_SIZE)
|
|
69
|
-
self._subscriptions = dict()
|
|
68
|
+
self._subscriptions:dict[AgentID, bool] = dict()
|
|
70
69
|
self._timeout = timeout
|
|
71
70
|
self.aid = AgentID("gateway-" + str(uuid.uuid4()), owner=self)
|
|
72
|
-
self.connector = connector(hostname, port,
|
|
71
|
+
self.connector = connector(host=hostname, port=port, reconnect_delay=5 if reconnect else -1)
|
|
73
72
|
self.connector.set_receive_callback(self._msg_rx)
|
|
74
73
|
try :
|
|
75
74
|
self.connector.connect()
|
|
@@ -321,18 +320,18 @@ class Gateway:
|
|
|
321
320
|
rsp.inResponseTo = json_msg.action
|
|
322
321
|
if json_msg.action == Actions.AGENTS.value:
|
|
323
322
|
rsp.agentIDs = [self.aid]
|
|
323
|
+
self._msg_tx(rsp)
|
|
324
324
|
elif json_msg.action == Actions.CONTAINS_AGENT.value:
|
|
325
325
|
rsp.answer = json_msg.agentID == self.aid
|
|
326
|
+
self._msg_tx(rsp)
|
|
326
327
|
elif json_msg.action == Actions.SERVICES.value:
|
|
327
328
|
rsp.services = []
|
|
329
|
+
self._msg_tx(rsp)
|
|
328
330
|
elif json_msg.action == Actions.AGENT_FOR_SERVICE.value:
|
|
329
331
|
rsp.agentID = None
|
|
332
|
+
self._msg_tx(rsp)
|
|
330
333
|
elif json_msg.action == Actions.AGENTS_FOR_SERVICE.value:
|
|
331
334
|
rsp.agentIDs = []
|
|
332
|
-
else:
|
|
333
|
-
rsp = None
|
|
334
|
-
|
|
335
|
-
if rsp:
|
|
336
335
|
self._msg_tx(rsp)
|
|
337
336
|
|
|
338
337
|
except Exception as e:
|
|
@@ -351,7 +350,7 @@ class Gateway:
|
|
|
351
350
|
logger.debug(f">>> {json_str}")
|
|
352
351
|
self.connector.send(json_str)
|
|
353
352
|
|
|
354
|
-
def _msg_tx_rx(self, json_msg: JSONMessage, timeout: int = None) -> Optional[JSONMessage]:
|
|
353
|
+
def _msg_tx_rx(self, json_msg: JSONMessage, timeout: Optional[int] = None) -> Optional[JSONMessage]:
|
|
355
354
|
"""Sends a JSONMessage and waits for a response.
|
|
356
355
|
|
|
357
356
|
Args:
|
|
@@ -408,8 +407,11 @@ class Gateway:
|
|
|
408
407
|
def __exit__(self, exc_type, exc_value, traceback) -> None:
|
|
409
408
|
self.close()
|
|
410
409
|
|
|
410
|
+
def __details__(self):
|
|
411
|
+
return f"(host:{self.connector.__details__()} connected={self.is_connected()})"
|
|
412
|
+
|
|
411
413
|
def __str__(self) -> str:
|
|
412
|
-
return f"Gateway(
|
|
414
|
+
return f"Gateway(self.__details__())"
|
|
413
415
|
|
|
414
416
|
def _repr_pretty_(self, p, cycle):
|
|
415
417
|
p.text(str(self) if not cycle else '...')
|
|
@@ -489,9 +491,13 @@ class ThreadSafeDeque(MutableSequence):
|
|
|
489
491
|
with self._lock:
|
|
490
492
|
self._dq.appendleft(item)
|
|
491
493
|
|
|
492
|
-
def pop(self):
|
|
494
|
+
def pop(self, index: int = -1):
|
|
493
495
|
with self._lock:
|
|
494
|
-
|
|
496
|
+
if index == -1:
|
|
497
|
+
return self._dq.pop()
|
|
498
|
+
item = self._dq[index]
|
|
499
|
+
del self._dq[index]
|
|
500
|
+
return item
|
|
495
501
|
|
|
496
502
|
def popleft(self):
|
|
497
503
|
with self._lock:
|
|
@@ -3,7 +3,7 @@ import base64
|
|
|
3
3
|
import struct
|
|
4
4
|
import logging
|
|
5
5
|
from enum import Enum
|
|
6
|
-
from typing import List, Optional, Any
|
|
6
|
+
from typing import List, Optional, Any, Union
|
|
7
7
|
|
|
8
8
|
from .AgentID import AgentID
|
|
9
9
|
from .Message import Message
|
|
@@ -60,7 +60,7 @@ class JSONMessage:
|
|
|
60
60
|
logger.warning(f"Unknown attribute '{k}' in JSONMessage")
|
|
61
61
|
|
|
62
62
|
|
|
63
|
-
def _decode_base64(self, obj: dict) -> dict:
|
|
63
|
+
def _decode_base64(self, obj: dict) -> Union[dict, list]:
|
|
64
64
|
if (
|
|
65
65
|
isinstance(obj, dict)
|
|
66
66
|
and obj.get("clazz", "").startswith("[")
|
|
@@ -138,7 +138,7 @@ class JSONMessage:
|
|
|
138
138
|
return jm
|
|
139
139
|
|
|
140
140
|
@staticmethod
|
|
141
|
-
def createAgentForService(service: str) -> "JSONMessage":
|
|
141
|
+
def createAgentForService(service: str | Enum) -> "JSONMessage":
|
|
142
142
|
if not isinstance(service, str) or not service:
|
|
143
143
|
raise ValueError("service must be a non-empty string")
|
|
144
144
|
jm = JSONMessage()
|
|
@@ -147,7 +147,7 @@ class JSONMessage:
|
|
|
147
147
|
return jm
|
|
148
148
|
|
|
149
149
|
@staticmethod
|
|
150
|
-
def createAgentsForService(service: str) -> "JSONMessage":
|
|
150
|
+
def createAgentsForService(service: str | Enum) -> "JSONMessage":
|
|
151
151
|
if not isinstance(service, str) or not service:
|
|
152
152
|
raise ValueError("service must be a non-empty string")
|
|
153
153
|
jm = JSONMessage()
|
|
@@ -1,21 +1,29 @@
|
|
|
1
1
|
import sys
|
|
2
2
|
import logging
|
|
3
|
-
|
|
3
|
+
import keyword
|
|
4
|
+
from typing import Callable, Optional, Any, Dict, TYPE_CHECKING, Union, get_type_hints, overload
|
|
4
5
|
|
|
5
6
|
from .AgentID import AgentID
|
|
6
7
|
from .Performative import Performative
|
|
7
8
|
from .Utils import UUID7
|
|
8
9
|
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from .Gateway import Gateway
|
|
12
|
+
|
|
9
13
|
logger = logging.getLogger(__name__)
|
|
10
14
|
logger.addHandler(logging.NullHandler())
|
|
11
15
|
|
|
16
|
+
_MESSAGE_REGISTRY: Dict[str, type["Message"]] = {}
|
|
17
|
+
_NUMPY_AVAILABLE:bool = False
|
|
18
|
+
|
|
12
19
|
# Attempt to import numpy for array handling
|
|
13
20
|
# If numpy is not available, we don't need to
|
|
14
21
|
# handle numpy arrays in Message
|
|
15
22
|
try:
|
|
16
23
|
import numpy
|
|
24
|
+
_NUMPY_AVAILABLE = True
|
|
17
25
|
|
|
18
|
-
def _serialize_numpy_array(value: numpy.ndarray, key: str, props: Dict)
|
|
26
|
+
def _serialize_numpy_array(value: numpy.ndarray, key: str, props: Dict):
|
|
19
27
|
"""Convert a numpy array to a JSON-serializable dict, mark complex arrays."""
|
|
20
28
|
if numpy.iscomplexobj(value):
|
|
21
29
|
props[f"{key}__isComplex"] = True
|
|
@@ -23,33 +31,95 @@ try:
|
|
|
23
31
|
return value.tolist()
|
|
24
32
|
|
|
25
33
|
except ImportError:
|
|
26
|
-
|
|
27
|
-
def _serialize_numpy_array(value:
|
|
34
|
+
_NUMPY_AVAILABLE = False
|
|
35
|
+
def _serialize_numpy_array(value: numpy.ndarray, key: str, props: Dict):
|
|
28
36
|
return value
|
|
29
37
|
|
|
38
|
+
def _normalize_field_name(name: str) -> str:
|
|
39
|
+
"""
|
|
40
|
+
Normalize a field name by stripping trailing underscores from Python keywords.
|
|
41
|
+
"""
|
|
42
|
+
if not name.startswith('_') and name.endswith('_') and keyword.iskeyword(name[:-1]):
|
|
43
|
+
return name[:-1]
|
|
44
|
+
return name
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _message_clazz(class_: type["Message"]) -> str:
|
|
48
|
+
clazz_name = class_.__dict__.get('__clazz__')
|
|
49
|
+
if isinstance(clazz_name, str) and clazz_name:
|
|
50
|
+
return clazz_name
|
|
51
|
+
return "org.arl.fjage.Message"
|
|
52
|
+
|
|
53
|
+
def _register_message_class(class_: type["Message"], fqcn: Optional[str] = None) -> type["Message"]:
|
|
54
|
+
if not issubclass(class_, Message):
|
|
55
|
+
raise TypeError('@message can only be used with Message subclasses')
|
|
56
|
+
|
|
57
|
+
# check if something is already registered with the same name or clazz
|
|
58
|
+
if class_.__name__ in _MESSAGE_REGISTRY and _MESSAGE_REGISTRY[class_.__name__] != class_:
|
|
59
|
+
logger.warning(f"Overriding existing message class registered with name '{class_.__name__}': {_MESSAGE_REGISTRY[class_.__name__]} -> {class_}")
|
|
60
|
+
if fqcn:
|
|
61
|
+
if fqcn in _MESSAGE_REGISTRY and _MESSAGE_REGISTRY[fqcn] != class_:
|
|
62
|
+
logger.warning(f"Overriding existing message class registered with clazz '{fqcn}': {_MESSAGE_REGISTRY[fqcn]} -> {class_}")
|
|
63
|
+
if fqcn.split('.')[-1] in _MESSAGE_REGISTRY and _MESSAGE_REGISTRY[fqcn.split('.')[-1]] != class_:
|
|
64
|
+
logger.warning(f"Overriding existing message class registered with name '{fqcn.split('.')[-1]}': {_MESSAGE_REGISTRY[fqcn.split('.')[-1]]} -> {class_}")
|
|
65
|
+
|
|
66
|
+
sys.modules[__name__].__dict__[class_.__name__] = class_
|
|
67
|
+
_MESSAGE_REGISTRY[class_.__name__] = class_
|
|
68
|
+
|
|
69
|
+
clazz_name = fqcn or getattr(class_, '__clazz__', None)
|
|
70
|
+
if isinstance(clazz_name, str) and clazz_name:
|
|
71
|
+
_MESSAGE_REGISTRY[clazz_name] = class_
|
|
72
|
+
_MESSAGE_REGISTRY[clazz_name.split('.')[-1]] = class_
|
|
73
|
+
|
|
74
|
+
return class_
|
|
75
|
+
|
|
76
|
+
def _instantiate_message(class_: type["Message"]) -> "Message":
|
|
77
|
+
try:
|
|
78
|
+
return class_()
|
|
79
|
+
except TypeError:
|
|
80
|
+
instance = class_.__new__(class_)
|
|
81
|
+
if isinstance(instance, Message):
|
|
82
|
+
Message.__init__(instance)
|
|
83
|
+
return instance
|
|
84
|
+
|
|
30
85
|
class Message:
|
|
31
86
|
"""Base class for messages transmitted by one agent to another."""
|
|
87
|
+
msgID: str
|
|
88
|
+
perf: Performative
|
|
89
|
+
sender: Optional[AgentID]
|
|
90
|
+
recipient: Optional[AgentID]
|
|
91
|
+
inReplyTo: Optional[str]
|
|
92
|
+
sentAt: Optional[int]
|
|
93
|
+
__clazz__: str
|
|
32
94
|
|
|
33
95
|
def __init__(self, in_reply_to_msg: Optional["Message"] = None,
|
|
34
96
|
perf: Performative = Performative.INFORM, **kwargs):
|
|
35
|
-
self.__clazz__ =
|
|
97
|
+
self.__clazz__ = _message_clazz(type(self))
|
|
36
98
|
self.msgID = str(UUID7.generate())
|
|
37
99
|
self.perf = perf
|
|
38
100
|
self.sender: Optional[AgentID] = None
|
|
39
101
|
self.recipient: Optional[AgentID] = in_reply_to_msg.sender if in_reply_to_msg else None
|
|
40
102
|
self.inReplyTo: Optional[str] = in_reply_to_msg.msgID if in_reply_to_msg else None
|
|
103
|
+
self.sentAt: Optional[int] = None
|
|
104
|
+
|
|
105
|
+
if self.__clazz__.endswith('Req') and self.perf == Performative.INFORM:
|
|
106
|
+
self.perf = Performative.REQUEST
|
|
41
107
|
|
|
42
108
|
# Set extra kwargs
|
|
43
109
|
for k, v in kwargs.items():
|
|
44
110
|
setattr(self, k, v)
|
|
45
111
|
|
|
46
|
-
def
|
|
112
|
+
def __getattr__(self, name):
|
|
47
113
|
# Deal with attributes that are keywords in Python
|
|
48
114
|
# by allowing them to be accessed with a trailing underscore
|
|
49
115
|
# e.g., msg.from --> msg.from_
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
116
|
+
normalized_name = _normalize_field_name(name)
|
|
117
|
+
if normalized_name != name:
|
|
118
|
+
return getattr(self, normalized_name)
|
|
119
|
+
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
|
|
120
|
+
|
|
121
|
+
def __setattr__(self, name, value):
|
|
122
|
+
object.__setattr__(self, _normalize_field_name(name), value)
|
|
53
123
|
|
|
54
124
|
def to_json(self) -> Dict[str, Any]:
|
|
55
125
|
"""Convert the message to a JSON-serializable dict.
|
|
@@ -60,12 +130,13 @@ class Message:
|
|
|
60
130
|
for key, value in self.__dict__.items():
|
|
61
131
|
if key.startswith("_"):
|
|
62
132
|
continue
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
133
|
+
wire_key = _normalize_field_name(key)
|
|
134
|
+
if hasattr(value, "to_json") and callable(getattr(value, "to_json")):
|
|
135
|
+
props[wire_key] = value.to_json()
|
|
136
|
+
elif _NUMPY_AVAILABLE is True and isinstance(value, numpy.ndarray):
|
|
137
|
+
props[wire_key] = _serialize_numpy_array(value, wire_key, props)
|
|
67
138
|
else:
|
|
68
|
-
props[
|
|
139
|
+
props[wire_key] = value
|
|
69
140
|
return {"clazz": self.__clazz__, "data": props}
|
|
70
141
|
|
|
71
142
|
@classmethod
|
|
@@ -81,32 +152,37 @@ class Message:
|
|
|
81
152
|
qclazz = json_obj["clazz"]
|
|
82
153
|
clazz_name = qclazz.split(".")[-1]
|
|
83
154
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
rv_cls
|
|
155
|
+
rv_cls = _MESSAGE_REGISTRY.get(qclazz) or _MESSAGE_REGISTRY.get(clazz_name)
|
|
156
|
+
|
|
157
|
+
if rv_cls is None:
|
|
158
|
+
module = sys.modules[__name__]
|
|
159
|
+
rv_cls = getattr(module, clazz_name, None)
|
|
87
160
|
|
|
88
161
|
# Else default to base Message class
|
|
89
162
|
if rv_cls is None:
|
|
90
163
|
rv_cls = Message
|
|
91
164
|
|
|
92
|
-
rv = rv_cls
|
|
165
|
+
rv = _instantiate_message(rv_cls)
|
|
93
166
|
rv.__clazz__ = qclazz
|
|
94
167
|
|
|
95
168
|
for key, value in json_obj["data"].items():
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
169
|
+
normalized_key = _normalize_field_name(key)
|
|
170
|
+
if normalized_key in ("sender", "recipient") and isinstance(value, str):
|
|
171
|
+
setattr(rv, normalized_key, AgentID.from_json(value, owner=owner))
|
|
172
|
+
elif get_type_hints(rv_cls).get(normalized_key) == Optional[AgentID] and isinstance(value, str):
|
|
173
|
+
setattr(rv, normalized_key, AgentID.from_json(value, owner=owner))
|
|
174
|
+
elif normalized_key == "perf" and isinstance(value, str):
|
|
175
|
+
setattr(rv, normalized_key, Performative(value))
|
|
176
|
+
elif isinstance(value, list) and f"{key}__isComplex" in json_obj["data"]:
|
|
101
177
|
is_complex = json_obj["data"].get(f"{key}__isComplex", False)
|
|
102
|
-
if is_complex:
|
|
103
|
-
setattr(rv,
|
|
178
|
+
if is_complex and len(value) % 2 == 0:
|
|
179
|
+
setattr(rv, normalized_key, [complex(value[i], value[i + 1]) for i in range(0, len(value), 2)])
|
|
104
180
|
else:
|
|
105
|
-
setattr(rv,
|
|
181
|
+
setattr(rv, normalized_key, value)
|
|
106
182
|
elif key.endswith('__isComplex'):
|
|
107
183
|
continue
|
|
108
184
|
else:
|
|
109
|
-
setattr(rv,
|
|
185
|
+
setattr(rv, normalized_key, value)
|
|
110
186
|
return rv
|
|
111
187
|
|
|
112
188
|
def __str__(self) -> str:
|
|
@@ -144,7 +220,7 @@ class GenericMessage(Message):
|
|
|
144
220
|
self.__clazz__ = "org.arl.fjage.GenericMessage"
|
|
145
221
|
|
|
146
222
|
|
|
147
|
-
def MessageClass(name: str, parent:
|
|
223
|
+
def MessageClass(name: str, parent: type[Message] = Message) -> type[Message]:
|
|
148
224
|
"""Creates an unqualified message class based on a fully qualified name.
|
|
149
225
|
|
|
150
226
|
Args:
|
|
@@ -162,24 +238,42 @@ def MessageClass(name: str, parent: Type[Message] = Message) -> Type[Message]:
|
|
|
162
238
|
self.__clazz__ = name
|
|
163
239
|
if name.endswith('Req'):
|
|
164
240
|
self.perf = Performative.REQUEST
|
|
165
|
-
|
|
166
|
-
if not k.startswith('_') and k.endswith('_'):
|
|
167
|
-
k = k[:-1]
|
|
168
|
-
setattr(self, k, v)
|
|
241
|
+
_update_attributes(self, kwargs)
|
|
169
242
|
|
|
170
243
|
class_ = type(sname, (parent,), {"__init__": __init__})
|
|
171
|
-
|
|
172
|
-
|
|
244
|
+
return _register_message_class(class_, name)
|
|
245
|
+
|
|
246
|
+
@overload
|
|
247
|
+
def message(arg: type[Message]) -> type[Message]: ...
|
|
248
|
+
|
|
249
|
+
@overload
|
|
250
|
+
def message(arg: str) -> Callable[[type[Message]], type[Message]]: ...
|
|
251
|
+
|
|
252
|
+
def message(arg: type[Message] | str) -> Union[type[Message], Callable[..., type[Message]]]:
|
|
253
|
+
"""Decorator to register a Message subclass for JSON inflation.
|
|
254
|
+
|
|
255
|
+
Can be used as ``@message`` or ``@message('org.example.MyMessage')``.
|
|
256
|
+
"""
|
|
173
257
|
|
|
258
|
+
def decorate(class_: type["Message"], fqcn: Optional[str] = None) -> type["Message"]:
|
|
259
|
+
if not issubclass(class_, Message):
|
|
260
|
+
raise TypeError('@message can only be used with Message subclasses')
|
|
174
261
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
262
|
+
clazz_name = fqcn or class_.__dict__.get('__clazz__') or class_.__name__
|
|
263
|
+
class_.__clazz__ = clazz_name
|
|
264
|
+
return _register_message_class(class_, clazz_name)
|
|
178
265
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
266
|
+
if isinstance(arg, type):
|
|
267
|
+
return decorate(arg)
|
|
268
|
+
|
|
269
|
+
def decorator(class_: type["Message"]) -> type["Message"]:
|
|
270
|
+
return decorate(class_, arg)
|
|
271
|
+
|
|
272
|
+
return decorator
|
|
273
|
+
|
|
274
|
+
def _update_attributes(obj: Any, kwargs: Dict[str, Any]) -> None:
|
|
275
|
+
for key, value in kwargs.items():
|
|
276
|
+
setattr(obj, _normalize_field_name(key), value)
|
|
183
277
|
|
|
184
278
|
def _short(p):
|
|
185
279
|
if p is None:
|
|
@@ -204,7 +298,7 @@ def _value(v):
|
|
|
204
298
|
|
|
205
299
|
class _GenericObject:
|
|
206
300
|
def __init__(self, **kwargs):
|
|
207
|
-
self
|
|
301
|
+
_update_attributes(self, kwargs)
|
|
208
302
|
|
|
209
303
|
def __str__(self):
|
|
210
304
|
return self.__dict__['clazz'] + '(...)'
|
|
@@ -212,7 +306,13 @@ class _GenericObject:
|
|
|
212
306
|
def _repr_pretty_(self, p, cycle):
|
|
213
307
|
p.text(str(self) if not cycle else '...')
|
|
214
308
|
|
|
215
|
-
|
|
309
|
+
@message('org.arl.fjage.param.ParameterReq')
|
|
310
|
+
class ParameterReq(Message):
|
|
311
|
+
index: int
|
|
312
|
+
requests: list[dict]
|
|
313
|
+
perf: Performative
|
|
314
|
+
param: Optional[str]
|
|
315
|
+
value: Optional[Any]
|
|
216
316
|
|
|
217
317
|
def __init__(self, index=-1, **kwargs):
|
|
218
318
|
super().__init__()
|
|
@@ -221,7 +321,7 @@ class ParameterReq(_ParameterReq):
|
|
|
221
321
|
self.perf = Performative.REQUEST
|
|
222
322
|
self.param = None
|
|
223
323
|
self.value = None
|
|
224
|
-
self
|
|
324
|
+
_update_attributes(self, kwargs)
|
|
225
325
|
|
|
226
326
|
def get(self, param: str):
|
|
227
327
|
""" Request a parameter by name.
|
|
@@ -262,15 +362,20 @@ class ParameterReq(_ParameterReq):
|
|
|
262
362
|
def _repr_pretty_(self, p, cycle):
|
|
263
363
|
p.text(str(self) if not cycle else '...')
|
|
264
364
|
|
|
265
|
-
|
|
266
|
-
class ParameterRsp(
|
|
365
|
+
@message("org.arl.fjage.param.ParameterRsp")
|
|
366
|
+
class ParameterRsp(Message):
|
|
367
|
+
index: int
|
|
368
|
+
values: Optional[dict]
|
|
369
|
+
perf: Performative
|
|
370
|
+
param: Optional[str]
|
|
371
|
+
value: Optional[Any]
|
|
267
372
|
|
|
268
373
|
def __init__(self, **kwargs):
|
|
269
374
|
super().__init__()
|
|
270
375
|
self.index = -1
|
|
271
376
|
self.values = dict()
|
|
272
377
|
self.perf = Performative.INFORM
|
|
273
|
-
self
|
|
378
|
+
_update_attributes(self, kwargs)
|
|
274
379
|
|
|
275
380
|
def get(self, param:str):# -> Any | AgentID | _GenericObject | dict | Any | None:
|
|
276
381
|
"""Get the value of a parameter by name from the response.
|
|
@@ -297,7 +402,7 @@ class ParameterRsp(_ParameterRsp):
|
|
|
297
402
|
return _value(self.values[v])
|
|
298
403
|
return None
|
|
299
404
|
|
|
300
|
-
def parameters(self) -> dict[str,
|
|
405
|
+
def parameters(self) -> dict[str, Any]:
|
|
301
406
|
"""Get all parameters in the response as a dictionary."""
|
|
302
407
|
if 'values' in self.__dict__ and self.values is not None:
|
|
303
408
|
p = self.values.copy()
|
|
@@ -320,4 +425,65 @@ class ParameterRsp(_ParameterRsp):
|
|
|
320
425
|
return self.__class__.__name__ + ':' + self.perf.value + '[' + (('index:' + str(self.index) + ' ') if self.index >= 0 else '') + p.strip() + ']'
|
|
321
426
|
|
|
322
427
|
def _repr_pretty_(self, p, cycle):
|
|
323
|
-
p.text(str(self) if not cycle else '...')
|
|
428
|
+
p.text(str(self) if not cycle else '...')
|
|
429
|
+
|
|
430
|
+
@message('org.arl.fjage.shell.PutFileReq')
|
|
431
|
+
class PutFileReq(Message):
|
|
432
|
+
filename: Optional[str]
|
|
433
|
+
contents: Optional[list[int]]
|
|
434
|
+
offset: int
|
|
435
|
+
|
|
436
|
+
def __init__(self, filename: Optional[str] = None, contents: Optional[list[int]] = None,
|
|
437
|
+
offset: int = 0, **kwargs):
|
|
438
|
+
super().__init__(perf=Performative.REQUEST)
|
|
439
|
+
self.filename: Optional[str] = filename
|
|
440
|
+
self.contents: Optional[list[int]] = contents
|
|
441
|
+
self.offset: int = offset
|
|
442
|
+
_update_attributes(self, kwargs)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
@message('org.arl.fjage.shell.GetFileReq')
|
|
446
|
+
class GetFileReq(Message):
|
|
447
|
+
filename: Optional[str]
|
|
448
|
+
offset: int
|
|
449
|
+
length: int
|
|
450
|
+
|
|
451
|
+
def __init__(self, filename: Optional[str] = None, offset: int = 0,
|
|
452
|
+
length: int = 0, **kwargs):
|
|
453
|
+
super().__init__(perf=Performative.REQUEST)
|
|
454
|
+
self.filename: Optional[str] = filename
|
|
455
|
+
self.offset: int = offset
|
|
456
|
+
self.length: int = length
|
|
457
|
+
_update_attributes(self, kwargs)
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
@message('org.arl.fjage.shell.ShellExecReq')
|
|
461
|
+
class ShellExecReq(Message):
|
|
462
|
+
command: Optional[str]
|
|
463
|
+
script: Optional[str]
|
|
464
|
+
scriptArgs: Optional[list[str]]
|
|
465
|
+
ans: bool
|
|
466
|
+
|
|
467
|
+
def __init__(self, command: Optional[str] = None, script: Optional[str] = None,
|
|
468
|
+
scriptArgs: Optional[list[str]] = None, ans: bool = False, **kwargs):
|
|
469
|
+
super().__init__(perf=Performative.REQUEST)
|
|
470
|
+
self._command: Optional[str] = None
|
|
471
|
+
self._script: Optional[str] = None
|
|
472
|
+
self.command = command
|
|
473
|
+
self.script = script
|
|
474
|
+
self.scriptArgs: Optional[list[str]] = scriptArgs
|
|
475
|
+
self.ans: bool = ans
|
|
476
|
+
_update_attributes(self, kwargs)
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
@message('org.arl.fjage.shell.GetFileRsp')
|
|
480
|
+
class GetFileRsp(Message):
|
|
481
|
+
|
|
482
|
+
def __init__(self, filename: Optional[str] = None, offset: int = 0,
|
|
483
|
+
contents: Optional[list[int]] = None, directory: bool = False, **kwargs):
|
|
484
|
+
super().__init__(perf=Performative.INFORM)
|
|
485
|
+
self.filename: Optional[str] = filename
|
|
486
|
+
self.offset: int = offset
|
|
487
|
+
self.contents: Optional[list[int]] = contents
|
|
488
|
+
self.directory: bool = directory
|
|
489
|
+
_update_attributes(self, kwargs)
|
|
@@ -2,30 +2,28 @@ import socket
|
|
|
2
2
|
import logging
|
|
3
3
|
import threading
|
|
4
4
|
import time
|
|
5
|
-
from typing import Callable, List, Optional
|
|
5
|
+
from typing import Any, Callable, List, Optional
|
|
6
6
|
|
|
7
7
|
from .Connector import Connector
|
|
8
8
|
|
|
9
9
|
logger = logging.getLogger(__name__)
|
|
10
10
|
logger.addHandler(logging.NullHandler())
|
|
11
11
|
|
|
12
|
+
|
|
13
|
+
|
|
12
14
|
class TCPConnector(Connector):
|
|
13
15
|
"""Simple TCP connector using synchronous sockets."""
|
|
14
16
|
|
|
15
|
-
def __init__(
|
|
16
|
-
self
|
|
17
|
-
host
|
|
18
|
-
port: int,
|
|
19
|
-
reconnect_delay: float = 2.0,
|
|
20
|
-
):
|
|
21
|
-
if not host or not isinstance(host, str):
|
|
17
|
+
def __init__(self, **kwargs: Any ):
|
|
18
|
+
self.host = kwargs.get("host")
|
|
19
|
+
if not self.host or not isinstance(self.host, str) or self.host.strip() == "":
|
|
22
20
|
raise ValueError("host must be a non-empty string")
|
|
23
|
-
|
|
21
|
+
self.port:int = kwargs.get("port", 0)
|
|
22
|
+
if not isinstance(self.port, int) or not (0 < self.port < 65536):
|
|
24
23
|
raise ValueError("port must be an integer 1-65535")
|
|
25
|
-
|
|
26
|
-
self.
|
|
27
|
-
|
|
28
|
-
self.reconnect_delay = reconnect_delay
|
|
24
|
+
self.reconnect_delay:int = kwargs.get("reconnect_delay", -2)
|
|
25
|
+
if not isinstance(self.reconnect_delay, (int, float)) or self.reconnect_delay < -1:
|
|
26
|
+
raise ValueError("reconnect_delay must be a non-negative number or -1 for no reconnect")
|
|
29
27
|
|
|
30
28
|
# Socket and connection state
|
|
31
29
|
self._socket: Optional[socket.socket] = None
|
|
@@ -99,7 +97,10 @@ class TCPConnector(Connector):
|
|
|
99
97
|
self._cleanup_socket()
|
|
100
98
|
raise ConnectionError(f"Failed to send message: {e}")
|
|
101
99
|
|
|
102
|
-
def
|
|
100
|
+
def __details__(self):
|
|
101
|
+
return f"{self.host}:{self.port}"
|
|
102
|
+
|
|
103
|
+
def __repr__(self):
|
|
103
104
|
return f"TCPConnector(host={self.host}, port={self.port}, connected={self.is_connected()})"
|
|
104
105
|
|
|
105
106
|
# Internal methods
|
|
@@ -118,6 +119,9 @@ class TCPConnector(Connector):
|
|
|
118
119
|
buffer = ""
|
|
119
120
|
|
|
120
121
|
try:
|
|
122
|
+
if not self._socket:
|
|
123
|
+
return
|
|
124
|
+
|
|
121
125
|
# Set socket to non-blocking for periodic stop checks
|
|
122
126
|
self._socket.settimeout(0.1)
|
|
123
127
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import logging
|
|
2
2
|
|
|
3
3
|
from .Gateway import Gateway
|
|
4
|
-
from .Message import Message, MessageClass, ParameterReq, ParameterRsp, PutFileReq, GetFileReq, ShellExecReq, GetFileRsp
|
|
4
|
+
from .Message import Message, MessageClass, message, ParameterReq, ParameterRsp, PutFileReq, GetFileReq, ShellExecReq, GetFileRsp
|
|
5
5
|
from .Performative import Performative
|
|
6
6
|
from .AgentID import AgentID
|
|
7
7
|
from .Services import Services
|
|
@@ -18,6 +18,7 @@ __all__ = [
|
|
|
18
18
|
"Gateway",
|
|
19
19
|
"Message",
|
|
20
20
|
"MessageClass",
|
|
21
|
+
"message",
|
|
21
22
|
"Performative",
|
|
22
23
|
"AgentID",
|
|
23
24
|
"Services",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fjagepy
|
|
3
|
-
Version: 2.0
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: fjage Gateway in Python
|
|
5
5
|
Author-email: Chinmay Pendharkar <chinmay@subnero.com>
|
|
6
6
|
License: BSD-3-Clause
|
|
@@ -14,6 +14,7 @@ License-File: LICENSE
|
|
|
14
14
|
Provides-Extra: dev
|
|
15
15
|
Requires-Dist: pytest==8.3.5; extra == "dev"
|
|
16
16
|
Requires-Dist: numpy==2.3.0; extra == "dev"
|
|
17
|
+
Requires-Dist: mypy==1.19.0; extra == "dev"
|
|
17
18
|
Provides-Extra: docs
|
|
18
19
|
Requires-Dist: sphinx==8.2.3; extra == "docs"
|
|
19
20
|
Requires-Dist: sphinx-rtd-theme==3.0.2; extra == "docs"
|
|
@@ -128,6 +129,31 @@ important_msg = gw.receive(my_filter, timeout=1000)
|
|
|
128
129
|
|
|
129
130
|
gw.close()
|
|
130
131
|
```
|
|
132
|
+
|
|
133
|
+
### User-Defined Message Classes
|
|
134
|
+
|
|
135
|
+
Use `@message` to register your own message subclasses so incoming JSON can be inflated back into the right Python type.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
from fjagepy import Message, message
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@message('org.example.CustomReq')
|
|
142
|
+
class CustomReq(Message):
|
|
143
|
+
def __init__(self, text=None):
|
|
144
|
+
super().__init__()
|
|
145
|
+
self.text = text
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
outgoing = CustomReq('hello')
|
|
149
|
+
payload = outgoing.to_json()
|
|
150
|
+
|
|
151
|
+
# Later, when a message with the same clazz arrives from fjage:
|
|
152
|
+
incoming = Message.from_json(payload)
|
|
153
|
+
assert isinstance(incoming, CustomReq)
|
|
154
|
+
assert incoming.text == 'hello'
|
|
155
|
+
```
|
|
156
|
+
|
|
131
157
|
## Advanced Usage
|
|
132
158
|
|
|
133
159
|
### Custom Connectors
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "fjagepy"
|
|
7
|
-
version = "2.0
|
|
7
|
+
version = "2.1.0"
|
|
8
8
|
description = "fjage Gateway in Python"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = {text = "BSD-3-Clause"}
|
|
@@ -23,5 +23,8 @@ testpaths = ["test"]
|
|
|
23
23
|
addopts = "-ra -q"
|
|
24
24
|
|
|
25
25
|
[project.optional-dependencies]
|
|
26
|
-
dev = ["pytest==8.3.5", "numpy==2.3.0", ]
|
|
27
|
-
docs = ["sphinx==8.2.3", "sphinx-rtd-theme==3.0.2", "myst-parser==4.0.1"]
|
|
26
|
+
dev = ["pytest==8.3.5", "numpy==2.3.0", "mypy==1.19.0"]
|
|
27
|
+
docs = ["sphinx==8.2.3", "sphinx-rtd-theme==3.0.2", "myst-parser==4.0.1"]
|
|
28
|
+
|
|
29
|
+
[tool.mypy]
|
|
30
|
+
check_untyped_defs = true
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
|
|
3
|
+
from fjagepy import Message, AgentID, Performative, MessageClass, message
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@message
|
|
7
|
+
class DecoratedMessage(Message):
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@message('org.arl.fjage.test.DecoratedReq')
|
|
12
|
+
class DecoratedReq(Message):
|
|
13
|
+
def __init__(self, value=None):
|
|
14
|
+
super().__init__()
|
|
15
|
+
self.value = value
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@message('org.arl.fjage.test.RequiredArgsMessage')
|
|
19
|
+
class RequiredArgsMessage(Message):
|
|
20
|
+
def __init__(self, token):
|
|
21
|
+
super().__init__()
|
|
22
|
+
self.token = token
|
|
23
|
+
|
|
24
|
+
def test_message_construction():
|
|
25
|
+
"""Message should be constructable."""
|
|
26
|
+
msg = Message()
|
|
27
|
+
assert isinstance(msg, Message)
|
|
28
|
+
|
|
29
|
+
def test_message_unique_id():
|
|
30
|
+
"""Message should have a unique ID."""
|
|
31
|
+
msg1 = Message()
|
|
32
|
+
msg2 = Message()
|
|
33
|
+
assert msg1.msgID != msg2.msgID
|
|
34
|
+
|
|
35
|
+
def test_message_serialization():
|
|
36
|
+
"""Message should serialize and deserialize back identically."""
|
|
37
|
+
msg = Message()
|
|
38
|
+
msg.id = "123"
|
|
39
|
+
msg.clazz = "org.arl.fjage.Message"
|
|
40
|
+
msg.perf = Performative.INFORM
|
|
41
|
+
msg.sender = AgentID("agent1")
|
|
42
|
+
msg.recipient = AgentID("agent2")
|
|
43
|
+
|
|
44
|
+
js = msg.to_json()
|
|
45
|
+
msg2 = Message.from_json(js)
|
|
46
|
+
|
|
47
|
+
assert msg2.id == msg.id
|
|
48
|
+
assert msg2.clazz == msg.clazz
|
|
49
|
+
assert msg2.perf == msg.perf
|
|
50
|
+
assert msg2.sender == msg.sender
|
|
51
|
+
assert msg2.recipient == msg.recipient
|
|
52
|
+
|
|
53
|
+
def test_messageclass_custom_message():
|
|
54
|
+
"""MessageClass should create custom message classes."""
|
|
55
|
+
msgName = 'NewMessage'
|
|
56
|
+
NewMessage = MessageClass(msgName)
|
|
57
|
+
assert callable(NewMessage)
|
|
58
|
+
nm = NewMessage()
|
|
59
|
+
nm.__clazz__ = msgName
|
|
60
|
+
assert isinstance(nm, NewMessage)
|
|
61
|
+
|
|
62
|
+
def test_messageclass_custom_message_with_parent():
|
|
63
|
+
"""MessageClass should create custom message classes with parent."""
|
|
64
|
+
msgName = 'New2Message'
|
|
65
|
+
parentName = 'ParentMessage'
|
|
66
|
+
ParentMessage = MessageClass(parentName)
|
|
67
|
+
NewMessage = MessageClass(msgName, ParentMessage)
|
|
68
|
+
assert callable(NewMessage)
|
|
69
|
+
nm = NewMessage()
|
|
70
|
+
nm.__clazz__ = msgName
|
|
71
|
+
assert isinstance(nm, NewMessage)
|
|
72
|
+
assert isinstance(nm, ParentMessage)
|
|
73
|
+
|
|
74
|
+
def test_messageclass_name_req():
|
|
75
|
+
"""MessageClass should set perf to REQUEST if name ends with Req."""
|
|
76
|
+
msgName = 'NewReq'
|
|
77
|
+
NewReq = MessageClass(msgName)
|
|
78
|
+
nr = NewReq()
|
|
79
|
+
assert nr.perf == Performative.REQUEST
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_message_encode_numpy_array():
|
|
83
|
+
"""Message should encode numpy arrays correctly."""
|
|
84
|
+
import numpy as np
|
|
85
|
+
arr = np.array([1, 2, 3])
|
|
86
|
+
msg = Message()
|
|
87
|
+
msg.data = arr
|
|
88
|
+
js = msg.to_json()
|
|
89
|
+
assert 'data__isComplex' not in js['data']
|
|
90
|
+
assert (js['data']['data'] == [1, 2 ,3])
|
|
91
|
+
|
|
92
|
+
def test_message_encode_complex_array():
|
|
93
|
+
"""Message should encode complex arrays correctly."""
|
|
94
|
+
import numpy as np
|
|
95
|
+
arr = np.array([1+2j, 3+4j, 5+6j])
|
|
96
|
+
msg = Message()
|
|
97
|
+
msg.data = arr
|
|
98
|
+
js = msg.to_json()
|
|
99
|
+
assert 'data__isComplex' in js['data']
|
|
100
|
+
assert js['data']['data__isComplex'] is True
|
|
101
|
+
assert (js['data']['data'] == [1, 2 ,3 ,4 ,5 ,6])
|
|
102
|
+
|
|
103
|
+
def test_message_decode_complex_array():
|
|
104
|
+
"""Message should decode complex arrays correctly."""
|
|
105
|
+
js = {"clazz": "org.arl.fjage.Message", "data": { "signal" : [1,2,3,4,5,6], "signal__isComplex": True }}
|
|
106
|
+
msg = Message.from_json(js)
|
|
107
|
+
assert isinstance(msg.signal, list)
|
|
108
|
+
assert msg.signal == [1+2j, 3+4j, 5+6j]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_message_runtime_assignment_normalizes_keyword_fields():
|
|
112
|
+
"""Message should store Python-safe keyword names using wire names."""
|
|
113
|
+
msg = Message()
|
|
114
|
+
msg.from_ = "alpha"
|
|
115
|
+
|
|
116
|
+
assert msg.from_ == "alpha"
|
|
117
|
+
assert getattr(msg, 'from') == "alpha"
|
|
118
|
+
assert 'from' in msg.__dict__
|
|
119
|
+
assert 'from_' not in msg.__dict__
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def test_message_to_json_serializes_python_safe_keyword_fields():
|
|
123
|
+
"""Message should serialize Python-safe keyword names to canonical wire names."""
|
|
124
|
+
msg = Message(from_="alpha")
|
|
125
|
+
|
|
126
|
+
js = msg.to_json()
|
|
127
|
+
|
|
128
|
+
assert js['data']['from'] == 'alpha'
|
|
129
|
+
assert 'from_' not in js['data']
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def test_message_from_json_normalizes_canonical_keyword_fields():
|
|
133
|
+
"""Message should expose canonical wire keyword names via Python-safe accessors."""
|
|
134
|
+
js = {"clazz": "org.arl.fjage.Message", "data": {"from": "alpha"}}
|
|
135
|
+
|
|
136
|
+
msg = Message.from_json(js)
|
|
137
|
+
|
|
138
|
+
assert msg is not None
|
|
139
|
+
assert msg.from_ == 'alpha'
|
|
140
|
+
assert getattr(msg, 'from') == 'alpha'
|
|
141
|
+
assert 'from' in msg.__dict__
|
|
142
|
+
assert 'from_' not in msg.__dict__
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def test_message_keyword_field_round_trip_uses_wire_name():
|
|
146
|
+
"""Message keyword fields should round-trip through JSON using canonical wire names."""
|
|
147
|
+
outgoing = Message(from_="alpha")
|
|
148
|
+
|
|
149
|
+
incoming = Message.from_json(outgoing.to_json())
|
|
150
|
+
|
|
151
|
+
assert incoming is not None
|
|
152
|
+
assert incoming.from_ == 'alpha'
|
|
153
|
+
assert getattr(incoming, 'from') == 'alpha'
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def test_message_decorator_registers_external_class():
|
|
157
|
+
"""@message should register decorated classes for inflation."""
|
|
158
|
+
js = {"clazz": "DecoratedMessage", "data": {"value": 7}}
|
|
159
|
+
msg = Message.from_json(js)
|
|
160
|
+
assert isinstance(msg, DecoratedMessage)
|
|
161
|
+
assert msg.value == 7
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def test_message_decorator_sets_registered_clazz_and_perf():
|
|
165
|
+
"""@message should apply the registered clazz to new instances."""
|
|
166
|
+
msg = DecoratedReq(value=9)
|
|
167
|
+
assert msg.__clazz__ == 'org.arl.fjage.test.DecoratedReq'
|
|
168
|
+
assert msg.perf == Performative.REQUEST
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def test_message_decorator_preserves_constructor_signature():
|
|
172
|
+
"""@message should not replace the decorated constructor signature."""
|
|
173
|
+
assert str(inspect.signature(DecoratedReq)) == '(value=None)'
|
|
174
|
+
assert str(inspect.signature(RequiredArgsMessage)) == '(token)'
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def test_message_decorator_inflates_without_noarg_constructor():
|
|
178
|
+
"""@message should inflate registered classes even if __init__ needs args."""
|
|
179
|
+
js = {"clazz": "org.arl.fjage.test.RequiredArgsMessage", "data": {"token": "abc"}}
|
|
180
|
+
msg = Message.from_json(js)
|
|
181
|
+
assert isinstance(msg, RequiredArgsMessage)
|
|
182
|
+
assert msg.token == 'abc'
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
from fjagepy import Message, AgentID, Performative, MessageClass
|
|
2
|
-
|
|
3
|
-
def test_message_construction():
|
|
4
|
-
"""Message should be constructable."""
|
|
5
|
-
msg = Message()
|
|
6
|
-
assert isinstance(msg, Message)
|
|
7
|
-
|
|
8
|
-
def test_message_unique_id():
|
|
9
|
-
"""Message should have a unique ID."""
|
|
10
|
-
msg1 = Message()
|
|
11
|
-
msg2 = Message()
|
|
12
|
-
assert msg1.msgID != msg2.msgID
|
|
13
|
-
|
|
14
|
-
def test_message_serialization():
|
|
15
|
-
"""Message should serialize and deserialize back identically."""
|
|
16
|
-
msg = Message()
|
|
17
|
-
msg.id = "123"
|
|
18
|
-
msg.clazz = "org.arl.fjage.Message"
|
|
19
|
-
msg.perf = Performative.INFORM
|
|
20
|
-
msg.sender = AgentID("agent1")
|
|
21
|
-
msg.recipient = AgentID("agent2")
|
|
22
|
-
|
|
23
|
-
js = msg.to_json()
|
|
24
|
-
msg2 = Message.from_json(js)
|
|
25
|
-
|
|
26
|
-
assert msg2.id == msg.id
|
|
27
|
-
assert msg2.clazz == msg.clazz
|
|
28
|
-
assert msg2.perf == msg.perf
|
|
29
|
-
assert msg2.sender == msg.sender
|
|
30
|
-
assert msg2.recipient == msg.recipient
|
|
31
|
-
|
|
32
|
-
def test_messageclass_custom_message():
|
|
33
|
-
"""MessageClass should create custom message classes."""
|
|
34
|
-
msgName = 'NewMessage'
|
|
35
|
-
NewMessage = MessageClass(msgName)
|
|
36
|
-
assert callable(NewMessage)
|
|
37
|
-
nm = NewMessage()
|
|
38
|
-
nm.__clazz__ = msgName
|
|
39
|
-
assert isinstance(nm, NewMessage)
|
|
40
|
-
|
|
41
|
-
def test_messageclass_custom_message_with_parent():
|
|
42
|
-
"""MessageClass should create custom message classes with parent."""
|
|
43
|
-
msgName = 'New2Message'
|
|
44
|
-
parentName = 'ParentMessage'
|
|
45
|
-
ParentMessage = MessageClass(parentName)
|
|
46
|
-
NewMessage = MessageClass(msgName, ParentMessage)
|
|
47
|
-
assert callable(NewMessage)
|
|
48
|
-
nm = NewMessage()
|
|
49
|
-
nm.__clazz__ = msgName
|
|
50
|
-
assert isinstance(nm, NewMessage)
|
|
51
|
-
assert isinstance(nm, ParentMessage)
|
|
52
|
-
|
|
53
|
-
def test_messageclass_name_req():
|
|
54
|
-
"""MessageClass should set perf to REQUEST if name ends with Req."""
|
|
55
|
-
msgName = 'NewReq'
|
|
56
|
-
NewReq = MessageClass(msgName)
|
|
57
|
-
nr = NewReq()
|
|
58
|
-
assert nr.perf == Performative.REQUEST
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
def test_message_encode_numpy_array():
|
|
62
|
-
"""Message should encode numpy arrays correctly."""
|
|
63
|
-
import numpy as np
|
|
64
|
-
arr = np.array([1, 2, 3])
|
|
65
|
-
msg = Message()
|
|
66
|
-
msg.data = arr
|
|
67
|
-
js = msg.to_json()
|
|
68
|
-
assert 'data__isComplex' not in js['data']
|
|
69
|
-
assert (js['data']['data'] == [1, 2 ,3])
|
|
70
|
-
|
|
71
|
-
def test_message_encode_complex_array():
|
|
72
|
-
"""Message should encode complex arrays correctly."""
|
|
73
|
-
import numpy as np
|
|
74
|
-
arr = np.array([1+2j, 3+4j, 5+6j])
|
|
75
|
-
msg = Message()
|
|
76
|
-
msg.data = arr
|
|
77
|
-
js = msg.to_json()
|
|
78
|
-
assert 'data__isComplex' in js['data']
|
|
79
|
-
assert js['data']['data__isComplex'] is True
|
|
80
|
-
assert (js['data']['data'] == [1, 2 ,3 ,4 ,5 ,6])
|
|
81
|
-
|
|
82
|
-
def test_message_decode_complex_array():
|
|
83
|
-
"""Message should decode complex arrays correctly."""
|
|
84
|
-
js = {"clazz": "org.arl.fjage.Message", "data": { "signal" : [1,2,3,4,5,6], "signal__isComplex": True }}
|
|
85
|
-
msg = Message.from_json(js)
|
|
86
|
-
assert isinstance(msg.signal, list)
|
|
87
|
-
assert msg.signal == [1+2j, 3+4j, 5+6j]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|