forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB99bf2dfIvan Molodetskikh1 year ago2106 commits

transaction.rs193 lines, 6.4 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 // FIXME: come up with some way to control the deadline timer from tests.
97 #[cfg(not(test))]
98 if let Some(inner) = inner.upgrade() {
99 trace!("deadline reached, completing transaction");
100 inner.complete();
101 } else {
102 // We should remove the timer automatically. But this callback can still
103 // just happen to run while the ping callback is scheduled, leading to this
104 // branch being legitimately taken.
105 trace!("transaction completed without removing the timer");
106 }
107
108 TimeoutAction::Drop
109 })
110 .unwrap();
111
112 // Add a ping source that will be used to remove the timer automatically.
113 let (ping, source) = make_ping().unwrap();
114 let loop_handle = event_loop.clone();
115 event_loop
116 .insert_source(source, move |_, _, _| {
117 loop_handle.remove(token);
118 })
119 .unwrap();
120
121 *cell = Deadline::Registered { remove: ping };
122 }
123 }
124
125 /// Returns whether this transaction has already completed.
126 pub fn is_completed(&self) -> bool {
127 self.inner.is_completed()
128 }
129
130 /// Returns whether this is the last instance of this transaction.
131 pub fn is_last(&self) -> bool {
132 Arc::strong_count(&self.inner) == 1
133 }
134}
135
136impl Drop for Transaction {
137 fn drop(&mut self) {
138 let _span = trace_span!("drop", transaction = ?Arc::as_ptr(&self.inner)).entered();
139
140 if self.is_last() {
141 // If this was the last transaction, complete it.
142 trace!("last transaction dropped, completing");
143 self.inner.complete();
144
145 // Also remove the timer.
146 if let Deadline::Registered { remove } = &*self.deadline.borrow() {
147 remove.ping();
148 };
149 }
150 }
151}
152
153impl TransactionBlocker {
154 pub fn completed() -> Self {
155 Self(Weak::new())
156 }
157}
158
159impl Blocker for TransactionBlocker {
160 fn state(&self) -> BlockerState {
161 if self.0.upgrade().map_or(true, |x| x.is_completed()) {
162 BlockerState::Released
163 } else {
164 BlockerState::Pending
165 }
166 }
167}
168
169impl Inner {
170 fn new() -> Self {
171 Self {
172 completed: AtomicBool::new(false),
173 notifications: Mutex::new(None),
174 }
175 }
176
177 fn is_completed(&self) -> bool {
178 self.completed.load(Ordering::Relaxed)
179 }
180
181 fn complete(&self) {
182 self.completed.store(true, Ordering::Relaxed);
183
184 let mut guard = self.notifications.lock().unwrap();
185 if let Some((sender, clients)) = guard.take() {
186 for client in clients {
187 if let Err(err) = sender.send(client) {
188 warn!("error sending blocker notification: {err:?}");
189 };
190 }
191 }
192 }
193}