forked from crossbario/autobahn-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage.py
More file actions
10257 lines (8487 loc) · 346 KB
/
Copy pathmessage.py
File metadata and controls
10257 lines (8487 loc) · 346 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
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) typedef int GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###############################################################################
import binascii
import re
import textwrap
from pprint import pformat
from typing import Any, Dict, Literal, Optional, overload
import autobahn
from autobahn.util import hlval
from autobahn.wamp.exception import InvalidUriError, ProtocolError
from autobahn.wamp.role import ROLE_NAME_TO_CLASS
try:
import cbor2
from autobahn import flatbuffers
from autobahn.wamp import message_fbs
except ImportError:
_HAS_WAMP_FLATBUFFERS = False
else:
_HAS_WAMP_FLATBUFFERS = True
__all__ = (
"PAYLOAD_ENC_CRYPTO_BOX",
"PAYLOAD_ENC_MQTT",
"PAYLOAD_ENC_STANDARD_IDENTIFIERS",
"Abort",
"Authenticate",
"Call",
"Cancel",
"Challenge",
"Error",
"Event",
"Goodbye",
"Hello",
"Interrupt",
"Invocation",
"Message",
"MessageWithAppPayload",
"MessageWithForwardFor",
"Publish",
"Published",
"Register",
"Registered",
"Result",
"Subscribe",
"Subscribed",
"Unregister",
"Unregistered",
"Unsubscribe",
"Unsubscribed",
"Welcome",
"Yield",
"check_or_raise_extra",
"check_or_raise_id",
"check_or_raise_realm_name",
"check_or_raise_uri",
"identify_realm_name_category",
"is_valid_enc_algo",
"is_valid_enc_serializer",
)
# all realm names in Autobahn/Crossbar.io must match this
_URI_PAT_REALM_NAME = re.compile(r"^[A-Za-z][A-Za-z\d_\-@\.]{2,254}$")
# if Ethereum addresses are enabled, realm names which are "0x" prefixed Ethereum addresses are also valid
_URI_PAT_REALM_NAME_ETH = re.compile(r"^0x([A-Fa-f\d]{40})$")
# realms names might also specifically match ENS URIs
_URI_PAT_REALM_NAME_ENS = re.compile(r"^([a-z\d_\-@\.]{2,250})\.eth$")
# since WAMP recommends using reverse dotted notation, reverse ENS names can be checked with this pattern
_URI_PAT_REALM_NAME_ENS_REVERSE = re.compile(r"^eth\.([a-z\d_\-@\.]{2,250})$")
# strict URI check allowing empty URI components
_URI_PAT_STRICT_EMPTY = re.compile(r"^(([\da-z_]+\.)|\.)*([\da-z_]+)?$")
# loose URI check allowing empty URI components
_URI_PAT_LOOSE_EMPTY = re.compile(r"^(([^\s\.#]+\.)|\.)*([^\s\.#]+)?$")
# strict URI check disallowing empty URI components
_URI_PAT_STRICT_NON_EMPTY = re.compile(r"^([\da-z_]+\.)*([\da-z_]+)$")
# loose URI check disallowing empty URI components
_URI_PAT_LOOSE_NON_EMPTY = re.compile(r"^([^\s\.#]+\.)*([^\s\.#]+)$")
# strict URI check disallowing empty URI components in all but the last component
_URI_PAT_STRICT_LAST_EMPTY = re.compile(r"^([\da-z_]+\.)*([\da-z_]*)$")
# loose URI check disallowing empty URI components in all but the last component
_URI_PAT_LOOSE_LAST_EMPTY = re.compile(r"^([^\s\.#]+\.)*([^\s\.#]*)$")
# custom (=implementation specific) WAMP attributes (used in WAMP message details/options)
_CUSTOM_ATTRIBUTE = re.compile(r"^x_([a-z][\da-z_]+)?$")
# Value for algo attribute in end-to-end encrypted messages using cryptobox, which
# is a scheme based on Curve25519, SHA512, Salsa20 and Poly1305.
# See: http://cr.yp.to/highspeed/coolnacl-20120725.pdf
PAYLOAD_ENC_CRYPTO_BOX = "cryptobox"
# Payload transparency identifier for MQTT payloads (which are arbitrary binary).
PAYLOAD_ENC_MQTT = "mqtt"
# Payload transparency identifier for XBR payloads
PAYLOAD_ENC_XBR = "xbr"
# Payload transparency algorithm identifiers from the WAMP spec.
PAYLOAD_ENC_STANDARD_IDENTIFIERS = [
PAYLOAD_ENC_CRYPTO_BOX,
PAYLOAD_ENC_MQTT,
PAYLOAD_ENC_XBR,
]
# Payload transparency serializer identifiers from the WAMP spec.
PAYLOAD_ENC_STANDARD_SERIALIZERS = ["json", "msgpack", "cbor", "ubjson", "flatbuffers"]
ENC_ALGO_NONE = 0
ENC_ALGO_CRYPTOBOX = 1
ENC_ALGO_MQTT = 2
ENC_ALGO_XBR = 3
ENC_ALGOS = {
ENC_ALGO_NONE: "null",
ENC_ALGO_CRYPTOBOX: "cryptobox",
ENC_ALGO_MQTT: "mqtt",
ENC_ALGO_XBR: "xbr",
}
ENC_ALGOS_FROMSTR = {key: value for value, key in ENC_ALGOS.items()}
ENC_SER_NONE = 0
ENC_SER_JSON = 1
ENC_SER_MSGPACK = 2
ENC_SER_CBOR = 3
ENC_SER_UBJSON = 4
ENC_SER_OPAQUE = 5
ENC_SER_FLATBUFFERS = 6
ENC_SERS = {
ENC_SER_NONE: "null",
ENC_SER_JSON: "json",
ENC_SER_MSGPACK: "msgpack",
ENC_SER_CBOR: "cbor",
ENC_SER_UBJSON: "ubjson",
ENC_SER_OPAQUE: "opaque",
ENC_SER_FLATBUFFERS: "flatbuffers",
}
ENC_SERS_FROMSTR = {key: value for value, key in ENC_SERS.items()}
def is_valid_enc_algo(enc_algo):
"""
For WAMP payload transparency mode, check if the provided ``enc_algo``
identifier in the WAMP message is a valid one.
Currently defined standard identifiers are:
* ``"cryptobox"``
* ``"mqtt"``
* ``"xbr"``
Users can select arbitrary identifiers too, but these MUST start with ``"x_"``.
:param enc_algo: The payload transparency algorithm identifier to check.
:type enc_algo: str
:returns: Returns ``True`` if and only if the payload transparency
algorithm identifier is valid.
:rtype: bool
"""
return type(enc_algo) == str and (
enc_algo in PAYLOAD_ENC_STANDARD_IDENTIFIERS
or _CUSTOM_ATTRIBUTE.match(enc_algo)
)
def is_valid_enc_serializer(enc_serializer):
"""
For WAMP payload transparency mode, check if the provided ``enc_serializer``
identifier in the WAMP message is a valid one.
Currently, the only standard defined identifier are
* ``"json"``
* ``"msgpack"``
* ``"cbor"``
* ``"ubjson"``
* ``"flatbuffers"``
Users can select arbitrary identifiers too, but these MUST start with ``"x_"``.
:param enc_serializer: The payload transparency serializer identifier to check.
:type enc_serializer: str
:returns: Returns ``True`` if and only if the payload transparency
serializer identifier is valid.
:rtype: bool
"""
return type(enc_serializer) == str and (
enc_serializer in PAYLOAD_ENC_STANDARD_SERIALIZERS
or _CUSTOM_ATTRIBUTE.match(enc_serializer)
)
def b2a(data, max_len=40):
if type(data) == str:
s = data
elif type(data) == bytes:
s = binascii.b2a_hex(data).decode("ascii")
elif data is None:
s = "-"
else:
s = "{}".format(data)
if len(s) > max_len:
return s[:max_len] + ".."
else:
return s
def identify_realm_name_category(value: Any) -> Optional[str]:
"""
Identify the real name category of the given value:
* ``"standalone"``: A normal, standalone WAMP realm name, e.g. ``"realm1"``.
* ``"eth"``: An Ethereum address, e.g. ``"0xe59C7418403CF1D973485B36660728a5f4A8fF9c"``.
* ``"ens"``: An Ethereum ENS name, e.g. ``"wamp-proto.eth"``.
* ``"reverse_ens"``: An Ethereum ENS name in reverse notation, e.g. ``"eth.wamp-proto"``.
* ``None``: The value is not a WAMP realm name.
:param value: The value for which to identify realm name category.
:return: The category identified, one of ``["standalone", "eth", "ens", "reverse-ens"]``
or ``None``.
"""
if type(value) != str:
return None
if _URI_PAT_REALM_NAME.match(value):
if _URI_PAT_REALM_NAME_ENS.match(value):
return "ens"
elif _URI_PAT_REALM_NAME_ENS_REVERSE.match(value):
return "reverse_ens"
else:
return "standalone"
elif _URI_PAT_REALM_NAME_ETH.match(value):
return "eth"
else:
return None
@overload
def check_or_raise_uri(
value: Any,
message: str,
strict: bool,
allow_empty_components: bool,
allow_last_empty: bool,
allow_none: Literal[True],
) -> str | None:
pass
@overload
def check_or_raise_uri(
value: Any,
message: str = "WAMP message invalid",
strict: bool = False,
allow_empty_components: bool = False,
allow_last_empty: bool = False,
allow_none: Literal[False] = False,
) -> str:
pass
def check_or_raise_uri(
value: Any,
message: str = "WAMP message invalid",
strict: bool = False,
allow_empty_components: bool = False,
allow_last_empty: bool = False,
allow_none: bool = False,
) -> str | None:
"""
Check a value for being a valid WAMP URI.
If the value is not a valid WAMP URI is invalid, raises :class:`autobahn.wamp.exception.InvalidUriError`,
otherwise returns the value.
:param value: The value to check.
:param message: Prefix for message in exception raised when value is invalid.
:param strict: If ``True``, do a strict check on the URI (the WAMP spec SHOULD behavior).
:param allow_empty_components: If ``True``, allow empty URI components (for pattern based
subscriptions and registrations).
:param allow_last_empty: If ``True``, allow the last URI component to be empty (for prefix based
subscriptions and registrations).
:param allow_none: If ``True``, allow ``None`` for URIs.
:returns: The URI value (if valid).
:raises: instance of :class:`autobahn.wamp.exception.InvalidUriError`
"""
if value is None:
if allow_none:
return
else:
raise InvalidUriError("{0}: URI cannot be null".format(message))
if type(value) != str:
if not (value is None and allow_none):
raise InvalidUriError(
"{0}: invalid type {1} for URI".format(message, type(value))
)
if strict:
if allow_last_empty:
pat = _URI_PAT_STRICT_LAST_EMPTY
elif allow_empty_components:
pat = _URI_PAT_STRICT_EMPTY
else:
pat = _URI_PAT_STRICT_NON_EMPTY
else:
if allow_last_empty:
pat = _URI_PAT_LOOSE_LAST_EMPTY
elif allow_empty_components:
pat = _URI_PAT_LOOSE_EMPTY
else:
pat = _URI_PAT_LOOSE_NON_EMPTY
if not pat.match(value):
raise InvalidUriError(
'{0}: invalid value "{1}" for URI (did not match pattern "{2}" with options strict={3}, allow_empty_components={4}, allow_last_empty={5}, allow_none={6})'.format(
message,
value,
pat.pattern,
strict,
allow_empty_components,
allow_last_empty,
allow_none,
)
)
else:
return value
def check_or_raise_realm_name(value, message="WAMP message invalid", allow_eth=True):
"""
Check a value for being a valid WAMP URI.
If the value is not a valid WAMP URI is invalid, raises :class:`autobahn.wamp.exception.InvalidUriError`,
otherwise returns the value.
:param value: The value to check, e.g. ``"realm1"`` or ``"com.example.myapp"`` or ``"eth.example"``.
:param message: Prefix for message in exception raised when value is invalid.
:param allow_eth: If ``True``, allow Ethereum addresses as realm names,
e.g. ``"0xe59C7418403CF1D973485B36660728a5f4A8fF9c"``.
:returns: The URI value (if valid).
:raises: instance of :class:`autobahn.wamp.exception.InvalidUriError`
"""
if value is None:
raise InvalidUriError("{0}: realm name cannot be null".format(message))
if type(value) != str:
raise InvalidUriError(
"{0}: invalid type {1} for realm name".format(message, type(value))
)
if allow_eth:
if _URI_PAT_REALM_NAME.match(value) or _URI_PAT_REALM_NAME_ETH.match(value):
return value
else:
raise InvalidUriError(
'{0}: invalid value "{1}" for realm name (did not match patterns '
'"{2}" or "{3}")'.format(
message,
value,
_URI_PAT_REALM_NAME.pattern,
_URI_PAT_REALM_NAME_ETH.pattern,
)
)
else:
if _URI_PAT_REALM_NAME.match(value):
return value
else:
raise InvalidUriError(
'{0}: invalid value "{1}" for realm name (did not match pattern '
'"{2}")'.format(message, value, _URI_PAT_REALM_NAME.pattern)
)
def check_or_raise_id(value: Any, message: str = "WAMP message invalid") -> int:
"""
Check a value for being a valid WAMP ID.
If the value is not a valid WAMP ID, raises :class:`autobahn.wamp.exception.ProtocolError`,
otherwise return the value.
:param value: The value to check.
:param message: Prefix for message in exception raised when value is invalid.
:returns: The ID value (if valid).
:raises: instance of :class:`autobahn.wamp.exception.ProtocolError`
"""
if type(value) != int:
raise ProtocolError("{0}: invalid type {1} for ID".format(message, type(value)))
# the value 0 for WAMP IDs is possible in certain WAMP messages, e.g. UNREGISTERED with
# router revocation signaling!
if value < 0 or value > 9007199254740992: # 2**53
raise ProtocolError("{0}: invalid value {1} for ID".format(message, value))
return value
def check_or_raise_extra(
value: Any, message: str = "WAMP message invalid"
) -> Dict[str, Any]:
"""
Check a value for being a valid WAMP extra dictionary.
If the value is not a valid WAMP extra dictionary, raises :class:`autobahn.wamp.exception.ProtocolError`,
otherwise return the value.
:param value: The value to check.
:param message: Prefix for message in exception raised when value is invalid.
:returns: The extra dictionary (if valid).
:raises: instance of :class:`autobahn.wamp.exception.ProtocolError`
"""
if type(value) != dict:
raise ProtocolError(
"{0}: invalid type {1} for WAMP extra".format(message, type(value))
)
for k in value.keys():
if not isinstance(k, str):
raise ProtocolError(
"{0}: invalid type {1} for key in WAMP extra ('{2}')".format(
message, type(k), k
)
)
return value
def _validate_kwargs(kwargs, message="WAMP message invalid"):
"""
Check a value for being a valid WAMP kwargs dictionary.
If the value is not a valid WAMP kwargs dictionary,
raises :class:`autobahn.wamp.exception.ProtocolError`.
Otherwise return the kwargs.
The WAMP spec requires that the keys in kwargs are proper
strings (unicode), not bytes. Note that the WAMP spec
says nothing about keys in application payload. Key in the
latter can be potentially of other type (if that is really
wanted).
:param kwargs: The keyword arguments to check.
:type kwargs: dict
:param message: Prefix for message in exception raised when
value is invalid.
:type message: str
:returns: The kwargs dictionary (if valid).
:rtype: dict
:raises: instance of
:class:`autobahn.wamp.exception.ProtocolError`
"""
if kwargs is not None:
if type(kwargs) != dict:
raise ProtocolError(
"{0}: invalid type {1} for WAMP kwargs".format(message, type(kwargs))
)
for k in kwargs.keys():
if not isinstance(k, str):
raise ProtocolError(
"{0}: invalid type {1} for key in WAMP kwargs ('{2}')".format(
message, type(k), k
)
)
return kwargs
class Message(object):
"""
WAMP message base class.
.. note:: This is not supposed to be instantiated, but subclassed only.
"""
MESSAGE_TYPE = None
"""
WAMP message type code.
"""
__slots__ = (
"_from_fbs",
"_serialized",
"_correlation_id",
"_correlation_uri",
"_correlation_is_anchor",
"_correlation_is_last",
"_router_internal",
)
def __init__(self, from_fbs=None):
# only filled in case this object has flatbuffers underlying
self._from_fbs = from_fbs
# serialization cache: mapping from ISerializer instances to serialized bytes
self._serialized = {}
# user attributes for message correlation (mainly for message tracing)
self._correlation_id = None
self._correlation_uri = None
self._correlation_is_anchor = None
self._correlation_is_last = None
# non-serialized 'internal' attributes (used by Crossbar router)
self._router_internal = None
@property
def correlation_id(self):
return self._correlation_id
@correlation_id.setter
def correlation_id(self, value):
assert value is None or type(value) == str
self._correlation_id = value
@property
def correlation_uri(self):
return self._correlation_uri
@correlation_uri.setter
def correlation_uri(self, value):
assert value is None or type(value) == str
self._correlation_uri = value
@property
def correlation_is_anchor(self):
return self._correlation_is_anchor
@correlation_is_anchor.setter
def correlation_is_anchor(self, value):
assert value is None or type(value) == bool
self._correlation_is_anchor = value
@property
def correlation_is_last(self):
return self._correlation_is_last
@correlation_is_last.setter
def correlation_is_last(self, value):
assert value is None or type(value) == bool
self._correlation_is_last = value
def __eq__(self, other):
"""
Compare this message to another message for equality.
:param other: The other message to compare with.
:type other: obj
:returns: ``True`` iff the messages are equal.
:rtype: bool
"""
if not isinstance(other, self.__class__):
return False
# we only want the actual message data attributes (not eg _serialize)
for k in self.__slots__:
if k not in [
"_serialized",
"_correlation_id",
"_correlation_uri",
"_correlation_is_anchor",
"_correlation_is_last",
] and not k.startswith("_"):
if not getattr(self, k) == getattr(other, k):
return False
return True
def __ne__(self, other):
"""
Compare this message to another message for inequality.
:param other: The other message to compare with.
:type other: obj
:returns: ``True`` iff the messages are not equal.
:rtype: bool
"""
return not self.__eq__(other)
def __str__(self) -> str:
return "{}\n{}".format(
hlval(self.__class__.__name__.upper() + "::", color="blue", bold=True),
hlval(
textwrap.indent(pformat(self.marshal()), " "),
color="blue",
bold=False,
),
)
@staticmethod
def parse(wmsg):
"""
Factory method that parses a unserialized raw message (as returned byte
:func:`autobahn.interfaces.ISerializer.unserialize`) into an instance
of this class.
:returns: An instance of this class.
:rtype: obj
"""
raise NotImplementedError()
def marshal(self):
raise NotImplementedError()
@staticmethod
def cast(buf):
raise NotImplementedError()
def build(self, builder, serializer=None):
"""
Build a FlatBuffers representation of this message.
:param builder: A FlatBuffers builder to serialize into.
:type builder: flatbuffers.Builder
:param serializer: The transport serializer (ISerializer) to use for
application payload serialization. Uses PAYLOAD_SERIALIZER_ID to
determine how to serialize args/kwargs/payload.
:type serializer: ISerializer or None
:returns: Offset to the serialized message in the builder.
"""
raise NotImplementedError()
def uncache(self):
"""
Resets the serialization cache.
"""
self._serialized = {}
def serialize(self, serializer):
"""
Serialize this object into a wire level bytes representation and cache
the resulting bytes. If the cache already contains an entry for the given
serializer, return the cached representation directly.
:param serializer: The wire level serializer to use.
:type serializer: An instance that implements :class:`autobahn.interfaces.ISerializer`
:returns: The serialized bytes.
:rtype: bytes
"""
# only serialize if not cached ..
if serializer not in self._serialized:
if serializer.NAME == "flatbuffers":
# flatbuffers get special treatment ..
builder = flatbuffers.Builder(1024)
# Get parent ISerializer to access payload serialization
parent_serializer = getattr(serializer, "_parent_serializer", None)
# this is the core method writing out this message (self) to a (new) flatbuffer
# FIXME: implement this method for all classes derived from Message
obj = self.build(builder, parent_serializer)
builder.Finish(obj)
buf = builder.Output()
self._serialized[serializer] = bytes(buf)
else:
# all other serializers first marshal() the object and then serialize the latter
self._serialized[serializer] = serializer.serialize(self.marshal())
# cache is filled now: return serialized, cached bytes
return self._serialized[serializer]
class MessageWithAppPayload(object):
"""
Mixin for WAMP messages carrying application payload (Category 4).
The 7 data plane messages: PUBLISH, EVENT, CALL, INVOCATION, YIELD, RESULT, ERROR
Attributes (the "6-set"):
args, kwargs, payload, enc_algo, enc_key, enc_serializer
These six attributes form an inseparable unit. In E2EE mode, attributes
enc_algo/enc_key/enc_serializer must all be present or all be None.
Note on __slots__:
This mixin has __slots__ = () (empty tuple). This is REQUIRED for multiple
inheritance with __slots__. DO NOT REMOVE! Empty __slots__ means "I add no
new slots but allow derived classes to use slots". Without this, the class
would get a __dict__ and break the slots chain. See docs/wamp/message-design.rst
for detailed explanation.
Note on initialization:
Uses _init_app_payload() method instead of __init__() to avoid complex super()
chains in multiple inheritance. Concrete classes call this method explicitly.
"""
__slots__ = () # REQUIRED: Empty slots for mixin pattern. DO NOT REMOVE!
def _init_app_payload(
self,
args=None,
kwargs=None,
payload=None,
enc_algo=None,
enc_key=None,
enc_serializer=None,
):
"""
Initialize application payload attributes.
Note: This is NOT __init__() to avoid super() complexity in multiple inheritance.
Concrete message classes call this method explicitly after Message.__init__().
:param args: Positional arguments (list/tuple)
:param kwargs: Keyword arguments (dict)
:param payload: Opaque payload bytes (for E2EE)
:param enc_algo: Encoding/encryption algorithm identifier
:param enc_key: Key identifier for decryption
:param enc_serializer: Payload serializer ID (e.g., "cbor", "json")
"""
self._args = args
self._kwargs = _validate_kwargs(kwargs)
self._payload = payload
self._enc_algo = enc_algo
self._enc_key = enc_key
self._enc_serializer = enc_serializer
def _get_payload_serializer_id(self):
"""
Get the serializer ID to use for payload deserialization.
Returns the enc_serializer if set, otherwise defaults to "cbor"
for backward compatibility.
"""
return self._enc_serializer if self._enc_serializer else "cbor"
def _deserialize_payload(self, data_bytes, ser_id):
"""
Deserialize payload data using the specified serializer.
Uses memoryview (zero-copy) where possible. Converts to bytes
only for JSON and FlexBuffers which don't support memoryview.
:param data_bytes: memoryview of the serialized data
:param ser_id: Serializer ID string ("json", "cbor", "msgpack", etc.)
:return: Deserialized Python object (list, dict, etc.)
"""
# Special case: FlexBuffers (quasi-dynamic typing)
if ser_id == "flexbuffers":
from autobahn.flatbuffers import flexbuffers
root = flexbuffers.GetRoot(bytes(data_bytes))
return root
# Import the appropriate deserializer
if ser_id == "json":
import json
# JSON requires bytes() conversion
return json.loads(bytes(data_bytes))
elif ser_id == "cbor":
import cbor2
# cbor2 supports memoryview (zero-copy)
return cbor2.loads(data_bytes)
elif ser_id == "msgpack":
import msgpack
# msgpack supports memoryview (zero-copy)
return msgpack.unpackb(data_bytes)
elif ser_id == "ubjson":
import ubjson
# ubjson supports memoryview (zero-copy)
return ubjson.loadb(data_bytes)
else:
# Fallback to CBOR for unknown serializers
import cbor2
return cbor2.loads(data_bytes)
@property
def args(self):
"""Lazy deserialization of args from FlatBuffers"""
if self._args is None and self._from_fbs:
if self._from_fbs.ArgsLength():
ser_id = self._get_payload_serializer_id()
args_bytes = self._from_fbs.ArgsAsBytes() # Returns memoryview
if ser_id == "flexbuffers":
root = self._deserialize_payload(args_bytes, ser_id)
self._args = root.AsVector.Value # Returns Python list
else:
self._args = self._deserialize_payload(args_bytes, ser_id)
return self._args
@args.setter
def args(self, value):
assert value is None or type(value) in [list, tuple]
self._args = value
@property
def kwargs(self):
"""Lazy deserialization of kwargs from FlatBuffers"""
if self._kwargs is None and self._from_fbs:
if self._from_fbs.KwargsLength():
ser_id = self._get_payload_serializer_id()
kwargs_bytes = self._from_fbs.KwargsAsBytes() # Returns memoryview
if ser_id == "flexbuffers":
root = self._deserialize_payload(kwargs_bytes, ser_id)
self._kwargs = root.AsMap.Value # Returns Python dict
else:
self._kwargs = self._deserialize_payload(kwargs_bytes, ser_id)
return self._kwargs
@kwargs.setter
def kwargs(self, value):
assert value is None or type(value) == dict
self._kwargs = value
@property
def payload(self):
"""Lazy deserialization of payload from FlatBuffers"""
if self._payload is None and self._from_fbs:
if self._from_fbs.PayloadLength():
self._payload = self._from_fbs.PayloadAsBytes()
return self._payload
@payload.setter
def payload(self, value):
assert value is None or type(value) == bytes
self._payload = value
@property
def enc_algo(self):
"""Lazy deserialization of enc_algo from FlatBuffers"""
if self._enc_algo is None and self._from_fbs:
enc_algo = self._from_fbs.PptScheme()
if enc_algo:
# Convert FlatBuffers enum integer to string
self._enc_algo = ENC_ALGOS.get(enc_algo)
return self._enc_algo
@enc_algo.setter
def enc_algo(self, value):
assert value is None or is_valid_enc_algo(value)
self._enc_algo = value
@property
def enc_key(self):
"""Lazy deserialization of enc_key from FlatBuffers"""
if self._enc_key is None and self._from_fbs:
self._enc_key = self._from_fbs.PptKeyid()
return self._enc_key
@enc_key.setter
def enc_key(self, value):
assert value is None or type(value) == str
self._enc_key = value
@property
def enc_serializer(self):
"""Lazy deserialization of enc_serializer from FlatBuffers"""
if self._enc_serializer is None and self._from_fbs:
enc_serializer = self._from_fbs.PptSerializer()
if enc_serializer:
# Convert FlatBuffers enum integer to string
self._enc_serializer = ENC_SERS.get(enc_serializer)
return self._enc_serializer
@enc_serializer.setter
def enc_serializer(self, value):
assert value is None or is_valid_enc_serializer(value)
self._enc_serializer = value
class MessageWithForwardFor(object):
"""
Mixin for WAMP messages with forward_for (Category 3 & 4).
Category 3: Subscribe, Unsubscribe, Register, Unregister, Cancel, Interrupt
Category 4: PUBLISH, EVENT, CALL, INVOCATION, YIELD, RESULT, ERROR
Note on __slots__:
This mixin has __slots__ = () (empty tuple). This is REQUIRED for multiple
inheritance with __slots__. DO NOT REMOVE! Empty __slots__ means "I add no
new slots but allow derived classes to use slots". Without this, the class
would get a __dict__ and break the slots chain. See docs/wamp/message-design.rst
for detailed explanation.
Note on initialization:
Uses _init_forward_for() method instead of __init__() to avoid complex super()
chains in multiple inheritance. Concrete classes call this method explicitly.
"""
__slots__ = () # REQUIRED: Empty slots for mixin pattern. DO NOT REMOVE!
def _init_forward_for(self, forward_for=None):
"""
Initialize forwarding attributes.
Note: This is NOT __init__() to avoid super() complexity in multiple inheritance.
Concrete message classes call this method explicitly after Message.__init__().
:param forward_for: Forwarding chain metadata (list of dicts)
"""
self._forward_for = forward_for
@property
def forward_for(self):
"""
Property-based access to WAMP message forward_for attribute.
Primary purpose: Provides property-based access to the forward_for attribute
for ALL WAMP serializers (JSON, MessagePack, CBOR, UBJSON, FlatBuffers).
FlatBuffers detail: For FlatBuffers serialization specifically, this property
performs lazy deserialization - the forward_for list is only deserialized from
the underlying FlatBuffers Principal objects when first accessed. For other
serializers (JSON, CBOR, etc.), the entire WAMP message is deserialized in one
go during message parsing, so this property simply returns the pre-parsed value.
:return: List of forwarding chain entries, each a dict with keys:
- 'session' (int): WAMP session ID
- 'authid' (str or None): Authentication ID
- 'authrole' (str): Authentication role
:rtype: list[dict] or None
"""
if self._forward_for is None and self._from_fbs:
# Check if this message type has forward_for in FlatBuffers schema
# Category 1 messages don't have forward_for
if hasattr(self._from_fbs, 'ForwardForLength') and self._from_fbs.ForwardForLength():
forward_for = []
for j in range(self._from_fbs.ForwardForLength()):
principal = self._from_fbs.ForwardFor(j)
# Principal is now a table and supports authid/authrole
authid = principal.Authid()
if authid:
authid = (
authid.decode("utf-8")
if isinstance(authid, bytes)
else authid
)
authrole = principal.Authrole()
if authrole:
authrole = (
authrole.decode("utf-8")
if isinstance(authrole, bytes)
else authrole
)
forward_for.append(
{
"session": principal.Session(),
"authid": authid,
"authrole": authrole,
}
)
self._forward_for = forward_for
return self._forward_for
@forward_for.setter
def forward_for(self, value):
"""
Set the forward_for attribute.
:param value: List of forwarding chain entries, each a dict with keys:
- 'session' (int): WAMP session ID
- 'authid' (str or None): Authentication ID
- 'authrole' (str): Authentication role
:type value: list[dict] or None
"""
assert value is None or type(value) == list
if value: