forked from apache/fory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_serialization.pyx
More file actions
2220 lines (2006 loc) · 87.8 KB
/
_serialization.pyx
File metadata and controls
2220 lines (2006 loc) · 87.8 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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# distutils: language = c++
# cython: embedsignature = True
# cython: language_level = 3
# cython: annotate = True
import datetime
import logging
import os
import platform
import time
import warnings
from typing import TypeVar, Union, Iterable
from pyfory._util import get_bit, set_bit, clear_bit
from pyfory import _fory as fmod
from pyfory._fory import Language
from pyfory._fory import _PicklerStub, _UnpicklerStub, Pickler, Unpickler
from pyfory._fory import _ENABLE_TYPE_REGISTRATION_FORCIBLY
from pyfory.lib import mmh3
from pyfory.meta.metastring import Encoding
from pyfory.type import is_primitive_type
from pyfory.util import is_little_endian
from pyfory.includes.libserialization cimport \
(TypeId, IsNamespacedType, Fory_PyBooleanSequenceWriteToBuffer, Fory_PyFloatSequenceWriteToBuffer)
from libc.stdint cimport int8_t, int16_t, int32_t, int64_t, uint64_t
from libc.stdint cimport *
from libcpp.vector cimport vector
from cpython cimport PyObject
from cpython.dict cimport PyDict_Next
from cpython.ref cimport *
from cpython.list cimport PyList_New, PyList_SET_ITEM
from cpython.tuple cimport PyTuple_New, PyTuple_SET_ITEM
from libcpp cimport bool as c_bool
from libcpp.utility cimport pair
from cython.operator cimport dereference as deref
from pyfory._util cimport Buffer
from pyfory.includes.libabsl cimport flat_hash_map
from pyfory.meta.metastring import MetaStringDecoder
try:
import numpy as np
except ImportError:
np = None
cimport cython
logger = logging.getLogger(__name__)
ENABLE_FORY_CYTHON_SERIALIZATION = os.environ.get(
"ENABLE_FORY_CYTHON_SERIALIZATION", "True").lower() in ("true", "1")
cdef extern from *:
"""
#define int2obj(obj_addr) ((PyObject *)(obj_addr))
#define obj2int(obj_ref) (Py_INCREF(obj_ref), ((int64_t)(obj_ref)))
"""
object int2obj(int64_t obj_addr)
int64_t obj2int(object obj_ref)
dict _PyDict_NewPresized(Py_ssize_t minused)
Py_ssize_t Py_SIZE(object obj)
cdef int8_t NULL_FLAG = -3
# This flag indicates that object is a not-null value.
# We don't use another byte to indicate REF, so that we can save one byte.
cdef int8_t REF_FLAG = -2
# this flag indicates that the object is a non-null value.
cdef int8_t NOT_NULL_VALUE_FLAG = -1
# this flag indicates that the object is a referencable and first read.
cdef int8_t REF_VALUE_FLAG = 0
# Global MetaString decoder for namespace bytes to str
namespace_decoder = MetaStringDecoder(".", "_")
# Global MetaString decoder for typename bytes to str
typename_decoder = MetaStringDecoder("$", "_")
@cython.final
cdef class MapRefResolver:
cdef flat_hash_map[uint64_t, int32_t] written_objects_id # id(obj) -> ref_id
# Hold object to avoid tmp object gc when serialize nested fields/objects.
cdef vector[PyObject *] written_objects
cdef vector[PyObject *] read_objects
cdef vector[int32_t] read_ref_ids
cdef object read_object
cdef c_bool ref_tracking
def __cinit__(self, c_bool ref_tracking):
self.read_object = None
self.ref_tracking = ref_tracking
# Special methods of extension types must be declared with def, not cdef.
def __dealloc__(self):
self.reset()
cpdef inline c_bool write_ref_or_null(self, Buffer buffer, obj):
if not self.ref_tracking:
if obj is None:
buffer.write_int8(NULL_FLAG)
return True
else:
buffer.write_int8(NOT_NULL_VALUE_FLAG)
return False
if obj is None:
buffer.write_int8(NULL_FLAG)
return True
cdef uint64_t object_id = <uintptr_t> <PyObject *> obj
cdef int32_t next_id
cdef flat_hash_map[uint64_t, int32_t].iterator it = \
self.written_objects_id.find(object_id)
if it == self.written_objects_id.end():
next_id = self.written_objects_id.size()
self.written_objects_id[object_id] = next_id
self.written_objects.push_back(<PyObject *> obj)
Py_INCREF(obj)
buffer.write_int8(REF_VALUE_FLAG)
return False
else:
# The obj has been written previously.
buffer.write_int8(REF_FLAG)
buffer.write_varuint32(<uint64_t> deref(it).second)
return True
cpdef inline int8_t read_ref_or_null(self, Buffer buffer):
cdef int8_t head_flag = buffer.read_int8()
if not self.ref_tracking:
return head_flag
cdef int32_t ref_id
if head_flag == REF_FLAG:
# read reference id and get object from reference resolver
ref_id = buffer.read_varuint32()
self.read_object = <object> (self.read_objects[ref_id])
return REF_FLAG
else:
self.read_object = None
return head_flag
cpdef inline int32_t preserve_ref_id(self):
if not self.ref_tracking:
return -1
next_read_ref_id = self.read_objects.size()
self.read_objects.push_back(NULL)
self.read_ref_ids.push_back(next_read_ref_id)
return next_read_ref_id
cpdef inline int32_t try_preserve_ref_id(self, Buffer buffer):
if not self.ref_tracking:
# `NOT_NULL_VALUE_FLAG` can be used as stub reference id because we use
# `refId >= NOT_NULL_VALUE_FLAG` to read data.
return buffer.read_int8()
head_flag = buffer.read_int8()
if head_flag == REF_FLAG:
# read reference id and get object from reference resolver
ref_id = buffer.read_varuint32()
self.read_object = <object> (self.read_objects[ref_id])
# `head_flag` except `REF_FLAG` can be used as stub reference id because
# we use `refId >= NOT_NULL_VALUE_FLAG` to read data.
return head_flag
else:
self.read_object = None
if head_flag == REF_VALUE_FLAG:
return self.preserve_ref_id()
return head_flag
cpdef inline reference(self, obj):
if not self.ref_tracking:
return
cdef int32_t ref_id = self.read_ref_ids.back()
self.read_ref_ids.pop_back()
cdef c_bool need_inc = self.read_objects[ref_id] == NULL
if need_inc:
Py_INCREF(obj)
self.read_objects[ref_id] = <PyObject *> obj
cpdef inline get_read_object(self, id_=None):
if not self.ref_tracking:
return None
if id_ is None:
return self.read_object
cdef int32_t ref_id = id_
return <object> (self.read_objects[ref_id])
cpdef inline set_read_object(self, int32_t ref_id, obj):
if not self.ref_tracking:
return
if ref_id >= 0:
need_inc = self.read_objects[ref_id] == NULL
if need_inc:
Py_INCREF(obj)
self.read_objects[ref_id] = <PyObject *> obj
cpdef inline reset(self):
self.reset_write()
self.reset_read()
cpdef inline reset_write(self):
self.written_objects_id.clear()
for item in self.written_objects:
Py_XDECREF(item)
self.written_objects.clear()
cpdef inline reset_read(self):
if not self.ref_tracking:
return
for item in self.read_objects:
Py_XDECREF(item)
self.read_objects.clear()
self.read_ref_ids.clear()
self.read_object = None
cdef int8_t USE_TYPE_NAME = 0
cdef int8_t USE_TYPE_ID = 1
# preserve 0 as flag for type id not set in TypeInfo`
cdef int8_t NO_TYPE_ID = 0
cdef int8_t DEFAULT_DYNAMIC_WRITE_META_STR_ID = fmod.DEFAULT_DYNAMIC_WRITE_META_STR_ID
cdef int8_t INT64_TYPE_ID = fmod.INT64_TYPE_ID
cdef int8_t FLOAT64_TYPE_ID = fmod.FLOAT64_TYPE_ID
cdef int8_t BOOL_TYPE_ID = fmod.BOOL_TYPE_ID
cdef int8_t STRING_TYPE_ID = fmod.STRING_TYPE_ID
cdef int16_t MAGIC_NUMBER = fmod.MAGIC_NUMBER
cdef int32_t NOT_NULL_INT64_FLAG = fmod.NOT_NULL_INT64_FLAG
cdef int32_t NOT_NULL_FLOAT64_FLAG = fmod.NOT_NULL_FLOAT64_FLAG
cdef int32_t NOT_NULL_BOOL_FLAG = fmod.NOT_NULL_BOOL_FLAG
cdef int32_t NOT_NULL_STRING_FLAG = fmod.NOT_NULL_STRING_FLAG
cdef int32_t SMALL_STRING_THRESHOLD = fmod.SMALL_STRING_THRESHOLD
@cython.final
cdef class MetaStringBytes:
cdef public bytes data
cdef int16_t length
cdef public int8_t encoding
cdef public int64_t hashcode
cdef public int16_t dynamic_write_string_id
def __init__(self, data, hashcode):
self.data = data
self.length = len(data)
self.hashcode = hashcode
self.encoding = hashcode & 0xff
self.dynamic_write_string_id = DEFAULT_DYNAMIC_WRITE_META_STR_ID
def __eq__(self, other):
return type(other) is MetaStringBytes and other.hashcode == self.hashcode
def __hash__(self):
return self.hashcode
def decode(self, decoder):
return decoder.decode(self.data, Encoding(self.encoding))
def __repr__(self):
return f"MetaStringBytes(data={self.data}, hashcode={self.hashcode})"
@cython.final
cdef class MetaStringResolver:
cdef:
int16_t dynamic_write_string_id
vector[PyObject *] _c_dynamic_written_enum_string
vector[PyObject *] _c_dynamic_id_to_enum_string_vec
# hash -> MetaStringBytes
flat_hash_map[int64_t, PyObject *] _c_hash_to_metastr_bytes
flat_hash_map[pair[int64_t, int64_t], PyObject *] _c_hash_to_small_metastring_bytes
set _enum_str_set
dict _metastr_to_metastr_bytes
def __init__(self):
self._enum_str_set = set()
self._metastr_to_metastr_bytes = dict()
cpdef inline write_meta_string_bytes(
self, Buffer buffer, MetaStringBytes metastr_bytes):
cdef int16_t dynamic_type_id = metastr_bytes.dynamic_write_string_id
cdef int32_t length = metastr_bytes.length
if dynamic_type_id == DEFAULT_DYNAMIC_WRITE_META_STR_ID:
dynamic_type_id = self.dynamic_write_string_id
metastr_bytes.dynamic_write_string_id = dynamic_type_id
self.dynamic_write_string_id += 1
self._c_dynamic_written_enum_string.push_back(<PyObject *> metastr_bytes)
buffer.write_varuint32(length << 1)
if length <= SMALL_STRING_THRESHOLD:
buffer.write_int8(metastr_bytes.encoding)
else:
buffer.write_int64(metastr_bytes.hashcode)
buffer.write_bytes(metastr_bytes.data)
else:
buffer.write_varuint32(((dynamic_type_id + 1) << 1) | 1)
cpdef inline MetaStringBytes read_meta_string_bytes(self, Buffer buffer):
cdef int32_t header = buffer.read_varuint32()
cdef int32_t length = header >> 1
if header & 0b1 != 0:
return <MetaStringBytes> self._c_dynamic_id_to_enum_string_vec[length - 1]
cdef int64_t v1 = 0, v2 = 0, hashcode
cdef PyObject * enum_str_ptr
cdef int32_t reader_index
cdef encoding = 0
if length <= SMALL_STRING_THRESHOLD:
encoding = buffer.read_int8()
if length <= 8:
v1 = buffer.read_bytes_as_int64(length)
else:
v1 = buffer.read_int64()
v2 = buffer.read_bytes_as_int64(length - 8)
hashcode = ((v1 * 31 + v2) >> 8 << 8) | encoding
enum_str_ptr = self._c_hash_to_small_metastring_bytes[pair[int64_t, int64_t](v1, v2)]
if enum_str_ptr == NULL:
reader_index = buffer.reader_index
str_bytes = buffer.get_bytes(reader_index - length, length)
enum_str = MetaStringBytes(str_bytes, hashcode=hashcode)
self._enum_str_set.add(enum_str)
enum_str_ptr = <PyObject *> enum_str
self._c_hash_to_small_metastring_bytes[pair[int64_t, int64_t](v1, v2)] = enum_str_ptr
else:
hashcode = buffer.read_int64()
reader_index = buffer.reader_index
buffer.check_bound(reader_index, length)
buffer.reader_index = reader_index + length
enum_str_ptr = self._c_hash_to_metastr_bytes[hashcode]
if enum_str_ptr == NULL:
str_bytes = buffer.get_bytes(reader_index, length)
enum_str = MetaStringBytes(str_bytes, hashcode=hashcode)
self._enum_str_set.add(enum_str)
enum_str_ptr = <PyObject *> enum_str
self._c_hash_to_metastr_bytes[hashcode] = enum_str_ptr
self._c_dynamic_id_to_enum_string_vec.push_back(enum_str_ptr)
return <MetaStringBytes> enum_str_ptr
def get_metastr_bytes(self, metastr):
metastr_bytes = self._metastr_to_metastr_bytes.get(metastr)
if metastr_bytes is not None:
return metastr_bytes
cdef int64_t v1 = 0, v2 = 0, hashcode
length = len(metastr.encoded_data)
if length <= SMALL_STRING_THRESHOLD:
data_buf = Buffer(metastr.encoded_data)
if length <= 8:
v1 = data_buf.read_bytes_as_int64(length)
else:
v1 = data_buf.read_int64()
v2 = data_buf.read_bytes_as_int64(length - 8)
value_hash = ((v1 * 31 + v2) >> 8 << 8) | metastr.encoding.value
else:
value_hash = mmh3.hash_buffer(metastr.encoded_data, seed=47)[0]
value_hash = value_hash >> 8 << 8
value_hash |= metastr.encoding.value & 0xFF
self._metastr_to_metastr_bytes[metastr] = metastr_bytes = MetaStringBytes(metastr.encoded_data, value_hash)
return metastr_bytes
cpdef inline reset_read(self):
self._c_dynamic_id_to_enum_string_vec.clear()
cpdef inline reset_write(self):
if self.dynamic_write_string_id != 0:
self.dynamic_write_string_id = 0
for ptr in self._c_dynamic_written_enum_string:
(<MetaStringBytes> ptr).dynamic_write_string_id = \
DEFAULT_DYNAMIC_WRITE_META_STR_ID
self._c_dynamic_written_enum_string.clear()
@cython.final
cdef class TypeInfo:
"""
If dynamic_type is true, the serializer will be a dynamic typed serializer
and it will write type info when writing the data.
In such cases, the `write_typeinfo` should not write typeinfo.
In general, if we have 4 type for one class, we will have 5 serializers.
For example, we have int8/16/32/64/128 for python `int` type, then we have 6 serializers
for python `int`: `Int8/1632/64/128Serializer` for `int8/16/32/64/128` each, and another
`IntSerializer` for `int` which will dispatch to different `int8/16/32/64/128` type
according the actual value.
We do not get the acutal type here, because it will introduce extra computing.
For example, we have want to get actual `Int8/16/32/64Serializer`, we must check and
extract the actutal here which will introduce cost, and we will do same thing again
when serializing the actual data.
"""
cdef public object cls
cdef public int16_t type_id
cdef public Serializer serializer
cdef public MetaStringBytes namespace_bytes
cdef public MetaStringBytes typename_bytes
cdef public c_bool dynamic_type
def __init__(
self,
cls: Union[type, TypeVar] = None,
type_id: int = NO_TYPE_ID,
serializer: Serializer = None,
namespace_bytes: MetaStringBytes = None,
typename_bytes: MetaStringBytes = None,
dynamic_type: bool = False,
):
self.cls = cls
self.type_id = type_id
self.serializer = serializer
self.namespace_bytes = namespace_bytes
self.typename_bytes = typename_bytes
self.dynamic_type = dynamic_type
def __repr__(self):
return f"TypeInfo(cls={self.cls}, type_id={self.type_id}, " \
f"serializer={self.serializer})"
cpdef str decode_namespace(self):
if self.namespace_bytes is None:
return ""
return self.namespace_bytes.decode(namespace_decoder)
cpdef str decode_typename(self):
if self.typename_bytes is None:
return ""
return self.typename_bytes.decode(typename_decoder)
@cython.final
cdef class TypeResolver:
cdef:
readonly Fory fory
readonly MetaStringResolver metastring_resolver
object _resolver
vector[PyObject *] _c_registered_id_to_type_info
# cls -> TypeInfo
flat_hash_map[uint64_t, PyObject *] _c_types_info
# hash -> TypeInfo
flat_hash_map[pair[int64_t, int64_t], PyObject *] _c_meta_hash_to_typeinfo
MetaStringResolver meta_string_resolver
def __init__(self, fory):
self.fory = fory
self.metastring_resolver = fory.metastring_resolver
from pyfory._registry import TypeResolver
self._resolver = TypeResolver(fory)
def initialize(self):
self._resolver.initialize()
for typeinfo in self._resolver._types_info.values():
self._populate_typeinfo(typeinfo)
def register(
self,
cls: Union[type, TypeVar],
*,
type_id: int = None,
namespace: str = None,
typename: str = None,
serializer=None,
):
self.register_type(cls, type_id=type_id, namespace=namespace, typename=typename, serializer=serializer)
def register_type(
self,
cls: Union[type, TypeVar],
*,
type_id: int = None,
namespace: str = None,
typename: str = None,
serializer=None,
):
typeinfo = self._resolver.register_type(
cls,
type_id=type_id,
namespace=namespace,
typename=typename,
serializer=serializer,
)
self._populate_typeinfo(typeinfo)
cdef _populate_typeinfo(self, typeinfo):
type_id = typeinfo.type_id
if type_id >= self._c_registered_id_to_type_info.size():
self._c_registered_id_to_type_info.resize(type_id * 2, NULL)
if type_id > 0 and (self.fory.language == Language.PYTHON or not IsNamespacedType(type_id)):
self._c_registered_id_to_type_info[type_id] = <PyObject *> typeinfo
self._c_types_info[<uintptr_t> <PyObject *> typeinfo.cls] = <PyObject *> typeinfo
if typeinfo.typename_bytes is not None:
self._load_bytes_to_typeinfo(type_id, typeinfo.namespace_bytes, typeinfo.typename_bytes)
def register_serializer(self, cls: Union[type, TypeVar], serializer):
typeinfo1 = self._resolver.get_typeinfo(cls)
self._resolver.register_serializer(cls, serializer)
typeinfo2 = self._resolver.get_typeinfo(cls)
if typeinfo1.type_id != typeinfo2.type_id:
self._c_registered_id_to_type_info[typeinfo1.type_id] = NULL
self._populate_typeinfo(typeinfo2)
cpdef inline Serializer get_serializer(self, cls):
"""
Returns
-------
Returns or create serializer for the provided type
"""
return self.get_typeinfo(cls).serializer
cpdef inline TypeInfo get_typeinfo(self, cls, create=True):
cdef PyObject * typeinfo_ptr = self._c_types_info[<uintptr_t> <PyObject *> cls]
cdef TypeInfo type_info
if typeinfo_ptr != NULL:
type_info = <object> typeinfo_ptr
if type_info.serializer is not None:
return type_info
else:
type_info.serializer = self._resolver._create_serializer(cls)
return type_info
elif not create:
return None
else:
type_info = self._resolver.get_typeinfo(cls, create=create)
self._c_types_info[<uintptr_t> <PyObject *> cls] = <PyObject *> type_info
self._populate_typeinfo(type_info)
return type_info
cdef inline TypeInfo _load_bytes_to_typeinfo(
self, int32_t type_id, MetaStringBytes ns_metabytes, MetaStringBytes type_metabytes):
cdef PyObject * typeinfo_ptr = self._c_meta_hash_to_typeinfo[
pair[int64_t, int64_t](ns_metabytes.hashcode, type_metabytes.hashcode)]
if typeinfo_ptr != NULL:
return <TypeInfo> typeinfo_ptr
typeinfo = self._resolver._load_metabytes_to_typeinfo(ns_metabytes, type_metabytes)
typeinfo_ptr = <PyObject *> typeinfo
self._c_meta_hash_to_typeinfo[pair[int64_t, int64_t](
ns_metabytes.hashcode, type_metabytes.hashcode)] = typeinfo_ptr
return typeinfo
cpdef write_typeinfo(self, Buffer buffer, TypeInfo typeinfo):
if typeinfo.dynamic_type:
return
cdef:
int32_t type_id = typeinfo.type_id
int32_t internal_type_id = type_id & 0xFF
buffer.write_varuint32(type_id)
if IsNamespacedType(internal_type_id):
self.metastring_resolver.write_meta_string_bytes(buffer, typeinfo.namespace_bytes)
self.metastring_resolver.write_meta_string_bytes(buffer, typeinfo.typename_bytes)
cpdef inline TypeInfo read_typeinfo(self, Buffer buffer):
cdef:
int32_t type_id = buffer.read_varuint32()
if type_id < 0:
type_id = -type_id
if type_id > self._c_registered_id_to_type_info.size():
raise ValueError(f"Unexpected type_id {type_id}")
cdef:
int32_t internal_type_id = type_id & 0xFF
MetaStringBytes namespace_bytes, typename_bytes
if IsNamespacedType(internal_type_id):
namespace_bytes = self.metastring_resolver.read_meta_string_bytes(buffer)
typename_bytes = self.metastring_resolver.read_meta_string_bytes(buffer)
return self._load_bytes_to_typeinfo(type_id, namespace_bytes, typename_bytes)
typeinfo_ptr = self._c_registered_id_to_type_info[type_id]
if typeinfo_ptr == NULL:
raise ValueError(f"Unexpected type_id {type_id}")
typeinfo = <TypeInfo> typeinfo_ptr
return typeinfo
cpdef inline reset(self):
pass
cpdef inline reset_read(self):
pass
cpdef inline reset_write(self):
pass
@cython.final
cdef class Fory:
cdef readonly object language
cdef readonly c_bool ref_tracking
cdef readonly c_bool require_type_registration
cdef readonly c_bool is_py
cdef readonly MapRefResolver ref_resolver
cdef readonly TypeResolver type_resolver
cdef readonly MetaStringResolver metastring_resolver
cdef readonly SerializationContext serialization_context
cdef Buffer buffer
cdef public object pickler # pickle.Pickler
cdef public object unpickler # Optional[pickle.Unpickler]
cdef object _buffer_callback
cdef object _buffers # iterator
cdef object _unsupported_callback
cdef object _unsupported_objects # iterator
cdef object _peer_language
def __init__(
self,
language=Language.PYTHON,
ref_tracking: bool = False,
require_type_registration: bool = True,
):
"""
:param require_type_registration:
Whether to require registering types for serialization, enabled by default.
If disabled, unknown insecure types can be deserialized, which can be
insecure and cause remote code execution attack if the types
`__new__`/`__init__`/`__eq__`/`__hash__` method contain malicious code.
Do not disable type registration if you can't ensure your environment are
*indeed secure*. We are not responsible for security risks if
you disable this option.
"""
self.language = language
if _ENABLE_TYPE_REGISTRATION_FORCIBLY or require_type_registration:
self.require_type_registration = True
else:
self.require_type_registration = False
self.ref_tracking = ref_tracking
self.ref_resolver = MapRefResolver(ref_tracking)
self.is_py = self.language == Language.PYTHON
self.metastring_resolver = MetaStringResolver()
self.type_resolver = TypeResolver(self)
self.type_resolver.initialize()
self.serialization_context = SerializationContext()
self.buffer = Buffer.allocate(32)
if not require_type_registration:
warnings.warn(
"Type registration is disabled, unknown types can be deserialized "
"which may be insecure.",
RuntimeWarning,
stacklevel=2,
)
self.pickler = Pickler(self.buffer)
else:
self.pickler = _PicklerStub()
self.unpickler = _UnpicklerStub()
self.unpickler = None
self._buffer_callback = None
self._buffers = None
self._unsupported_callback = None
self._unsupported_objects = None
self._peer_language = None
def register_serializer(self, cls: Union[type, TypeVar], Serializer serializer):
self.type_resolver.register_serializer(cls, serializer)
def register_type(
self,
cls: Union[type, TypeVar],
*,
type_id: int = None,
namespace: str = None,
typename: str = None,
serializer=None,
):
self.type_resolver.register_type(
cls, type_id=type_id, namespace=namespace, typename=typename, serializer=serializer)
def serialize(
self, obj,
Buffer buffer=None,
buffer_callback=None,
unsupported_callback=None
) -> Union[Buffer, bytes]:
try:
return self._serialize(
obj,
buffer,
buffer_callback=buffer_callback,
unsupported_callback=unsupported_callback)
finally:
self.reset_write()
cpdef inline _serialize(
self, obj, Buffer buffer, buffer_callback=None, unsupported_callback=None):
self._buffer_callback = buffer_callback
self._unsupported_callback = unsupported_callback
if buffer is not None:
self.pickler = Pickler(self.buffer)
else:
self.buffer.writer_index = 0
buffer = self.buffer
if self.language == Language.XLANG:
buffer.write_int16(MAGIC_NUMBER)
cdef int32_t mask_index = buffer.writer_index
# 1byte used for bit mask
buffer.grow(1)
buffer.writer_index = mask_index + 1
if obj is None:
set_bit(buffer, mask_index, 0)
else:
clear_bit(buffer, mask_index, 0)
# set endian
if is_little_endian:
set_bit(buffer, mask_index, 1)
else:
clear_bit(buffer, mask_index, 1)
if self.language == Language.XLANG:
# set reader as x_lang.
set_bit(buffer, mask_index, 2)
# set writer language.
buffer.write_int8(Language.PYTHON.value)
else:
# set reader as native.
clear_bit(buffer, mask_index, 2)
if self._buffer_callback is not None:
set_bit(buffer, mask_index, 3)
else:
clear_bit(buffer, mask_index, 3)
cdef int32_t start_offset
if self.language == Language.PYTHON:
self.serialize_ref(buffer, obj)
else:
self.xserialize_ref(buffer, obj)
if buffer is not self.buffer:
return buffer
else:
return buffer.to_bytes(0, buffer.writer_index)
cpdef inline serialize_ref(
self, Buffer buffer, obj, TypeInfo typeinfo=None):
cls = type(obj)
if cls is str:
buffer.write_int16(NOT_NULL_STRING_FLAG)
buffer.write_string(obj)
return
elif cls is int:
buffer.write_int16(NOT_NULL_INT64_FLAG)
buffer.write_varint64(obj)
return
elif cls is bool:
buffer.write_int16(NOT_NULL_BOOL_FLAG)
buffer.write_bool(obj)
return
elif cls is float:
buffer.write_int16(NOT_NULL_FLOAT64_FLAG)
buffer.write_double(obj)
return
if self.ref_resolver.write_ref_or_null(buffer, obj):
return
if typeinfo is None:
typeinfo = self.type_resolver.get_typeinfo(cls)
self.type_resolver.write_typeinfo(buffer, typeinfo)
typeinfo.serializer.write(buffer, obj)
cpdef inline serialize_nonref(self, Buffer buffer, obj):
cls = type(obj)
if cls is str:
buffer.write_varuint32(STRING_TYPE_ID)
buffer.write_string(obj)
return
elif cls is int:
buffer.write_varuint32(INT64_TYPE_ID)
buffer.write_varint64(obj)
return
elif cls is bool:
buffer.write_varuint32(BOOL_TYPE_ID)
buffer.write_bool(obj)
return
elif cls is float:
buffer.write_varuint32(FLOAT64_TYPE_ID)
buffer.write_double(obj)
return
cdef TypeInfo typeinfo = self.type_resolver.get_typeinfo(cls)
self.type_resolver.write_typeinfo(buffer, typeinfo)
typeinfo.serializer.write(buffer, obj)
cpdef inline xserialize_ref(
self, Buffer buffer, obj, Serializer serializer=None):
if serializer is None or serializer.need_to_write_ref:
if not self.ref_resolver.write_ref_or_null(buffer, obj):
self.xserialize_nonref(
buffer, obj, serializer=serializer
)
else:
if obj is None:
buffer.write_int8(NULL_FLAG)
else:
buffer.write_int8(NOT_NULL_VALUE_FLAG)
self.xserialize_nonref(
buffer, obj, serializer=serializer
)
cpdef inline xserialize_nonref(
self, Buffer buffer, obj, Serializer serializer=None):
if serializer is None:
typeinfo = self.type_resolver.get_typeinfo(type(obj))
self.type_resolver.write_typeinfo(buffer, typeinfo)
serializer = typeinfo.serializer
serializer.xwrite(buffer, obj)
def deserialize(
self,
buffer: Union[Buffer, bytes],
buffers: Iterable = None,
unsupported_objects: Iterable = None,
):
try:
if type(buffer) == bytes:
buffer = Buffer(buffer)
return self._deserialize(buffer, buffers, unsupported_objects)
finally:
self.reset_read()
cpdef inline _deserialize(
self, Buffer buffer, buffers=None, unsupported_objects=None):
if not self.require_type_registration:
self.unpickler = Unpickler(buffer)
if unsupported_objects is not None:
self._unsupported_objects = iter(unsupported_objects)
if self.language == Language.XLANG:
magic_numer = buffer.read_int16()
assert magic_numer == MAGIC_NUMBER, (
f"The fory xlang serialization must start with magic number {hex(MAGIC_NUMBER)}. "
"Please check whether the serialization is based on the xlang protocol and the "
"data didn't corrupt."
)
cdef int32_t reader_index = buffer.reader_index
buffer.reader_index = reader_index + 1
if get_bit(buffer, reader_index, 0):
return None
cdef c_bool is_little_endian_ = get_bit(buffer, reader_index, 1)
assert is_little_endian_, (
"Big endian is not supported for now, "
"please ensure peer machine is little endian."
)
cdef c_bool is_target_x_lang = get_bit(buffer, reader_index, 2)
if is_target_x_lang:
self._peer_language = Language(buffer.read_int8())
else:
self._peer_language = Language.PYTHON
cdef c_bool is_out_of_band_serialization_enabled = \
get_bit(buffer, reader_index, 3)
if is_out_of_band_serialization_enabled:
assert buffers is not None, (
"buffers shouldn't be null when the serialized stream is "
"produced with buffer_callback not null."
)
self._buffers = iter(buffers)
else:
assert buffers is None, (
"buffers should be null when the serialized stream is "
"produced with buffer_callback null."
)
if not is_target_x_lang:
return self.deserialize_ref(buffer)
return self.xdeserialize_ref(buffer)
cpdef inline deserialize_ref(self, Buffer buffer):
cdef MapRefResolver ref_resolver = self.ref_resolver
cdef int32_t ref_id = ref_resolver.try_preserve_ref_id(buffer)
if ref_id < NOT_NULL_VALUE_FLAG:
return ref_resolver.get_read_object()
# indicates that the object is first read.
cdef TypeInfo typeinfo = self.type_resolver.read_typeinfo(buffer)
cls = typeinfo.cls
if cls is str:
return buffer.read_string()
elif cls is int:
return buffer.read_varint64()
elif cls is bool:
return buffer.read_bool()
elif cls is float:
return buffer.read_double()
o = typeinfo.serializer.read(buffer)
ref_resolver.set_read_object(ref_id, o)
return o
cpdef inline deserialize_nonref(self, Buffer buffer):
"""Deserialize not-null and non-reference object from buffer."""
cdef TypeInfo typeinfo = self.type_resolver.read_typeinfo(buffer)
cls = typeinfo.cls
if cls is str:
return buffer.read_string()
elif cls is int:
return buffer.read_varint64()
elif cls is bool:
return buffer.read_bool()
elif cls is float:
return buffer.read_double()
return typeinfo.serializer.read(buffer)
cpdef inline xdeserialize_ref(self, Buffer buffer, Serializer serializer=None):
cdef MapRefResolver ref_resolver
cdef int32_t ref_id
if serializer is None or serializer.need_to_write_ref:
ref_resolver = self.ref_resolver
ref_id = ref_resolver.try_preserve_ref_id(buffer)
# indicates that the object is first read.
if ref_id >= NOT_NULL_VALUE_FLAG:
o = self.xdeserialize_nonref(
buffer, serializer=serializer
)
ref_resolver.set_read_object(ref_id, o)
return o
else:
return ref_resolver.get_read_object()
cdef int8_t head_flag = buffer.read_int8()
if head_flag == NULL_FLAG:
return None
return self.xdeserialize_nonref(
buffer, serializer=serializer
)
cpdef inline xdeserialize_nonref(
self, Buffer buffer, Serializer serializer=None):
if serializer is None:
serializer = self.type_resolver.read_typeinfo(buffer).serializer
return serializer.xread(buffer)
cpdef inline write_buffer_object(self, Buffer buffer, buffer_object):
if self._buffer_callback is not None and self._buffer_callback(buffer_object):
buffer.write_bool(False)
return
buffer.write_bool(True)
cdef int32_t size = buffer_object.total_bytes()
# writer length.
buffer.write_varuint32(size)
cdef int32_t writer_index = buffer.writer_index
buffer.ensure(writer_index + size)
cdef Buffer buf = buffer.slice(buffer.writer_index, size)
buffer_object.write_to(buf)
buffer.writer_index += size
cpdef inline Buffer read_buffer_object(self, Buffer buffer):
cdef c_bool in_band = buffer.read_bool()
if not in_band:
assert self._buffers is not None
return next(self._buffers)
cdef int32_t size = buffer.read_varuint32()
cdef Buffer buf = buffer.slice(buffer.reader_index, size)
buffer.reader_index += size
return buf
cpdef inline handle_unsupported_write(self, Buffer buffer, obj):
if self._unsupported_callback is None or self._unsupported_callback(obj):
buffer.write_bool(True)
self.pickler.dump(obj)
else:
buffer.write_bool(False)
cpdef inline handle_unsupported_read(self, Buffer buffer):
cdef c_bool in_band = buffer.read_bool()
if in_band:
if self.unpickler is None:
self.unpickler.buffer = Unpickler(buffer)
return self.unpickler.load()
else:
assert self._unsupported_objects is not None
return next(self._unsupported_objects)
cpdef inline write_ref_pyobject(
self, Buffer buffer, value, TypeInfo typeinfo=None):
if self.ref_resolver.write_ref_or_null(buffer, value):
return
if typeinfo is None:
typeinfo = self.type_resolver.get_typeinfo(type(value))
self.type_resolver.write_typeinfo(buffer, typeinfo)
typeinfo.serializer.write(buffer, value)
cpdef inline read_ref_pyobject(self, Buffer buffer):
cdef MapRefResolver ref_resolver = self.ref_resolver
cdef int32_t ref_id = ref_resolver.try_preserve_ref_id(buffer)
if ref_id < NOT_NULL_VALUE_FLAG:
return ref_resolver.get_read_object()
# indicates that the object is first read.
cdef TypeInfo typeinfo = self.type_resolver.read_typeinfo(buffer)
o = typeinfo.serializer.read(buffer)
ref_resolver.set_read_object(ref_id, o)
return o
cpdef inline reset_write(self):
self.ref_resolver.reset_write()
self.type_resolver.reset_write()
self.metastring_resolver.reset_write()
self.serialization_context.reset()
self.pickler.clear_memo()
self._unsupported_callback = None
cpdef inline reset_read(self):
self.ref_resolver.reset_read()
self.type_resolver.reset_read()
self.metastring_resolver.reset_read()
self.serialization_context.reset()
self._buffers = None
self.unpickler = None
self._unsupported_objects = None
cpdef inline reset(self):
self.reset_write()
self.reset_read()
cpdef inline write_nullable_pybool(Buffer buffer, value):