-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcompost_rpc.py
More file actions
2173 lines (1815 loc) · 76.4 KB
/
Copy pathcompost_rpc.py
File metadata and controls
2173 lines (1815 loc) · 76.4 KB
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Main module of Compost
"""
__version__ = "0.7.0.dev"
import sys
import subprocess
import logging
import threading
import typing
import uuid
import socket
from string import Template
from dataclasses import dataclass, astuple
from queue import Queue, Empty
from pathlib import Path
from datetime import datetime
from inspect import Parameter, signature, Signature
from typing import Any, Callable, Concatenate, ParamSpec, TypeVar, runtime_checkable, get_args, get_origin
from abc import ABC, abstractmethod
from struct import Struct, unpack_from, pack
from enum import Enum
MIN_PYTHON = (3, 10)
if sys.version_info < MIN_PYTHON:
sys.exit("Python %s.%s or later is required." % MIN_PYTHON)
logger = logging.getLogger(__name__)
try:
import colorful as cf
import traceback
COMPOST_COLORS = {
'info': '#6CA6CD',
'warn': '#EEEE00',
'err': '#BB0000',
'success': '#00CD66'
}
cf.update_palette(COMPOST_COLORS)
# Set colors for exceptions
def colorful_exception_hook(exc_type, exc_value, exc_traceback):
# Call the default exception hook for KeyboardInterrupt
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
traceback_lines = [str(
cf.bold(cf.err(line)) if line.startswith(exc_type.__name__)
else cf.info(line) if not line.startswith(' ')
else line
)
for line in traceback.format_exception(exc_type, exc_value, exc_traceback)
]
traceback_message = ''.join(traceback_lines)
print(traceback_message)
sys.excepthook = colorful_exception_hook
except ImportError:
class ColorfulDummy:
def __getattr__(cls, name):
def pipe (s: str) -> str:
return s
return pipe
cf = ColorfulDummy()
class _String:
def __init__(self, val: str = "", indent: int = 0) -> None:
self._indent = indent
self._str = val
def __add__(self, other):
return _String(self._str + str(other), self._indent)
def __str__(self) -> str:
return self._str
def indent_inc(self):
self._indent += 1
def indent_dec(self):
self._indent -= 1
if self._indent < 0:
self._indent = 0
def add(self, lines: str | tuple, end: str = "\n"):
indent = " " * self._indent
if isinstance(lines, tuple):
for line in lines:
self._str += f"{indent}{line}{end}"
else:
self._str += f"{indent}{lines}{end}"
_C = TypeVar("C")
def _ceiling_division(n: int, d: int):
return -(n // -d)
def _scase(arg: str, to_upper: bool = True) -> str:
"Convert CamelCase to snake_case"
if (len(arg) == 0):
return arg
out = [ c if c.islower() else f"_{c}"
for c in arg[1:]
]
out = "".join([arg[0], *out])
return out.upper() if to_upper else out.lower()
def _pcase(arg: str) -> str:
"Convert snake_case to PascalCase"
if (len(arg) == 0):
return arg
s = arg.split("_")
out = []
for i, part in enumerate(s):
if len(part) == 0 or part.isspace():
continue
part_next = s[i+1] if i+1 < len(s) else " "
out.append(part[0].upper() + part[1:].lower() if len(part) > 1 else part[0].upper())
if (part[-1].isdigit() and part_next[0].isdigit()):
out.append("_")
return "".join(out)
def _ccase(arg: str) -> str:
"Convert snake_case to lower camelCase"
if (len(arg) == 0):
return arg
out = _pcase(arg)
return "".join([out[0].lower(), *out[1:]]) if len(out) > 1 else out[0].lower()
def _issubclass(cls: Any, class_or_tuple: type | tuple[type]) -> bool:
"""Custom version of issubclass that does not raise an exception if cls is not a class, but
returns False."""
try:
return issubclass(cls, class_or_tuple)
except TypeError:
return False
class RpcError(Exception):
"""Generic RPC error."""
pass
class RequestTimeoutError(RpcError):
"""Response not received in time."""
pass
class RequestError(RpcError):
"""Received error message instead of a result."""
pass
class UnknownRpcIdError(RpcError):
"""Remote does not know the rpc_id. Incompatible protocol."""
pass
class UnexpectedTxnError(RpcError):
"""Received unexpected txn value."""
pass
class MalformedMessageError(RpcError):
"""Received malformed message."""
pass
class MemUnit:
"""Represents a memory size that can be specified in bits or bytes. Now immutable."""
BITS_PER_BYTE = 8
@classmethod
def from_bytes(cls, bytes_: int) -> "MemUnit":
return cls(bits=bytes_ * cls.BITS_PER_BYTE)
def __init__(self, bits: int = 0):
self._bits = bits
@property
def bits(self) -> int:
return self._bits
@bits.setter
def bits(self, value: int):
self._bits = value
@property
def bytes(self) -> int:
return (self.bits + self.BITS_PER_BYTE - 1) // self.BITS_PER_BYTE
@bytes.setter
def bytes(self, value: int):
self._bits = value * self.BITS_PER_BYTE
def byte_align(self):
"""Aligns the MemUnit to the next byte boundary if not already aligned."""
if not self.is_byte_aligned():
self._bits = self.bytes * self.BITS_PER_BYTE
def is_byte_aligned(self) -> bool:
return (self._bits % self.BITS_PER_BYTE) == 0
def __repr__(self) -> str:
return f"MemUnit(bits={self.bits}, bytes={self.bytes})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, MemUnit):
return NotImplemented
return self.bits == other.bits
def __add__(self, other: "MemUnit") -> "MemUnit":
if not isinstance(other, MemUnit):
raise TypeError("Expected MemUnit instance")
return MemUnit(self.bits + other.bits)
class U64(int):
"""64-bit unsigned integer"""
size = MemUnit(64)
fmt = ">Q"
def __new__(cls, value, *args, **kwargs):
if value < 0:
raise ValueError("Unsigned type cannot hold negative value")
if value >= 2**64:
raise ValueError("Value too large for 64 bit unsigned integer")
return super().__new__(cls, value)
def __str__(self):
return "%d" % int(self)
def __repr__(self):
return "U64(%d)" % int(self)
class I64(int):
"""64-bit signed integer"""
size = MemUnit(64)
fmt = ">q"
def __new__(cls, value, *args, **kwargs):
# TODO
if value < -(2**64):
raise ValueError("Unsigned type cannot hold negative value")
if value >= 2**64:
raise ValueError("Value too large for 64 bit unsigned integer")
return super().__new__(cls, value)
def __str__(self):
return "%d" % int(self)
def __repr__(self):
return "I64(%d)" % int(self)
class U32(int):
"""32-bit unsigned integer"""
size = MemUnit(32)
fmt = ">I"
def __new__(cls, value, *args, **kwargs):
if value < 0:
raise ValueError("Unsigned type cannot hold negative value")
if value >= 2**32:
raise ValueError("Value too large for 32 bit unsigned integer")
return super().__new__(cls, value)
def __str__(self):
return "%d" % int(self)
def __repr__(self):
return "U32(%d)" % int(self)
class I32(int):
"""32-bit signed integer"""
size = MemUnit(32)
fmt = ">i"
def __new__(cls, value, *args, **kwargs):
# TODO
if value < -(2**31):
raise ValueError("Unsigned type cannot hold negative value")
if value >= 2**31:
raise ValueError("Value too large for 32 bit unsigned integer")
return super().__new__(cls, value)
def __str__(self):
return "%d" % int(self)
def __repr__(self):
return "I32(%d)" % int(self)
class U16(int):
"""16-bit unsigned integer"""
size = MemUnit(16)
fmt = ">H"
def __new__(cls, value, *args, **kwargs):
if value < 0:
raise ValueError("Unsigned type cannot hold negative value")
if value >= 2**16:
raise ValueError("Value too large for 16 bit unsigned integer")
return super().__new__(cls, value)
def __str__(self):
return f"{int(self)}"
def __repr__(self):
return f"U16({int(self)})"
class I16(int):
"""16-bit signed integer"""
size = MemUnit(16)
fmt = ">h"
def __new__(cls, value, *args, **kwargs):
# TODO
if value < -(2**15):
raise ValueError("Value is less than minimum for 16 bit signed integer")
if value >= 2**15:
raise ValueError("Value too large for 16 bit signed integer")
return super().__new__(cls, value)
def __str__(self):
return f"{int(self)}"
def __repr__(self):
return f"I16({int(self)})"
class U8(int):
"""8-bit unsigned integer"""
size = MemUnit(8)
fmt = ">B"
def __new__(cls, value, *args, **kwargs):
if value < 0:
raise ValueError("Unsigned type cannot hold negative value")
if value >= 2**8:
raise ValueError("Value too large for 8 bit unsigned integer")
return super().__new__(cls, value)
def __str__(self):
return f"{int(self)}"
def __repr__(self):
return f"U8({int(self)})"
class I8(int):
"""8-bit signed integer"""
size = MemUnit(8)
fmt = ">b"
def __new__(cls, value, *args, **kwargs):
# TODO
if value < -(2**7):
raise ValueError("Value is less than minimum for 8 bit signed integer")
if value >= 2**7:
raise ValueError("Value too large for 8 bit signed integer")
return super().__new__(cls, value)
def __str__(self):
return f"{int(self)}"
def __repr__(self):
return f"I8({int(self)})"
class F32(float):
"""32-bit floating point number"""
size = MemUnit(32)
fmt = ">f"
def __new__(cls, value, *args, **kwargs):
return super(cls, cls).__new__(cls, value)
def __str__(self):
return f"{float(self)}"
def __repr__(self):
return f"F32({float(self)})"
class F64(float):
"""64-bit floating point number"""
size = MemUnit(64)
fmt = ">d"
def __new__(cls, value, *args, **kwargs):
return super(cls, cls).__new__(cls, value)
def __str__(self):
return f"{float(self)}"
def __repr__(self):
return f"F64({float(self)})"
class BitU(int):
"""Unsigned bit precise integer"""
size = MemUnit()
def __class_getitem__(cls, key) -> type["BitU"]:
if not isinstance(key, int):
raise TypeError("BitU index must be an integer")
if key < 0:
raise ValueError("BitU index must be non-negative")
if key > 32:
raise ValueError("BitU index must be less than 32")
return type(f"BitU[{key}]", (BitU, ), {"size": MemUnit(key)})
def __new__(cls, value, *args, **kwargs):
if value < 0:
raise ValueError("Unsigned type cannot hold negative value")
if value >= 2**cls.size.bits:
raise ValueError(f"Value too large for {cls.size.bits} bit unsigned integer")
return super().__new__(cls, value)
def __str__(self):
return "%d" % int(self)
def __repr__(self):
return "BitU%d(%d)" % (self.size.bits, int(self))
@classmethod
def unpack(cls, buffer: memoryview, offset: MemUnit) -> tuple[int, MemUnit]:
val = 0
byte_index = offset.bits // MemUnit.BITS_PER_BYTE
bits_remaining = cls.size.bits
bit_position = offset.bits
while bits_remaining > 0:
bits_to_fill = 8 - (bit_position % 8)
bits_to_place = min(bits_remaining, bits_to_fill)
shift = bits_to_fill - bits_to_place
mask = (1 << bits_to_place) - 1
bit_value = (buffer[byte_index] >> shift) & mask
bit_position += bits_to_place
byte_index += 1
bits_remaining -= bits_to_place
val |= bit_value << bits_remaining
offset += cls.size
return val, offset
@classmethod
def pack(cls, buffer: memoryview, offset: MemUnit, value: int):
"""Serializes integer numeric type to specific bit offset in the buffer. The value may be packed to lower bit-size."""
byte_index = offset.bits // MemUnit.BITS_PER_BYTE
bits_remaining = cls.size.bits
bit_position = offset.bits
while bits_remaining > 0:
bits_to_fill = MemUnit.BITS_PER_BYTE - (bit_position % MemUnit.BITS_PER_BYTE)
bits_to_place = bits_remaining if bits_remaining <= bits_to_fill else bits_to_fill
shift = bits_to_fill - bits_to_place
mask = (1 << bits_to_place) - 1
bit_value = (value >> bits_remaining - bits_to_place) & mask
buffer[byte_index] &= ~(mask << shift)
buffer[byte_index] |= (bit_value << shift)
bit_position += bits_to_place
byte_index += 1
bits_remaining -= bits_to_place
offset += cls.size
return offset
_NUMERIC_PRIMITIVE_TYPES = (
U64,
I64,
U32,
I32,
U16,
I16,
U8,
I8,
F32,
F64
)
_SUPPORTED_PRIMITIVE_TYPES = (
*_NUMERIC_PRIMITIVE_TYPES,
str,
bytes,
)
_CUSTOM_USER_TYPES: list[type] = []
class _CompostStruct:
size: MemUnit = MemUnit(0)
dynamic_members: list[tuple[str, type]] = []
layout: list[MemUnit] = []
def unpack_payload(types: list[type], payload: bytes) -> tuple:
"""Deserializes message payload into a tuple of Python objects"""
def _unpack(buffer: memoryview, offset, t: type) -> tuple[list, MemUnit]:
ret = []
if _issubclass(t, _CompostStruct):
offset.byte_align()
members = []
for _, member_t in t.__annotations__.items():
values, offset = _unpack(buffer, offset, member_t)
members.append(*values)
ret.append(t(*members))
elif _issubclass(t, (bytes, str)):
(length,) = unpack_from(">H", payload, offset.bytes)
offset.bytes += 2
data_bytes = payload[offset.bytes : offset.bytes + length]
if _issubclass(t, (bytes,)):
ret.append(data_bytes)
if _issubclass(t, (str,)):
ret.append(data_bytes.decode())
offset.bytes += length
elif get_origin(t) is list:
(length,) = unpack_from(">H", payload, offset.bytes)
offset.bytes += 2
(inner_type,) = get_args(t)
length //= inner_type.size.bytes
list_ = []
for o in range(offset.bytes, offset.bytes + length * inner_type.size.bytes, inner_type.size.bytes):
list_.append(*unpack_from(inner_type.fmt, payload, o))
ret.append(list_)
offset.bytes += length * inner_type.size.bytes
elif _issubclass(t, Enum):
if _issubclass(t, BitU):
val, offset = t.unpack(memoryview(payload), offset)
ret.append(t(val))
elif _issubclass(t, I8):
ret.append(t(*unpack_from(I8.fmt, payload, offset.bytes)))
offset += I8.size
elif _issubclass(t, U8):
ret.append(t(*unpack_from(U8.fmt, payload, offset.bytes)))
offset += U8.size
elif _issubclass(t, I16):
ret.append(t(*unpack_from(I16.fmt, payload, offset.bytes)))
offset += I16.size
else:
TypeError("Unsupported enum backing type")
elif _issubclass(t, BitU):
val, offset = t.unpack(memoryview(payload), offset)
ret.append(val)
elif _issubclass(t, _NUMERIC_PRIMITIVE_TYPES):
ret.append(*unpack_from(t.fmt, payload, offset.bytes))
offset += t.size
else:
TypeError("Unsupported type")
return ret, offset
ret = []
offset = MemUnit()
buffer = memoryview(payload)
for item in types:
values, offset = _unpack(buffer, offset, item)
ret.extend(values)
return tuple(ret)
def pack_payload(types: list[type], *args) -> bytes:
"""Serializes Python objects in arguments to bytes"""
def _pack(buffer: memoryview, offset: MemUnit, t: type, value) -> MemUnit:
if _issubclass(t, (_CompostStruct, )):
offset.byte_align()
for (_, member_type), member in zip(t.__annotations__.items(), astuple(value)):
offset = _pack(buffer, offset, member_type, member)
elif _issubclass(t, (bytes, str)):
offset.byte_align()
if _issubclass(t, (str,)):
value = str.encode(value)
value = bytes(value)
buffer[offset.bytes:offset.bytes+2] = pack(">H", len(value))
offset.bytes += 2
buffer[offset.bytes:offset.bytes+len(value)] = value
offset.bytes += len(value)
elif get_origin(t) is list:
offset.byte_align()
if not isinstance(value, list):
raise TypeError("value must be of type: list")
(inner_type,) = get_args(t)
buffer[offset.bytes:offset.bytes+2] = pack(">H", len(value) * inner_type.size.bytes)
offset.bytes += 2
for i in value:
buffer[offset.bytes:offset.bytes+inner_type.size.bytes] = pack(inner_type.fmt, i)
offset += inner_type.size
elif _issubclass(t, (BitU)):
offset = t.pack(buffer, offset, value)
elif _issubclass(t, _NUMERIC_PRIMITIVE_TYPES):
offset.byte_align()
buffer[offset.bytes:offset.bytes+t.size.bytes] = pack(t.fmt, value)
offset += t.size
elif _issubclass(t, Enum):
if _issubclass(t, BitU):
t.pack(buffer, offset, value)
offset += t.size
elif _issubclass(t, I8):
offset.byte_align()
buffer[offset.bytes] = pack(I8.fmt, value.value)
offset += I8.size
elif _issubclass(t, U8):
offset.byte_align()
buffer[offset.bytes] = pack(U8.fmt, value.value)
offset += U8.size
else:
raise TypeError("Unsupported type")
return offset
buffer = memoryview(bytearray(1024))
offset = MemUnit()
if len(args) != len(types):
raise ValueError("Incorrect number of arguments")
for typ, value in zip(types, args):
offset = _pack(buffer, offset, typ, value)
return bytes(buffer[0:offset.bytes])
class CallDirection(Enum):
TO_REMOTE = 0
TO_LOCAL = 1
TWO_WAY = 2
class Header:
"Compost message header"
header_struct = Struct(">BBH")
def __init__(self, len_: int, txn: int, resp: bool, rpc_id: int) -> None:
self.len = len_
self.txn = txn
self.resp = resp
self.rpc_id = rpc_id
def __repr__(self) -> str:
return f"Header(len={self.len}, txn={self.txn}, rpc_id={hex(self.rpc_id)}, resp={self.resp})"
def payload_byte_len(self) -> int:
"""Returns the length of the payload in bytes."""
return 4 * self.len
def msg_byte_len(self) -> int:
"""Returns the length of the message in bytes."""
return 4 + self.payload_byte_len()
def pack(self) -> bytes:
rpc_id_and_flags = self.rpc_id & 0x0FFF
if self.resp:
rpc_id_and_flags |= 0x1000
return self.header_struct.pack(self.len, self.txn, rpc_id_and_flags)
@classmethod
def unpack(cls, header: bytes) -> "Header":
(len_, txn, rpc_id_and_flags) = cls.header_struct.unpack(header)
rpc_id = rpc_id_and_flags & 0x0FFF
response = bool(rpc_id_and_flags & 0x1000)
return cls(len_, txn, response, rpc_id)
class Msg:
"""Raw Compost message that does not know the meaning of the payload."""
def __init__(self, header: Header, payload: bytes):
self.header = header
self.payload = payload
def __len__(self) -> int:
return 4 + 4 * self.header.len
def __repr__(self) -> str:
return f"Msg({self.header}, payload={self.payload.hex(' ')})"
def pack(self) -> bytes:
assert 4 * self.header.len >= len(self.payload)
if 4 * self.header.len > len(self.payload):
self.payload += b"\0" * (4 * self.header.len - len(self.payload))
return self.header.pack() + self.payload
@classmethod
def unpack(cls, payload: bytes) -> "Msg":
return cls(Header.unpack(payload[0:4]), payload[4:])
@classmethod
def from_data(cls, txn: int, response: bool, rpc_id: int, payload: bytes) -> "Msg":
return cls(Header(_ceiling_division(len(payload), 4), txn, response, rpc_id), payload)
class PayloadSerdes:
def __init__(self, types: list[type]):
self.types = types
def pack(self, *args) -> bytes:
return pack_payload(self.types, *args)
def unpack(self, data: bytes) -> tuple:
return unpack_payload(self.types, data)
class Rpc:
def __init__(
self,
rpc_id: int,
name: str,
req_serdes: PayloadSerdes,
resp_serdes: PayloadSerdes,
call_sig: Signature,
is_notification: bool,
direction : CallDirection,
doc: str | None,
):
self.rpc_id = rpc_id
self.name = name
self.req_serdes = req_serdes
self.resp_serdes = resp_serdes
self.call_sig = call_sig
self.is_notification = is_notification
self.direction = direction
self.subscribers = []
if doc is None:
self.__doc__ = name
else:
self.__doc__ = doc
def get_param_items(self) -> list[tuple[str, Parameter]]:
_, *parameters_items = self.call_sig.parameters.items()
return parameters_items
def subscribe(self, callback):
self.subscribers.append(callback)
def unsubscribe(self, callback):
self.subscribers.remove(callback)
def __get__(self, instance, cls):
self.instance = instance
return self
def __call__(self, *args, **kwargs):
if self.is_notification:
self.instance._session.send_notif(self.rpc_id, self.req_serdes.pack(*args))
return None
else:
response = self.instance._session.rpc(self.rpc_id, self.req_serdes.pack(*args))
ret_tuple = self.resp_serdes.unpack(response)
if ret_tuple:
return ret_tuple[0]
else:
return None
def __repr__(self) -> str:
return f"Rpc(rpc_id=0x{self.rpc_id:04X}, req_types='{self.req_serdes}', resp_types='{self.resp_serdes}')"
class Endpoint(Enum):
REMOTE = 0
LOCAL = 1
def is_call_outbound(self, call: Rpc):
return (call.direction == CallDirection.TO_LOCAL and self == Endpoint.REMOTE
or call.direction == CallDirection.TO_REMOTE and self == Endpoint.LOCAL
or call.direction == CallDirection.TWO_WAY)
def is_call_inbound(self, call: Rpc):
return (call.direction == CallDirection.TO_LOCAL and self == Endpoint.LOCAL
or call.direction == CallDirection.TO_REMOTE and self == Endpoint.REMOTE
or call.direction == CallDirection.TWO_WAY)
def _validate_type(t: type, context: str = ""):
error_message_start = "Type" if len(context) == 0 else f"{context} of"
if get_origin(t) is list:
if len(get_args(t)) != 1:
raise TypeError(f"{error_message_start} list[...] must have exactly one type argument")
(inner_type,) = get_args(t)
if not _issubclass(inner_type, _NUMERIC_PRIMITIVE_TYPES):
raise TypeError(f"{error_message_start} list[...] may only contain primitive types")
def _is_type_dynamic(t: type):
if get_origin(t) is list or _issubclass(t, (bytes, str)):
return True
elif _issubclass(t, _CompostStruct):
return t.dynamic_members
else:
return False
def enum(cls: _C) -> _C:
"""Decorator for enums to make them usable with Compost RPC defintions.
Use this for enum definitions ala C.
Example::
from compost_rpc import enum
@enum
class OtaResult(I8, Enum):
OTA_OK = 0
OTA_ERR = 1
"""
if not _issubclass(cls, Enum):
raise TypeError("compost_enum supports only Enum types")
if not _issubclass(cls, (I8, U8, I16, BitU)):
raise TypeError("compost_enum supports only I8, U8, I16 or BitInt data type for Enums")
def __deepcopy__(self,memo):
return self
def __copy__(self):
return self
cls.__deepcopy__ = __deepcopy__
cls.__copy__ = __copy__
cls.backing_type = cls.__bases__[0]
_CUSTOM_USER_TYPES.append(cls)
return cls
def struct(cls: _C) -> type[_C]:
"""Decorator for classes to make them usable with Compost RPC definitions.
Use this for structure definitions ala C.
Example::
from compost_rpc import struct
@struct
class OtaCoreLoad:
core0: I8
core1: I8
dsph: I8
"""
datacls = dataclass(type(cls.__name__, (cls, _CompostStruct), dict(cls.__dict__)))
datacls.layout = [MemUnit(0)]
datacls.dynamic_members = []
for member_name, member_t in datacls.__annotations__.items():
_validate_type(member_t, "compost_struct member")
if _issubclass(member_t, _CompostStruct) and member_t.dynamic_members:
datacls.dynamic_members.append((member_name, member_t))
datacls.layout[-1] = datacls.layout[-1] + member_t.layout[0]
datacls.layout.extend(member_t.layout[1:])
elif get_origin(member_t) is list or _issubclass(member_t, (bytes, str)):
datacls.dynamic_members.append((member_name, member_t))
datacls.layout[-1] = datacls.layout[-1] + MemUnit.from_bytes(2)
datacls.layout.append(MemUnit(0))
else:
datacls.layout[-1] = datacls.layout[-1] + member_t.size
datacls.size = MemUnit(0)
for x in datacls.layout:
datacls.size = datacls.size + x
_CUSTOM_USER_TYPES.append(datacls)
return datacls
_P = ParamSpec("P") # Captures the parameters of the function
_R = TypeVar("R") # Captures the return type of the function
class RpcTypingProtocol(typing.Protocol[_P, _R]):
def subscribe(self, handler): ...
def unsubscribe(self, handler): ...
def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: ...
def rpc(rpc_id: int, notification: bool = False, direction: CallDirection = CallDirection.TO_REMOTE) -> Callable[[Callable[Concatenate[Any, _P], _R]], RpcTypingProtocol[_P, _R]]:
'''Registers function as remotely callable.
Example::
from compost_rpc import rpc
@rpc(0x001)
def read8(self, address: U32) -> U8:
"""Reads 8 bits of data from the specified address"""
'''
class Decorator:
def __init__(self, func: Callable):
sig = signature(func)
req_types = []
_, *parameters_items = sig.parameters.items()
for name, t in parameters_items:
_validate_type(t.annotation, "rpc parameter")
if _issubclass(t.annotation, (*_SUPPORTED_PRIMITIVE_TYPES, _CompostStruct)) or get_origin(t.annotation) is list:
req_types.append(t.annotation)
else:
raise TypeError(f'Parameter "{name}" has unsupported type: {t.annotation.__name__}')
resp_types = []
_validate_type(sig.return_annotation, "rpc return value")
if sig.return_annotation is sig.empty:
pass
elif get_origin(sig.return_annotation) is list or \
_issubclass(sig.return_annotation, (tuple, _CompostStruct)) or \
_issubclass(sig.return_annotation, _SUPPORTED_PRIMITIVE_TYPES):
resp_types.append(sig.return_annotation)
else:
raise TypeError(f"Unsupported return type: {sig.return_annotation.__name__}")
req = PayloadSerdes(req_types)
resp = PayloadSerdes(resp_types)
self.rpc = Rpc(rpc_id, func.__name__, req, resp, sig, notification, direction, func.__doc__)
# Called at the time the owning class owner is created
def __set_name__(self, owner: Protocol, name):
owner._validate_rpc_id(rpc_id)
owner._rpcs[self.rpc.rpc_id] = self.rpc
# Replace ourselves with the original method
setattr(owner, name, self.rpc)
return Decorator
def notification(rpc_id: int, direction : CallDirection = CallDirection.TO_LOCAL) -> Callable[[Callable[Concatenate[Any, _P], _R]], RpcTypingProtocol[_P, _R]]:
'''Registers function as notification.
Example::
from compost_rpc import struct
@struct
class LogMessage:
severity: U8
tag: U8
message: list[U8]
@notification(0x100)
def notify_log(self, log: LogMessage):
"""Sends the log message."""
'''
return rpc(rpc_id, notification=True, direction=direction)
@runtime_checkable
class Transport(typing.Protocol):
def send(self, msg: bytes):
"""Sends Compost message over the transport"""
raise NotImplementedError
def receive(self) -> bytes:
"""Receives Compost message over the transport"""
raise NotImplementedError
class SerialTransport(Transport):
def __init__(self, serial_port: str, baudrate: int) -> None:
try:
import serial
except ImportError:
raise ImportError("Package pyserial not found. Install pyserial to use the serial transport with Compost.")
self.port = serial.Serial(serial_port, baudrate, write_timeout=1)
def send(self, msg: bytes):
sent = 0
while sent < len(msg):
sent += self.port.write(msg[sent:])
def receive(self) -> bytes:
header = self.port.read(4)
if len(header) < 4:
raise RuntimeError("Malformed message: Header length < 4")
payload = self.port.read(Header.unpack(header).payload_byte_len())
return header + payload
class TcpTransport(Transport):
def __init__(self, target_ip: str, target_port: int) -> None:
self.tcp_port = target_port
self.ip_address = target_ip
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)