forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

subscription.rs857 lines, 33.4 KiBHistoryRawDownload
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 let removed = subscribers.remove(&subscriber_id);
327 if subscribers.is_empty() {
328 lock.subscribers.remove(&emitter_key);
329 }
330 // Drop the subscriber only after releasing the lock: its callback
331 // may own another `Subscription` (or an `UndoManager`) on this set,
332 // whose drop takes this lock again (loro-dev/loro#1162).
333 drop(lock);
334 drop(removed);
335 return;
336 }
337
338 // We didn't manage to remove the subscription, which means it was dropped
339 // while invoking the callback. Mark it as dropped so that we can remove it
340 // later.
341 lock.dropped_subscribers
342 .insert((emitter_key, subscriber_id));
343 })))),
344 };
345 let subscription = Subscription {
346 unsubscribe: Arc::downgrade(&inner_sub.unsubscribe),
347 };
348
349 let subscriber = Subscriber {
350 active: active.clone(),
351 callback,
352 _sub: inner_sub,
353 };
354 // Subscribing to an emitter that is mid-emit is legal and
355 // happens whenever one thread adds a listener while another is
356 // delivering events for the same key (or a callback subscribes
357 // re-entrantly). The map is checked out by `retain` in that
358 // window, so park the subscriber instead of unwrapping a
359 // `Left` that is not there.
360 if matches!(lock.subscribers.get(&emitter_key_1), Some(Either::Right(_))) {
361 lock.pending_subscribers
362 .entry(emitter_key_1)
363 .or_default()
364 .insert(subscriber_id, subscriber);
365 } else {
366 lock.subscribers
367 .entry(emitter_key_1)
368 .or_insert_with(|| Either::Left(BTreeMap::new()))
369 .as_mut()
370 .unwrap_left()
371 .insert(subscriber_id, subscriber);
372 }
373 (subscription, move || active.store(true, Ordering::Relaxed))
374 }
375
376 #[allow(unused)]
377 pub fn remove(&self, emitter: &EmitterKey) -> impl IntoIterator<Item = Callback> {
378 let mut lock = self.0.lock();
379 let subscribers = lock.subscribers.remove(emitter);
380 // A subscriber parked mid-emit belongs to the emitter being
381 // removed; it never became visible, so it goes with it.
382 let parked = lock.pending_subscribers.remove(emitter);
383 // Drop callbacks outside the lock; see the unsubscribe closure in `insert`.
384 drop(lock);
385 drop(parked);
386 subscribers
387 .and_then(|x| x.left().map(|s| s.into_values()))
388 .into_iter()
389 .flatten()
390 .filter_map(|subscriber| {
391 if subscriber.active.load(Ordering::Relaxed) {
392 Some(subscriber.callback)
393 } else {
394 None
395 }
396 })
397 }
398
399 pub fn is_recursive_calling(&self, emitter: &EmitterKey) -> bool {
400 if let Some(Either::Right(thread_id)) = self.0.lock().subscribers.get(emitter) {
401 *thread_id == thread::current().id()
402 } else {
403 false
404 }
405 }
406
407 /// Call the given callback for each subscriber to the given emitter.
408 /// If the callback returns false, the subscriber is removed.
409 pub fn retain(
410 &self,
411 emitter: &EmitterKey,
412 f: &mut dyn FnMut(&mut Callback) -> bool,
413 ) -> Result<(), SubscriptionError> {
414 let mut subscribers = {
415 let inner = loop {
416 let mut subscriber_set_state = self.0.lock();
417 let Some(set) = subscriber_set_state.subscribers.get_mut(emitter) else {
418 return Ok(());
419 };
420 match set {
421 Either::Left(_) => {
422 break std::mem::replace(set, Either::Right(thread::current().id()))
423 .unwrap_left();
424 }
425 Either::Right(lock_thread) => {
426 if thread::current().id() == *lock_thread {
427 return Err(SubscriptionError::CannotEmitEventDueToRecursiveCall);
428 } else {
429 // return Ok(());
430 drop(subscriber_set_state);
431 #[cfg(loom)]
432 loom::thread::yield_now();
433 #[cfg(not(loom))]
434 std::thread::sleep(std::time::Duration::from_millis(10));
435 }
436 }
437 }
438 };
439 inner
440 };
441
442 // A panicking callback must not take the checked-out subscribers with
443 // it: the marker left in their place would make later emits on this
444 // thread queue forever and emits on other threads wait forever. The
445 // other subscribers still get the event, the map is put back, and the
446 // first panic is raised again at the end.
447 let mut panic = DeferredPanic::default();
448 subscribers.retain(|_, subscriber| {
449 if !subscriber.active.load(Ordering::Relaxed) {
450 return true;
451 }
452 panic.run(|| f(&mut subscriber.callback)).unwrap_or(true)
453 });
454
455 let mut lock = self.0.lock();
456
457 // Add any new subscribers that were added while invoking the callback.
458 if let Some(Either::Left(new_subscribers)) = lock.subscribers.remove(emitter) {
459 subscribers.extend(new_subscribers);
460 }
461 // …including those parked because this emitter was checked
462 // out. Folded in BEFORE the dropped sweep below, so one that
463 // was unsubscribed again mid-emit is still dropped.
464 if let Some(parked) = lock.pending_subscribers.remove(emitter) {
465 subscribers.extend(parked);
466 }
467
468 // Remove any dropped subscriptions that were dropped while invoking the callback.
469 let mut removed = Vec::new();
470 for (dropped_emitter, dropped_subscription_id) in mem::take(&mut lock.dropped_subscribers) {
471 if *emitter == dropped_emitter {
472 removed.extend(subscribers.remove(&dropped_subscription_id));
473 } else {
474 lock.dropped_subscribers
475 .insert((dropped_emitter, dropped_subscription_id));
476 }
477 }
478
479 lock.subscribers
480 .insert(emitter.clone(), Either::Left(subscribers));
481 // Drop callbacks outside the lock; see the unsubscribe closure in `insert`.
482 drop(lock);
483 drop(removed);
484 panic.resume();
485 Ok(())
486 }
487
488 pub fn is_empty(&self) -> bool {
489 self.0.lock().subscribers.is_empty()
490 }
491
492 pub fn may_include(&self, emitter: &EmitterKey) -> bool {
493 self.0.lock().subscribers.contains_key(emitter)
494 }
495}
496
497impl<EmitterKey, Callback> Default for SubscriberSet<EmitterKey, Callback>
498where
499 EmitterKey: 'static + Ord + Clone + Debug + Send + Sync,
500 Callback: 'static + Send + Sync,
501{
502 fn default() -> Self {
503 Self::new()
504 }
505}
506
507impl<EmitterKey, Callback> std::fmt::Debug for SubscriberSet<EmitterKey, Callback>
508where
509 EmitterKey: 'static + Ord + Clone + Debug + Send + Sync,
510 Callback: 'static + Send + Sync,
511{
512 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
513 let lock = self.0.lock();
514 f.debug_struct("SubscriberSet")
515 .field("subscriber_count", &lock.subscribers.len())
516 .field("dropped_subscribers_count", &lock.dropped_subscribers.len())
517 .field("next_subscriber_id", &lock.next_subscriber_id)
518 .finish()
519 }
520}
521
522fn post_inc(next_subscriber_id: &mut usize) -> usize {
523 let ans = *next_subscriber_id;
524 *next_subscriber_id += 1;
525 ans
526}
527type Callback = Box<dyn FnOnce() + 'static + Send + Sync>;
528
529/// A handle to a subscription created by GPUI. When dropped, the subscription
530/// is cancelled and the callback will no longer be invoked.
531#[must_use]
532pub struct Subscription {
533 unsubscribe: Weak<Mutex<Option<Callback>>>,
534}
535
536impl std::fmt::Debug for Subscription {
537 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
538 f.debug_struct("Subscription").finish()
539 }
540}
541
542impl Subscription {
543 /// Detaches the subscription from this handle. The callback will
544 /// continue to be invoked until the doc has been subscribed to
545 /// are dropped
546 pub fn detach(self) {
547 if let Some(unsubscribe) = self.unsubscribe.upgrade() {
548 unsubscribe.lock().take();
549 }
550 }
551
552 /// Unsubscribes the subscription.
553 #[inline]
554 pub fn unsubscribe(self) {
555 drop(self)
556 }
557}
558
559impl Drop for Subscription {
560 fn drop(&mut self) {
561 if let Some(unsubscribe) = self.unsubscribe.upgrade() {
562 let unsubscribe = unsubscribe.lock().take();
563 if let Some(unsubscribe) = unsubscribe {
564 unsubscribe();
565 }
566 }
567 }
568}
569
570struct InnerSubscription {
571 unsubscribe: Arc<Mutex<Option<Callback>>>,
572}
573
574impl Drop for InnerSubscription {
575 fn drop(&mut self) {
576 self.unsubscribe.lock().take();
577 }
578}
579
580/// A wrapper around `SubscriberSet` that automatically handles recursive event emission.
581///
582/// This struct differs from `SubscriberSet` in the following ways:
583/// 1. It automatically handles the `CannotEmitEventDueToRecursiveCall` error that can occur in `SubscriberSet`.
584/// 2. When a recursive event emission is detected, it queues the event instead of throwing an error.
585/// 3. After the current event processing is complete, it automatically processes the queued events.
586///
587/// This behavior ensures that all events are processed in the order they were emitted, even in cases
588/// where recursive event emission would normally cause an error.
589#[derive(Clone)]
590pub struct SubscriberSetWithQueue<EmitterKey, Callback, Payload> {
591 subscriber_set: SubscriberSet<EmitterKey, Callback>,
592 queue: Arc<Mutex<BTreeMap<EmitterKey, Vec<Payload>>>>,
593}
594
595impl<EmitterKey, Callback, Payload> Debug
596 for SubscriberSetWithQueue<EmitterKey, Callback, Payload>
597{
598 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
599 f.debug_struct("SubscriberSetWithQueue").finish()
600 }
601}
602
603impl<EmitterKey, Callback, Payload> Default
604 for SubscriberSetWithQueue<EmitterKey, Callback, Payload>
605where
606 EmitterKey: 'static + Ord + Clone + Debug + Send + Sync,
607 Callback: 'static + Send + Sync + for<'a> FnMut(&'a Payload) -> bool,
608 Payload: Send + Sync + Debug,
609{
610 fn default() -> Self {
611 Self::new()
612 }
613}
614
615pub struct WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> {
616 subscriber_set: Weak<Mutex<SubscriberSetState<EmitterKey, Callback>>>,
617 queue: Weak<Mutex<BTreeMap<EmitterKey, Vec<Payload>>>>,
618}
619
620impl<EmitterKey, Callback, Payload> Debug
621 for WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload>
622{
623 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
624 f.debug_struct("WeakSubscriberSetWithQueue").finish()
625 }
626}
627
628impl<EmitterKey, Callback, Payload> Clone
629 for WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload>
630{
631 fn clone(&self) -> Self {
632 Self {
633 subscriber_set: self.subscriber_set.clone(),
634 queue: self.queue.clone(),
635 }
636 }
637}
638
639impl<EmitterKey, Callback, Payload> WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> {
640 pub fn upgrade(self) -> Option<SubscriberSetWithQueue<EmitterKey, Callback, Payload>> {
641 Some(SubscriberSetWithQueue {
642 subscriber_set: SubscriberSet(self.subscriber_set.upgrade()?),
643 queue: self.queue.upgrade()?,
644 })
645 }
646}
647
648/// Runs steps that must all happen even if one of them panics, such as calling
649/// every subscriber and delivering every event, and raises the first panic
650/// once they are done. A subscriber is user code; its panic must not drop
651/// events or local updates meant for others.
652#[derive(Default)]
653pub(crate) struct DeferredPanic(Option<Box<dyn std::any::Any + Send + 'static>>);
654
655impl DeferredPanic {
656 pub fn run<R>(&mut self, f: impl FnOnce() -> R) -> Option<R> {
657 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
658 Ok(ans) => Some(ans),
659 Err(payload) => {
660 self.0.get_or_insert(payload);
661 None
662 }
663 }
664 }
665
666 pub fn has_panic(&self) -> bool {
667 self.0.is_some()
668 }
669
670 pub fn resume(self) {
671 if let Some(payload) = self.0 {
672 std::panic::resume_unwind(payload);
673 }
674 }
675}
676
677impl<EmitterKey, Callback, Payload> SubscriberSetWithQueue<EmitterKey, Callback, Payload>
678where
679 EmitterKey: 'static + Ord + Clone + Debug + Send + Sync,
680 Callback: 'static + Send + Sync + for<'a> FnMut(&'a Payload) -> bool,
681 Payload: Send + Sync + Debug,
682{
683 pub fn new() -> Self {
684 Self {
685 subscriber_set: SubscriberSet::new(),
686 queue: Arc::new(Mutex::new(Default::default())),
687 }
688 }
689
690 pub fn downgrade(&self) -> WeakSubscriberSetWithQueue<EmitterKey, Callback, Payload> {
691 WeakSubscriberSetWithQueue {
692 subscriber_set: Arc::downgrade(&self.subscriber_set.0),
693 queue: Arc::downgrade(&self.queue),
694 }
695 }
696
697 pub fn inner(&self) -> &SubscriberSet<EmitterKey, Callback> {
698 &self.subscriber_set
699 }
700
701 pub fn emit(&self, key: &EmitterKey, payload: Payload) {
702 let mut panic = DeferredPanic::default();
703 let mut pending_events: SmallVec<[Payload; 1]> = SmallVec::new();
704 pending_events.push(payload);
705 while let Some(payload) = pending_events.pop() {
706 // A subscriber that panicked still had the payload delivered to the others.
707 let result = panic
708 .run(|| {
709 self.subscriber_set
710 .retain(key, &mut |callback| (callback)(&payload))
711 })
712 .unwrap_or(Ok(()));
713 match result {
714 Ok(_) => {
715 let mut queue = self.queue.lock();
716 if let Some(new_pending_events) = queue.remove(key) {
717 pending_events.extend(new_pending_events);
718 }
719 }
720 Err(SubscriptionError::CannotEmitEventDueToRecursiveCall) => {
721 let mut queue = self.queue.lock();
722 queue.entry(key.clone()).or_default().push(payload);
723 }
724 }
725 }
726 panic.resume();
727 }
728}
729
730#[cfg(test)]
731mod test {
732 use super::*;
733
734 #[test]
735 fn test_inner_subscription_drop() {
736 let subscriber_set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new();
737 let (subscription, activate) = subscriber_set.insert(1, Box::new(move |_: &i32| true));
738 activate();
739 drop(subscriber_set);
740 assert!(subscription.unsubscribe.upgrade().is_none());
741 }
742
743 /// Subscribing while the same emitter is mid-emit must not panic.
744 /// `retain` checks the emitter's map out and leaves a `ThreadId`
745 /// marker in its place, so an `insert` landing in that window used
746 /// to `unwrap_left()` the marker and take the process down with
747 /// `called Either::unwrap_left() on a Right value`. The new
748 /// subscriber is parked and folded in when `retain` restores the
749 /// map — so it is registered, but does not fire for the event
750 /// already being delivered.
751 #[test]
752 fn insert_during_emit_does_not_panic() {
753 let set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new();
754 let late_fired = Arc::new(AtomicBool::new(false));
755
756 // The first subscriber subscribes AGAIN from inside its own
757 // callback: the emitter is checked out at that moment, which
758 // is exactly the state that used to panic.
759 let set_inner = set.clone();
760 let flag = late_fired.clone();
761 let (_sub, activate) = set.insert(
762 1,
763 Box::new(move |_: &i32| {
764 let flag = flag.clone();
765 let (sub, activate) = set_inner.insert(
766 1,
767 Box::new(move |_: &i32| {
768 flag.store(true, Ordering::Relaxed);
769 true
770 }),
771 );
772 activate();
773 std::mem::forget(sub);
774 true
775 }),
776 );
777 activate();
778
779 set.retain(&1, &mut |callback| callback(&1)).unwrap();
780 assert!(
781 !late_fired.load(Ordering::Relaxed),
782 "a subscriber added mid-emit must not receive the event being delivered"
783 );
784
785 // The parked subscriber was folded back in, so the NEXT emit
786 // reaches it.
787 set.retain(&1, &mut |callback| callback(&1)).unwrap();
788 assert!(
789 late_fired.load(Ordering::Relaxed),
790 "a subscriber added mid-emit must be registered for later events"
791 );
792 }
793
794 /// The cross-thread flavour: one thread emits while another
795 /// subscribes to the same emitter.
796 #[test]
797 fn concurrent_insert_and_emit_do_not_panic() {
798 use std::sync::{atomic::AtomicUsize, mpsc};
799 let set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new();
800
801 // The first emit parks inside the callback until released, which
802 // keeps the emitter checked out for as long as the test needs.
803 let (entered_tx, entered_rx) = mpsc::channel::<()>();
804 let (release_tx, release_rx) = mpsc::channel::<()>();
805 let entered_tx = std::sync::Mutex::new(Some(entered_tx));
806 let release_rx = std::sync::Mutex::new(release_rx);
807 let (_sub, activate) = set.insert(
808 1,
809 Box::new(move |_: &i32| {
810 if let Some(tx) = entered_tx.lock().unwrap().take() {
811 tx.send(()).unwrap();
812 release_rx.lock().unwrap().recv().unwrap();
813 }
814 true
815 }),
816 );
817 activate();
818
819 let emitter = set.clone();
820 let t = std::thread::spawn(move || {
821 emitter.retain(&1, &mut |callback| callback(&1)).unwrap();
822 });
823
824 // Only subscribe once the emitting thread is inside the callback,
825 // so this insert is guaranteed to land while the emitter is
826 // checked out.
827 entered_rx.recv().unwrap();
828 let late_calls = Arc::new(AtomicUsize::new(0));
829 let late_calls_clone = late_calls.clone();
830 let (sub, activate) = set.insert(
831 1,
832 Box::new(move |_: &i32| {
833 late_calls_clone.fetch_add(1, Ordering::SeqCst);
834 true
835 }),
836 );
837 activate();
838 release_tx.send(()).unwrap();
839 t.join().unwrap();
840 assert_eq!(late_calls.load(Ordering::SeqCst), 0);
841
842 set.retain(&1, &mut |callback| callback(&1)).unwrap();
843 assert_eq!(late_calls.load(Ordering::SeqCst), 1);
844 drop(sub);
845 }
846
847 #[test]
848 fn test_inner_subscription_drop_2() {
849 let subscriber_set = SubscriberSet::<i32, Box<dyn Fn(&i32) -> bool + Send + Sync>>::new();
850 let (subscription, activate) = subscriber_set.insert(1, Box::new(move |_: &i32| false));
851 activate();
852 subscriber_set
853 .retain(&1, &mut |callback| callback(&1))
854 .unwrap();
855 assert!(subscription.unsubscribe.upgrade().is_none());
856 }
857}