forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB64a9351Ivan Molodetskikh2 years ago1319 commits

transaction.rs191 lines, 6.3 KiBHistoryRawDownload
1use std::cell::RefCell;
2use std::rc::Rc;
3use std::sync::atomic::AtomicBool;
4use std::sync::mpsc::Sender;
5use std::sync::{Arc, Mutex, Weak};
6use std::time::{Duration, Instant};
7
8use atomic::Ordering;
9use calloop::ping::{make_ping, Ping};
10use calloop::timer::{TimeoutAction, Timer};
11use calloop::LoopHandle;
12use smithay::reexports::wayland_server::Client;
13use smithay::wayland::compositor::{Blocker, BlockerState};
14
15/// Default time limit, after which the transaction completes.
16///
17/// Serves to avoid hanging when a client fails to respond to a configure promptly.
18const TIME_LIMIT: Duration = Duration::from_millis(300);
19
20/// Transaction between Wayland clients.
21///
22/// How to use it:
23/// 1. Create a transaction with [`Transaction::new()`].
24/// 2. Clone it as many times as you need.
25/// 3. Before adding the transaction as a commit blocker, remember to call
26/// [`Transaction::add_notification()`] to receive a notification when the transaction completes.
27/// 4. Before adding the transaction as a commit blocker, remember to call
28/// [`Transaction::register_deadline_timer()`] to make sure the transaction completes when
29/// reaching the deadline.
30/// 5. In your surface pre-commit handler, if the transaction corresponding to that commit isn't
31/// ready, get a blocker with [`Transaction::blocker()`] and add it to the surface.
32#[derive(Debug, Clone)]
33pub struct Transaction {
34 inner: Arc<Inner>,
35 deadline: Rc<RefCell<Deadline>>,
36}
37
38/// Blocker for a [`Transaction`].
39#[derive(Debug)]
40pub struct TransactionBlocker(Weak<Inner>);
41
42#[derive(Debug)]
43enum Deadline {
44 NotRegistered(Instant),
45 Registered { remove: Ping },
46}
47
48#[derive(Debug)]
49struct Inner {
50 /// Whether the transaction is completed.
51 completed: AtomicBool,
52 /// Notifications to send out upon completing the transaction.
53 notifications: Mutex<Option<(Sender<Client>, Vec<Client>)>>,
54}
55
56impl Transaction {
57 /// Creates a new transaction.
58 #[allow(clippy::new_without_default)]
59 pub fn new() -> Self {
60 Self {
61 inner: Arc::new(Inner::new()),
62 deadline: Rc::new(RefCell::new(Deadline::NotRegistered(
63 Instant::now() + TIME_LIMIT,
64 ))),
65 }
66 }
67
68 /// Gets a blocker for this transaction.
69 pub fn blocker(&self) -> TransactionBlocker {
70 trace!(transaction = ?Arc::as_ptr(&self.inner), "generating blocker");
71 TransactionBlocker(Arc::downgrade(&self.inner))
72 }
73
74 /// Adds a notification for when this transaction completes.
75 pub fn add_notification(&self, sender: Sender<Client>, client: Client) {
76 if self.is_completed() {
77 error!("tried to add notification to a completed transaction");
78 return;
79 }
80
81 let mut guard = self.inner.notifications.lock().unwrap();
82 guard.get_or_insert((sender, Vec::new())).1.push(client);
83 }
84
85 /// Registers this transaction's deadline timer on an event loop.
86 pub fn register_deadline_timer<T: 'static>(&self, event_loop: &LoopHandle<'static, T>) {
87 let mut cell = self.deadline.borrow_mut();
88 if let Deadline::NotRegistered(deadline) = *cell {
89 let timer = Timer::from_deadline(deadline);
90 let inner = Arc::downgrade(&self.inner);
91 let token = event_loop
92 .insert_source(timer, move |_, _, _| {
93 let _span = trace_span!("deadline timer", transaction = ?Weak::as_ptr(&inner))
94 .entered();
95
96 if let Some(inner) = inner.upgrade() {
97 trace!("deadline reached, completing transaction");
98 inner.complete();
99 } else {
100 // We should remove the timer automatically. But this callback can still
101 // just happen to run while the ping callback is scheduled, leading to this
102 // branch being legitimately taken.
103 trace!("transaction completed without removing the timer");
104 }
105
106 TimeoutAction::Drop
107 })
108 .unwrap();
109
110 // Add a ping source that will be used to remove the timer automatically.
111 let (ping, source) = make_ping().unwrap();
112 let loop_handle = event_loop.clone();
113 event_loop
114 .insert_source(source, move |_, _, _| {
115 loop_handle.remove(token);
116 })
117 .unwrap();
118
119 *cell = Deadline::Registered { remove: ping };
120 }
121 }
122
123 /// Returns whether this transaction has already completed.
124 pub fn is_completed(&self) -> bool {
125 self.inner.is_completed()
126 }
127
128 /// Returns whether this is the last instance of this transaction.
129 pub fn is_last(&self) -> bool {
130 Arc::strong_count(&self.inner) == 1
131 }
132}
133
134impl Drop for Transaction {
135 fn drop(&mut self) {
136 let _span = trace_span!("drop", transaction = ?Arc::as_ptr(&self.inner)).entered();
137
138 if self.is_last() {
139 // If this was the last transaction, complete it.
140 trace!("last transaction dropped, completing");
141 self.inner.complete();
142
143 // Also remove the timer.
144 if let Deadline::Registered { remove } = &*self.deadline.borrow() {
145 remove.ping();
146 };
147 }
148 }
149}
150
151impl TransactionBlocker {
152 pub fn completed() -> Self {
153 Self(Weak::new())
154 }
155}
156
157impl Blocker for TransactionBlocker {
158 fn state(&self) -> BlockerState {
159 if self.0.upgrade().map_or(true, |x| x.is_completed()) {
160 BlockerState::Released
161 } else {
162 BlockerState::Pending
163 }
164 }
165}
166
167impl Inner {
168 fn new() -> Self {
169 Self {
170 completed: AtomicBool::new(false),
171 notifications: Mutex::new(None),
172 }
173 }
174
175 fn is_completed(&self) -> bool {
176 self.completed.load(Ordering::Relaxed)
177 }
178
179 fn complete(&self) {
180 self.completed.store(true, Ordering::Relaxed);
181
182 let mut guard = self.notifications.lock().unwrap();
183 if let Some((sender, clients)) = guard.take() {
184 for client in clients {
185 if let Err(err) = sender.send(client) {
186 warn!("error sending blocker notification: {err:?}");
187 };
188 }
189 }
190 }
191}