forked from y-crdt/ypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathy_map.rs
647 lines (579 loc) · 21.3 KB
/
y_map.rs
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
use pyo3::exceptions::{PyKeyError, PyTypeError};
use pyo3::prelude::*;
use pyo3::types::PyDict;
use std::cell::RefCell;
use std::collections::HashMap;
use std::mem::ManuallyDrop;
use std::ops::DerefMut;
use std::rc::Rc;
use yrs::types::map::{MapEvent, MapIter};
use yrs::types::{DeepObservable, ToJson};
use yrs::{Map, MapRef, Observable, SubscriptionId, TransactionMut};
use crate::json_builder::JsonBuilder;
use crate::shared_types::{
DeepSubscription, DefaultPyErr, PreliminaryObservationException, ShallowSubscription,
SharedType, SubId, TypeWithDoc,
};
use crate::type_conversions::{events_into_py, PyObjectWrapper, ToPython, WithDocToPython};
use crate::y_doc::{WithDoc, YDocInner};
use crate::y_transaction::{YTransaction, YTransactionInner};
/// Collection used to store key-value entries in an unordered manner. Keys are always represented
/// as UTF-8 strings. Values can be any value type supported by Yrs: JSON-like primitives as well as
/// shared data types.
///
/// In terms of conflict resolution, [Map] uses logical last-write-wins principle, meaning the past
/// updates are automatically overridden and discarded by newer ones, while concurrent updates made
/// by different peers are resolved into a single value using document id seniority to establish
/// order.
#[pyclass(unsendable)]
pub struct YMap(pub SharedType<TypeWithDoc<MapRef>, HashMap<String, PyObject>>);
impl WithDoc<YMap> for MapRef {
fn with_doc(self, doc: Rc<RefCell<YDocInner>>) -> YMap {
YMap(SharedType::new(TypeWithDoc::new(self, doc)))
}
}
#[pymethods]
impl YMap {
/// Creates a new preliminary instance of a `YMap` shared data type, with its state
/// initialized to provided parameter.
///
/// Preliminary instances can be nested into other shared data types such as `YArray` and `YMap`.
/// Once a preliminary instance has been inserted this way, it becomes integrated into Ypy
/// document store and cannot be nested again: attempt to do so will result in an exception.
#[new]
pub fn new(dict: &PyDict) -> PyResult<Self> {
let mut map: HashMap<String, PyObject> = HashMap::new();
for (k, v) in dict.iter() {
let k = k.downcast::<pyo3::types::PyString>()?.to_string();
let v: PyObject = v.into();
map.insert(k, v);
}
Ok(YMap(SharedType::Prelim(map)))
}
/// Returns true if this is a preliminary instance of `YMap`.
///
/// Preliminary instances can be nested into other shared data types such as `YArray` and `YMap`.
/// Once a preliminary instance has been inserted this way, it becomes integrated into Ypy
/// document store and cannot be nested again: attempt to do so will result in an exception.
#[getter]
pub fn prelim(&self) -> bool {
matches!(&self.0, SharedType::Prelim(_))
}
pub fn __len__(&self) -> usize {
match &self.0 {
SharedType::Integrated(v) => v.with_transaction(|txn| v.len(txn)) as usize,
SharedType::Prelim(v) => v.len(),
}
}
/// Returns a number of elements stored within this instance of `YArray` using a provided transaction.
fn _len(&self, txn: &YTransactionInner) -> usize {
match &self.0 {
SharedType::Integrated(v) => v.len(txn) as usize,
SharedType::Prelim(v) => v.len(),
}
}
pub fn __str__(&self) -> String {
Python::with_gil(|py| match &self.0 {
SharedType::Integrated(y_array) => {
y_array.with_transaction(|txn| y_array.to_json(txn).into_py(py).to_string())
}
SharedType::Prelim(py_contents) => py_contents.clone().into_py(py).to_string(),
})
}
pub fn __dict__(&self) -> PyResult<PyObject> {
Python::with_gil(|py| match &self.0 {
SharedType::Integrated(v) => v.with_transaction(|txn| Ok(v.to_json(txn).into_py(py))),
SharedType::Prelim(map) => {
let dict = PyDict::new(py);
for (k, v) in map.iter() {
dict.set_item(k, v)?;
}
Ok(dict.into())
}
})
}
pub fn __repr__(&self) -> String {
format!("YMap({})", self.__str__())
}
/// Converts contents of this `YMap` instance into a JSON representation.
pub fn to_json(&self) -> PyResult<String> {
let mut json_builder = JsonBuilder::new();
match &self.0 {
SharedType::Integrated(dict) => {
dict.with_transaction(|txn| json_builder.append_json(&dict.to_json(txn)))?
}
SharedType::Prelim(dict) => json_builder.append_json(dict)?,
}
Ok(json_builder.into())
}
/// Sets a given `key`-`value` entry within this instance of `YMap`. If another entry was
/// already stored under given `key`, it will be overridden with new `value`.
pub fn set(&mut self, txn: &mut YTransaction, key: &str, value: PyObject) -> PyResult<()> {
txn.transact(|txn| self._set(txn, key, value))
}
fn _set(&mut self, txn: &mut YTransactionInner, key: &str, value: PyObject) {
match &mut self.0 {
SharedType::Integrated(v) => {
v.insert(
txn,
key.to_string(),
PyObjectWrapper::new(value, v.doc.clone()),
);
}
SharedType::Prelim(v) => {
v.insert(key.to_string(), value);
}
}
}
/// Updates `YMap` with the key value pairs in the `items` object.
pub fn update(&mut self, txn: &mut YTransaction, items: PyObject) -> PyResult<()> {
txn.transact(|txn| self._update(txn, items))?
}
fn _update(&mut self, txn: &mut YTransactionInner, items: PyObject) -> PyResult<()> {
Python::with_gil(|py| {
// Handle collection types
if let Ok(dict) = items.extract::<HashMap<String, PyObject>>(py) {
dict.into_iter().for_each(|(k, v)| self._set(txn, &k, v));
return Ok(());
}
// Handle iterable of tuples
match items.as_ref(py).iter() {
Ok(iterable) => {
for value in iterable {
match value {
Ok(kv_pair) => {
if let Ok((key, value)) = kv_pair.extract::<(String, PyObject)>() {
self._set(txn, &key, value);
} else {
return Err(PyTypeError::new_err(format!("Update items should be formatted as (str, value) tuples, found: {}", kv_pair)));
}
}
Err(err) => return Err(err),
}
}
Ok(())
}
Err(err) => Err(err),
}
})
}
/// Removes an entry identified by a given `key` from this instance of `YMap`, if such exists.
pub fn pop(
&mut self,
txn: &mut YTransaction,
key: &str,
fallback: Option<PyObject>,
) -> PyResult<PyObject> {
txn.transact(|txn| self._pop(txn, key, fallback))?
}
fn _pop(
&mut self,
txn: &mut YTransactionInner,
key: &str,
fallback: Option<PyObject>,
) -> PyResult<PyObject> {
let popped = match &mut self.0 {
SharedType::Integrated(v) => v
.inner
.remove(txn, key)
.map(|value| Python::with_gil(|py| value.with_doc_into_py(v.doc.clone(), py))),
SharedType::Prelim(v) => v.remove(key),
};
if let Some(value) = popped {
Ok(value)
} else if let Some(fallback) = fallback {
Ok(fallback)
} else {
Err(PyKeyError::new_err(key.to_string()))
}
}
/// Retrieves an item from the map. If the item isn't found, the fallback value is returned.
pub fn get(&self, key: &str, fallback: Option<PyObject>) -> PyObject {
self.__getitem__(key)
.ok()
.unwrap_or_else(|| fallback.unwrap_or_else(|| Python::with_gil(|py| py.None())))
}
/// Returns value of an entry stored under given `key` within this instance of `YMap`,
/// or `undefined` if no such entry existed.
pub fn __getitem__(&self, key: &str) -> PyResult<PyObject> {
let entry = match &self.0 {
SharedType::Integrated(y_map) => y_map.with_transaction(|txn| {
y_map.inner.get(txn, key).map(|value| {
Python::with_gil(|py| value.with_doc_into_py(y_map.doc.clone(), py))
})
}),
SharedType::Prelim(hash_map) => hash_map.get(key).cloned(),
};
entry.ok_or_else(|| PyKeyError::new_err(key.to_string()))
}
/// Returns an item view that can be used to traverse over all entries stored within this
/// instance of `YMap`. Order of entry is not specified.
///
/// Example:
///
/// ```python
/// from y_py import YDoc
///
/// # document on machine A
/// doc = YDoc()
/// map = doc.get_map('name')
/// with doc.begin_transaction() as txn:
/// map.set(txn, 'key1', 'value1')
/// map.set(txn, 'key2', true)
/// for (key, value) in map.entries(txn)):
/// print(key, value)
/// ```
pub fn items(&self) -> ItemView {
ItemView::new(self)
}
pub fn keys(&self) -> KeyView {
KeyView::new(self)
}
pub fn __iter__(&self) -> KeyIterator {
self.keys().__iter__()
}
pub fn values(&self) -> ValueView {
ValueView::new(self)
}
pub fn observe(&mut self, f: PyObject) -> PyResult<ShallowSubscription> {
match &mut self.0 {
SharedType::Integrated(v) => {
let doc = v.doc.clone();
let sub_id: SubscriptionId = v
.inner
.observe(move |txn: &TransactionMut, e| {
Python::with_gil(|py| {
let e = YMapEvent::new(e, txn, doc.clone());
if let Err(err) = f.call1(py, (e,)) {
err.restore(py)
}
})
})
.into();
Ok(ShallowSubscription(sub_id))
}
SharedType::Prelim(_) => Err(PreliminaryObservationException::default_message()),
}
}
pub fn observe_deep(&mut self, f: PyObject) -> PyResult<DeepSubscription> {
match &mut self.0 {
SharedType::Integrated(map) => {
let doc = map.doc.clone();
let sub: SubscriptionId = map
.inner
.observe_deep(move |txn, events| {
Python::with_gil(|py| {
let events = events_into_py(txn, events, doc.clone());
if let Err(err) = f.call1(py, (events,)) {
err.restore(py)
}
})
})
.into();
Ok(DeepSubscription(sub))
}
SharedType::Prelim(_) => Err(PreliminaryObservationException::default_message()),
}
}
/// Cancels the observer callback associated with the `subscripton_id`.
pub fn unobserve(&mut self, subscription_id: SubId) -> PyResult<()> {
match &mut self.0 {
SharedType::Integrated(map) => {
match subscription_id {
SubId::Shallow(ShallowSubscription(id)) => map.unobserve(id),
SubId::Deep(DeepSubscription(id)) => map.unobserve_deep(id),
}
Ok(())
}
SharedType::Prelim(_) => Err(PreliminaryObservationException::default_message()),
}
}
}
#[pyclass(unsendable)]
pub struct ItemView(*const YMap);
impl ItemView {
pub fn new(map: &YMap) -> Self {
let inner = map as *const YMap;
ItemView(inner)
}
}
#[pymethods]
impl ItemView {
fn __iter__(slf: PyRef<Self>) -> YMapIterator {
YMapIterator::from(slf.0)
}
fn __len__(&self) -> usize {
let ymap = unsafe { &*self.0 };
match &ymap.0 {
SharedType::Integrated(map) => map.with_transaction(|txn| map.len(txn) as usize),
SharedType::Prelim(map) => map.len(),
}
}
fn __str__(&self) -> String {
let vals: String = YMapIterator::from(self.0)
.map(|(key, val)| format!("({key}, {val})"))
.collect::<Vec<String>>()
.join(", ");
format!("{{{vals}}}")
}
fn __repr__(&self) -> String {
let data = self.__str__();
format!("ItemView({data})")
}
fn __contains__(&self, el: PyObject) -> bool {
let ymap = unsafe { &*self.0 };
let kv: Result<(String, PyObject), _> = Python::with_gil(|py| el.extract(py));
kv.ok()
.and_then(|(key, value)| match &ymap.0 {
SharedType::Integrated(map) => map.with_transaction(|txn| {
if map.contains_key(txn, &key) {
map.get(txn, &key).map(|v| {
Python::with_gil(|py| {
v.with_doc_into_py(map.doc.clone(), py).as_ref(py).eq(value)
})
.unwrap_or(false)
})
} else {
None
}
}),
SharedType::Prelim(map) if map.contains_key(&key) => map
.get(&key)
.map(|v| Python::with_gil(|py| v.as_ref(py).eq(value).unwrap_or(false))),
_ => None,
})
.unwrap_or(false)
}
}
#[pyclass(unsendable)]
pub struct KeyView(*const YMap);
impl KeyView {
pub fn new(map: &YMap) -> Self {
let inner = map as *const YMap;
KeyView(inner)
}
}
#[pymethods]
impl KeyView {
fn __iter__(&self) -> KeyIterator {
KeyIterator(YMapIterator::from(self.0))
}
fn __len__(&self) -> usize {
let ymap = unsafe { &*self.0 };
match &ymap.0 {
SharedType::Integrated(map) => map.with_transaction(|txn| map.len(txn) as usize),
SharedType::Prelim(map) => map.len(),
}
}
fn __str__(&self) -> String {
let vals: String = YMapIterator::from(self.0)
.map(|(key, _)| key)
.collect::<Vec<String>>()
.join(", ");
format!("{{{vals}}}")
}
fn __repr__(&self) -> String {
let data = self.__str__();
format!("KeyView({data})")
}
fn __contains__(&self, el: PyObject) -> bool {
let ymap = unsafe { &*self.0 };
let key: Result<String, _> = Python::with_gil(|py| el.extract(py));
key.ok()
.map(|key| match &ymap.0 {
SharedType::Integrated(map) => {
map.with_transaction(|txn| map.contains_key(txn, &key))
}
SharedType::Prelim(map) => map.contains_key(&key),
})
.unwrap_or(false)
}
}
#[pyclass(unsendable)]
pub struct ValueView(*const YMap);
impl ValueView {
pub fn new(map: &YMap) -> Self {
let inner = map as *const YMap;
ValueView(inner)
}
}
#[pymethods]
impl ValueView {
fn __iter__(slf: PyRef<Self>) -> ValueIterator {
ValueIterator(YMapIterator::from(slf.0))
}
fn __len__(&self) -> usize {
let ymap = unsafe { &*self.0 };
match &ymap.0 {
SharedType::Integrated(map) => map.with_transaction(|txn| map.len(txn) as usize),
SharedType::Prelim(map) => map.len(),
}
}
fn __str__(&self) -> String {
let vals: String = YMapIterator::from(self.0)
.map(|(_, v)| v.to_string())
.collect::<Vec<String>>()
.join(", ");
format!("{{{vals}}}")
}
fn __repr__(&self) -> String {
let data = self.__str__();
format!("ValueView({data})")
}
}
pub enum InnerYMapIterator {
Integrated(TypeWithDoc<MapIter<'static, &'static YTransactionInner, YTransactionInner>>),
Prelim(std::collections::hash_map::Iter<'static, String, PyObject>),
}
#[pyclass(unsendable)]
pub struct YMapIterator(ManuallyDrop<InnerYMapIterator>);
impl Drop for YMapIterator {
fn drop(&mut self) {
unsafe { ManuallyDrop::drop(&mut self.0) }
}
}
impl From<*const YMap> for YMapIterator {
fn from(inner_map_ptr: *const YMap) -> Self {
let map = unsafe { &*inner_map_ptr };
match &map.0 {
SharedType::Integrated(val) => {
let iter = val.with_transaction(|txn| {
let txn = txn as *const YTransactionInner;
unsafe { val.iter(&*txn) }
});
let shared_iter =
InnerYMapIterator::Integrated(TypeWithDoc::new(iter, val.doc.clone()));
YMapIterator(ManuallyDrop::new(shared_iter))
}
SharedType::Prelim(val) => {
let shared_iter = InnerYMapIterator::Prelim(val.iter());
YMapIterator(ManuallyDrop::new(shared_iter))
}
}
}
}
impl Iterator for YMapIterator {
type Item = (String, PyObject);
fn next(&mut self) -> Option<Self::Item> {
match self.0.deref_mut() {
InnerYMapIterator::Integrated(iter) => Python::with_gil(|py| {
iter.next()
.map(|(k, v)| (k.to_string(), v.with_doc_into_py(iter.doc.clone(), py)))
}),
InnerYMapIterator::Prelim(iter) => iter.next().map(|(k, v)| (k.clone(), v.clone())),
}
}
}
#[pymethods]
impl YMapIterator {
fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
pub fn __next__(mut slf: PyRefMut<Self>) -> Option<(String, PyObject)> {
slf.next()
}
}
#[pyclass(unsendable)]
pub struct KeyIterator(YMapIterator);
#[pymethods]
impl KeyIterator {
fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
fn __next__(mut slf: PyRefMut<Self>) -> Option<String> {
slf.0.next().map(|(k, _)| k)
}
}
#[pyclass(unsendable)]
pub struct ValueIterator(YMapIterator);
#[pymethods]
impl ValueIterator {
fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
fn __next__(mut slf: PyRefMut<Self>) -> Option<PyObject> {
slf.0.next().map(|(_, v)| v)
}
}
/// Event generated by `YMap.observe` method. Emitted during transaction commit phase.
#[pyclass(unsendable)]
pub struct YMapEvent {
inner: *const MapEvent,
doc: Rc<RefCell<YDocInner>>,
txn: *const TransactionMut<'static>,
target: Option<PyObject>,
keys: Option<PyObject>,
}
impl YMapEvent {
pub fn new(event: &MapEvent, txn: &TransactionMut, doc: Rc<RefCell<YDocInner>>) -> Self {
let inner = event as *const MapEvent;
// HACK: get rid of lifetime
let txn = unsafe { std::mem::transmute::<&TransactionMut, &TransactionMut<'static>>(txn) };
let txn = txn as *const TransactionMut;
YMapEvent {
inner,
doc,
txn,
target: None,
keys: None,
}
}
fn inner(&self) -> &MapEvent {
unsafe { self.inner.as_ref().unwrap() }
}
fn txn(&self) -> &TransactionMut {
unsafe { self.txn.as_ref().unwrap() }
}
}
#[pymethods]
impl YMapEvent {
/// Returns a current shared type instance, that current event changes refer to.
#[getter]
pub fn target(&mut self) -> PyObject {
if let Some(target) = self.target.as_ref() {
target.clone()
} else {
let target: PyObject = Python::with_gil(|py| {
let target = self.inner().target().clone();
target.with_doc(self.doc.clone()).into_py(py)
});
self.target = Some(target.clone());
target
}
}
pub fn __repr__(&mut self) -> String {
let target = self.target();
let keys = self.keys();
let path = self.path();
format!("YMapEvent(target={target}, keys={keys}, path={path})")
}
/// Returns an array of keys and indexes creating a path from root type down to current instance
/// of shared type (accessible via `target` getter).
pub fn path(&self) -> PyObject {
Python::with_gil(|py| self.inner().path().into_py(py))
}
// Returns a list of key-value changes made over corresponding `YMap` collection within
// bounds of current transaction. These changes follow a format:
//
// / - { action: 'add'|'update'|'delete', oldValue: any|undefined, newValue: any|undefined }
#[getter]
pub fn keys(&mut self) -> PyObject {
if let Some(keys) = &self.keys {
keys.clone()
} else {
let keys: PyObject = Python::with_gil(|py| {
let keys = self.inner().keys(self.txn());
let result = PyDict::new(py);
for (key, value) in keys.iter() {
let key = &**key;
result
.set_item(key, value.with_doc_into_py(self.doc.clone(), py))
.unwrap();
}
result.into()
});
self.keys = Some(keys.clone());
keys
}
}
}