-
Notifications
You must be signed in to change notification settings - Fork 1
/
_payload.py
451 lines (363 loc) · 11.6 KB
/
_payload.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
"""Module defining the Payload class and its subclasses?"""
from __future__ import annotations
import dataclasses
import json
from collections.abc import Iterable
from typing import Dict, Optional, cast
from pysparkplug import _protobuf as protobuf
from pysparkplug._datatype import DataType
from pysparkplug._metric import Metric
from pysparkplug._types import Protocol, Self
__all__ = [
"NBirth",
"DBirth",
"NData",
"DData",
"NCmd",
"DCmd",
"NDeath",
"DDeath",
"State",
]
class Payload(Protocol):
"""Protocol defining the methods a payload should have"""
@classmethod
def decode(cls, raw: bytes, *, birth: Optional[Birth] = None) -> Self:
"""Construct a Payload object from bytes
Args:
raw:
bytes to decode into a Payload object
birth:
the Birth object associated with this message,
for decoding aliases and dropped dtypes
Returns:
Payload object
"""
def encode(self, *, include_dtypes: bool = False) -> bytes:
"""Encode Payload object into bytes
Args:
include_dtypes:
whether or not to include dtypes
Returns:
encoded payload in bytes
"""
class _PBPayload:
@classmethod
def decode(cls, raw: bytes, *, birth: Optional[Birth] = None) -> Self:
"""Construct a Payload object from bytes
Args:
raw:
bytes to decode into a Payload object
birth:
the Birth object associated with this message,
for decoding aliases and dropped dtypes
Returns:
Payload object
"""
payload = protobuf.Payload.FromString(raw)
if birth is not None:
for metric in payload.metrics:
if not metric.name:
metric.name = birth.get_name(metric.alias)
if metric.datatype == DataType.UNKNOWN:
metric.datatype = birth.get_dtype(metric.name)
if not payload.HasField("timestamp"):
raise ValueError("Sparkplug payload missing required timestamp field")
kwargs = {
"timestamp": payload.timestamp,
"metrics": tuple(Metric.from_pb(metric) for metric in payload.metrics),
}
if payload.HasField("seq"):
kwargs["seq"] = payload.seq
return cls(**kwargs)
def encode(self, *, include_dtypes: bool = False) -> bytes:
"""Encode Payload object into bytes
Args:
include_dtypes:
whether or not to include dtypes
Returns:
encoded payload in bytes
"""
payload = protobuf.Payload()
payload.timestamp = self.timestamp # type: ignore[attr-defined] # pylint: disable=no-member
if hasattr(self, "seq"):
payload.seq = self.seq
payload.metrics.extend(
metric.to_pb(include_dtype=include_dtypes)
for metric in self.metrics # type: ignore[attr-defined] # pylint: disable=no-member
)
return cast(bytes, payload.SerializeToString())
@dataclasses.dataclass(frozen=True)
class Birth(_PBPayload):
"""Class representing a Birth payload
Args:
timestamp:
timestamp at message sending time
seq:
sequence number
metrics:
metrics associated with this payload
"""
timestamp: int
seq: int
metrics: Iterable[Metric]
_names_mapping: Dict[int, str] = dataclasses.field(
init=False, default_factory=dict, repr=False
)
_dtypes_mapping: Dict[str, DataType] = dataclasses.field(
init=False, default_factory=dict, repr=False
)
def __post_init__(self) -> None:
for metric in self.metrics:
if metric.name is None:
raise ValueError(
f"Metric {metric} must have a defined name when provided to a Birth payload"
)
if metric.datatype == DataType.UNKNOWN:
raise ValueError(
f"Metric {metric} must have a defined datatype when provided to a Birth payload"
)
if metric.alias is not None:
self._names_mapping[metric.alias] = metric.name
self._dtypes_mapping[metric.name] = metric.datatype
@classmethod
def decode(cls, raw: bytes, *, birth: Optional[Birth] = None) -> Self:
"""Construct a Birth object from bytes
Args:
raw:
bytes to decode into a Birth object
birth:
unused input since Births payloads are self-contained
Returns:
Birth object
"""
birth = None # don't use previous birth to determine name/datatypes
return super().decode(raw, birth=birth)
def encode(self, *, include_dtypes: bool = False) -> bytes:
"""Encode Birth object into bytes
Args:
include_dtypes:
whether or not to include dtypes
Returns:
encoded payload in bytes
"""
include_dtypes = True # always include datatypes
return super().encode(include_dtypes=include_dtypes)
def get_name(self, alias: int) -> str:
"""Get the name of the metric with the requested alias
Args:
alias:
the alias of the metric we want the name of
Returns:
the name of the metric
"""
return self._names_mapping[alias]
def get_dtype(self, name: str) -> DataType:
"""Get the dtype of the metric with the requested name
Args:
name:
the name of the metric we want the dtype of
Returns:
the dtype of the metric
"""
return self._dtypes_mapping[name]
class NBirth(Birth):
"""Class representing an NBirth payload
Args:
timestamp:
timestamp at message sending time
seq:
sequence number
metrics:
metrics associated with this payload
"""
class DBirth(Birth):
"""Class representing a DBirth payload
Args:
timestamp:
timestamp at message sending time
seq:
sequence number
metrics:
metrics associated with this payload
"""
@dataclasses.dataclass(frozen=True)
class _Data(_PBPayload):
timestamp: int
seq: int
metrics: Iterable[Metric]
class NData(_Data):
"""Class representing an NData payload
Args:
timestamp:
timestamp at message sending time
seq:
sequence number
metrics:
metrics associated with this payload
"""
class DData(_Data):
"""Class representing a DData payload
Args:
timestamp:
timestamp at message sending time
seq:
sequence number
metrics:
metrics associated with this payload
"""
@dataclasses.dataclass(frozen=True)
class _Cmd(_PBPayload):
timestamp: int
metrics: Iterable[Metric]
class NCmd(_Cmd):
"""Class representing an NCmd payload
Args:
timestamp:
timestamp at message sending time
metrics:
metrics associated with this payload
"""
class DCmd(_Cmd):
"""Class representing a DCmd payload
Args:
timestamp:
timestamp at message sending time
metrics:
metrics associated with this payload
"""
@dataclasses.dataclass(frozen=True)
class NDeath:
"""Class representing an NDeath payload
Args:
timestamp:
timestamp at message sending time
bd_seq_metric:
birth death sequence number metric
"""
timestamp: Optional[int]
bd_seq_metric: Metric
@classmethod
def decode(
cls,
raw: bytes,
*,
birth: Optional[Birth] = None, # pylint: disable=unused-argument
) -> Self:
"""Construct an NDeath object from bytes
Args:
raw:
bytes to decode into a NDeath object
birth:
unused input since NDeaths don't have any metrics with aliases or dropped dtypes
Returns:
NDeath object
"""
payload = protobuf.Payload.FromString(raw)
return cls(
timestamp=payload.timestamp if not payload.HasField("timestamp") else None,
bd_seq_metric=Metric.from_pb(payload.metrics[0]),
)
def encode(self, *, include_dtypes: bool = False) -> bytes:
"""Encode NDeath object into bytes
Args:
include_dtypes:
whether or not to include dtypes
Returns:
encoded payload in bytes
"""
include_dtypes = True # always include datatypes
payload = protobuf.Payload()
if self.timestamp is not None:
payload.timestamp = self.timestamp
payload.metrics.append(self.bd_seq_metric.to_pb(include_dtype=include_dtypes))
return cast(bytes, payload.SerializeToString())
@dataclasses.dataclass(frozen=True)
class DDeath:
"""Class representing a DDeath payload
Args:
timestamp:
timestamp at message sending time
seq:
sequence number
"""
timestamp: int
seq: int
@classmethod
def decode(
cls,
raw: bytes,
*,
birth: Optional[Birth] = None, # pylint: disable=unused-argument
) -> Self:
"""Construct a DDeath object from bytes
Args:
raw:
bytes to decode into a DDeath object
birth:
unused input since DDeaths don't have any metrics
Returns:
DDeath object
"""
payload = protobuf.Payload.FromString(raw)
return cls(
timestamp=payload.timestamp,
seq=payload.seq,
)
def encode(
self, *, include_dtypes: bool = False # pylint: disable=unused-argument
) -> bytes:
"""Encode DDeath object into bytes
Args:
include_dtypes:
unused input since DDeaths have no metrics
Returns:
encoded payload in bytes
"""
payload = protobuf.Payload()
payload.timestamp = self.timestamp
payload.seq = self.seq
return cast(bytes, payload.SerializeToString())
@dataclasses.dataclass(frozen=True)
class State:
"""Class representing a State payload
Args:
timestamp:
timestamp at message sending time
online:
whether or not the primary host application is online
"""
timestamp: int
online: bool
@classmethod
def decode(
cls,
raw: bytes,
*,
birth: Optional[Birth] = None, # pylint: disable=unused-argument
) -> Self:
"""Construct a State object from bytes
Args:
raw:
bytes to decode into a Payload object
birth:
unused input since States don't have any metrics
Returns:
State object
"""
state = json.loads(raw)
return cls(
timestamp=state["timestamp"],
online=state["online"],
)
def encode(
self, *, include_dtypes: bool = False # pylint: disable=unused-argument
) -> bytes:
"""Encode State object into bytes
Args:
include_dtypes:
unused input since States have no metrics
Returns:
encoded payload in bytes
"""
return json.dumps({"timestamp": self.timestamp, "online": self.online}).encode()