i18n_next/change.rs
1//! Change notifications (DESIGN 4.5 `listeners`, 8b.5): `subscribe` and [`Change`].
2//!
3//! A change is any write that can change what a lookup answers: `set_locale` to another
4//! locale, `add_messages`, `reload`, and `add_file` when it completes a pair. A lazy load
5//! and an eviction answer exactly what was there before, so they send nothing and keep
6//! [`I18n::version`] (an eviction still publishes a snapshot under a new internal cache
7//! key: thread caches must drop the old snapshot to free it).
8//!
9//! Changes are delivered in version order (`Listeners::drain`): each is queued under the
10//! writer lock, and one thread at a time delivers the queue.
11
12use crate::i18n::{I18n, Inner};
13use crate::lazy::lock;
14use std::collections::VecDeque;
15use std::fmt;
16use std::panic::{AssertUnwindSafe, catch_unwind};
17use std::sync::atomic::{AtomicBool, Ordering};
18use std::sync::{Arc, Mutex, Weak};
19
20/// A listener and whether its subscription is still alive: `send` checks it before each
21/// call, so a listener dropped while others run is not called afterwards.
22struct Entry {
23 live: AtomicBool,
24 f: Box<dyn Fn(&Change) + Send + Sync>,
25}
26
27type Listener = Arc<Entry>;
28
29/// What changed: the active locale after the write and the new snapshot version.
30#[derive(Debug, Clone, PartialEq, Eq)]
31#[non_exhaustive]
32pub struct Change {
33 /// The active locale after the change.
34 pub locale: Arc<str>,
35 /// The snapshot version the change produced ([`I18n::version`]).
36 pub version: u64,
37}
38
39/// The listeners of one instance.
40#[derive(Default)]
41pub(crate) struct Listeners {
42 list: Mutex<(u64, Vec<(u64, Listener)>)>,
43 /// Changes not delivered yet, in version order, and whether a thread is delivering.
44 queue: Mutex<(VecDeque<Change>, bool)>,
45}
46
47impl Listeners {
48 /// Queues `change`. Called under the writer lock, so the queue is in version order.
49 pub(crate) fn push(&self, change: Change) {
50 lock(&self.queue).0.push_back(change);
51 }
52
53 /// Delivers the queued changes in order, unless another thread (or this one, from
54 /// inside a listener) is delivering already: that one delivers them after its current
55 /// change. So every listener sees versions in increasing order, never two at once.
56 pub(crate) fn drain(&self) {
57 let mut q = lock(&self.queue);
58 if q.1 {
59 return;
60 }
61 q.1 = true;
62 while let Some(change) = q.0.pop_front() {
63 drop(q);
64 self.send(&change);
65 q = lock(&self.queue);
66 }
67 q.1 = false;
68 }
69
70 /// Calls every listener with `change`, over a copy of the list (a listener may
71 /// subscribe or unsubscribe); a panicking listener does not stop the others.
72 fn send(&self, change: &Change) {
73 let listeners: Vec<Listener> = {
74 let list = lock(&self.list);
75 if list.1.is_empty() {
76 return;
77 }
78 list.1.iter().map(|(_, f)| f.clone()).collect()
79 };
80 for e in listeners {
81 // Acquire: pairs with the release in `Subscription::drop`.
82 if e.live.load(Ordering::Acquire) {
83 let _ = catch_unwind(AssertUnwindSafe(|| (e.f)(change)));
84 }
85 }
86 }
87}
88
89/// A subscription made by [`I18n::subscribe`]: dropping it unsubscribes. It does not keep
90/// the catalog alive.
91#[must_use = "dropping a Subscription unsubscribes at once"]
92pub struct Subscription {
93 inner: Weak<Inner>,
94 id: u64,
95}
96
97impl fmt::Debug for Subscription {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 f.debug_struct("Subscription")
100 .field("id", &self.id)
101 .finish_non_exhaustive()
102 }
103}
104
105impl Drop for Subscription {
106 fn drop(&mut self) {
107 if let Some(inner) = self.inner.upgrade() {
108 // Dropped after the lock: a listener may own subscriptions of its own.
109 let gone: Vec<_> = lock(&inner.listeners.list)
110 .1
111 .extract_if(.., |(id, _)| *id == self.id)
112 .collect();
113 for (_, e) in &gone {
114 e.live.store(false, Ordering::Release);
115 }
116 drop(gone);
117 }
118 }
119}
120
121impl I18n {
122 /// Calls `f` after every change of what lookups can answer: `set_locale` to another
123 /// locale, `add_messages`, `reload`, and `add_file` when it completes a pair. A lazy
124 /// load and a page eviction answer the same as before and call nothing.
125 ///
126 /// Listeners run after the new snapshot is in, in subscription order, over a copy of
127 /// the list; a listener that panics is skipped, the others still run. Changes are
128 /// delivered one at a time in version order: on the writing thread, unless another
129 /// thread is delivering already (then that thread delivers this change after its own,
130 /// and the write returns without waiting). A write from inside a listener is delivered
131 /// after the current change, once every listener has seen it.
132 ///
133 /// Once its [`Subscription`] is dropped a listener is not called again, also not by a
134 /// notification already running on the same thread (another listener dropped it).
135 /// Dropping does not wait for other threads: a notification running on another thread
136 /// that already passed this listener's check may still call it once, during or right
137 /// after the drop.
138 ///
139 /// ```
140 /// use i18n_next::I18n;
141 /// use std::sync::{Arc, Mutex};
142 ///
143 /// let i18n = I18n::builder().messages("de", None, "{}").build()?;
144 /// let seen = Arc::new(Mutex::new(Vec::new()));
145 /// let log = seen.clone();
146 /// let sub = i18n.subscribe(move |c| log.lock().unwrap().push((c.locale.to_string(), c.version)));
147 /// i18n.set_locale("de")?;
148 /// drop(sub);
149 /// i18n.set_locale("en")?;
150 /// assert_eq!(*seen.lock().unwrap(), [("de".to_owned(), 1)]);
151 /// # Ok::<(), i18n_next::Error>(())
152 /// ```
153 pub fn subscribe(&self, f: impl Fn(&Change) + Send + Sync + 'static) -> Subscription {
154 let mut list = lock(&self.inner.listeners.list);
155 list.0 += 1;
156 let id = list.0;
157 list.1.push((
158 id,
159 Arc::new(Entry {
160 live: AtomicBool::new(true),
161 f: Box::new(f),
162 }),
163 ));
164 Subscription {
165 inner: Arc::downgrade(&self.inner),
166 id,
167 }
168 }
169}