nasdaq-protocols 0.0.1a1__py3-none-any.whl
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.
- nasdaq_protocols/__init__.py +0 -0
- nasdaq_protocols/common/__init__.py +5 -0
- nasdaq_protocols/common/message/__init__.py +4 -0
- nasdaq_protocols/common/message/codegen.py +70 -0
- nasdaq_protocols/common/message/parser.py +232 -0
- nasdaq_protocols/common/message/structures.py +287 -0
- nasdaq_protocols/common/message/templates/__init__.py +0 -0
- nasdaq_protocols/common/message/templates/enum.mustache +9 -0
- nasdaq_protocols/common/message/templates/init.mustache +3 -0
- nasdaq_protocols/common/message/templates/message_ouch_itch.mustache +77 -0
- nasdaq_protocols/common/message/templates/record.mustache +15 -0
- nasdaq_protocols/common/message/types.py +236 -0
- nasdaq_protocols/common/message_queue.py +155 -0
- nasdaq_protocols/common/session.py +296 -0
- nasdaq_protocols/common/types.py +83 -0
- nasdaq_protocols/common/utils.py +86 -0
- nasdaq_protocols/fix/__init__.py +3 -0
- nasdaq_protocols/fix/_reader.py +63 -0
- nasdaq_protocols/fix/core.py +486 -0
- nasdaq_protocols/fix/types.py +165 -0
- nasdaq_protocols/itch/__init__.py +43 -0
- nasdaq_protocols/itch/codegen.py +29 -0
- nasdaq_protocols/itch/core.py +38 -0
- nasdaq_protocols/itch/session.py +87 -0
- nasdaq_protocols/ouch/__init__.py +43 -0
- nasdaq_protocols/ouch/codegen.py +29 -0
- nasdaq_protocols/ouch/core.py +47 -0
- nasdaq_protocols/ouch/session.py +90 -0
- nasdaq_protocols/soup/__init__.py +79 -0
- nasdaq_protocols/soup/_reader.py +50 -0
- nasdaq_protocols/soup/core.py +344 -0
- nasdaq_protocols/soup/session.py +279 -0
- nasdaq_protocols/tools/__init__.py +0 -0
- nasdaq_protocols/tools/new_project.py +141 -0
- nasdaq_protocols/tools/templates/__init__.py +0 -0
- nasdaq_protocols/tools/templates/ouch_itch_xml.mustache +82 -0
- nasdaq_protocols/tools/templates/toml.mustache +53 -0
- nasdaq_protocols/tools/templates/tox.mustache +21 -0
- nasdaq_protocols-0.0.1a1.dist-info/METADATA +34 -0
- nasdaq_protocols-0.0.1a1.dist-info/RECORD +43 -0
- nasdaq_protocols-0.0.1a1.dist-info/WHEEL +5 -0
- nasdaq_protocols-0.0.1a1.dist-info/entry_points.txt +4 -0
- nasdaq_protocols-0.0.1a1.dist-info/top_level.txt +1 -0
|
File without changes
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from importlib import resources
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import attrs
|
|
6
|
+
import chevron
|
|
7
|
+
from .parser import Definitions
|
|
8
|
+
from . import templates
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
'Generator'
|
|
13
|
+
]
|
|
14
|
+
TEMPLATES_PATH = resources.files(templates)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@attrs.define(auto_attribs=True)
|
|
18
|
+
class Generator:
|
|
19
|
+
definitions: Definitions
|
|
20
|
+
impl: str
|
|
21
|
+
app_name: str
|
|
22
|
+
op_dir: str
|
|
23
|
+
template: str
|
|
24
|
+
prefix: str = ''
|
|
25
|
+
generate_init_file: bool = False
|
|
26
|
+
_op_file: str = None
|
|
27
|
+
_module_name: str = None
|
|
28
|
+
_init_file: str = None
|
|
29
|
+
|
|
30
|
+
def __attrs_post_init__(self):
|
|
31
|
+
prefix = f'{self.prefix}_' if self.prefix else ''
|
|
32
|
+
self._module_name = f'{prefix}{self.impl}_{self.app_name}'
|
|
33
|
+
self._op_file = os.path.join(self.op_dir, f'{self._module_name}.py')
|
|
34
|
+
self._init_file = os.path.join(self.op_dir, '__init__.py')
|
|
35
|
+
self.template = self.template if self.template.endswith('.mustache') else f'{self.template}.mustache'
|
|
36
|
+
self.template = os.path.join(str(TEMPLATES_PATH), self.template)
|
|
37
|
+
Path(self.op_dir).mkdir(parents=True, exist_ok=True)
|
|
38
|
+
|
|
39
|
+
def generate(self, extra_context=None):
|
|
40
|
+
generated_files = []
|
|
41
|
+
context = self.definitions.get_codegen_context()
|
|
42
|
+
context.update(
|
|
43
|
+
{
|
|
44
|
+
'impl': self.impl,
|
|
45
|
+
'app_name': self.app_name,
|
|
46
|
+
}
|
|
47
|
+
)
|
|
48
|
+
context.update(extra_context or {})
|
|
49
|
+
|
|
50
|
+
Generator._generate(self.template, context, self._op_file)
|
|
51
|
+
generated_files.append(self._op_file)
|
|
52
|
+
|
|
53
|
+
if self.generate_init_file:
|
|
54
|
+
context = {
|
|
55
|
+
'modules': [
|
|
56
|
+
{'name': self._module_name}
|
|
57
|
+
]
|
|
58
|
+
}
|
|
59
|
+
init_template = os.path.join(str(TEMPLATES_PATH), 'init.mustache')
|
|
60
|
+
Generator._generate(init_template, context, self._init_file)
|
|
61
|
+
generated_files.append(self._init_file)
|
|
62
|
+
|
|
63
|
+
return generated_files
|
|
64
|
+
|
|
65
|
+
@staticmethod
|
|
66
|
+
def _generate(template, context, op_file):
|
|
67
|
+
with open(op_file, 'a', encoding='utf-8') as op, open(template, 'r', encoding='utf-8') as inp:
|
|
68
|
+
code_as_string = chevron.render(inp.read(), context, partials_path=str(TEMPLATES_PATH))
|
|
69
|
+
op.write(code_as_string)
|
|
70
|
+
print(f'Generated: {op_file}')
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
from xml.etree import ElementTree
|
|
3
|
+
|
|
4
|
+
import attrs
|
|
5
|
+
from .types import TypeDefinition
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
'EnumVal',
|
|
10
|
+
'EnumDef',
|
|
11
|
+
'FieldDef',
|
|
12
|
+
'RecordDef',
|
|
13
|
+
'MessageDef',
|
|
14
|
+
'Definitions',
|
|
15
|
+
'Parser'
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@attrs.define(auto_attribs=True)
|
|
20
|
+
class EnumVal:
|
|
21
|
+
name: str
|
|
22
|
+
description: str
|
|
23
|
+
value: str
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@attrs.define(auto_attribs=True)
|
|
27
|
+
class EnumDef:
|
|
28
|
+
name: str = ''
|
|
29
|
+
type: str = None
|
|
30
|
+
values: list[EnumVal] = attrs.field(factory=list)
|
|
31
|
+
|
|
32
|
+
def get_codegen_context(self, _definitions: 'Definitions'):
|
|
33
|
+
return {
|
|
34
|
+
'name': self.name,
|
|
35
|
+
'quote': TypeDefinition.Definitions[self.type].hint == 'str',
|
|
36
|
+
'values': [
|
|
37
|
+
{
|
|
38
|
+
'name': field.name,
|
|
39
|
+
'value': field.value
|
|
40
|
+
} for field in self.values
|
|
41
|
+
]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@attrs.define(auto_attribs=True)
|
|
46
|
+
class FieldDef:
|
|
47
|
+
Definitions = {}
|
|
48
|
+
name: str
|
|
49
|
+
type: str = None
|
|
50
|
+
ref: str = None
|
|
51
|
+
array: str = None
|
|
52
|
+
length: int = None
|
|
53
|
+
default: str = None
|
|
54
|
+
endian: str = None
|
|
55
|
+
|
|
56
|
+
def get_codegen_context(self, definitions: 'Definitions'):
|
|
57
|
+
field_context = self._field_context(definitions)
|
|
58
|
+
field_context.update({'name': self.name})
|
|
59
|
+
return field_context
|
|
60
|
+
|
|
61
|
+
def _field_context(self, definitions: 'Definitions'):
|
|
62
|
+
context = {
|
|
63
|
+
'type': '',
|
|
64
|
+
'default': False,
|
|
65
|
+
'default_value': '',
|
|
66
|
+
'quote': False,
|
|
67
|
+
'hint': ''
|
|
68
|
+
}
|
|
69
|
+
types_ = [self.type, self.ref]
|
|
70
|
+
if all(_ is None for _ in types_) or all(_ is not None for _ in types_):
|
|
71
|
+
raise ValueError(f'{self.name=}, invalid type and ref value')
|
|
72
|
+
|
|
73
|
+
if self.ref:
|
|
74
|
+
type_, hint = self.ref, self.ref
|
|
75
|
+
elif self.type.startswith('enum:'):
|
|
76
|
+
enum_name = self.type.replace('enum:', '')
|
|
77
|
+
if enum_name not in definitions.enums:
|
|
78
|
+
raise ValueError(f'{enum_name=} not found in definitions')
|
|
79
|
+
enum_def = definitions.enums[enum_name]
|
|
80
|
+
enum_type = TypeDefinition.Definitions[enum_def.type]
|
|
81
|
+
type_, hint = enum_type.__name__, enum_name
|
|
82
|
+
elif self.type.startswith('record:'):
|
|
83
|
+
rec = self.type.replace('record:', '')
|
|
84
|
+
if rec not in definitions.records:
|
|
85
|
+
raise ValueError(f'{rec=} not found in definitions')
|
|
86
|
+
rec = definitions.records[rec]
|
|
87
|
+
type_, hint = rec.name, rec.name
|
|
88
|
+
else:
|
|
89
|
+
type_ = TypeDefinition.Definitions[self.type].__name__
|
|
90
|
+
hint = TypeDefinition.Definitions[self.type].hint
|
|
91
|
+
|
|
92
|
+
endian = 'uint_2_be' if self.endian == 'big' else 'uint_2'
|
|
93
|
+
endian = TypeDefinition.Definitions[endian].__name__
|
|
94
|
+
|
|
95
|
+
if self.array is not None:
|
|
96
|
+
type_ = f'Array({type_}, {endian})'
|
|
97
|
+
hint = f'list[{hint}]'
|
|
98
|
+
if self.array == 'double':
|
|
99
|
+
type_ = f'Array({type_}, {endian})'
|
|
100
|
+
hint = f'list[{hint}]'
|
|
101
|
+
|
|
102
|
+
is_fixed_len_str = self.type in ['str_ascii_n', 'str_iso-8859-1_n']
|
|
103
|
+
type_ = f'{type_}(length={self.length})' if is_fixed_len_str else type_
|
|
104
|
+
|
|
105
|
+
context['type'] = type_
|
|
106
|
+
context['hint'] = hint
|
|
107
|
+
context['quote'] = 'Char' in type_ or 'String' in type_
|
|
108
|
+
context['default'] = self.default is not None
|
|
109
|
+
context['default_value'] = self.default
|
|
110
|
+
|
|
111
|
+
return context
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@attrs.define(auto_attribs=True)
|
|
115
|
+
class RecordDef:
|
|
116
|
+
name: str
|
|
117
|
+
fields: list[FieldDef]
|
|
118
|
+
|
|
119
|
+
def get_codegen_context(self, definitions: 'Definitions'):
|
|
120
|
+
return {
|
|
121
|
+
'name': self.name,
|
|
122
|
+
'fields': [field.get_codegen_context(definitions) for field in self.fields]
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@attrs.define(auto_attribs=True)
|
|
127
|
+
class MessageDef:
|
|
128
|
+
name: str
|
|
129
|
+
id: str = attrs.field(converter=lambda x: x if x.isdigit() else str(ord(x))) # pylint: disable=C0103
|
|
130
|
+
group: str = None
|
|
131
|
+
fields: list[FieldDef] = []
|
|
132
|
+
direction: str = None
|
|
133
|
+
|
|
134
|
+
def get_codegen_context(self, definitions: 'Definitions'):
|
|
135
|
+
return {
|
|
136
|
+
'name': self.name,
|
|
137
|
+
'indicator': self.id,
|
|
138
|
+
'group': self.group,
|
|
139
|
+
'fields': [field.get_codegen_context(definitions) for field in self.fields],
|
|
140
|
+
'direction': self.direction
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@attrs.define(auto_attribs=True)
|
|
145
|
+
class Definitions:
|
|
146
|
+
enums: dict[str, EnumDef] = {}
|
|
147
|
+
records: dict[str, RecordDef] = {}
|
|
148
|
+
messages: list[MessageDef] = []
|
|
149
|
+
|
|
150
|
+
def get_codegen_context(self):
|
|
151
|
+
return {
|
|
152
|
+
'enums': [enum.get_codegen_context(self) for enum in self.enums.values()],
|
|
153
|
+
'messages': [message.get_codegen_context(self) for message in self.messages],
|
|
154
|
+
'records': [record.get_codegen_context(self) for record in self.records.values()],
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class Parser:
|
|
159
|
+
@staticmethod
|
|
160
|
+
def parse(file: str) -> Definitions:
|
|
161
|
+
root = ElementTree.parse(file).getroot()
|
|
162
|
+
elements = list(root)
|
|
163
|
+
definitions = Definitions()
|
|
164
|
+
|
|
165
|
+
for element in elements:
|
|
166
|
+
if element.tag == 'enums-root':
|
|
167
|
+
definitions.enums = {_.name: _ for _ in Parser._parse_enums(element)}
|
|
168
|
+
elif element.tag == 'fielddef-root':
|
|
169
|
+
FieldDef.Definitions = Parser._parse_fielddefs(element)
|
|
170
|
+
elif element.tag == 'records-root':
|
|
171
|
+
definitions.records = {_.name: _ for _ in Parser._parse_records(element)}
|
|
172
|
+
elif element.tag == 'messages-root':
|
|
173
|
+
definitions.messages = Parser._parse_messages(element)
|
|
174
|
+
|
|
175
|
+
return definitions
|
|
176
|
+
|
|
177
|
+
@staticmethod
|
|
178
|
+
def _parse_fielddefs(element) -> dict[str, FieldDef]:
|
|
179
|
+
return {f.name: f for f in Parser._parse_fields(element)}
|
|
180
|
+
|
|
181
|
+
@staticmethod
|
|
182
|
+
def _parse_records(element) -> list[RecordDef]:
|
|
183
|
+
return [RecordDef(record.get('id'), Parser._parse_fields(record[0])) for record in list(element)]
|
|
184
|
+
|
|
185
|
+
@staticmethod
|
|
186
|
+
def _parse_messages(element) -> list[MessageDef]:
|
|
187
|
+
def create_msg(child):
|
|
188
|
+
return MessageDef(
|
|
189
|
+
child.get('id'), child.get('message-id'), child.get('message-group'),
|
|
190
|
+
Parser._parse_fields(child[0] if len(child) else None),
|
|
191
|
+
child.get('direction')
|
|
192
|
+
)
|
|
193
|
+
return [create_msg(child) for child in list(element) if child is not None]
|
|
194
|
+
|
|
195
|
+
@staticmethod
|
|
196
|
+
def _parse_fields(element) -> list[FieldDef]:
|
|
197
|
+
if element:
|
|
198
|
+
return [Parser._parse_field(field) for field in list(element) if field is not None]
|
|
199
|
+
return []
|
|
200
|
+
|
|
201
|
+
@staticmethod
|
|
202
|
+
def _parse_field(element):
|
|
203
|
+
f_def = None
|
|
204
|
+
if element is not None:
|
|
205
|
+
if element.get('def', False):
|
|
206
|
+
field = copy.deepcopy(FieldDef.Definitions[element.get('def')])
|
|
207
|
+
field.name = element.get('name', field.name)
|
|
208
|
+
return field
|
|
209
|
+
|
|
210
|
+
f_def = FieldDef(
|
|
211
|
+
element.get('name'),
|
|
212
|
+
element.get('type'),
|
|
213
|
+
element.get('ref'),
|
|
214
|
+
element.get('array'),
|
|
215
|
+
element.get('length'),
|
|
216
|
+
element.get('default'),
|
|
217
|
+
element.get('endian')
|
|
218
|
+
)
|
|
219
|
+
return f_def
|
|
220
|
+
|
|
221
|
+
@staticmethod
|
|
222
|
+
def _parse_enums(element):
|
|
223
|
+
if element:
|
|
224
|
+
return [Parser._parse_enum(e) for e in list(element) if e is not None]
|
|
225
|
+
return []
|
|
226
|
+
|
|
227
|
+
@staticmethod
|
|
228
|
+
def _parse_enum(element):
|
|
229
|
+
def _parse_value(val_element):
|
|
230
|
+
return EnumVal(val_element.get('name'), val_element.get('description'), val_element.text)
|
|
231
|
+
|
|
232
|
+
return EnumDef(element.get('id'), element.get('type'), [_parse_value(_) for _ in element if _ is not None])
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This module contains the structures used to represent the messages in the protocol.
|
|
3
|
+
"""
|
|
4
|
+
import inspect
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from itertools import chain
|
|
7
|
+
from collections import OrderedDict, defaultdict
|
|
8
|
+
from typing import Any, Type, ClassVar, Callable
|
|
9
|
+
import attrs
|
|
10
|
+
|
|
11
|
+
from nasdaq_protocols.common.utils import logable
|
|
12
|
+
from nasdaq_protocols.common.types import Serializable
|
|
13
|
+
from .types import TypeDefinition, Short, Boolean
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
'DuplicateMessageException',
|
|
18
|
+
'Field',
|
|
19
|
+
'Record',
|
|
20
|
+
'RecordWithPresentBit',
|
|
21
|
+
'Array',
|
|
22
|
+
'CommonMessage'
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@attrs.define(auto_exc=True)
|
|
27
|
+
class DuplicateMessageException(Exception):
|
|
28
|
+
"""
|
|
29
|
+
Exception raised when a message is already defined in the app.
|
|
30
|
+
|
|
31
|
+
:param existing_msg: Already registered message with the same id.
|
|
32
|
+
:param new_msg: New message that is being registered.
|
|
33
|
+
"""
|
|
34
|
+
existing_msg: Any
|
|
35
|
+
new_msg: Any
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@attrs.define(auto_attribs=True)
|
|
39
|
+
class Field:
|
|
40
|
+
"""
|
|
41
|
+
Represents a field in a record or message.
|
|
42
|
+
|
|
43
|
+
:param name: Name of the field.
|
|
44
|
+
|
|
45
|
+
"""
|
|
46
|
+
name: str
|
|
47
|
+
type: Type[TypeDefinition] | TypeDefinition
|
|
48
|
+
default_value: Any = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@attrs.define(eq=False, hash=False)
|
|
52
|
+
class _Record(TypeDefinition):
|
|
53
|
+
Fields: ClassVar[list[Field]]
|
|
54
|
+
IndexedFields: ClassVar[dict[str, Field]]
|
|
55
|
+
default_value: ClassVar[Any] = None
|
|
56
|
+
|
|
57
|
+
values = attrs.field(type=dict[str, Any], default=attrs.Factory(lambda self: self.init_values(), takes_self=True))
|
|
58
|
+
|
|
59
|
+
def __init_subclass__(cls):
|
|
60
|
+
try:
|
|
61
|
+
cls.IndexedFields = OrderedDict((f.name, f) for f in cls.Fields)
|
|
62
|
+
cls.type_cls = cls
|
|
63
|
+
cls.hint = cls.__name__
|
|
64
|
+
cls.log.debug('Subclassed %s', cls.__name__)
|
|
65
|
+
except AttributeError:
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
def init_values(self):
|
|
69
|
+
# if any field is a record, flatten it.
|
|
70
|
+
# Does not support nested records.
|
|
71
|
+
return {_.name: _.type() for _ in self.Fields if inspect.isclass(_.type) and issubclass(_.type, _Record)}
|
|
72
|
+
|
|
73
|
+
def __attrs_post_init__(self):
|
|
74
|
+
for field in self.Fields:
|
|
75
|
+
try:
|
|
76
|
+
if issubclass(field.type, _Record) and field.name not in self.values:
|
|
77
|
+
self.values[field.name] = field.type()
|
|
78
|
+
except TypeError:
|
|
79
|
+
pass
|
|
80
|
+
|
|
81
|
+
@staticmethod
|
|
82
|
+
def is_record(type_):
|
|
83
|
+
return inspect.isclass(type_) and issubclass(type_, _Record)
|
|
84
|
+
|
|
85
|
+
@classmethod
|
|
86
|
+
def to_str(cls, record: Type['_Record']):
|
|
87
|
+
return str(record)
|
|
88
|
+
|
|
89
|
+
def __str__(self):
|
|
90
|
+
return f"{{'{self.__class__.__name__}':{{{self.values}}}}}"
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def from_str(cls, _str):
|
|
94
|
+
raise NotImplementedError('this method is not available')
|
|
95
|
+
|
|
96
|
+
def __getattr__(self, item: str):
|
|
97
|
+
try:
|
|
98
|
+
return self.get_field_value(item)
|
|
99
|
+
except KeyError:
|
|
100
|
+
return self.__dict__[item]
|
|
101
|
+
|
|
102
|
+
def __setattr__(self, key, value):
|
|
103
|
+
try:
|
|
104
|
+
field = self.IndexedFields[key]
|
|
105
|
+
if isinstance(value, Enum):
|
|
106
|
+
value = value.value
|
|
107
|
+
if not isinstance(value, field.type.type_cls):
|
|
108
|
+
raise ValueError(f'type mismatch, {self.__class__.__name__}:{field.name},'
|
|
109
|
+
f' expected type {field.type.hint}, received {type(value)}')
|
|
110
|
+
self.values[key] = value
|
|
111
|
+
except KeyError:
|
|
112
|
+
self.__dict__[key] = value
|
|
113
|
+
|
|
114
|
+
def get_field_value(self, key: str) -> Any:
|
|
115
|
+
field = self.IndexedFields[key]
|
|
116
|
+
try:
|
|
117
|
+
return self.values[key]
|
|
118
|
+
except KeyError:
|
|
119
|
+
return field.type.default_value if field.default_value is None else field.default_value
|
|
120
|
+
|
|
121
|
+
@staticmethod
|
|
122
|
+
def get_value(any_: Any) -> dict[str, Any] | list[dict[str, Any]] | Any:
|
|
123
|
+
if isinstance(any_, _Record):
|
|
124
|
+
return {any_.__class__.__name__: _Record.get_value(any_.values)}
|
|
125
|
+
if isinstance(any_, list):
|
|
126
|
+
return [_Record.get_value(_) for _ in any_]
|
|
127
|
+
if isinstance(any_, dict):
|
|
128
|
+
return {k: _Record.get_value(v) for k, v in any_.items()}
|
|
129
|
+
return any_
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@attrs.define
|
|
133
|
+
class Record(_Record):
|
|
134
|
+
"""
|
|
135
|
+
Represents a record in the message.
|
|
136
|
+
"""
|
|
137
|
+
@classmethod
|
|
138
|
+
def from_bytes(cls, bytes_: bytes) -> tuple[int, Any]:
|
|
139
|
+
offset = 0
|
|
140
|
+
values = {}
|
|
141
|
+
for field in cls.Fields:
|
|
142
|
+
offset1, value = field.type.from_bytes(bytes_[offset:])
|
|
143
|
+
offset += offset1
|
|
144
|
+
values[field.name] = value
|
|
145
|
+
return offset, cls(values)
|
|
146
|
+
|
|
147
|
+
@classmethod
|
|
148
|
+
def to_bytes(cls, record: 'Record') -> tuple[int, bytes]:
|
|
149
|
+
segments = list(zip(*(f.type.to_bytes(record.get_field_value(f.name)) for f in cls.Fields)))
|
|
150
|
+
return sum(segments[0]), b''.join(segments[1])
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@attrs.define
|
|
154
|
+
class RecordWithPresentBit(Record):
|
|
155
|
+
"""
|
|
156
|
+
Represents a record with a present bit in the message.
|
|
157
|
+
"""
|
|
158
|
+
@classmethod
|
|
159
|
+
def from_bytes(cls, bytes_: bytes) -> tuple[int, Any]:
|
|
160
|
+
offset, present = Boolean.from_bytes(bytes_)
|
|
161
|
+
if not present:
|
|
162
|
+
return 1, None
|
|
163
|
+
offset1, value = super(RecordWithPresentBit, cls).from_bytes(bytes_[offset:])
|
|
164
|
+
return offset+offset1, value
|
|
165
|
+
|
|
166
|
+
@classmethod
|
|
167
|
+
def to_bytes(cls, record: 'Record') -> tuple[int, bytes]:
|
|
168
|
+
if record is None or len(record.values) == 0:
|
|
169
|
+
return Boolean.to_bytes(False)
|
|
170
|
+
offset, bytes_ = Boolean.to_bytes(True)
|
|
171
|
+
offset1, bytes1_ = super(RecordWithPresentBit, cls).to_bytes(record)
|
|
172
|
+
return offset+offset1, bytes_+bytes1_
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@attrs.define
|
|
176
|
+
class Array(TypeDefinition):
|
|
177
|
+
default_value: ClassVar[list[Any]] = []
|
|
178
|
+
type_cls: ClassVar = list
|
|
179
|
+
hint: ClassVar[str] = 'list'
|
|
180
|
+
|
|
181
|
+
type = attrs.field(type=TypeDefinition)
|
|
182
|
+
length_type = attrs.field(default=Short)
|
|
183
|
+
packer = attrs.field(init=False, type=Callable[[Type[TypeDefinition]], tuple[int, bytes]])
|
|
184
|
+
unpacker = attrs.field(init=False, type=Callable[[bytes], tuple[int, Any]])
|
|
185
|
+
|
|
186
|
+
def __attrs_post_init__(self):
|
|
187
|
+
if issubclass(self.type, RecordWithPresentBit):
|
|
188
|
+
record_cls = super(RecordWithPresentBit, self.type)
|
|
189
|
+
self.packer, self.unpacker = record_cls.to_bytes, record_cls.from_bytes
|
|
190
|
+
else:
|
|
191
|
+
self.packer, self.unpacker = self.type.to_bytes, self.type.from_bytes
|
|
192
|
+
|
|
193
|
+
@classmethod
|
|
194
|
+
def to_str(cls, _any: Any):
|
|
195
|
+
raise NotImplementedError('this method is not available for array types')
|
|
196
|
+
|
|
197
|
+
@classmethod
|
|
198
|
+
def from_str(cls, _str: str):
|
|
199
|
+
raise NotImplementedError('this method is not available for array types')
|
|
200
|
+
|
|
201
|
+
def to_bytes(self, list_: list[Any]) -> tuple[int, bytes]:
|
|
202
|
+
items = (self.packer(_) for _ in list_)
|
|
203
|
+
segments = list(zip(*chain([self.length_type.to_bytes(len(list_))], items)))
|
|
204
|
+
return sum(segments[0]), b''.join(segments[1])
|
|
205
|
+
|
|
206
|
+
def from_bytes(self, bytes_: bytes) -> tuple[int, Any]:
|
|
207
|
+
offset, len_ = self.length_type.from_bytes(bytes_)
|
|
208
|
+
data = []
|
|
209
|
+
for _ in range(len_):
|
|
210
|
+
offset1, value = self.unpacker(bytes_[offset:])
|
|
211
|
+
offset += offset1
|
|
212
|
+
data.append(value)
|
|
213
|
+
return offset, data
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@attrs.define
|
|
217
|
+
@logable
|
|
218
|
+
class CommonMessage(Serializable):
|
|
219
|
+
MsgIdToClsMap: ClassVar[dict] = defaultdict(dict)
|
|
220
|
+
MsgNameToMsgMap: ClassVar[dict] = defaultdict(dict)
|
|
221
|
+
MsgId: ClassVar[Serializable] = None
|
|
222
|
+
MsgIdClass: ClassVar[Serializable] = None
|
|
223
|
+
BodyRecord: ClassVar[Type[Record]] = None
|
|
224
|
+
AppName: ClassVar[str] = None
|
|
225
|
+
|
|
226
|
+
record = attrs.field(default=None)
|
|
227
|
+
|
|
228
|
+
def __init_subclass__(cls, **kwargs):
|
|
229
|
+
cls.log.debug('CommonMessage: subclassing %s, params = %s', cls.__name__, str(kwargs))
|
|
230
|
+
cls.MsgIdClass = kwargs.get('msg_id_cls', cls.MsgIdClass)
|
|
231
|
+
cls.AppName = kwargs.get('app_name', cls.AppName)
|
|
232
|
+
cls.MsgId = kwargs.get('msg_id', cls.MsgId)
|
|
233
|
+
|
|
234
|
+
if all(_ in kwargs for _ in ['app_name', 'msg_id_cls', 'msg_id']):
|
|
235
|
+
if cls.MsgId in CommonMessage.MsgIdToClsMap[cls.AppName]:
|
|
236
|
+
raise DuplicateMessageException(
|
|
237
|
+
existing_msg=CommonMessage.MsgIdToClsMap[cls.AppName][cls.MsgId],
|
|
238
|
+
new_msg=cls
|
|
239
|
+
)
|
|
240
|
+
CommonMessage.MsgIdToClsMap[cls.AppName][cls.MsgId] = cls
|
|
241
|
+
CommonMessage.MsgNameToMsgMap[cls.AppName][cls.__name__] = cls
|
|
242
|
+
|
|
243
|
+
def __attrs_post_init__(self):
|
|
244
|
+
if self.record is None:
|
|
245
|
+
self.record = self.BodyRecord() # pylint: disable=E1102
|
|
246
|
+
|
|
247
|
+
def to_bytes(self) -> tuple[int, bytes]:
|
|
248
|
+
cls = self.__class__
|
|
249
|
+
bytes_ = cls.MsgId.to_bytes()[1] + cls.BodyRecord.to_bytes(self.record)[1]
|
|
250
|
+
return len(bytes_), bytes_
|
|
251
|
+
|
|
252
|
+
@classmethod
|
|
253
|
+
def from_bytes(cls, bytes_: bytes) -> tuple[int, 'CommonMessage']:
|
|
254
|
+
len_, msg_id = cls.MsgIdClass.from_bytes(bytes_)
|
|
255
|
+
try:
|
|
256
|
+
msg_cls = CommonMessage.MsgIdToClsMap[cls.AppName][msg_id]
|
|
257
|
+
except KeyError:
|
|
258
|
+
cls.log.error('Unknown message id %s', msg_id)
|
|
259
|
+
raise
|
|
260
|
+
msg_len, data = msg_cls.BodyRecord.from_bytes(bytes_[len_:])
|
|
261
|
+
return len_ + msg_len, msg_cls(data)
|
|
262
|
+
|
|
263
|
+
def __getattr__(self, item):
|
|
264
|
+
try:
|
|
265
|
+
_ = self.BodyRecord.IndexedFields[item]
|
|
266
|
+
return getattr(self.record, item)
|
|
267
|
+
except KeyError:
|
|
268
|
+
return self.__dict__[item]
|
|
269
|
+
|
|
270
|
+
def __setattr__(self, key, value):
|
|
271
|
+
try:
|
|
272
|
+
_ = self.BodyRecord.IndexedFields[key]
|
|
273
|
+
setattr(self.record, key, value)
|
|
274
|
+
except KeyError:
|
|
275
|
+
self.__dict__[key] = value
|
|
276
|
+
|
|
277
|
+
@classmethod
|
|
278
|
+
def get_msg_classes(cls) -> list[Type['CommonMessage']]:
|
|
279
|
+
return CommonMessage.MsgIdToClsMap[cls.AppName].values()
|
|
280
|
+
|
|
281
|
+
@classmethod
|
|
282
|
+
def get_msg_cls_by_name(cls, name: str):
|
|
283
|
+
return CommonMessage.MsgNameToMsgMap[cls.AppName][name]
|
|
284
|
+
|
|
285
|
+
@classmethod
|
|
286
|
+
def get_msg_cls_by_indicator(cls, indicator: Any):
|
|
287
|
+
return CommonMessage.MsgIdToClsMap[cls.AppName][indicator]
|
|
File without changes
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
from typing import Callable, Awaitable, Type
|
|
3
|
+
|
|
4
|
+
from nasdaq_protocols.common import logable
|
|
5
|
+
from nasdaq_protocols.common.message import *
|
|
6
|
+
from nasdaq_protocols import soup, {{impl}}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
'Message',
|
|
11
|
+
'ClientSession',
|
|
12
|
+
'connect_async',
|
|
13
|
+
{{#enums}}
|
|
14
|
+
'{{name}}',
|
|
15
|
+
{{/enums}}
|
|
16
|
+
{{#records}}
|
|
17
|
+
'{{name}}',
|
|
18
|
+
{{/records}}
|
|
19
|
+
{{#messages}}
|
|
20
|
+
'{{name}}',
|
|
21
|
+
{{/messages}}
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@logable
|
|
26
|
+
class Message({{impl}}.Message, app_name='{{app_name}}'):
|
|
27
|
+
def __init_subclass__(cls, **kwargs):
|
|
28
|
+
cls.log.debug('subclassing %s, params = %s', cls.__name__, str(kwargs))
|
|
29
|
+
if 'indicator' not in kwargs:
|
|
30
|
+
raise ValueError('expected "indicator" when subclassing {{app_name}}.Message')
|
|
31
|
+
|
|
32
|
+
kwargs['app_name'] = '{{app_name}}'
|
|
33
|
+
super().__init_subclass__(**kwargs)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ClientSession({{impl}}.ClientSession):
|
|
37
|
+
@classmethod
|
|
38
|
+
def decode(cls, bytes_: bytes) -> [int, Message]:
|
|
39
|
+
return Message.from_bytes(bytes_)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def connect_async(remote: tuple[str, int], user: str, passwd: str, session_id,
|
|
43
|
+
sequence: int = 0,
|
|
44
|
+
session_factory: Callable[[soup.SoupClientSession], ClientSession] = None,
|
|
45
|
+
on_msg_coro: Callable[[Type[Message]], Awaitable[None]] = None,
|
|
46
|
+
on_close_coro: Callable[[], Awaitable[None]] = None,
|
|
47
|
+
client_heartbeat_interval: int = 10,
|
|
48
|
+
server_heartbeat_interval: int = 10) -> ClientSession:
|
|
49
|
+
if session_factory is None:
|
|
50
|
+
def session_factory(x):
|
|
51
|
+
return ClientSession(x, on_msg_coro=on_msg_coro, on_close_coro=on_close_coro)
|
|
52
|
+
|
|
53
|
+
return await {{impl}}.connect_async(
|
|
54
|
+
remote, user, passwd, session_id, sequence,
|
|
55
|
+
session_factory, on_msg_coro, on_close_coro,
|
|
56
|
+
client_heartbeat_interval, server_heartbeat_interval
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
{{> enum}}
|
|
61
|
+
{{> record}}
|
|
62
|
+
# Messages
|
|
63
|
+
{{#messages}}
|
|
64
|
+
class {{name}}(Message, indicator={{indicator}}, direction='{{direction}}'):
|
|
65
|
+
class BodyRecord(Record):
|
|
66
|
+
Fields = [
|
|
67
|
+
{{#fields}}
|
|
68
|
+
Field('{{name}}', {{{type}}}{{#default}}, default_value={{#quote}}'{{/quote}}{{default_value}}{{#quote}}'{{/quote}}{{/default}}),
|
|
69
|
+
{{/fields}}
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
{{#fields}}
|
|
73
|
+
{{name}}: {{hint}}
|
|
74
|
+
{{/fields}}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
{{/messages}}
|