Skip to main content

tuwunel_core/utils/
two_phase_counter.rs

1//! Two-Phase Counter.
2
3use std::{
4	collections::VecDeque,
5	ops::{Deref, Range},
6	sync::{Arc, RwLock},
7};
8
9use crate::{Result, checked, is_equal_to};
10
11/// Two-Phase Counter.
12///
13/// This device solves the problem of a One-Phase Counter (or just a counter)
14/// which is incremented to provide unique sequence numbers (or index numbers)
15/// fundamental to server operation. For example, let's say a new Matrix Pdu
16/// is received: the counter is incremented and its value becomes the PduId
17/// used as a key for the Pdu value when writing to the database.
18///
19/// Problem: With a single counter shared by both writers and readers, pending
20/// writes might still be in-flight and not visible to readers after the writer
21/// incremented it. For example, client-sync sees the counter at a certain
22/// value, but that value has no Pdu found because its write has not been
23/// completed with global visibility. Client-sync will then move on to the next
24/// counter value having missed the data from the current one.
25pub struct Counter<F: Fn(u64) -> Result + Send + Sync> {
26	/// Self is intended to be `Arc<Counter>` with inner state mutable via Lock.
27	inner: RwLock<State<F>>,
28}
29
30/// Inner protected state for Two-Phase Counter.
31pub struct State<F: Fn(u64) -> Result + Send + Sync> {
32	/// Monotonic counter. The next sequence number is drawn by adding one to
33	/// this value. That number will be persisted and added to `pending`.
34	dispatched: u64,
35
36	/// Callback to persist the next sequence number drawn from `dispatched`.
37	/// This prevents pending numbers from being reused after server restart.
38	commit: F,
39
40	/// List of pending sequence numbers. One less than the minimum value in
41	/// this list is the "retirement" sequence number where all writes have
42	/// completed and all reads are globally visible.
43	pending: VecDeque<u64>,
44
45	/// Callback to notify updates of the retirement value. This is likely
46	/// called from the destructor of a permit/guard; try not to panic.
47	release: F,
48}
49
50#[clippy::has_significant_drop]
51/// Holds a dispatched sequence number until its write operation retires.
52///
53/// The permit dereferences to its unique sequence number and records the
54/// retirement frontier sampled at dispatch. Dropping it retires the sequence
55/// through the shared counter so the retirement frontier advances in order.
56pub struct Permit<F: Fn(u64) -> Result + Send + Sync> {
57	/// Link back to the shared-state.
58	state: Arc<Counter<F>>,
59
60	/// The retirement value computed as a courtesy when this permit was
61	/// created.
62	retired: u64,
63
64	/// Sequence number of this permit.
65	id: u64,
66}
67
68impl<F: Fn(u64) -> Result + Send + Sync> Counter<F> {
69	/// Construct a new Two-Phase counter state. The value of `init` is
70	/// considered retired, and the next sequence number dispatched will be one
71	/// greater.
72	pub fn new(init: u64, commit: F, release: F) -> Arc<Self> {
73		Arc::new(Self {
74			inner: State::new(init, commit, release).into(),
75		})
76	}
77
78	/// Obtain a sequence number to conduct write operations for the scope.
79	pub fn next(self: &Arc<Self>) -> Result<Permit<F>> {
80		let (retired, id) = self.inner.write()?.dispatch()?;
81
82		Ok(Permit::<F> { state: self.clone(), retired, id })
83	}
84
85	/// Load the current and dispatched values simultaneously
86	#[inline]
87	pub fn range(&self) -> Range<u64> {
88		let inner = self.inner.read().expect("locked for reading");
89
90		Range {
91			start: inner.retired(),
92			end: inner.dispatched,
93		}
94	}
95
96	/// Load the highest sequence number safe for reading, also known as the
97	/// retirement value with writes "globally visible."
98	#[inline]
99	pub fn current(&self) -> u64 {
100		self.inner
101			.read()
102			.expect("locked for reading")
103			.retired()
104	}
105
106	/// Load the highest sequence number (dispatched); may still be pending or
107	/// may be retired.
108	#[inline]
109	pub fn dispatched(&self) -> u64 {
110		self.inner
111			.read()
112			.expect("locked for reading")
113			.dispatched
114	}
115}
116
117impl<F: Fn(u64) -> Result + Send + Sync> State<F> {
118	/// Create new state, starting from `init`. The next sequence number
119	/// dispatched will be one greater than `init`.
120	fn new(dispatched: u64, commit: F, release: F) -> Self {
121		Self {
122			dispatched,
123			commit,
124			pending: VecDeque::new(),
125			release,
126		}
127	}
128
129	/// Dispatch the next sequence number as pending. The retired value is
130	/// calculated as a courtesy while the state is under lock.
131	fn dispatch(&mut self) -> Result<(u64, u64)> {
132		let prev = self.dispatched;
133		let retired = self.retired();
134		let dispatched = checked!(prev + 1)?;
135		debug_assert!(
136			!self.check_pending(dispatched),
137			"sequence number cannot already be pending",
138		);
139
140		(self.commit)(dispatched)?;
141		self.dispatched = dispatched;
142		self.pending.push_back(self.dispatched);
143		Ok((retired, self.dispatched))
144	}
145
146	/// Retire the sequence number `id`.
147	fn retire(&mut self, id: u64) {
148		debug_assert!(self.check_pending(id), "sequence number must be currently pending");
149
150		let index = self
151			.pending_index(id)
152			.expect("sequence number must be found as pending");
153
154		let removed = self
155			.pending
156			.remove(index)
157			.expect("sequence number at index must be removed");
158
159		debug_assert_eq!(removed, id, "sequence number removed must match id");
160
161		// release only occurs when the oldest value retires
162		if index != 0 {
163			return;
164		}
165
166		// release occurs for the maximum retired value
167		let release = if self.pending.is_empty() { self.dispatched } else { id };
168
169		debug_assert!(release >= id, "sequence number released must not be less than id");
170
171		(self.release)(release).expect("release callback should not error");
172	}
173
174	/// Calculate the retired sequence number, one less than the lowest pending
175	/// sequence number. If nothing is pending the value of `dispatched` has
176	/// been previously retired and is returned.
177	fn retired(&self) -> u64 {
178		debug_assert!(
179			self.pending.iter().is_sorted(),
180			"Pending values should be naturally sorted"
181		);
182
183		self.pending
184			.front()
185			.map(|val| val.saturating_sub(1))
186			.unwrap_or(self.dispatched)
187	}
188
189	/// Get the position of `id` in the pending list.
190	fn pending_index(&self, id: u64) -> Option<usize> {
191		debug_assert!(
192			self.pending.iter().is_sorted(),
193			"Pending values should be naturally sorted"
194		);
195
196		self.pending.binary_search(&id).ok()
197	}
198
199	/// Check for `id` in the pending list sequentially (for debug and assertion
200	/// purposes only)
201	fn check_pending(&self, id: u64) -> bool { self.pending.iter().any(is_equal_to!(&id)) }
202}
203
204impl<F: Fn(u64) -> Result + Send + Sync> Permit<F> {
205	/// Access the retired sequence number sampled at this permit's creation.
206	/// This may be outdated prior to access. Obtained as a courtesy under lock.
207	#[inline]
208	#[must_use]
209	pub fn retired(&self) -> &u64 { &self.retired }
210
211	/// Access the sequence number obtained by this permit; a unique value
212	#[inline]
213	#[must_use]
214	pub fn id(&self) -> &u64 { &self.id }
215}
216
217impl<F: Fn(u64) -> Result + Send + Sync> Deref for Permit<F> {
218	type Target = u64;
219
220	#[inline]
221	fn deref(&self) -> &Self::Target { self.id() }
222}
223
224impl<F: Fn(u64) -> Result + Send + Sync> Drop for Permit<F> {
225	fn drop(&mut self) {
226		self.state
227			.inner
228			.write()
229			.expect("locked for writing")
230			.retire(self.id);
231	}
232}