ycpp 0.1.3__cp312-abi3-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. ycpp/__init__.py +110 -0
  2. ycpp/_array.py +318 -0
  3. ycpp/_awareness.py +268 -0
  4. ycpp/_doc.py +718 -0
  5. ycpp/_event.py +188 -0
  6. ycpp/_id_map.py +620 -0
  7. ycpp/_map.py +267 -0
  8. ycpp/_provider.py +180 -0
  9. ycpp/_snapshot.py +28 -0
  10. ycpp/_sticky_index.py +59 -0
  11. ycpp/_stream.py +91 -0
  12. ycpp/_sync.py +192 -0
  13. ycpp/_text.py +239 -0
  14. ycpp/_transaction.py +287 -0
  15. ycpp/_typed.py +122 -0
  16. ycpp/_undo.py +201 -0
  17. ycpp/_update.py +18 -0
  18. ycpp/_xml.py +452 -0
  19. ycpp/_ycpp.lib +0 -0
  20. ycpp/_ycpp.pyd +0 -0
  21. ycpp-0.1.3.data/headers/fast_float/ascii_number.h +766 -0
  22. ycpp-0.1.3.data/headers/fast_float/bigint.h +638 -0
  23. ycpp-0.1.3.data/headers/fast_float/constexpr_feature_detect.h +53 -0
  24. ycpp-0.1.3.data/headers/fast_float/decimal_to_binary.h +212 -0
  25. ycpp-0.1.3.data/headers/fast_float/digit_comparison.h +455 -0
  26. ycpp-0.1.3.data/headers/fast_float/fast_float.h +91 -0
  27. ycpp-0.1.3.data/headers/fast_float/fast_table.h +708 -0
  28. ycpp-0.1.3.data/headers/fast_float/float_common.h +1432 -0
  29. ycpp-0.1.3.data/headers/fast_float/parse_number.h +488 -0
  30. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_arithmetic.hpp +267 -0
  31. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_bit.hpp +230 -0
  32. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_cast.hpp +43 -0
  33. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_complex.hpp +112 -0
  34. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_details.hpp +386 -0
  35. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_logical.hpp +240 -0
  36. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_math.hpp +2601 -0
  37. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_memory.hpp +1006 -0
  38. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_rounding.hpp +72 -0
  39. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_swizzle.hpp +260 -0
  40. ycpp-0.1.3.data/headers/xsimd/arch/common/xsimd_common_trigo.hpp +996 -0
  41. ycpp-0.1.3.data/headers/xsimd/arch/utils/shifts.hpp +82 -0
  42. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx.hpp +2111 -0
  43. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx2.hpp +1591 -0
  44. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512bw.hpp +724 -0
  45. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512cd.hpp +28 -0
  46. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512dq.hpp +270 -0
  47. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512er.hpp +17 -0
  48. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512f.hpp +2919 -0
  49. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512ifma.hpp +17 -0
  50. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512pf.hpp +17 -0
  51. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512vbmi.hpp +76 -0
  52. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512vbmi2.hpp +130 -0
  53. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512vnni_avx512bw.hpp +17 -0
  54. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avx512vnni_avx512vbmi2.hpp +17 -0
  55. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_avxvnni.hpp +17 -0
  56. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_common.hpp +26 -0
  57. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_common_fwd.hpp +127 -0
  58. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_constants.hpp +393 -0
  59. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_emulated.hpp +787 -0
  60. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_fma3_avx.hpp +93 -0
  61. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_fma3_avx2.hpp +46 -0
  62. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_fma3_sse.hpp +97 -0
  63. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_fma4.hpp +92 -0
  64. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_i8mm_neon64.hpp +17 -0
  65. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_isa.hpp +146 -0
  66. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_neon.hpp +3580 -0
  67. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_neon64.hpp +1614 -0
  68. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_rvv.hpp +1515 -0
  69. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_scalar.hpp +1210 -0
  70. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_sse2.hpp +2333 -0
  71. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_sse3.hpp +66 -0
  72. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_sse4_1.hpp +510 -0
  73. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_sse4_2.hpp +44 -0
  74. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_ssse3.hpp +186 -0
  75. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_sve.hpp +1186 -0
  76. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_vsx.hpp +916 -0
  77. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_vxe.hpp +787 -0
  78. ycpp-0.1.3.data/headers/xsimd/arch/xsimd_wasm.hpp +1819 -0
  79. ycpp-0.1.3.data/headers/xsimd/config/xsimd_arch.hpp +242 -0
  80. ycpp-0.1.3.data/headers/xsimd/config/xsimd_config.hpp +620 -0
  81. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features.hpp +50 -0
  82. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features_arm.hpp +132 -0
  83. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features_ppc.hpp +54 -0
  84. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features_riscv.hpp +95 -0
  85. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features_s390x.hpp +56 -0
  86. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpu_features_x86.hpp +1044 -0
  87. ycpp-0.1.3.data/headers/xsimd/config/xsimd_cpuid.hpp +144 -0
  88. ycpp-0.1.3.data/headers/xsimd/config/xsimd_getauxval.hpp +159 -0
  89. ycpp-0.1.3.data/headers/xsimd/config/xsimd_macros.hpp +76 -0
  90. ycpp-0.1.3.data/headers/xsimd/math/xsimd_rem_pio2.hpp +707 -0
  91. ycpp-0.1.3.data/headers/xsimd/memory/xsimd_aligned_allocator.hpp +349 -0
  92. ycpp-0.1.3.data/headers/xsimd/memory/xsimd_alignment.hpp +102 -0
  93. ycpp-0.1.3.data/headers/xsimd/types/xsimd_all_registers.hpp +57 -0
  94. ycpp-0.1.3.data/headers/xsimd/types/xsimd_api.hpp +3106 -0
  95. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx2_register.hpp +44 -0
  96. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512bw_register.hpp +51 -0
  97. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512cd_register.hpp +51 -0
  98. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512dq_register.hpp +51 -0
  99. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512er_register.hpp +51 -0
  100. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512f_register.hpp +77 -0
  101. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512ifma_register.hpp +51 -0
  102. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512pf_register.hpp +51 -0
  103. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512vbmi2_register.hpp +51 -0
  104. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512vbmi_register.hpp +51 -0
  105. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512vnni_avx512bw_register.hpp +54 -0
  106. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx512vnni_avx512vbmi2_register.hpp +53 -0
  107. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avx_register.hpp +64 -0
  108. ycpp-0.1.3.data/headers/xsimd/types/xsimd_avxvnni_register.hpp +44 -0
  109. ycpp-0.1.3.data/headers/xsimd/types/xsimd_batch.hpp +1665 -0
  110. ycpp-0.1.3.data/headers/xsimd/types/xsimd_batch_constant.hpp +571 -0
  111. ycpp-0.1.3.data/headers/xsimd/types/xsimd_batch_fwd.hpp +41 -0
  112. ycpp-0.1.3.data/headers/xsimd/types/xsimd_common_arch.hpp +49 -0
  113. ycpp-0.1.3.data/headers/xsimd/types/xsimd_emulated_register.hpp +80 -0
  114. ycpp-0.1.3.data/headers/xsimd/types/xsimd_fma3_avx2_register.hpp +50 -0
  115. ycpp-0.1.3.data/headers/xsimd/types/xsimd_fma3_avx_register.hpp +50 -0
  116. ycpp-0.1.3.data/headers/xsimd/types/xsimd_fma3_sse_register.hpp +50 -0
  117. ycpp-0.1.3.data/headers/xsimd/types/xsimd_fma4_register.hpp +50 -0
  118. ycpp-0.1.3.data/headers/xsimd/types/xsimd_i8mm_neon64_register.hpp +55 -0
  119. ycpp-0.1.3.data/headers/xsimd/types/xsimd_neon64_register.hpp +55 -0
  120. ycpp-0.1.3.data/headers/xsimd/types/xsimd_neon_register.hpp +130 -0
  121. ycpp-0.1.3.data/headers/xsimd/types/xsimd_register.hpp +96 -0
  122. ycpp-0.1.3.data/headers/xsimd/types/xsimd_rvv_register.hpp +491 -0
  123. ycpp-0.1.3.data/headers/xsimd/types/xsimd_sse2_register.hpp +59 -0
  124. ycpp-0.1.3.data/headers/xsimd/types/xsimd_sse3_register.hpp +49 -0
  125. ycpp-0.1.3.data/headers/xsimd/types/xsimd_sse4_1_register.hpp +48 -0
  126. ycpp-0.1.3.data/headers/xsimd/types/xsimd_sse4_2_register.hpp +48 -0
  127. ycpp-0.1.3.data/headers/xsimd/types/xsimd_ssse3_register.hpp +48 -0
  128. ycpp-0.1.3.data/headers/xsimd/types/xsimd_sve_register.hpp +216 -0
  129. ycpp-0.1.3.data/headers/xsimd/types/xsimd_traits.hpp +408 -0
  130. ycpp-0.1.3.data/headers/xsimd/types/xsimd_utils.hpp +462 -0
  131. ycpp-0.1.3.data/headers/xsimd/types/xsimd_vsx_register.hpp +77 -0
  132. ycpp-0.1.3.data/headers/xsimd/types/xsimd_vxe_register.hpp +86 -0
  133. ycpp-0.1.3.data/headers/xsimd/types/xsimd_wasm_register.hpp +59 -0
  134. ycpp-0.1.3.data/headers/xsimd/utils/bits.hpp +122 -0
  135. ycpp-0.1.3.data/headers/xsimd/utils/xsimd_type_traits.hpp +145 -0
  136. ycpp-0.1.3.data/headers/xsimd/xsimd.hpp +43 -0
  137. ycpp-0.1.3.dist-info/DELVEWHEEL +2 -0
  138. ycpp-0.1.3.dist-info/METADATA +15 -0
  139. ycpp-0.1.3.dist-info/RECORD +142 -0
  140. ycpp-0.1.3.dist-info/WHEEL +4 -0
  141. ycpp.libs/msvcp140-9cb625fcbc2fbbd6fca1aee8b24b0ebe.dll +0 -0
  142. ycpp.libs/msvcp140_1-84ac1bc84e09d193dd6ad98c84c0fd94.dll +0 -0
ycpp/_map.py ADDED
@@ -0,0 +1,267 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Generic, TypeVar
4
+
5
+ from . import _ycpp
6
+ from ._event import Subscription, arg_count
7
+ from ._stream import EventStreams
8
+
9
+ _MISSING, _VALUE, _MAP, _TEXT, _ARRAY, _DOC = range(6)
10
+ _NESTED = None
11
+ T = TypeVar("T")
12
+
13
+
14
+ def _subdoc_class():
15
+ from ._doc import Doc
16
+
17
+ return Doc
18
+
19
+
20
+ def nested_types():
21
+ """(Map, Text, Array), imported once the sibling modules have finished loading.
22
+
23
+ Text and Array are not imported at module scope: `_array` imports Map, so whichever of the two
24
+ loads first would see a half-built module. Nothing here runs before the package is imported.
25
+ """
26
+ global _NESTED
27
+ if _NESTED is None:
28
+ from ._array import Array
29
+ from ._text import Text
30
+
31
+ _NESTED = (Map, Text, Array)
32
+ return _NESTED
33
+
34
+
35
+ class Map(EventStreams, Generic[T]):
36
+ """A shared map, dict-like and shaped like pycrdt's Map."""
37
+
38
+ def __init__(self, init=None, *, _doc=None, _integrated=None) -> None:
39
+ self._doc = _doc
40
+ self._prelim = None if _integrated is not None else init
41
+ self._ref = _integrated
42
+ self._subscriptions = []
43
+ self._init_event_streams()
44
+
45
+ def _integrate(self, doc, ref) -> None:
46
+ prelim, self._prelim = self._prelim, None
47
+ self._doc = doc
48
+ self._ref = ref
49
+ self._init(prelim)
50
+
51
+ def _init(self, value) -> None:
52
+ if value is None:
53
+ return
54
+ with self.doc.transaction():
55
+ for key, item in value.items():
56
+ self._set(key, item)
57
+
58
+ def _set(self, key, value) -> None:
59
+ ref = self._ref
60
+ from ._xml import _is_fragment
61
+
62
+ if isinstance(value, _subdoc_class()):
63
+ # A map set replaces the key itself, so nothing has to be erased first: erasing would
64
+ # lose the old value when the store is refused because the document already has a parent.
65
+ ref.set_doc(key, value._doc)
66
+ return
67
+ if _is_fragment(value):
68
+ if ref.contains(key):
69
+ ref.erase(key)
70
+ value._integrate(self._doc, ref.make_xml_fragment(key))
71
+ value._init()
72
+ return
73
+ types = _NESTED or nested_types()
74
+ if not isinstance(value, types):
75
+ ref.set(key, value)
76
+ return
77
+ _, text_type, array_type = types
78
+ if ref.contains(key):
79
+ ref.erase(key)
80
+ if isinstance(value, text_type):
81
+ value._integrate(self._doc, ref.make_text(key))
82
+ elif isinstance(value, array_type):
83
+ value._integrate(self._doc, ref.make_array(key))
84
+ else:
85
+ value._integrate(self._doc, ref.make_child(key))
86
+
87
+ def _check_key(self, key) -> None:
88
+ if not isinstance(key, str):
89
+ raise RuntimeError("Key must be of type string")
90
+ if not self.integrated.contains(key):
91
+ raise KeyError(key)
92
+
93
+ @property
94
+ def doc(self):
95
+ if self._doc is None:
96
+ raise RuntimeError("Not integrated in a document yet")
97
+ return self._doc
98
+
99
+ @property
100
+ def integrated(self):
101
+ if self._ref is None:
102
+ raise RuntimeError("Not integrated in a document yet")
103
+ return self._ref
104
+
105
+ @property
106
+ def is_prelim(self) -> bool:
107
+ return self._prelim is not None
108
+
109
+ @property
110
+ def is_integrated(self) -> bool:
111
+ return self._ref is not None
112
+
113
+ @property
114
+ def prelim(self):
115
+ return self._prelim
116
+
117
+ @property
118
+ def type_name(self) -> str:
119
+ return "map"
120
+
121
+ def to_py(self):
122
+ if self._ref is None:
123
+ if self._prelim is None:
124
+ return None
125
+ return {
126
+ key: item.to_py() if isinstance(item, Map) else item
127
+ for key, item in self._prelim.items()
128
+ }
129
+ return self._ref.as_dict()
130
+
131
+ def __len__(self) -> int:
132
+ return len(self.integrated)
133
+
134
+ def __str__(self) -> str:
135
+ return self.integrated.to_json()
136
+
137
+ def __delitem__(self, key) -> None:
138
+ if not isinstance(key, str):
139
+ raise RuntimeError("Key must be of type string")
140
+ ref = self._ref
141
+ if ref is None:
142
+ raise RuntimeError("Not integrated in a document yet")
143
+ if not ref.contains(key):
144
+ raise KeyError(key)
145
+ doc = self._doc
146
+ try:
147
+ ref.erase(key)
148
+ finally:
149
+ doc._raise_observer_errors()
150
+
151
+ def __getitem__(self, key):
152
+ if not isinstance(key, str):
153
+ raise RuntimeError("Key must be of type string")
154
+ ref = self._ref
155
+ if ref is None:
156
+ raise RuntimeError("Not integrated in a document yet")
157
+ from ._xml import XmlFragment
158
+
159
+ fragment = ref.child_xml_fragment(key)
160
+ if fragment.connected():
161
+ return XmlFragment(_doc=self._doc, _integrated=fragment)
162
+ kind, value = ref.lookup(key)
163
+ if kind == _VALUE:
164
+ return value
165
+ if kind == _MISSING:
166
+ raise KeyError(key)
167
+ if kind == _DOC:
168
+ return _subdoc_class()._wrapped(value)
169
+ if kind == _MAP:
170
+ return Map(_doc=self._doc, _integrated=value)
171
+ _, text_type, array_type = _NESTED or nested_types()
172
+ if kind == _TEXT:
173
+ return text_type(_doc=self._doc, _integrated=value)
174
+ return array_type(_doc=self._doc, _integrated=value)
175
+
176
+ def __setitem__(self, key, value) -> None:
177
+ if not isinstance(key, str):
178
+ raise RuntimeError("Key must be of type string")
179
+ ref = self._ref
180
+ if ref is None:
181
+ raise RuntimeError("Not integrated in a document yet")
182
+ doc = self._doc
183
+ try:
184
+ from ._xml import _is_fragment
185
+
186
+ if (
187
+ isinstance(value, _NESTED or nested_types())
188
+ or isinstance(value, _subdoc_class())
189
+ or _is_fragment(value)
190
+ ):
191
+ self._set(key, value)
192
+ else:
193
+ ref.set(key, value)
194
+ finally:
195
+ doc._raise_observer_errors()
196
+
197
+ def __iter__(self):
198
+ return self.keys()
199
+
200
+ def __contains__(self, key) -> bool:
201
+ return isinstance(key, str) and self.integrated.contains(key)
202
+
203
+ def get(self, *args):
204
+ key, *default = args
205
+ if not isinstance(key, str):
206
+ raise RuntimeError("Key must be of type string")
207
+ kind, value = self.integrated.lookup(key)
208
+ if kind == _VALUE:
209
+ return value
210
+ if kind == _MISSING:
211
+ return default[0] if default else None
212
+ return self[key]
213
+
214
+ def pop(self, *args):
215
+ key, *default = args
216
+ if not self.__contains__(key):
217
+ if not default:
218
+ raise KeyError(key)
219
+ return default[0]
220
+ value = self[key]
221
+ if isinstance(value, nested_types()):
222
+ value = value.to_py()
223
+ del self[key]
224
+ return value
225
+
226
+ def keys(self):
227
+ return iter(self.integrated.keys())
228
+
229
+ def values(self):
230
+ for key in self.integrated.keys():
231
+ yield self[key]
232
+
233
+ def items(self):
234
+ for key in self.integrated.keys():
235
+ yield key, self[key]
236
+
237
+ def clear(self) -> None:
238
+ ref = self.integrated
239
+ doc = self._doc
240
+ try:
241
+ ref.clear()
242
+ finally:
243
+ doc._raise_observer_errors()
244
+
245
+ def update(self, value) -> None:
246
+ self._init(value)
247
+
248
+ def observe(self, callback) -> Subscription:
249
+ observer = self._doc._observe_map(self.integrated)
250
+ self._doc._map_observers[observer] = (self, callback, arg_count(callback))
251
+ subscription = Subscription(self._doc, observer)
252
+ self._subscriptions.append(subscription)
253
+ return subscription
254
+
255
+ def observe_deep(self, callback) -> Subscription:
256
+ observer = self._doc._observe_deep_map(self.integrated)
257
+ self._doc._deep_observers[observer] = (callback, arg_count(callback))
258
+ subscription = Subscription(self._doc, observer)
259
+ self._subscriptions.append(subscription)
260
+ return subscription
261
+
262
+ def unobserve(self, subscription) -> None:
263
+ self._subscriptions.remove(subscription)
264
+ subscription.drop()
265
+
266
+ def __repr__(self) -> str:
267
+ return f"Map({self.to_py()!r})"
ycpp/_provider.py ADDED
@@ -0,0 +1,180 @@
1
+ """The pure-Python websocket provider of pycrdt 0.14.13, over a transport-agnostic Channel. It
2
+ carries sync messages both ways and forwards every document update as it is produced."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from contextlib import AsyncExitStack, asynccontextmanager
7
+ from logging import Logger, getLogger
8
+ from sys import exc_info
9
+ from typing import AsyncIterator, Protocol, TYPE_CHECKING
10
+
11
+ from anyio import TASK_STATUS_IGNORED, Event, Lock, TaskHandle, create_task_group
12
+ from anyio.abc import TaskGroup, TaskStatus
13
+
14
+ from ._event import TransactionEvent
15
+ from ._stream import UnsubscribableStream
16
+ from ._sync import (
17
+ YMessageType,
18
+ YSyncMessageType,
19
+ create_sync_message,
20
+ create_update_message,
21
+ handle_sync_message,
22
+ )
23
+
24
+ if TYPE_CHECKING:
25
+ from ._doc import Doc
26
+
27
+
28
+ class Channel(Protocol):
29
+ """A transport-agnostic stream used to synchronize a document through a provider.
30
+
31
+ Messages can be received through the channel using an async iterator, until the connection is
32
+ closed, or directly by calling `recv()`.
33
+ """
34
+
35
+ @property
36
+ def path(self) -> str:
37
+ """A string identifying the other endpoint."""
38
+ ...
39
+
40
+ def __aiter__(self) -> Channel:
41
+ return self
42
+
43
+ async def __anext__(self) -> bytes:
44
+ return await self.recv()
45
+
46
+ async def send(self, message: bytes) -> None:
47
+ """Send a message through the channel."""
48
+ ...
49
+
50
+ async def recv(self) -> bytes:
51
+ """Receive a message from the channel."""
52
+ ...
53
+
54
+
55
+ class Provider:
56
+ """A provider synchronizes a document through a channel."""
57
+
58
+ def __init__(self, doc: Doc, channel: Channel, log: Logger | None = None) -> None:
59
+ self._doc = doc
60
+ self._channel = channel
61
+ self.log = log or getLogger(__name__)
62
+ self.started = Event()
63
+ self.synced = Event()
64
+ self._start_lock = Lock()
65
+ self._task_group: TaskGroup | None = None
66
+ self._events: UnsubscribableStream[TransactionEvent] | None = None
67
+ self._updates_task: TaskHandle[None] | None = None
68
+
69
+ async def _run(self) -> None:
70
+ async for message in self._channel:
71
+ if len(message) < 2 or message[0] != YMessageType.SYNC:
72
+ if len(message) < 2:
73
+ self.log.warning(
74
+ "Skipping malformed message from endpoint: %s", self._channel.path
75
+ )
76
+ continue
77
+ try:
78
+ name = YSyncMessageType(message[1]).name
79
+ except ValueError:
80
+ self.log.warning(
81
+ "Skipping message with unknown type %s from endpoint: %s",
82
+ message[1],
83
+ self._channel.path,
84
+ )
85
+ continue
86
+ self.log.debug(
87
+ "Received %s message from endpoint: %s", name, self._channel.path
88
+ )
89
+ try:
90
+ reply = handle_sync_message(message[1:], self._doc)
91
+ except Exception:
92
+ # One bad frame must not end the connection: y-websocket logs and reads on.
93
+ self.log.warning(
94
+ "Skipping malformed %s message from endpoint: %s",
95
+ name,
96
+ self._channel.path,
97
+ exc_info=True,
98
+ )
99
+ continue
100
+ if message[1] == YSyncMessageType.SYNC_STEP2:
101
+ self.synced.set()
102
+ if reply is not None:
103
+ self.log.debug(
104
+ "Sending %s message to endpoint: %s",
105
+ YSyncMessageType.SYNC_STEP2.name,
106
+ self._channel.path,
107
+ )
108
+ await self._channel.send(reply)
109
+
110
+ async def _send_updates(self) -> None:
111
+ assert self._events is not None
112
+ async with self._events as events:
113
+ try:
114
+ self.log.debug(
115
+ "Sending %s message to endpoint: %s",
116
+ YSyncMessageType.SYNC_STEP1.name,
117
+ self._channel.path,
118
+ )
119
+ await self._channel.send(create_sync_message(self._doc))
120
+ async for event in events:
121
+ await self._channel.send(create_update_message(event.update))
122
+ finally:
123
+ events.unsubscribe()
124
+
125
+ async def __aenter__(self) -> Provider:
126
+ async with AsyncExitStack() as exit_stack:
127
+ self._task_group = await exit_stack.enter_async_context(
128
+ self._get_or_create_task_group()
129
+ )
130
+ await self._task_group.start(self.start)
131
+ self._exit_stack = exit_stack.pop_all()
132
+ return self
133
+
134
+ async def __aexit__(self, exc_type, exc_value, exc_tb):
135
+ if exc_type is None:
136
+ try:
137
+ assert self._events is not None
138
+ self._events.unsubscribe()
139
+ assert self._updates_task is not None
140
+ await self._updates_task
141
+ except BaseException:
142
+ await self.stop()
143
+ await self._exit_stack.__aexit__(*exc_info())
144
+ raise
145
+ await self.stop()
146
+ return await self._exit_stack.__aexit__(exc_type, exc_value, exc_tb)
147
+
148
+ @asynccontextmanager
149
+ async def _get_or_create_task_group(self) -> AsyncIterator[TaskGroup]:
150
+ if self._task_group is not None:
151
+ yield self._task_group
152
+ return
153
+
154
+ async with create_task_group() as tg:
155
+ yield tg
156
+
157
+ async def start(
158
+ self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED
159
+ ) -> None:
160
+ """Start the provider."""
161
+ async with self._start_lock:
162
+ if self._events is not None:
163
+ raise RuntimeError("Provider already started")
164
+ async with self._get_or_create_task_group() as self._task_group:
165
+ self._events = self._doc.events()
166
+ self._updates_task = self._task_group.start_soon(self._send_updates)
167
+ task_status.started()
168
+ self.started.set()
169
+ self._task_group.start_soon(self._run)
170
+
171
+ async def stop(self) -> None:
172
+ """Stop the provider immediately, discarding pending updates."""
173
+ if self._events is None:
174
+ raise RuntimeError("Provider not started")
175
+ self._events.unsubscribe()
176
+ self._events = None
177
+ self._updates_task = None
178
+ assert self._task_group is not None
179
+ self._task_group.cancel_scope.cancel()
180
+ self._task_group = None
ycpp/_snapshot.py ADDED
@@ -0,0 +1,28 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from . import _ycpp
6
+
7
+
8
+ @dataclass
9
+ class Snapshot:
10
+ """A point in a document's history, shaped like pycrdt's Snapshot.
11
+
12
+ A snapshot keeps the delete set and the state vector of a document at one moment: what was
13
+ deleted then, and how far each client had got. ``Doc.from_snapshot`` rebuilds a document as it
14
+ was at that moment, which needs a document that keeps deleted content (``skip_gc=True``).
15
+ """
16
+
17
+ _snapshot: _ycpp.Snapshot
18
+
19
+ @classmethod
20
+ def from_doc(cls, doc) -> "Snapshot":
21
+ return cls(doc._doc.snapshot())
22
+
23
+ def encode(self) -> bytes:
24
+ return self._snapshot.encode()
25
+
26
+ @classmethod
27
+ def decode(cls, data: bytes) -> "Snapshot":
28
+ return cls(_ycpp.Snapshot.decode(data))
ycpp/_sticky_index.py ADDED
@@ -0,0 +1,59 @@
1
+ """pycrdt's StickyIndex and Assoc: a Yjs relative position plus the sequence it was made from."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass
7
+ from enum import IntEnum
8
+
9
+ from . import _ycpp
10
+
11
+
12
+ class Assoc(IntEnum):
13
+ """Which side of the position later inserts land on: pycrdt.Assoc."""
14
+
15
+ AFTER = 0
16
+ BEFORE = -1
17
+
18
+
19
+ @dataclass
20
+ class StickyIndex:
21
+ """A position that follows edits, shaped like pycrdt's StickyIndex."""
22
+
23
+ _sticky_index: bytes
24
+ _sequence: object = None
25
+ _assoc: int = 0
26
+
27
+ @classmethod
28
+ def new(cls, sequence, index: int, assoc: Assoc = Assoc.AFTER) -> StickyIndex:
29
+ data = sequence.integrated.sticky_index(index, int(assoc))
30
+ return cls(data, sequence, int(assoc))
31
+
32
+ @classmethod
33
+ def decode(cls, data: bytes, sequence=None) -> StickyIndex:
34
+ raw = bytes(data)
35
+ return cls(raw, sequence, _ycpp.sticky_assoc(raw))
36
+
37
+ @classmethod
38
+ def from_json(cls, data, sequence=None) -> StickyIndex:
39
+ text = data if isinstance(data, str) else json.dumps(data)
40
+ raw = _ycpp.sticky_from_json(text)
41
+ return cls(raw, sequence, _ycpp.sticky_assoc(raw))
42
+
43
+ def get_index(self, transaction=None) -> int:
44
+ # Without a sequence the position needs a transaction to name the document it resolves in.
45
+ if self._sequence is not None:
46
+ return self._sequence._doc._doc.sticky_offset(self._sticky_index)
47
+ if transaction is None:
48
+ raise RuntimeError("No transaction available")
49
+ return transaction._doc._doc.sticky_offset(self._sticky_index)
50
+
51
+ @property
52
+ def assoc(self) -> Assoc:
53
+ return Assoc(self._assoc)
54
+
55
+ def encode(self) -> bytes:
56
+ return self._sticky_index
57
+
58
+ def to_json(self) -> dict:
59
+ return json.loads(_ycpp.sticky_json(self._sticky_index))
ycpp/_stream.py ADDED
@@ -0,0 +1,91 @@
1
+ """Streams that carry a document's events to async code, as pycrdt 0.14.13's _stream.py."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from functools import partial
7
+ from typing import TYPE_CHECKING, Callable, TypeVar, cast
8
+
9
+ from anyio import (
10
+ BrokenResourceError,
11
+ ClosedResourceError,
12
+ create_memory_object_stream,
13
+ )
14
+ from anyio.streams.memory import MemoryObjectReceiveStream
15
+
16
+ E = TypeVar("E")
17
+
18
+
19
+ class UnsubscribableStream(MemoryObjectReceiveStream[E]):
20
+ """A receive stream with an unsubscribe method.
21
+
22
+ Unsubscribing stops collecting items while leaving buffered items available to receive.
23
+ Iteration ends once the buffer is drained.
24
+ """
25
+
26
+ unsubscribe: Callable[[], None]
27
+ """Stop collecting items. Repeated calls have no effect."""
28
+
29
+ if TYPE_CHECKING:
30
+
31
+ def clone(self) -> UnsubscribableStream[E]: ...
32
+
33
+
34
+ class EventStreams:
35
+ """Asynchronous iteration over one shared type's events, as pycrdt's BaseType.events."""
36
+
37
+ def _init_event_streams(self) -> None:
38
+ self._send_streams: dict[bool, set] = {False: set(), True: set()}
39
+ self._event_subscription: dict[bool, object] = {}
40
+ self._events_lock = threading.Lock()
41
+
42
+ def events(
43
+ self,
44
+ deep: bool = False,
45
+ max_buffer_size: float = float("inf"),
46
+ ) -> UnsubscribableStream:
47
+ """Collects this type's events in a buffer, so a slow reader misses nothing."""
48
+ observe = self.observe_deep if deep else self.observe
49
+ with self._events_lock:
50
+ if not self._send_streams[deep]:
51
+ self._event_subscription[deep] = observe(partial(self._send_event, deep))
52
+ send_stream, receive_stream = create_memory_object_stream[object](
53
+ max_buffer_size=max_buffer_size
54
+ )
55
+ self._send_streams[deep].add(send_stream)
56
+ return _with_unsubscribe(
57
+ receive_stream, partial(self._unsubscribe_events, deep, send_stream)
58
+ )
59
+
60
+ def _unsubscribe_events(self, deep: bool, send_stream) -> None:
61
+ with self._events_lock:
62
+ send_streams = self._send_streams[deep]
63
+ if send_stream not in send_streams:
64
+ return
65
+ send_streams.remove(send_stream)
66
+ send_stream.close()
67
+ subscription = self._event_subscription.pop(deep) if not send_streams else None
68
+ if subscription is not None:
69
+ self.unobserve(subscription)
70
+
71
+ def _send_event(self, deep: bool, event) -> None:
72
+ with self._events_lock:
73
+ send_streams = tuple(self._send_streams[deep])
74
+ to_remove = []
75
+ for send_stream in send_streams:
76
+ try:
77
+ send_stream.send_nowait(event)
78
+ except (BrokenResourceError, ClosedResourceError):
79
+ to_remove.append(send_stream)
80
+ for send_stream in to_remove:
81
+ self._unsubscribe_events(deep, send_stream)
82
+
83
+
84
+ def _with_unsubscribe(
85
+ stream: MemoryObjectReceiveStream[E], unsubscribe: Callable[[], None]
86
+ ) -> UnsubscribableStream[E]:
87
+ stream = cast(UnsubscribableStream[E], stream)
88
+ stream.unsubscribe = unsubscribe
89
+ original_clone = stream.clone
90
+ stream.clone = lambda: _with_unsubscribe(original_clone(), unsubscribe) # type: ignore[method-assign]
91
+ return stream