forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

awareness.rs873 lines, 27.1 KiBHistoryRawDownload
1//! Ephemeral presence utilities.
2//!
3//! `EphemeralStore` is the recommended API: a timestamped, last-write-wins key-value
4//! store for transient presence data (cursors, selections, etc.). It supports:
5//! - Per-key timeouts: expired entries are skipped by `encode`/`encode_all` and removed
6//! by `remove_outdated`.
7//! - Import/export via `encode`/`apply` for syncing between peers.
8//! - Subscriptions for both local updates (raw bytes to send) and merged updates.
9//!
10//! The legacy `Awareness` type remains for backward compatibility but is deprecated in
11//! favor of `EphemeralStore`.
12use crate::sync::Mutex;
13use std::sync::atomic::AtomicI64;
14use std::sync::Arc;
15
16use loro_common::{LoroValue, PeerID};
17use rustc_hash::FxHashMap;
18use serde::de::{DeserializeSeed, EnumAccess, MapAccess, SeqAccess, VariantAccess};
19use serde::{Deserialize, Deserializer, Serialize};
20
21use crate::change::{get_sys_timestamp, Timestamp};
22use crate::{SubscriberSetWithQueue, Subscription};
23
24/// `Awareness` is a structure that tracks the ephemeral state of peers.
25///
26/// It can be used to synchronize cursor positions, selections, and the names of the peers.
27///
28/// The state of a specific peer is expected to be removed after a specified timeout. Use
29/// `remove_outdated` to eliminate outdated states.
30#[derive(Debug, Clone)]
31#[deprecated(since = "1.4.6", note = "Use `EphemeralStore` instead.")]
32pub struct Awareness {
33 peer: PeerID,
34 peers: FxHashMap<PeerID, PeerInfo>,
35 timeout: i64,
36}
37
38#[derive(Debug, Clone)]
39pub struct PeerInfo {
40 pub state: LoroValue,
41 pub counter: i32,
42 // This field is generated locally
43 pub timestamp: i64,
44}
45
46#[derive(Serialize, Deserialize)]
47struct EncodedPeerInfo {
48 peer: PeerID,
49 counter: i32,
50 record: LoroValue,
51}
52
53#[derive(Deserialize)]
54struct DecodedPeerInfo {
55 peer: PeerID,
56 counter: i32,
57 #[serde(deserialize_with = "deserialize_depth_limited_loro_value")]
58 record: LoroValue,
59}
60
61#[allow(deprecated)]
62impl Awareness {
63 pub fn new(peer: PeerID, timeout: i64) -> Awareness {
64 Awareness {
65 peer,
66 timeout,
67 peers: FxHashMap::default(),
68 }
69 }
70
71 pub fn encode(&self, peers: &[PeerID]) -> Vec<u8> {
72 let mut peers_info = Vec::new();
73 let now = get_sys_timestamp() as Timestamp;
74 for peer in peers {
75 if let Some(peer_info) = self.peers.get(peer) {
76 if now - peer_info.timestamp > self.timeout {
77 continue;
78 }
79
80 let encoded_peer_info = EncodedPeerInfo {
81 peer: *peer,
82 record: peer_info.state.clone(),
83 counter: peer_info.counter,
84 };
85 peers_info.push(encoded_peer_info);
86 }
87 }
88
89 postcard::to_allocvec(&peers_info).unwrap()
90 }
91
92 pub fn encode_all(&self) -> Vec<u8> {
93 let mut peers_info = Vec::new();
94 let now = get_sys_timestamp() as Timestamp;
95 for (peer, peer_info) in self.peers.iter() {
96 if now - peer_info.timestamp > self.timeout {
97 continue;
98 }
99
100 let encoded_peer_info = EncodedPeerInfo {
101 peer: *peer,
102 record: peer_info.state.clone(),
103 counter: peer_info.counter,
104 };
105 peers_info.push(encoded_peer_info);
106 }
107
108 postcard::to_allocvec(&peers_info).unwrap()
109 }
110
111 /// Try to apply encoded updates imported from another peer/process.
112 ///
113 /// Returns (updated, added).
114 pub fn try_apply(
115 &mut self,
116 encoded_peers_info: &[u8],
117 ) -> Result<(Vec<PeerID>, Vec<PeerID>), Box<str>> {
118 let peers_info: Vec<DecodedPeerInfo> = postcard::from_bytes(encoded_peers_info)
119 .map_err(|err| format!("Failed to decode awareness data: {err}").into_boxed_str())?;
120 let mut changed_peers = Vec::new();
121 let mut added_peers = Vec::new();
122 let now = get_sys_timestamp() as Timestamp;
123 for peer_info in peers_info {
124 match self.peers.get(&peer_info.peer) {
125 Some(x) if x.counter >= peer_info.counter || peer_info.peer == self.peer => {
126 // do nothing
127 }
128 _ => {
129 let old = self.peers.insert(
130 peer_info.peer,
131 PeerInfo {
132 counter: peer_info.counter,
133 state: peer_info.record,
134 timestamp: now,
135 },
136 );
137 if old.is_some() {
138 changed_peers.push(peer_info.peer);
139 } else {
140 added_peers.push(peer_info.peer);
141 }
142 }
143 }
144 }
145
146 Ok((changed_peers, added_peers))
147 }
148
149 /// Returns (updated, added)
150 pub fn apply(&mut self, encoded_peers_info: &[u8]) -> (Vec<PeerID>, Vec<PeerID>) {
151 self.try_apply(encoded_peers_info)
152 .expect("Failed to decode awareness data")
153 }
154
155 pub fn set_local_state(&mut self, value: impl Into<LoroValue>) {
156 self._set_local_state(value.into());
157 }
158
159 fn _set_local_state(&mut self, value: LoroValue) {
160 let peer = self.peers.entry(self.peer).or_insert_with(|| PeerInfo {
161 state: Default::default(),
162 counter: 0,
163 timestamp: 0,
164 });
165
166 peer.state = value;
167 peer.counter += 1;
168 peer.timestamp = get_sys_timestamp() as Timestamp;
169 }
170
171 pub fn get_local_state(&self) -> Option<LoroValue> {
172 self.peers.get(&self.peer).map(|x| x.state.clone())
173 }
174
175 pub fn remove_outdated(&mut self) -> Vec<PeerID> {
176 let now = get_sys_timestamp() as Timestamp;
177 let mut removed = Vec::new();
178 self.peers.retain(|id, v| {
179 if now - v.timestamp > self.timeout {
180 removed.push(*id);
181 false
182 } else {
183 true
184 }
185 });
186
187 removed
188 }
189
190 pub fn get_all_states(&self) -> &FxHashMap<PeerID, PeerInfo> {
191 &self.peers
192 }
193
194 pub fn peer(&self) -> PeerID {
195 self.peer
196 }
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200pub enum EphemeralEventTrigger {
201 Local,
202 Import,
203 Timeout,
204}
205
206#[derive(Debug, Clone)]
207pub struct EphemeralStoreEvent {
208 pub by: EphemeralEventTrigger,
209 pub added: Arc<Vec<String>>,
210 pub updated: Arc<Vec<String>>,
211 pub removed: Arc<Vec<String>>,
212}
213
214pub type LocalEphemeralCallback = Box<dyn Fn(&Vec<u8>) -> bool + Send + Sync + 'static>;
215pub type EphemeralSubscriber = Box<dyn Fn(&EphemeralStoreEvent) -> bool + Send + Sync + 'static>;
216
217/// `EphemeralStore` is a structure that tracks ephemeral key-value state across peers.
218///
219/// - Use it for syncing lightweight presence/state like cursors, selections, and UI hints.
220/// - Each key uses timestamp-based LWW (Last-Write-Wins) conflict resolution.
221/// - Timeout unit: milliseconds.
222/// - After timeout: entries are considered expired. They are omitted from
223/// `encode`/`encode_all`, and calling [`remove_outdated`] will purge them and
224/// notify subscribers with `EphemeralEventTrigger::Timeout`.
225///
226/// In Rust, you are responsible for periodically calling [`remove_outdated`]
227/// if you want timed-out entries to be removed and corresponding events to be
228/// emitted. In the WASM/TS wrapper, a timer runs automatically while the store
229/// is non-empty.
230///
231/// See: https://loro.dev/docs/tutorial/ephemeral
232///
233/// # Example
234///
235/// ```rust
236/// use loro_internal::awareness::EphemeralStore;
237///
238/// let mut store = EphemeralStore::new(1000);
239/// store.set("key", "value");
240/// let encoded = store.encode("key");
241/// let mut store2 = EphemeralStore::new(1000);
242/// store.subscribe_local_updates(Box::new(|data| {
243/// println!("local update: {:?}", data);
244/// true
245/// }));
246/// store2.apply(&encoded);
247/// assert_eq!(store2.get("key"), Some("value".into()));
248/// ```
249#[derive(Debug, Clone)]
250pub struct EphemeralStore {
251 inner: Arc<EphemeralStoreInner>,
252}
253
254impl EphemeralStore {
255 /// Create a new `EphemeralStore`.
256 ///
257 /// - `timeout`: inactivity timeout in milliseconds. If a key does not
258 /// receive updates within this duration, it is considered expired. It
259 /// will be skipped by `encode`/`encode_all`, and removed when
260 /// [`remove_outdated`] is called (triggering a `Timeout` event to
261 /// subscribers).
262 pub fn new(timeout: i64) -> Self {
263 Self {
264 inner: Arc::new(EphemeralStoreInner::new(timeout)),
265 }
266 }
267
268 /// Encode the latest value of `key`.
269 ///
270 /// Expired keys (past timeout) are omitted and produce an empty payload.
271 pub fn encode(&self, key: &str) -> Vec<u8> {
272 self.inner.encode(key)
273 }
274
275 /// Encode all non-expired keys.
276 ///
277 /// Entries that have exceeded the timeout are not included in the payload.
278 pub fn encode_all(&self) -> Vec<u8> {
279 self.inner.encode_all()
280 }
281
282 /// Apply encoded updates imported from another peer/process.
283 ///
284 /// Subscribers receive an event with `by = Import` and the lists of
285 /// `added`/`updated`/`removed` keys as appropriate.
286 pub fn apply(&self, data: &[u8]) -> Result<(), Box<str>> {
287 self.inner.apply(data)
288 }
289
290 pub fn set(&self, key: &str, value: impl Into<LoroValue>) {
291 self.inner.set(key, value)
292 }
293
294 pub fn delete(&self, key: &str) {
295 self.inner.delete(key)
296 }
297
298 pub fn get(&self, key: &str) -> Option<LoroValue> {
299 self.inner.get(key)
300 }
301
302 /// Remove entries whose last update timestamp has exceeded the timeout.
303 ///
304 /// If any keys are removed, subscribers receive an event with
305 /// `by = Timeout` and the `removed` keys. This does not run automatically
306 /// in Rust; call it on your own schedule.
307 pub fn remove_outdated(&self) {
308 self.inner.remove_outdated()
309 }
310
311 pub fn get_all_states(&self) -> FxHashMap<String, LoroValue> {
312 self.inner.get_all_states()
313 }
314
315 pub fn keys(&self) -> Vec<String> {
316 self.inner.keys()
317 }
318
319 /// Subscribe to local ephemeral/awareness updates.
320 ///
321 /// The callback receives encoded update bytes whenever local ephemeral state changes.
322 /// This is useful for syncing awareness information like cursor positions, selections,
323 /// or presence data to other peers in real-time.
324 ///
325 /// **Auto-unsubscription**: If the callback returns `false`, the subscription will be
326 /// automatically removed, providing a convenient way to implement one-time or conditional
327 /// subscriptions in Rust.
328 ///
329 /// # Parameters
330 /// - `callback`: Function that receives `&Vec<u8>` (encoded ephemeral updates) and returns `bool`
331 /// - Return `true` to keep the subscription active
332 /// - Return `false` to automatically unsubscribe
333 ///
334 /// # Example
335 /// ```rust
336 /// use loro_internal::awareness::EphemeralStore;
337 /// use std::sync::{Arc, Mutex};
338 ///
339 /// let store = EphemeralStore::new(30000);
340 /// let update_count = Arc::new(Mutex::new(0));
341 /// let count_clone = update_count.clone();
342 ///
343 /// // Subscribe and collect first 3 updates, then auto-unsubscribe
344 /// let sub = store.subscribe_local_updates(Box::new(move |bytes| {
345 /// println!("Received {} bytes of ephemeral data", bytes.len());
346 /// let mut count = count_clone.lock().unwrap();
347 /// *count += 1;
348 /// *count < 3 // Auto-unsubscribe after 3 updates
349 /// }));
350 ///
351 /// store.set("cursor", 42);
352 /// ```
353 pub fn subscribe_local_updates(&self, callback: LocalEphemeralCallback) -> Subscription {
354 self.inner.subscribe_local_updates(callback)
355 }
356
357 pub fn subscribe(&self, callback: EphemeralSubscriber) -> Subscription {
358 self.inner.subscribe(callback)
359 }
360}
361
362struct EphemeralStoreInner {
363 states: Mutex<FxHashMap<String, State>>,
364 local_subs: SubscriberSetWithQueue<(), LocalEphemeralCallback, Vec<u8>>,
365 subscribers: SubscriberSetWithQueue<(), EphemeralSubscriber, EphemeralStoreEvent>,
366 timeout: AtomicI64,
367}
368
369impl std::fmt::Debug for EphemeralStoreInner {
370 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
371 write!(
372 f,
373 "AwarenessV2 {{ states: {:?}, timeout: {:?} }}",
374 self.states, self.timeout
375 )
376 }
377}
378
379#[derive(Serialize, Deserialize)]
380struct EncodedState<'a> {
381 #[serde(borrow)]
382 key: &'a str,
383 value: Option<LoroValue>,
384 timestamp: i64,
385}
386
387#[derive(Deserialize)]
388struct DecodedState<'a> {
389 #[serde(borrow)]
390 key: &'a str,
391 #[serde(deserialize_with = "deserialize_optional_depth_limited_loro_value")]
392 value: Option<LoroValue>,
393 timestamp: i64,
394}
395
396const EPHEMERAL_VALUE_MAX_DEPTH: usize = 512;
397
398fn deserialize_optional_depth_limited_loro_value<'de, D>(
399 deserializer: D,
400) -> Result<Option<LoroValue>, D::Error>
401where
402 D: Deserializer<'de>,
403{
404 Option::<DepthLimitedLoroValue>::deserialize(deserializer)
405 .map(|value| value.map(DepthLimitedLoroValue::into_inner))
406}
407
408fn deserialize_depth_limited_loro_value<'de, D>(deserializer: D) -> Result<LoroValue, D::Error>
409where
410 D: Deserializer<'de>,
411{
412 LoroValueSeed {
413 remaining_depth: EPHEMERAL_VALUE_MAX_DEPTH,
414 }
415 .deserialize(deserializer)
416}
417
418struct DepthLimitedLoroValue(LoroValue);
419
420impl DepthLimitedLoroValue {
421 fn into_inner(self) -> LoroValue {
422 self.0
423 }
424}
425
426impl<'de> Deserialize<'de> for DepthLimitedLoroValue {
427 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
428 where
429 D: Deserializer<'de>,
430 {
431 deserialize_depth_limited_loro_value(deserializer).map(Self)
432 }
433}
434
435#[derive(Clone, Copy)]
436struct LoroValueSeed {
437 remaining_depth: usize,
438}
439
440impl LoroValueSeed {
441 fn nested<E>(self) -> Result<Self, E>
442 where
443 E: serde::de::Error,
444 {
445 let remaining_depth = self
446 .remaining_depth
447 .checked_sub(1)
448 .ok_or_else(|| E::custom("LoroValue nesting depth exceeded"))?;
449 Ok(Self { remaining_depth })
450 }
451}
452
453impl<'de> DeserializeSeed<'de> for LoroValueSeed {
454 type Value = LoroValue;
455
456 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
457 where
458 D: Deserializer<'de>,
459 {
460 if deserializer.is_human_readable() {
461 return Err(serde::de::Error::custom(
462 "human-readable LoroValue is not supported by the awareness decoder",
463 ));
464 }
465
466 deserializer.deserialize_enum(
467 "LoroValue",
468 &[
469 "Null",
470 "Bool",
471 "Double",
472 "I32",
473 "String",
474 "List",
475 "Map",
476 "Container",
477 "Binary",
478 ],
479 LoroValueSeedVisitor { seed: self },
480 )
481 }
482}
483
484struct LoroValueSeedVisitor {
485 seed: LoroValueSeed,
486}
487
488impl<'de> serde::de::Visitor<'de> for LoroValueSeedVisitor {
489 type Value = LoroValue;
490
491 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
492 formatter.write_str("a depth-limited LoroValue")
493 }
494
495 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
496 where
497 A: EnumAccess<'de>,
498 {
499 match data.variant()? {
500 (DepthLimitedLoroValueField::Null, v) => {
501 v.unit_variant()?;
502 Ok(LoroValue::Null)
503 }
504 (DepthLimitedLoroValueField::Bool, v) => v.newtype_variant().map(LoroValue::Bool),
505 (DepthLimitedLoroValueField::Double, v) => v.newtype_variant().map(LoroValue::Double),
506 (DepthLimitedLoroValueField::I32, v) => v.newtype_variant().map(LoroValue::I64),
507 (DepthLimitedLoroValueField::String, v) => v
508 .newtype_variant()
509 .map(|value: String| LoroValue::String(value.into())),
510 (DepthLimitedLoroValueField::List, v) => v
511 .newtype_variant_seed(LoroListSeed {
512 value_seed: self.seed.nested()?,
513 })
514 .map(|value| LoroValue::List(value.into())),
515 (DepthLimitedLoroValueField::Map, v) => v
516 .newtype_variant_seed(LoroMapSeed {
517 value_seed: self.seed.nested()?,
518 })
519 .map(|value| LoroValue::Map(value.into())),
520 (DepthLimitedLoroValueField::Container, v) => {
521 v.newtype_variant().map(LoroValue::Container)
522 }
523 (DepthLimitedLoroValueField::Binary, v) => v
524 .newtype_variant()
525 .map(|value: Vec<u8>| LoroValue::Binary(value.into())),
526 }
527 }
528}
529
530#[derive(Deserialize)]
531enum DepthLimitedLoroValueField {
532 Null,
533 Bool,
534 Double,
535 I32,
536 String,
537 List,
538 Map,
539 Container,
540 Binary,
541}
542
543struct LoroListSeed {
544 value_seed: LoroValueSeed,
545}
546
547impl<'de> DeserializeSeed<'de> for LoroListSeed {
548 type Value = Vec<LoroValue>;
549
550 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
551 where
552 D: Deserializer<'de>,
553 {
554 deserializer.deserialize_seq(LoroListVisitor {
555 value_seed: self.value_seed,
556 })
557 }
558}
559
560struct LoroListVisitor {
561 value_seed: LoroValueSeed,
562}
563
564impl<'de> serde::de::Visitor<'de> for LoroListVisitor {
565 type Value = Vec<LoroValue>;
566
567 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
568 formatter.write_str("a depth-limited LoroValue list")
569 }
570
571 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
572 where
573 A: SeqAccess<'de>,
574 {
575 let mut list = Vec::new();
576 while let Some(value) = seq.next_element_seed(self.value_seed)? {
577 list.push(value);
578 }
579 Ok(list)
580 }
581}
582
583struct LoroMapSeed {
584 value_seed: LoroValueSeed,
585}
586
587impl<'de> DeserializeSeed<'de> for LoroMapSeed {
588 type Value = FxHashMap<String, LoroValue>;
589
590 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
591 where
592 D: Deserializer<'de>,
593 {
594 deserializer.deserialize_map(LoroMapVisitor {
595 value_seed: self.value_seed,
596 })
597 }
598}
599
600struct LoroMapVisitor {
601 value_seed: LoroValueSeed,
602}
603
604impl<'de> serde::de::Visitor<'de> for LoroMapVisitor {
605 type Value = FxHashMap<String, LoroValue>;
606
607 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
608 formatter.write_str("a depth-limited LoroValue map")
609 }
610
611 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
612 where
613 A: MapAccess<'de>,
614 {
615 let mut value = FxHashMap::default();
616 while let Some(key) = map.next_key()? {
617 let entry = map.next_value_seed(self.value_seed)?;
618 value.insert(key, entry);
619 }
620 Ok(value)
621 }
622}
623
624#[derive(Debug, Clone)]
625struct State {
626 state: Option<LoroValue>,
627 timestamp: i64,
628}
629
630impl EphemeralStoreInner {
631 pub fn new(timeout: i64) -> EphemeralStoreInner {
632 EphemeralStoreInner {
633 timeout: AtomicI64::new(timeout),
634 states: Mutex::new(FxHashMap::default()),
635 local_subs: SubscriberSetWithQueue::new(),
636 subscribers: SubscriberSetWithQueue::new(),
637 }
638 }
639
640 pub fn encode(&self, key: &str) -> Vec<u8> {
641 let mut peers_info = Vec::new();
642 let now = get_sys_timestamp() as Timestamp;
643 let states = self.states.lock();
644 if let Some(peer_state) = states.get(key) {
645 if now - peer_state.timestamp > self.timeout.load(std::sync::atomic::Ordering::Relaxed)
646 {
647 return vec![];
648 }
649 let encoded_peer_info = EncodedState {
650 key,
651 value: peer_state.state.clone(),
652 timestamp: peer_state.timestamp,
653 };
654 peers_info.push(encoded_peer_info);
655 }
656
657 postcard::to_allocvec(&peers_info).unwrap()
658 }
659
660 pub fn encode_all(&self) -> Vec<u8> {
661 let mut peers_info = Vec::new();
662 let now = get_sys_timestamp() as Timestamp;
663 let states = self.states.lock();
664 for (key, peer_state) in states.iter() {
665 if now - peer_state.timestamp > self.timeout.load(std::sync::atomic::Ordering::Relaxed)
666 {
667 continue;
668 }
669 let encoded_peer_info = EncodedState {
670 key,
671 value: peer_state.state.clone(),
672 timestamp: peer_state.timestamp,
673 };
674 peers_info.push(encoded_peer_info);
675 }
676 postcard::to_allocvec(&peers_info).unwrap()
677 }
678
679 pub fn apply(&self, data: &[u8]) -> Result<(), Box<str>> {
680 let peers_info = match postcard::from_bytes::<Vec<DecodedState>>(data) {
681 Ok(ans) => ans,
682 Err(err) => return Err(format!("Failed to decode data: {}", err).into()),
683 };
684
685 let mut updated_keys = Vec::new();
686 let mut added_keys = Vec::new();
687 let mut removed_keys = Vec::new();
688 let now = get_sys_timestamp() as Timestamp;
689 let timeout = self.timeout.load(std::sync::atomic::Ordering::Relaxed);
690 let mut states = self.states.lock();
691 for DecodedState {
692 key,
693 value: record,
694 timestamp,
695 } in peers_info
696 {
697 if now - timestamp > timeout {
698 continue;
699 }
700
701 match states.get_mut(key) {
702 Some(peer_info) if peer_info.timestamp >= timestamp => {
703 // do nothing
704 }
705 _ => {
706 let old = states.insert(
707 key.to_string(),
708 State {
709 state: record.clone(),
710 timestamp,
711 },
712 );
713 match (old, record) {
714 (Some(_), Some(_)) => updated_keys.push(key.to_string()),
715 (None, Some(_)) => added_keys.push(key.to_string()),
716 (Some(_), None) => removed_keys.push(key.to_string()),
717 (None, None) => {}
718 }
719 }
720 }
721 }
722
723 drop(states);
724 if !self.subscribers.inner().is_empty() {
725 self.subscribers.emit(
726 &(),
727 EphemeralStoreEvent {
728 by: EphemeralEventTrigger::Import,
729 added: Arc::new(added_keys),
730 updated: Arc::new(updated_keys),
731 removed: Arc::new(removed_keys),
732 },
733 );
734 }
735
736 Ok(())
737 }
738
739 pub fn set(&self, key: &str, value: impl Into<LoroValue>) {
740 self._set_local_state(key, Some(value.into()));
741 }
742
743 pub fn delete(&self, key: &str) {
744 self._set_local_state(key, None);
745 }
746
747 pub fn get(&self, key: &str) -> Option<LoroValue> {
748 let states = self.states.lock();
749 states.get(key).and_then(|x| x.state.clone())
750 }
751
752 pub fn remove_outdated(&self) {
753 let now = get_sys_timestamp() as Timestamp;
754 let mut removed = Vec::new();
755 let mut states = self.states.lock();
756 states.retain(|key, state| {
757 if now - state.timestamp > self.timeout.load(std::sync::atomic::Ordering::Relaxed) {
758 if state.state.is_some() {
759 removed.push(key.clone());
760 }
761 false
762 } else {
763 true
764 }
765 });
766 drop(states);
767 if !self.subscribers.inner().is_empty() {
768 self.subscribers.emit(
769 &(),
770 EphemeralStoreEvent {
771 by: EphemeralEventTrigger::Timeout,
772 added: Arc::new(Vec::new()),
773 updated: Arc::new(Vec::new()),
774 removed: Arc::new(removed),
775 },
776 );
777 }
778 }
779
780 pub fn get_all_states(&self) -> FxHashMap<String, LoroValue> {
781 let states = self.states.lock();
782 states
783 .iter()
784 .filter(|(_, v)| v.state.is_some())
785 .map(|(k, v)| (k.clone(), v.state.clone().unwrap()))
786 .collect()
787 }
788
789 pub fn keys(&self) -> Vec<String> {
790 let states = self.states.lock();
791 states
792 .keys()
793 .filter(|&k| states.get(k).unwrap().state.is_some())
794 .map(|s| s.to_string())
795 .collect()
796 }
797
798 /// Subscribe to local ephemeral state updates.
799 ///
800 /// The callback receives encoded update bytes whenever the local peer's ephemeral state
801 /// is modified. This enables real-time synchronization of awareness data like cursor
802 /// positions, user presence, or temporary collaborative state.
803 ///
804 /// **Auto-unsubscription**: If the callback returns `false`, the subscription will be
805 /// automatically removed, making it easy to implement conditional or temporary subscriptions.
806 ///
807 /// # Parameters
808 /// - `callback`: Function that receives `&Vec<u8>` and returns `bool`
809 /// - Return `true` to maintain the subscription
810 /// - Return `false` to automatically unsubscribe
811 ///
812 /// # Returns
813 /// A `Subscription` that can be used to manually unsubscribe if needed.
814 pub fn subscribe_local_updates(&self, callback: LocalEphemeralCallback) -> Subscription {
815 let (sub, activate) = self.local_subs.inner().insert((), callback);
816 activate();
817 sub
818 }
819
820 pub fn subscribe(&self, callback: EphemeralSubscriber) -> Subscription {
821 let (sub, activate) = self.subscribers.inner().insert((), callback);
822 activate();
823 sub
824 }
825
826 fn _set_local_state(&self, key: &str, value: Option<LoroValue>) {
827 let is_delete = value.is_none();
828 let mut states = self.states.lock();
829 let old = states.insert(
830 key.to_string(),
831 State {
832 state: value,
833 timestamp: get_sys_timestamp() as Timestamp,
834 },
835 );
836
837 drop(states);
838 if !self.local_subs.inner().is_empty() {
839 self.local_subs.emit(&(), self.encode(key));
840 }
841 if !self.subscribers.inner().is_empty() {
842 if old.is_some() {
843 self.subscribers.emit(
844 &(),
845 EphemeralStoreEvent {
846 by: EphemeralEventTrigger::Local,
847 added: Arc::new(Vec::new()),
848 updated: if !is_delete {
849 Arc::new(vec![key.to_string()])
850 } else {
851 Arc::new(Vec::new())
852 },
853 removed: if !is_delete {
854 Arc::new(Vec::new())
855 } else {
856 Arc::new(vec![key.to_string()])
857 },
858 },
859 );
860 } else if !is_delete {
861 self.subscribers.emit(
862 &(),
863 EphemeralStoreEvent {
864 by: EphemeralEventTrigger::Local,
865 added: Arc::new(vec![key.to_string()]),
866 updated: Arc::new(Vec::new()),
867 removed: Arc::new(Vec::new()),
868 },
869 );
870 }
871 }
872 }
873}