Skip to main content

loro_internal/utils/
subscription.rs

1use either::Either;
2/*
3This file is modified from the original file in the following repo:
4https://github.com/zed-industries/zed
5
6
7Copyright 2022 - 2024 Zed Industries, Inc.
8
9   Licensed under the Apache License, Version 2.0 (the "License");
10   you may not use this file except in compliance with the License.
11   You may obtain a copy of the License at
12
13
14       http://www.apache.org/licenses/LICENSE-2.0
15
16
17   Unless required by applicable law or agreed to in writing, software
18   distributed under the License is distributed on an "AS IS" BASIS,
19   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   See the License for the specific language governing permissions and
21   limitations under the License.
22
23
24
25
26Apache License
27                           Version 2.0, January 2004
28                        http://www.apache.org/licenses/
29
30
31   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
32
33
34   1. Definitions.
35
36
37      "License" shall mean the terms and conditions for use, reproduction,
38      and distribution as defined by Sections 1 through 9 of this document.
39
40
41      "Licensor" shall mean the copyright owner or entity authorized by
42      the copyright owner that is granting the License.
43
44
45      "Legal Entity" shall mean the union of the acting entity and all
46      other entities that control, are controlled by, or are under common
47      control with that entity. For the purposes of this definition,
48      "control" means (i) the power, direct or indirect, to cause the
49      direction or management of such entity, whether by contract or
50      otherwise, or (ii) ownership of fifty percent (50%) or more of the
51      outstanding shares, or (iii) beneficial ownership of such entity.
52
53
54      "You" (or "Your") shall mean an individual or Legal Entity
55      exercising permissions granted by this License.
56
57
58      "Source" form shall mean the preferred form for making modifications,
59      including but not limited to software source code, documentation
60      source, and configuration files.
61
62
63      "Object" form shall mean any form resulting from mechanical
64      transformation or translation of a Source form, including but
65      not limited to compiled object code, generated documentation,
66      and conversions to other media types.
67
68
69      "Work" shall mean the work of authorship, whether in Source or
70      Object form, made available under the License, as indicated by a
71      copyright notice that is included in or attached to the work
72      (an example is provided in the Appendix below).
73
74
75      "Derivative Works" shall mean any work, whether in Source or Object
76      form, that is based on (or derived from) the Work and for which the
77      editorial revisions, annotations, elaborations, or other modifications
78      represent, as a whole, an original work of authorship. For the purposes
79      of this License, Derivative Works shall not include works that remain
80      separable from, or merely link (or bind by name) to the interfaces of,
81      the Work and Derivative Works thereof.
82
83
84      "Contribution" shall mean any work of authorship, including
85      the original version of the Work and any modifications or additions
86      to that Work or Derivative Works thereof, that is intentionally
87      submitted to Licensor for inclusion in the Work by the copyright owner
88      or by an individual or Legal Entity authorized to submit on behalf of
89      the copyright owner. For the purposes of this definition, "submitted"
90      means any form of electronic, verbal, or written communication sent
91      to the Licensor or its representatives, including but not limited to
92      communication on electronic mailing lists, source code control systems,
93      and issue tracking systems that are managed by, or on behalf of, the
94      Licensor for the purpose of discussing and improving the Work, but
95      excluding communication that is conspicuously marked or otherwise
96      designated in writing by the copyright owner as "Not a Contribution."
97
98
99      "Contributor" shall mean Licensor and any individual or Legal Entity
100      on behalf of whom a Contribution has been received by Licensor and
101      subsequently incorporated within the Work.
102
103
104   2. Grant of Copyright License. Subject to the terms and conditions of
105      this License, each Contributor hereby grants to You a perpetual,
106      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
107      copyright license to reproduce, prepare Derivative Works of,
108      publicly display, publicly perform, sublicense, and distribute the
109      Work and such Derivative Works in Source or Object form.
110
111
112   3. Grant of Patent License. Subject to the terms and conditions of
113      this License, each Contributor hereby grants to You a perpetual,
114      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
115      (except as stated in this section) patent license to make, have made,
116      use, offer to sell, sell, import, and otherwise transfer the Work,
117      where such license applies only to those patent claims licensable
118      by such Contributor that are necessarily infringed by their
119      Contribution(s) alone or by combination of their Contribution(s)
120      with the Work to which such Contribution(s) was submitted. If You
121      institute patent litigation against any entity (including a
122      cross-claim or counterclaim in a lawsuit) alleging that the Work
123      or a Contribution incorporated within the Work constitutes direct
124      or contributory patent infringement, then any patent licenses
125      granted to You under this License for that Work shall terminate
126      as of the date such litigation is filed.
127
128
129   4. Redistribution. You may reproduce and distribute copies of the
130      Work or Derivative Works thereof in any medium, with or without
131      modifications, and in Source or Object form, provided that You
132      meet the following conditions:
133
134
135      (a) You must give any other recipients of the Work or
136          Derivative Works a copy of this License; and
137
138
139      (b) You must cause any modified files to carry prominent notices
140          stating that You changed the files; and
141
142
143      (c) You must retain, in the Source form of any Derivative Works
144          that You distribute, all copyright, patent, trademark, and
145          attribution notices from the Source form of the Work,
146          excluding those notices that do not pertain to any part of
147          the Derivative Works; and
148
149
150      (d) If the Work includes a "NOTICE" text file as part of its
151          distribution, then any Derivative Works that You distribute must
152          include a readable copy of the attribution notices contained
153          within such NOTICE file, excluding those notices that do not
154          pertain to any part of the Derivative Works, in at least one
155          of the following places: within a NOTICE text file distributed
156          as part of the Derivative Works; within the Source form or
157          documentation, if provided along with the Derivative Works; or,
158          within a display generated by the Derivative Works, if and
159          wherever such third-party notices normally appear. The contents
160          of the NOTICE file are for informational purposes only and
161          do not modify the License. You may add Your own attribution
162          notices within Derivative Works that You distribute, alongside
163          or as an addendum to the NOTICE text from the Work, provided
164          that such additional attribution notices cannot be construed
165          as modifying the License.
166
167
168      You may add Your own copyright statement to Your modifications and
169      may provide additional or different license terms and conditions
170      for use, reproduction, or distribution of Your modifications, or
171      for any such Derivative Works as a whole, provided Your use,
172      reproduction, and distribution of the Work otherwise complies with
173      the conditions stated in this License.
174
175
176   5. Submission of Contributions. Unless You explicitly state otherwise,
177      any Contribution intentionally submitted for inclusion in the Work
178      by You to the Licensor shall be under the terms and conditions of
179      this License, without any additional terms or conditions.
180      Notwithstanding the above, nothing herein shall supersede or modify
181      the terms of any separate license agreement you may have executed
182      with Licensor regarding such Contributions.
183
184
185   6. Trademarks. This License does not grant permission to use the trade
186      names, trademarks, service marks, or product names of the Licensor,
187      except as required for reasonable and customary use in describing the
188      origin of the Work and reproducing the content of the NOTICE file.
189
190
191   7. Disclaimer of Warranty. Unless required by applicable law or
192      agreed to in writing, Licensor provides the Work (and each
193      Contributor provides its Contributions) on an "AS IS" BASIS,
194      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
195      implied, including, without limitation, any warranties or conditions
196      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
197      PARTICULAR PURPOSE. You are solely responsible for determining the
198      appropriateness of using or redistributing the Work and assume any
199      risks associated with Your exercise of permissions under this License.
200
201
202   8. Limitation of Liability. In no event and under no legal theory,
203      whether in tort (including negligence), contract, or otherwise,
204      unless required by applicable law (such as deliberate and grossly
205      negligent acts) or agreed to in writing, shall any Contributor be
206      liable to You for damages, including any direct, indirect, special,
207      incidental, or consequential damages of any character arising as a
208      result of this License or out of the use or inability to use the
209      Work (including but not limited to damages for loss of goodwill,
210      work stoppage, computer failure or malfunction, or any and all
211      other commercial damages or losses), even if such Contributor
212      has been advised of the possibility of such damages.
213
214
215   9. Accepting Warranty or Additional Liability. While redistributing
216      the Work or Derivative Works thereof, You may choose to offer,
217      and charge a fee for, acceptance of support, warranty, indemnity,
218      or other liability obligations and/or rights consistent with this
219      License. However, in accepting such obligations, You may act only
220      on Your own behalf and on Your sole responsibility, not on behalf
221      of any other Contributor, and only if You agree to indemnify,
222      defend, and hold each Contributor harmless for any liability
223      incurred by, or claims asserted against, such Contributor by reason
224      of your accepting any such warranty or additional liability.
225
226
227   END OF TERMS AND CONDITIONS
228
229*/
230use crate::sync::{thread, AtomicBool, Mutex};
231use smallvec::SmallVec;
232use std::collections::{BTreeMap, BTreeSet};
233use std::sync::atomic::Ordering;
234use std::sync::{Arc, Weak};
235use std::{fmt::Debug, mem};
236use thread::ThreadId;
237
238#[derive(Debug)]
239pub enum SubscriptionError {
240    CannotEmitEventDueToRecursiveCall,
241}
242
243impl std::fmt::Display for Subscription {
244    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245        write!(f, "SubscriptionError")
246    }
247}
248
249pub struct SubscriberSet<EmitterKey, Callback>(
250    Arc<Mutex<SubscriberSetState<EmitterKey, Callback>>>,
251);
252
253impl<EmitterKey, Callback> Clone for SubscriberSet<EmitterKey, Callback> {
254    fn clone(&self) -> Self {
255        SubscriberSet(self.0.clone())
256    }
257}
258
259struct SubscriberSetState<EmitterKey, Callback> {
260    subscribers: BTreeMap<EmitterKey, Either<BTreeMap<usize, Subscriber<Callback>>, ThreadId>>,
261    /// Subscribers added while their emitter was mid-emit.
262    ///
263    /// `retain` swaps an emitter's map out for a `ThreadId` marker
264    /// while it invokes callbacks, so during that window there is no
265    /// map to insert into. The marker cannot simply be replaced: it is
266    /// what makes a concurrent `retain` wait instead of emitting the
267    /// same emitter twice, and what lets `is_recursive_calling` spot a
268    /// re-entrant emit. Parking the new subscriber here keeps the
269    /// marker intact, and `retain` folds these back in when it
270    /// restores the map.
271    pending_subscribers: BTreeMap<EmitterKey, BTreeMap<usize, Subscriber<Callback>>>,
272    dropped_subscribers: BTreeSet<(EmitterKey, usize)>,
273    next_subscriber_id: usize,
274}
275
276struct Subscriber<Callback> {
277    active: Arc<AtomicBool>,
278    callback: Callback,
279    /// This field is used to drop the subscription when the subscriber is dropped.
280    _sub: InnerSubscription,
281}
282
283impl<EmitterKey, Callback> SubscriberSet<EmitterKey, Callback>
284where
285    EmitterKey: 'static + Ord + Clone + Debug + Send + Sync,
286    Callback: 'static + Send + Sync,
287{
288    pub fn new() -> Self {
289        Self(Arc::new(Mutex::new(SubscriberSetState {
290            subscribers: Default::default(),
291            pending_subscribers: Default::default(),
292            dropped_subscribers: Default::default(),
293            next_subscriber_id: 0,
294        })))
295    }
296
297    /// Inserts a new [`Subscription`] for the given `emitter_key`.
298    ///
299    /// By default, subscriptions are inert, meaning that they won't be listed when calling
300    /// `[SubscriberSet::remove]` or `[SubscriberSet::retain]`. This method returns a tuple
301    /// of a [`Subscription`] and an `impl FnOnce`, and you can use the latter to activate
302    /// the [`Subscription`].
303    pub fn insert(
304        &self,
305        emitter_key: EmitterKey,
306        callback: Callback,
307    ) -> (Subscription, impl FnOnce()) {
308        let active = Arc::new(AtomicBool::new(false));
309        let mut lock = self.0.lock();
310        let subscriber_id = post_inc(&mut lock.next_subscriber_id);
311        let this = Arc::downgrade(&self.0);
312        let emitter_key_1 = emitter_key.clone();
313        let inner_sub = InnerSubscription {
314            unsubscribe: Arc::new(Mutex::new(Some(Box::new(move || {
315                let Some(this) = this.upgrade() else {
316                    return;
317                };
318
319                let mut lock = this.lock();
320                let Some(subscribers) = lock.subscribers.get_mut(&emitter_key) else {
321                    // remove was called with this emitter_key
322                    return;
323                };
324
325                if let Either::Left(subscribers) = subscribers {
326                    subscribers.remove(&subscriber_id);
327                    if subscribers.is_empty() {
328                        lock.subscribers.remove(&emitter_key);
329                    }
330                    return;
331                }
332
333                // We didn't manage to remove the subscription, which means it was dropped
334                // while invoking the callback. Mark it as dropped so that we can remove it
335                // later.
336                lock.dropped_subscribers
337                    .insert((emitter_key, subscriber_id));
338            })))),
339        };
340        let subscription = Subscription {
341            unsubscribe: Arc::downgrade(&inner_sub.unsubscribe),
342        };
343
344        let subscriber = Subscriber {
345            active: active.clone(),
346            callback,
347            _sub: inner_sub,
348        };
349        // Subscribing to an emitter that is mid-emit is legal and
350        // happens whenever one thread adds a listener while another is
351        // delivering events for the same key (or a callback subscribes
352        // re-entrantly). The map is checked out by `retain` in that
353        // window, so park the subscriber instead of unwrapping a
354        // `Left` that is not there.
355        if matches!(lock.subscribers.get(&emitter_key_1), Some(Either::Right(_))) {
356            lock.pending_subscribers
357                .entry(emitter_key_1)
358                .or_default()
359                .insert(subscriber_id, subscriber);
360        } else {
361            lock.subscribers
362                .entry(emitter_key_1)
363                .or_insert_with(|| Either::Left(BTreeMap::new()))
364                .as_mut()
365                .unwrap_left()
366                .insert(subscriber_id, subscriber);
367        }
368        (subscription, move || active.store(true, Ordering::Relaxed))
369    }
370
371    #[allow(unused)]
372    pub fn remove(&self, emitter: &EmitterKey) -> impl IntoIterator<Item = Callback> {
373        let mut lock = self.0.lock();
374        let subscribers = lock.subscribers.remove(emitter);
375        // A subscriber parked mid-emit belongs to the emitter being
376        // removed; it never became visible, so it goes with it.
377        lock.pending_subscribers.remove(emitter);
378        subscribers
379            .and_then(|x| x.left().map(|s| s.into_values()))
380            .into_iter()
381            .flatten()
382            .filter_map(|subscriber| {
383                if subscriber.active.load(Ordering::Relaxed) {
384                    Some(subscriber.callback)
385                } else {
386                    None
387                }
388            })
389    }
390
391    pub fn is_recursive_calling(&self, emitter: &EmitterKey) -> bool {
392        if let Some(Either::Right(thread_id)) = self.0.lock().subscribers.get(emitter) {
393            *thread_id == thread::current().id()
394        } else {
395            false
396        }
397    }
398
399    /// Call the given callback for each subscriber to the given emitter.
400    /// If the callback returns false, the subscriber is removed.
401    pub fn retain(
402        &self,
403        emitter: &EmitterKey,
404        f: &mut dyn FnMut(&mut Callback) -> bool,
405    ) -> Result<(), SubscriptionError> {
406        let mut subscribers = {
407            let inner = loop {
408                let mut subscriber_set_state = self.0.lock();
409                let Some(set) = subscriber_set_state.subscribers.get_mut(emitter) else {
410                    return Ok(());
411                };
412                match set {
413                    Either::Left(_) => {
414                        break std::mem::replace(set, Either::Right(thread::current().id()))
415                            .unwrap_left();
416                    }
417                    Either::Right(lock_thread) => {
418                        if thread::current().id() == *lock_thread {
419                            return Err(SubscriptionError::CannotEmitEventDueToRecursiveCall);
420                        } else {
421                            // return Ok(());
422                            drop(subscriber_set_state);
423                            #[cfg(loom)]
424                            loom::thread::yield_now();
425                            #[cfg(not(loom))]
426                            std::thread::sleep(std::time::Duration::from_millis(10));
427                        }
428                    }
429                }
430            };
431            inner
432        };
433
434        subscribers.retain(|_, subscriber| {
435            if subscriber.active.load(Ordering::Relaxed) {
436                f(&mut subscriber.callback)
437            } else {
438                true
439            }
440        });
441
442        let mut lock = self.0.lock();
443
444        // Add any new subscribers that were added while invoking the callback.
445        if let Some(Either::Left(new_subscribers)) = lock.subscribers.remove(emitter) {
446            subscribers.extend(new_subscribers);
447        }
448        // …including those parked because this emitter was checked
449        // out. Folded in BEFORE the dropped sweep below, so one that
450        // was unsubscribed again mid-emit is still dropped.
451        if let Some(parked) = lock.pending_subscribers.remove(emitter) {
452            subscribers.extend(parked);
453        }
454
455        // Remove any dropped subscriptions that were dropped while invoking the callback.
456        for (dropped_emitter, dropped_subscription_id) in mem::take(&mut lock.dropped_subscribers) {
457            if *emitter == dropped_emitter {
458                subscribers.remove(&dropped_subscription_id);
459            } else {
460                lock.dropped_subscribers
461                    .insert((dropped_emitter, dropped_subscription_id));
462            }
463        }
464
465        lock.subscribers
466            .insert(emitter.clone(), Either::Left(subscribers));
467        Ok(())
468    }
469
470    pub fn is_empty(&self) -> bool {
471        self.0.lock().subscribers.is_empty()
472    }
473
474    pub fn may_include(&self, emitter: &EmitterKey) -> bool {
475        self.0.lock().subscribers.contains_key(emitter)
476    }
477}
478
479impl<EmitterKey, Callback> Default for SubscriberSet<EmitterKey, Callback>
480where
481    EmitterKey: 'static + Ord + Clone + Debug + Send + Sync,
482    Callback: 'static + Send + Sync,
483{
484    fn default() -> Self {
485        Self::new()
486    }
487}
488
489impl<EmitterKey, Callback> std::fmt::Debug for SubscriberSet<EmitterKey, Callback>
490where
491    EmitterKey: 'static + Ord + Clone + Debug + Send + Sync,
492    Callback: 'static + Send + Sync,
493{
494    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
495        let lock = self.0.lock();
496        f.debug_struct("SubscriberSet")
497            .field("subscriber_count", &lock.subscribers.len())
498            .field("dropped_subscribers_count", &lock.dropped_subscribers.len())
499            .field("next_subscriber_id", &lock.next_subscriber_id)
500            .finish()
501    }
502}
503
504fn post_inc(next_subscriber_id: &mut usize) -> usize {
505    let ans = *next_subscriber_id;
506    *next_subscriber_id += 1;
507    ans
508}
509type Callback = Box<dyn FnOnce() + 'static + Send + Sync>;
510
511/// A handle to a subscription created by GPUI. When dropped, the subscription
512/// is cancelled and the callback will no longer be invoked.
513#[must_use]
514pub struct Subscription {
515    unsubscribe: Weak<Mutex<Option<Callback>>>,
516}
517
518impl std::fmt::Debug for Subscription {
519    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
520        f.debug_struct("Subscription").finish()
521    }
522}
523
524impl Subscription {
525    /// Detaches the subscription from this handle. The callback will
526    /// continue to be invoked until the doc has been subscribed to
527    /// are dropped
528    pub fn detach(self) {
529        if let Some(unsubscribe) = self.unsubscribe.upgrade() {
530            unsubscribe.lock().take();
531        }
532    }
533
534    /// Unsubscribes the subscription.
535    #[inline]
536    pub fn unsubscribe(self) {
537        drop(self)
538    }
539}
540
541impl Drop for Subscription {
542    fn drop(&mut self) {
543        if let Some(unsubscribe) = self.unsubscribe.upgrade() {
544            let unsubscribe = unsubscribe.lock().take();
545            if let Some(unsubscribe) = unsubscribe {
546                unsubscribe();
547            }
548        }
549    }
550}
551
552struct InnerSubscription {
553    unsubscribe: Arc<Mutex<Option<Callback>>>,
554}
555
556impl Drop for InnerSubscription {
557    fn drop(&mut self) {
558        self.unsubscribe.lock().take();
559    }
560}
561
562/// A wrapper around `SubscriberSet` that automatically handles recursive event emission.
563///
564/// This struct differs from `SubscriberSet` in the following ways:
565/// 1. It automatically handles the `CannotEmitEventDueToRecursiveCall` error that can occur in `SubscriberSet`.
566/// 2. When a recursive event emission is detected, it queues the event instead of throwing an error.
567/// 3. After the current event processing is complete, it automatically processes the queued events.
568///
569/// This behavior ensures that all events are processed in the order they were emitted, even in cases
570/// where recursive event emission would normally cause an error.
571#[derive(Clone)]
572pub struct SubscriberSetWithQueue<EmitterKey, Callback, Payload> {
573    subscriber_set: SubscriberSet<EmitterKey, Callback>,
574    queue: Arc<Mutex<BTreeMap<EmitterKey, Vec<Payload>>>>,
575}
576
577impl<EmitterKey, Callback, Payload> Debug
578    for SubscriberSetWithQueue<EmitterKey, Callback, Payload>
579{
580    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
581        f.debug_struct("SubscriberSetWithQueue").finish()
582    }
583}
584
585impl<EmitterKey, Callback, Payload> Default
586    for SubscriberSetWithQueue<EmitterKey, Callback, Payload>
587where
588    EmitterKey: 'static + Ord + Clone + Debug + Send + Sync,
589    Callback: 'static + Send + Sync + for<'a> FnMut(&'a Payload) -> bool,
590    Payload: Send + Sync + Debug,
591{
592    fn default() -> Self {
593        Self::new()
594    }
595}
596
597pub struct WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> {
598    subscriber_set: Weak<Mutex<SubscriberSetState<EmitterKey, Callback>>>,
599    queue: Weak<Mutex<BTreeMap<EmitterKey, Vec<Payload>>>>,
600}
601
602impl<EmitterKey, Callback, Payload> Debug
603    for WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload>
604{
605    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
606        f.debug_struct("WeakSubscriberSetWithQueue").finish()
607    }
608}
609
610impl<EmitterKey, Callback, Payload> Clone
611    for WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload>
612{
613    fn clone(&self) -> Self {
614        Self {
615            subscriber_set: self.subscriber_set.clone(),
616            queue: self.queue.clone(),
617        }
618    }
619}
620
621impl<EmitterKey, Callback, Payload> WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> {
622    pub fn upgrade(self) -> Option<SubscriberSetWithQueue<EmitterKey, Callback, Payload>> {
623        Some(SubscriberSetWithQueue {
624            subscriber_set: SubscriberSet(self.subscriber_set.upgrade()?),
625            queue: self.queue.upgrade()?,
626        })
627    }
628}
629
630impl<EmitterKey, Callback, Payload> SubscriberSetWithQueue<EmitterKey, Callback, Payload>
631where
632    EmitterKey: 'static + Ord + Clone + Debug + Send + Sync,
633    Callback: 'static + Send + Sync + for<'a> FnMut(&'a Payload) -> bool,
634    Payload: Send + Sync + Debug,
635{
636    pub fn new() -> Self {
637        Self {
638            subscriber_set: SubscriberSet::new(),
639            queue: Arc::new(Mutex::new(Default::default())),
640        }
641    }
642
643    pub fn downgrade(&self) -> WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> {
644        WeakSubscriberSetWithQueue {
645            subscriber_set: Arc::downgrade(&self.subscriber_set.0),
646            queue: Arc::downgrade(&self.queue),
647        }
648    }
649
650    pub fn inner(&self) -> &SubscriberSet<EmitterKey, Callback> {
651        &self.subscriber_set
652    }
653
654    pub fn emit(&self, key: &EmitterKey, payload: Payload) {
655        let mut pending_events: SmallVec<[Payload; 1]> = SmallVec::new();
656        pending_events.push(payload);
657        while let Some(payload) = pending_events.pop() {
658            let result = self
659                .subscriber_set
660                .retain(key, &mut |callback| (callback)(&payload));
661            match result {
662                Ok(_) => {
663                    let mut queue = self.queue.lock();
664                    if let Some(new_pending_events) = queue.remove(key) {
665                        pending_events.extend(new_pending_events);
666                    }
667                }
668                Err(SubscriptionError::CannotEmitEventDueToRecursiveCall) => {
669                    let mut queue = self.queue.lock();
670                    queue.entry(key.clone()).or_default().push(payload);
671                }
672            }
673        }
674    }
675}
676
677#[cfg(test)]
678mod test {
679    use super::*;
680
681    #[test]
682    fn test_inner_subscription_drop() {
683        let subscriber_set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new();
684        let (subscription, activate) = subscriber_set.insert(1, Box::new(move |_: &i32| true));
685        activate();
686        drop(subscriber_set);
687        assert!(subscription.unsubscribe.upgrade().is_none());
688    }
689
690    /// Subscribing while the same emitter is mid-emit must not panic.
691    /// `retain` checks the emitter's map out and leaves a `ThreadId`
692    /// marker in its place, so an `insert` landing in that window used
693    /// to `unwrap_left()` the marker and take the process down with
694    /// `called Either::unwrap_left() on a Right value`. The new
695    /// subscriber is parked and folded in when `retain` restores the
696    /// map — so it is registered, but does not fire for the event
697    /// already being delivered.
698    #[test]
699    fn insert_during_emit_does_not_panic() {
700        let set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new();
701        let late_fired = Arc::new(AtomicBool::new(false));
702
703        // The first subscriber subscribes AGAIN from inside its own
704        // callback: the emitter is checked out at that moment, which
705        // is exactly the state that used to panic.
706        let set_inner = set.clone();
707        let flag = late_fired.clone();
708        let (_sub, activate) = set.insert(
709            1,
710            Box::new(move |_: &i32| {
711                let flag = flag.clone();
712                let (sub, activate) = set_inner.insert(
713                    1,
714                    Box::new(move |_: &i32| {
715                        flag.store(true, Ordering::Relaxed);
716                        true
717                    }),
718                );
719                activate();
720                std::mem::forget(sub);
721                true
722            }),
723        );
724        activate();
725
726        set.retain(&1, &mut |callback| callback(&1)).unwrap();
727        assert!(
728            !late_fired.load(Ordering::Relaxed),
729            "a subscriber added mid-emit must not receive the event being delivered"
730        );
731
732        // The parked subscriber was folded back in, so the NEXT emit
733        // reaches it.
734        set.retain(&1, &mut |callback| callback(&1)).unwrap();
735        assert!(
736            late_fired.load(Ordering::Relaxed),
737            "a subscriber added mid-emit must be registered for later events"
738        );
739    }
740
741    /// The cross-thread flavour: one thread emits while another
742    /// subscribes to the same emitter.
743    #[test]
744    fn concurrent_insert_and_emit_do_not_panic() {
745        use std::sync::{atomic::AtomicUsize, mpsc};
746        let set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new();
747
748        // The first emit parks inside the callback until released, which
749        // keeps the emitter checked out for as long as the test needs.
750        let (entered_tx, entered_rx) = mpsc::channel::<()>();
751        let (release_tx, release_rx) = mpsc::channel::<()>();
752        let entered_tx = std::sync::Mutex::new(Some(entered_tx));
753        let release_rx = std::sync::Mutex::new(release_rx);
754        let (_sub, activate) = set.insert(
755            1,
756            Box::new(move |_: &i32| {
757                if let Some(tx) = entered_tx.lock().unwrap().take() {
758                    tx.send(()).unwrap();
759                    release_rx.lock().unwrap().recv().unwrap();
760                }
761                true
762            }),
763        );
764        activate();
765
766        let emitter = set.clone();
767        let t = std::thread::spawn(move || {
768            emitter.retain(&1, &mut |callback| callback(&1)).unwrap();
769        });
770
771        // Only subscribe once the emitting thread is inside the callback,
772        // so this insert is guaranteed to land while the emitter is
773        // checked out.
774        entered_rx.recv().unwrap();
775        let late_calls = Arc::new(AtomicUsize::new(0));
776        let late_calls_clone = late_calls.clone();
777        let (sub, activate) = set.insert(
778            1,
779            Box::new(move |_: &i32| {
780                late_calls_clone.fetch_add(1, Ordering::SeqCst);
781                true
782            }),
783        );
784        activate();
785        release_tx.send(()).unwrap();
786        t.join().unwrap();
787        assert_eq!(late_calls.load(Ordering::SeqCst), 0);
788
789        set.retain(&1, &mut |callback| callback(&1)).unwrap();
790        assert_eq!(late_calls.load(Ordering::SeqCst), 1);
791        drop(sub);
792    }
793
794    #[test]
795    fn test_inner_subscription_drop_2() {
796        let subscriber_set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new();
797        let (subscription, activate) = subscriber_set.insert(1, Box::new(move |_: &i32| false));
798        activate();
799        subscriber_set
800            .retain(&1, &mut |callback| callback(&1))
801            .unwrap();
802        assert!(subscription.unsubscribe.upgrade().is_none());
803    }
804}