loro_internal/utils/
subscription.rs

1/*
2This file is modified from the original file in the following repo:
3https://github.com/zed-industries/zed
4
5
6Copyright 2022 - 2024 Zed Industries, Inc.
7
8   Licensed under the Apache License, Version 2.0 (the "License");
9   you may not use this file except in compliance with the License.
10   You may obtain a copy of the License at
11
12
13       http://www.apache.org/licenses/LICENSE-2.0
14
15
16   Unless required by applicable law or agreed to in writing, software
17   distributed under the License is distributed on an "AS IS" BASIS,
18   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   See the License for the specific language governing permissions and
20   limitations under the License.
21
22
23
24
25Apache License
26                           Version 2.0, January 2004
27                        http://www.apache.org/licenses/
28
29
30   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
31
32
33   1. Definitions.
34
35
36      "License" shall mean the terms and conditions for use, reproduction,
37      and distribution as defined by Sections 1 through 9 of this document.
38
39
40      "Licensor" shall mean the copyright owner or entity authorized by
41      the copyright owner that is granting the License.
42
43
44      "Legal Entity" shall mean the union of the acting entity and all
45      other entities that control, are controlled by, or are under common
46      control with that entity. For the purposes of this definition,
47      "control" means (i) the power, direct or indirect, to cause the
48      direction or management of such entity, whether by contract or
49      otherwise, or (ii) ownership of fifty percent (50%) or more of the
50      outstanding shares, or (iii) beneficial ownership of such entity.
51
52
53      "You" (or "Your") shall mean an individual or Legal Entity
54      exercising permissions granted by this License.
55
56
57      "Source" form shall mean the preferred form for making modifications,
58      including but not limited to software source code, documentation
59      source, and configuration files.
60
61
62      "Object" form shall mean any form resulting from mechanical
63      transformation or translation of a Source form, including but
64      not limited to compiled object code, generated documentation,
65      and conversions to other media types.
66
67
68      "Work" shall mean the work of authorship, whether in Source or
69      Object form, made available under the License, as indicated by a
70      copyright notice that is included in or attached to the work
71      (an example is provided in the Appendix below).
72
73
74      "Derivative Works" shall mean any work, whether in Source or Object
75      form, that is based on (or derived from) the Work and for which the
76      editorial revisions, annotations, elaborations, or other modifications
77      represent, as a whole, an original work of authorship. For the purposes
78      of this License, Derivative Works shall not include works that remain
79      separable from, or merely link (or bind by name) to the interfaces of,
80      the Work and Derivative Works thereof.
81
82
83      "Contribution" shall mean any work of authorship, including
84      the original version of the Work and any modifications or additions
85      to that Work or Derivative Works thereof, that is intentionally
86      submitted to Licensor for inclusion in the Work by the copyright owner
87      or by an individual or Legal Entity authorized to submit on behalf of
88      the copyright owner. For the purposes of this definition, "submitted"
89      means any form of electronic, verbal, or written communication sent
90      to the Licensor or its representatives, including but not limited to
91      communication on electronic mailing lists, source code control systems,
92      and issue tracking systems that are managed by, or on behalf of, the
93      Licensor for the purpose of discussing and improving the Work, but
94      excluding communication that is conspicuously marked or otherwise
95      designated in writing by the copyright owner as "Not a Contribution."
96
97
98      "Contributor" shall mean Licensor and any individual or Legal Entity
99      on behalf of whom a Contribution has been received by Licensor and
100      subsequently incorporated within the Work.
101
102
103   2. Grant of Copyright License. Subject to the terms and conditions of
104      this License, each Contributor hereby grants to You a perpetual,
105      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
106      copyright license to reproduce, prepare Derivative Works of,
107      publicly display, publicly perform, sublicense, and distribute the
108      Work and such Derivative Works in Source or Object form.
109
110
111   3. Grant of Patent License. Subject to the terms and conditions of
112      this License, each Contributor hereby grants to You a perpetual,
113      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
114      (except as stated in this section) patent license to make, have made,
115      use, offer to sell, sell, import, and otherwise transfer the Work,
116      where such license applies only to those patent claims licensable
117      by such Contributor that are necessarily infringed by their
118      Contribution(s) alone or by combination of their Contribution(s)
119      with the Work to which such Contribution(s) was submitted. If You
120      institute patent litigation against any entity (including a
121      cross-claim or counterclaim in a lawsuit) alleging that the Work
122      or a Contribution incorporated within the Work constitutes direct
123      or contributory patent infringement, then any patent licenses
124      granted to You under this License for that Work shall terminate
125      as of the date such litigation is filed.
126
127
128   4. Redistribution. You may reproduce and distribute copies of the
129      Work or Derivative Works thereof in any medium, with or without
130      modifications, and in Source or Object form, provided that You
131      meet the following conditions:
132
133
134      (a) You must give any other recipients of the Work or
135          Derivative Works a copy of this License; and
136
137
138      (b) You must cause any modified files to carry prominent notices
139          stating that You changed the files; and
140
141
142      (c) You must retain, in the Source form of any Derivative Works
143          that You distribute, all copyright, patent, trademark, and
144          attribution notices from the Source form of the Work,
145          excluding those notices that do not pertain to any part of
146          the Derivative Works; and
147
148
149      (d) If the Work includes a "NOTICE" text file as part of its
150          distribution, then any Derivative Works that You distribute must
151          include a readable copy of the attribution notices contained
152          within such NOTICE file, excluding those notices that do not
153          pertain to any part of the Derivative Works, in at least one
154          of the following places: within a NOTICE text file distributed
155          as part of the Derivative Works; within the Source form or
156          documentation, if provided along with the Derivative Works; or,
157          within a display generated by the Derivative Works, if and
158          wherever such third-party notices normally appear. The contents
159          of the NOTICE file are for informational purposes only and
160          do not modify the License. You may add Your own attribution
161          notices within Derivative Works that You distribute, alongside
162          or as an addendum to the NOTICE text from the Work, provided
163          that such additional attribution notices cannot be construed
164          as modifying the License.
165
166
167      You may add Your own copyright statement to Your modifications and
168      may provide additional or different license terms and conditions
169      for use, reproduction, or distribution of Your modifications, or
170      for any such Derivative Works as a whole, provided Your use,
171      reproduction, and distribution of the Work otherwise complies with
172      the conditions stated in this License.
173
174
175   5. Submission of Contributions. Unless You explicitly state otherwise,
176      any Contribution intentionally submitted for inclusion in the Work
177      by You to the Licensor shall be under the terms and conditions of
178      this License, without any additional terms or conditions.
179      Notwithstanding the above, nothing herein shall supersede or modify
180      the terms of any separate license agreement you may have executed
181      with Licensor regarding such Contributions.
182
183
184   6. Trademarks. This License does not grant permission to use the trade
185      names, trademarks, service marks, or product names of the Licensor,
186      except as required for reasonable and customary use in describing the
187      origin of the Work and reproducing the content of the NOTICE file.
188
189
190   7. Disclaimer of Warranty. Unless required by applicable law or
191      agreed to in writing, Licensor provides the Work (and each
192      Contributor provides its Contributions) on an "AS IS" BASIS,
193      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
194      implied, including, without limitation, any warranties or conditions
195      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
196      PARTICULAR PURPOSE. You are solely responsible for determining the
197      appropriateness of using or redistributing the Work and assume any
198      risks associated with Your exercise of permissions under this License.
199
200
201   8. Limitation of Liability. In no event and under no legal theory,
202      whether in tort (including negligence), contract, or otherwise,
203      unless required by applicable law (such as deliberate and grossly
204      negligent acts) or agreed to in writing, shall any Contributor be
205      liable to You for damages, including any direct, indirect, special,
206      incidental, or consequential damages of any character arising as a
207      result of this License or out of the use or inability to use the
208      Work (including but not limited to damages for loss of goodwill,
209      work stoppage, computer failure or malfunction, or any and all
210      other commercial damages or losses), even if such Contributor
211      has been advised of the possibility of such damages.
212
213
214   9. Accepting Warranty or Additional Liability. While redistributing
215      the Work or Derivative Works thereof, You may choose to offer,
216      and charge a fee for, acceptance of support, warranty, indemnity,
217      or other liability obligations and/or rights consistent with this
218      License. However, in accepting such obligations, You may act only
219      on Your own behalf and on Your sole responsibility, not on behalf
220      of any other Contributor, and only if You agree to indemnify,
221      defend, and hold each Contributor harmless for any liability
222      incurred by, or claims asserted against, such Contributor by reason
223      of your accepting any such warranty or additional liability.
224
225
226   END OF TERMS AND CONDITIONS
227
228*/
229use smallvec::SmallVec;
230use std::collections::{BTreeMap, BTreeSet};
231use std::sync::atomic::{AtomicBool, Ordering};
232use std::sync::{Mutex, Weak};
233use std::{fmt::Debug, mem, sync::Arc};
234
235#[derive(Debug)]
236pub enum SubscriptionError {
237    CannotEmitEventDueToRecursiveCall,
238}
239
240impl std::fmt::Display for Subscription {
241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        write!(f, "SubscriptionError")
243    }
244}
245
246pub(crate) struct SubscriberSet<EmitterKey, Callback>(
247    Arc<Mutex<SubscriberSetState<EmitterKey, Callback>>>,
248);
249
250impl<EmitterKey, Callback> Clone for SubscriberSet<EmitterKey, Callback> {
251    fn clone(&self) -> Self {
252        SubscriberSet(self.0.clone())
253    }
254}
255
256struct SubscriberSetState<EmitterKey, Callback> {
257    subscribers: BTreeMap<EmitterKey, Option<BTreeMap<usize, Subscriber<Callback>>>>,
258    dropped_subscribers: BTreeSet<(EmitterKey, usize)>,
259    next_subscriber_id: usize,
260}
261
262struct Subscriber<Callback> {
263    active: Arc<AtomicBool>,
264    callback: Callback,
265    /// This field is used to drop the subscription when the subscriber is dropped.
266    _sub: InnerSubscription,
267}
268
269impl<EmitterKey, Callback> SubscriberSet<EmitterKey, Callback>
270where
271    EmitterKey: 'static + Ord + Clone + Debug + Send + Sync,
272    Callback: 'static + Send + Sync,
273{
274    pub fn new() -> Self {
275        Self(Arc::new(Mutex::new(SubscriberSetState {
276            subscribers: Default::default(),
277            dropped_subscribers: Default::default(),
278            next_subscriber_id: 0,
279        })))
280    }
281
282    /// Inserts a new [`Subscription`] for the given `emitter_key`. By default, subscriptions
283    /// are inert, meaning that they won't be listed when calling `[SubscriberSet::remove]` or `[SubscriberSet::retain]`.
284    /// This method returns a tuple of a [`Subscription`] and an `impl FnOnce`, and you can use the latter
285    /// to activate the [`Subscription`].
286    pub fn insert(
287        &self,
288        emitter_key: EmitterKey,
289        callback: Callback,
290    ) -> (Subscription, impl FnOnce()) {
291        let active = Arc::new(AtomicBool::new(false));
292        let mut lock = self.0.try_lock().unwrap();
293        let subscriber_id = post_inc(&mut lock.next_subscriber_id);
294        let this = Arc::downgrade(&self.0);
295        let emitter_key_1 = emitter_key.clone();
296        let inner_sub = InnerSubscription {
297            unsubscribe: Arc::new(Mutex::new(Some(Box::new(move || {
298                let Some(this) = this.upgrade() else {
299                    return;
300                };
301
302                let mut lock = this.try_lock().unwrap();
303                let Some(subscribers) = lock.subscribers.get_mut(&emitter_key) else {
304                    // remove was called with this emitter_key
305                    return;
306                };
307
308                if let Some(subscribers) = subscribers {
309                    subscribers.remove(&subscriber_id);
310                    if subscribers.is_empty() {
311                        lock.subscribers.remove(&emitter_key);
312                    }
313                    return;
314                }
315
316                // We didn't manage to remove the subscription, which means it was dropped
317                // while invoking the callback. Mark it as dropped so that we can remove it
318                // later.
319                lock.dropped_subscribers
320                    .insert((emitter_key, subscriber_id));
321            })))),
322        };
323        let subscription = Subscription {
324            unsubscribe: Arc::downgrade(&inner_sub.unsubscribe),
325        };
326
327        lock.subscribers
328            .entry(emitter_key_1)
329            .or_default()
330            .get_or_insert_with(Default::default)
331            .insert(
332                subscriber_id,
333                Subscriber {
334                    active: active.clone(),
335                    callback,
336                    _sub: inner_sub,
337                },
338            );
339        (subscription, move || active.store(true, Ordering::Relaxed))
340    }
341
342    #[allow(unused)]
343    pub fn remove(&self, emitter: &EmitterKey) -> impl IntoIterator<Item = Callback> {
344        let mut lock = self.0.try_lock().unwrap();
345        let subscribers = lock.subscribers.remove(emitter);
346        subscribers
347            .unwrap_or_default()
348            .map(|s| s.into_values())
349            .into_iter()
350            .flatten()
351            .filter_map(|subscriber| {
352                if subscriber.active.load(Ordering::Relaxed) {
353                    Some(subscriber.callback)
354                } else {
355                    None
356                }
357            })
358    }
359
360    pub fn is_recursive_calling(&self, emitter: &EmitterKey) -> bool {
361        if let Some(set) = self.0.try_lock().unwrap().subscribers.get(emitter) {
362            set.is_none()
363        } else {
364            false
365        }
366    }
367
368    /// Call the given callback for each subscriber to the given emitter.
369    /// If the callback returns false, the subscriber is removed.
370    pub fn retain(
371        &self,
372        emitter: &EmitterKey,
373        f: &mut dyn FnMut(&mut Callback) -> bool,
374    ) -> Result<(), SubscriptionError> {
375        let mut subscribers = {
376            let mut subscriber_set_state = self.0.try_lock().unwrap();
377            let Some(set) = subscriber_set_state.subscribers.get_mut(emitter) else {
378                return Ok(());
379            };
380            let Some(inner) = set.take() else {
381                return Err(SubscriptionError::CannotEmitEventDueToRecursiveCall);
382            };
383            inner
384        };
385
386        subscribers.retain(|_, subscriber| {
387            if subscriber.active.load(Ordering::Relaxed) {
388                f(&mut subscriber.callback)
389            } else {
390                true
391            }
392        });
393        let mut lock = self.0.try_lock().unwrap();
394
395        // Add any new subscribers that were added while invoking the callback.
396        if let Some(Some(new_subscribers)) = lock.subscribers.remove(emitter) {
397            subscribers.extend(new_subscribers);
398        }
399
400        // Remove any dropped subscriptions that were dropped while invoking the callback.
401        for (dropped_emitter, dropped_subscription_id) in mem::take(&mut lock.dropped_subscribers) {
402            debug_assert_eq!(*emitter, dropped_emitter);
403            subscribers.remove(&dropped_subscription_id);
404        }
405
406        if !subscribers.is_empty() {
407            lock.subscribers.insert(emitter.clone(), Some(subscribers));
408        }
409
410        Ok(())
411    }
412
413    pub fn is_empty(&self) -> bool {
414        self.0.try_lock().unwrap().subscribers.is_empty()
415    }
416
417    pub fn may_include(&self, emitter: &EmitterKey) -> bool {
418        self.0.try_lock().unwrap().subscribers.contains_key(emitter)
419    }
420}
421
422fn post_inc(next_subscriber_id: &mut usize) -> usize {
423    let ans = *next_subscriber_id;
424    *next_subscriber_id += 1;
425    ans
426}
427type Callback = Box<dyn FnOnce() + 'static + Send + Sync>;
428
429/// A handle to a subscription created by GPUI. When dropped, the subscription
430/// is cancelled and the callback will no longer be invoked.
431#[must_use]
432pub struct Subscription {
433    unsubscribe: Weak<Mutex<Option<Callback>>>,
434}
435
436impl std::fmt::Debug for Subscription {
437    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
438        f.debug_struct("Subscription").finish()
439    }
440}
441
442impl Subscription {
443    /// Detaches the subscription from this handle. The callback will
444    /// continue to be invoked until the doc has been subscribed to
445    /// are dropped
446    pub fn detach(self) {
447        if let Some(unsubscribe) = self.unsubscribe.upgrade() {
448            unsubscribe.lock().unwrap().take();
449        }
450    }
451
452    /// Unsubscribes the subscription.
453    #[inline]
454    pub fn unsubscribe(self) {
455        drop(self)
456    }
457}
458
459impl Drop for Subscription {
460    fn drop(&mut self) {
461        if let Some(unsubscribe) = self.unsubscribe.upgrade() {
462            let unsubscribe = unsubscribe.lock().unwrap().take();
463            if let Some(unsubscribe) = unsubscribe {
464                unsubscribe();
465            }
466        }
467    }
468}
469
470struct InnerSubscription {
471    unsubscribe: Arc<Mutex<Option<Callback>>>,
472}
473
474impl Drop for InnerSubscription {
475    fn drop(&mut self) {
476        self.unsubscribe.lock().unwrap().take();
477    }
478}
479
480/// A wrapper around `SubscriberSet` that automatically handles recursive event emission.
481///
482/// This struct differs from `SubscriberSet` in the following ways:
483/// 1. It automatically handles the `CannotEmitEventDueToRecursiveCall` error that can occur in `SubscriberSet`.
484/// 2. When a recursive event emission is detected, it queues the event instead of throwing an error.
485/// 3. After the current event processing is complete, it automatically processes the queued events.
486///
487/// This behavior ensures that all events are processed in the order they were emitted, even in cases
488/// where recursive event emission would normally cause an error.
489pub(crate) struct SubscriberSetWithQueue<EmitterKey, Callback, Payload> {
490    subscriber_set: SubscriberSet<EmitterKey, Callback>,
491    queue: Arc<Mutex<BTreeMap<EmitterKey, Vec<Payload>>>>,
492}
493
494pub(crate) struct WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> {
495    subscriber_set: Weak<Mutex<SubscriberSetState<EmitterKey, Callback>>>,
496    queue: Weak<Mutex<BTreeMap<EmitterKey, Vec<Payload>>>>,
497}
498
499impl<EmitterKey, Callback, Payload> WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> {
500    pub fn upgrade(self) -> Option<SubscriberSetWithQueue<EmitterKey, Callback, Payload>> {
501        Some(SubscriberSetWithQueue {
502            subscriber_set: SubscriberSet(self.subscriber_set.upgrade()?),
503            queue: self.queue.upgrade()?,
504        })
505    }
506}
507
508impl<EmitterKey, Callback, Payload> SubscriberSetWithQueue<EmitterKey, Callback, Payload>
509where
510    EmitterKey: 'static + Ord + Clone + Debug + Send + Sync,
511    Callback: 'static + Send + Sync + for<'a> FnMut(&'a Payload) -> bool,
512    Payload: Send + Sync + Debug,
513{
514    pub fn new() -> Self {
515        Self {
516            subscriber_set: SubscriberSet::new(),
517            queue: Arc::new(Mutex::new(Default::default())),
518        }
519    }
520
521    pub fn downgrade(&self) -> WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> {
522        WeakSubscriberSetWithQueue {
523            subscriber_set: Arc::downgrade(&self.subscriber_set.0),
524            queue: Arc::downgrade(&self.queue),
525        }
526    }
527
528    pub fn inner(&self) -> &SubscriberSet<EmitterKey, Callback> {
529        &self.subscriber_set
530    }
531
532    pub(crate) fn emit(&self, key: &EmitterKey, payload: Payload) {
533        let mut pending_events: SmallVec<[Payload; 1]> = SmallVec::new();
534        pending_events.push(payload);
535        while let Some(payload) = pending_events.pop() {
536            let result = self
537                .subscriber_set
538                .retain(key, &mut |callback| (callback)(&payload));
539            match result {
540                Ok(_) => {
541                    let mut queue = self.queue.try_lock().unwrap();
542                    if let Some(new_pending_events) = queue.remove(key) {
543                        pending_events.extend(new_pending_events);
544                    }
545                }
546                Err(SubscriptionError::CannotEmitEventDueToRecursiveCall) => {
547                    let mut queue = self.queue.try_lock().unwrap();
548                    queue.entry(key.clone()).or_default().push(payload);
549                }
550            }
551        }
552    }
553}
554
555#[cfg(test)]
556mod test {
557    use super::*;
558
559    #[test]
560    fn test_inner_subscription_drop() {
561        let subscriber_set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new();
562        let (subscription, activate) = subscriber_set.insert(1, Box::new(move |_: &i32| true));
563        activate();
564        drop(subscriber_set);
565        assert!(subscription.unsubscribe.upgrade().is_none());
566    }
567
568    #[test]
569    fn test_inner_subscription_drop_2() {
570        let subscriber_set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new();
571        let (subscription, activate) = subscriber_set.insert(1, Box::new(move |_: &i32| false));
572        activate();
573        subscriber_set
574            .retain(&1, &mut |callback| callback(&1))
575            .unwrap();
576        assert!(subscription.unsubscribe.upgrade().is_none());
577    }
578}