1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
//! Registry of active connection push handles.
//!
//! `SessionRegistry` stores non-owning weak references to [`PushHandle`]s,
//! allowing asynchronous tasks to send frames to live connections without
//! preventing their cleanup. Dead entries can be pruned opportunistically or
//! lazily at lookup time.
use std::sync::{
Arc,
Weak,
atomic::{AtomicU64, Ordering},
};
use dashmap::DashMap;
use crate::push::{FrameLike, PushHandle, PushHandleInner};
/// Identifier assigned to a connection.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ConnectionId(u64);
impl From<u64> for ConnectionId {
fn from(value: u64) -> Self { Self(value) }
}
impl ConnectionId {
/// Create a new [`ConnectionId`] with the provided value.
///
/// # Examples
///
/// ```rust
/// use wireframe::session::ConnectionId;
///
/// let id = ConnectionId::new(42);
/// assert_eq!(id.as_u64(), 42);
/// ```
#[must_use]
pub const fn new(id: u64) -> Self { Self(id) }
/// Return the inner `u64` representation.
///
/// # Examples
///
/// ```rust
/// use wireframe::session::ConnectionId;
///
/// let id = ConnectionId::from(7u64);
/// assert_eq!(id.as_u64(), 7);
/// ```
#[must_use]
pub const fn as_u64(&self) -> u64 { self.0 }
}
impl std::fmt::Display for ConnectionId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ConnectionId({})", self.0)
}
}
/// Concurrent registry of push handles keyed by [`ConnectionId`].
///
/// The registry also owns the source of connection identifiers. Identifiers
/// start at one and increase monotonically, so a value freed by a closed
/// connection is never reused for a later one.
pub struct SessionRegistry<F> {
/// Weak references to the live push handles, keyed by connection.
entries: DashMap<ConnectionId, Weak<PushHandleInner<F>>>,
/// Next identifier handed to a connection.
next_id: AtomicU64,
}
impl<F> Default for SessionRegistry<F> {
fn default() -> Self { Self::new() }
}
impl<F> SessionRegistry<F> {
/// Create an empty registry.
///
/// The first identifier allocated by [`Self::allocate_connection_id`] is `1`.
///
/// # Examples
///
/// ```rust
/// use wireframe::session::{ConnectionId, SessionRegistry};
///
/// let registry = SessionRegistry::<u8>::new();
/// assert_eq!(registry.allocate_connection_id(), ConnectionId::new(1));
/// ```
#[must_use]
pub fn new() -> Self {
Self {
entries: DashMap::new(),
next_id: AtomicU64::new(1),
}
}
/// Allocate the next connection identifier no entry currently occupies.
///
/// Identifiers are unique for the lifetime of the registry and are never
/// reused. Callers should allocate one per accepted connection and store
/// it alongside the connection's push handle.
///
/// An identifier already present in the registry is skipped rather than
/// handed out. An application that still inserts entries by hand therefore
/// keeps them: the first server connection receives `1` only when no entry
/// occupies it, and otherwise the next free identifier.
///
/// # Panics
///
/// Panics when the `u64` identifier space is exhausted. That requires
/// allocating every possible identifier, so it is unrecoverable, not a wrap.
#[must_use]
pub fn allocate_connection_id(&self) -> ConnectionId {
self.claim_next(|candidate| !self.entries.contains_key(&candidate))
}
/// Take identifiers from the counter until `publish` accepts one.
///
/// A candidate is offered to `publish` before the next is taken, so a
/// publisher that cannot hold the identifier it is given can refuse it and
/// have the claim move on. The accepted candidate is therefore one the
/// caller holds.
///
/// # Panics
/// Panics when the `u64` identifier space is exhausted.
fn claim_next(&self, mut publish: impl FnMut(ConnectionId) -> bool) -> ConnectionId {
loop {
let Ok(id) = self
.next_id
.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
else {
panic!("connection identifier space exhausted");
};
let candidate = ConnectionId::new(id);
if publish(candidate) {
return candidate;
}
}
}
}
impl<F: FrameLike> SessionRegistry<F> {
/// Retain live entries and collect data from each upgraded handle.
fn retain_and_collect<T>(
&self,
mut map: impl FnMut(ConnectionId, Arc<PushHandleInner<F>>) -> T,
) -> Vec<T> {
let mut out = Vec::with_capacity(self.entries.len());
self.entries.retain(|id, weak| {
weak.upgrade().is_some_and(|inner| {
out.push(map(*id, inner));
true
})
});
out
}
/// Retrieve a [`PushHandle`] for `id` if the connection is still alive.
///
/// # Examples
///
/// ```rust
/// use wireframe::{
/// push::PushQueues,
/// session::{ConnectionId, SessionRegistry},
/// };
///
/// let (_queues, handle) = PushQueues::<u8>::builder()
/// .unlimited()
/// .build()
/// .expect("failed to build PushQueues");
/// let registry = SessionRegistry::default();
/// let id = ConnectionId::new(1);
/// assert!(registry.insert(id, &handle));
/// assert!(registry.get(&id).is_some());
/// ```
pub fn get(&self, id: &ConnectionId) -> Option<PushHandle<F>> {
let guard = self.entries.get(id);
let handle = guard.as_ref().and_then(|weak| weak.upgrade());
drop(guard);
if handle.is_none() {
self.entries
.remove_if(id, |_, weak| weak.strong_count() == 0);
}
handle.map(PushHandle::from_arc)
}
/// Insert a handle for a newly established connection.
///
/// Returns `true` when the handle was published, and `false` when a live
/// connection already owns the identifier: its entry is kept, so a manual
/// insert cannot displace the handle of a connection the registry
/// allocated that identifier to. Call [`Self::remove`] first to replace a
/// live entry deliberately.
///
/// A dead entry does not block publication. Its weak reference cannot
/// upgrade, so replacing it publishes the new handle under the same
/// identifier without affecting any live connection.
///
/// # Examples
///
/// ```rust
/// use wireframe::{
/// push::PushQueues,
/// session::{ConnectionId, SessionRegistry},
/// };
///
/// let (_queues, handle) = PushQueues::<u8>::builder()
/// .unlimited()
/// .build()
/// .expect("failed to build PushQueues");
/// let registry = SessionRegistry::default();
/// let id = ConnectionId::new(2);
/// assert!(registry.get(&id).is_none());
/// assert!(registry.insert(id, &handle));
/// assert!(registry.get(&id).is_some());
/// // A second publish would displace a live connection, so it is refused.
/// assert!(!registry.insert(id, &handle));
/// ```
#[must_use]
pub fn insert(&self, id: ConnectionId, handle: &PushHandle<F>) -> bool {
match self.entries.entry(id) {
dashmap::mapref::entry::Entry::Occupied(mut occupied) => {
if occupied.get().strong_count() > 0 {
return false;
}
occupied.insert(handle.downgrade());
}
dashmap::mapref::entry::Entry::Vacant(vacant) => {
vacant.insert(handle.downgrade());
}
}
true
}
/// Allocate an identifier and publish `handle` under it in one step.
///
/// Allocation and publication are a single claim, so a manual
/// [`Self::insert`] racing this call cannot leave the connection addressing
/// a handle it does not own: a live identifier is refused and retried.
///
/// # Panics
///
/// Panics when the `u64` identifier space is exhausted.
///
/// # Examples
///
/// ```rust
/// use wireframe::{push::PushQueues, session::SessionRegistry};
/// let (_queues, handle) = PushQueues::<u8>::builder()
/// .unlimited()
/// .build()
/// .expect("failed to build PushQueues");
/// let registry = SessionRegistry::default();
/// let id = registry.allocate_and_publish(&handle);
/// assert!(registry.get(&id).is_some());
/// ```
#[must_use]
pub fn allocate_and_publish(&self, handle: &PushHandle<F>) -> ConnectionId {
self.claim_next(|candidate| self.insert(candidate, handle))
}
/// Remove a handle, typically on connection teardown.
///
/// # Examples
///
/// ```rust
/// use wireframe::{
/// push::PushQueues,
/// session::{ConnectionId, SessionRegistry},
/// };
///
/// let (_queues, handle) = PushQueues::<u8>::builder()
/// .unlimited()
/// .build()
/// .expect("failed to build PushQueues");
/// let registry = SessionRegistry::default();
/// let id = ConnectionId::new(3);
/// assert!(registry.insert(id, &handle));
/// assert!(registry.get(&id).is_some());
/// registry.remove(&id);
/// assert!(registry.get(&id).is_none());
/// ```
pub fn remove(&self, id: &ConnectionId) { self.entries.remove(id); }
/// Remove the entry for `id` only while it still holds `handle`, reporting
/// whether one was removed. Teardown uses this rather than [`Self::remove`],
/// so a connection cannot remove a handle a later insert published under its
/// old identifier.
pub(crate) fn remove_owned(&self, id: ConnectionId, handle: &PushHandle<F>) -> bool {
let owned = handle.downgrade();
self.entries
.remove_if(&id, |_, weak| Weak::ptr_eq(weak, &owned))
.is_some()
}
/// Remove all stale weak references without returning any handles.
///
/// `DashMap::retain` acquires per-bucket write locks, so other operations
/// may contend briefly while the registry is pruned.
///
/// # Examples
///
/// ```rust
/// use wireframe::{
/// push::PushQueues,
/// session::{ConnectionId, SessionRegistry},
/// };
///
/// let registry = SessionRegistry::default();
/// let (_queues, handle) = PushQueues::<u8>::builder()
/// .unlimited()
/// .build()
/// .expect("failed to build PushQueues");
/// let id = ConnectionId::new(4);
/// assert!(registry.insert(id, &handle));
/// drop(handle);
/// registry.prune();
/// assert!(registry.get(&id).is_none());
/// ```
pub fn prune(&self) { self.entries.retain(|_, weak| weak.strong_count() > 0); }
/// Prune stale weak references, then collect the remaining live handles.
///
/// This method mutates the registry. Use [`Self::prune`] from a maintenance task
/// to clean up without collecting handles. `DashMap::retain` holds
/// per-bucket write locks while iterating.
///
/// # Examples
///
/// ```rust
/// use wireframe::{
/// push::PushQueues,
/// session::{ConnectionId, SessionRegistry},
/// };
///
/// let registry = SessionRegistry::default();
/// let (_q1, h1) = PushQueues::<u8>::builder()
/// .unlimited()
/// .build()
/// .expect("failed to build PushQueues");
/// let (_q2, h2) = PushQueues::<u8>::builder()
/// .unlimited()
/// .build()
/// .expect("failed to build PushQueues");
/// let id1 = ConnectionId::new(5);
/// let id2 = ConnectionId::new(6);
/// assert!(registry.insert(id1, &h1));
/// assert!(registry.insert(id2, &h2));
/// drop(h1);
/// let active = registry.active_handles();
/// assert_eq!(active.len(), 1);
/// assert_eq!(active[0].0, id2);
/// ```
#[must_use]
pub fn active_handles(&self) -> Vec<(ConnectionId, PushHandle<F>)> {
self.retain_and_collect(|id, inner| (id, PushHandle::from_arc(inner)))
}
/// Prune stale weak references, then return the IDs of the live connections.
///
/// This method mutates the registry. Use [`Self::prune`] from a maintenance task
/// to clean up without collecting handles. `DashMap::retain` holds
/// per-bucket write locks while iterating.
///
/// # Examples
///
/// ```rust
/// use wireframe::{
/// push::PushQueues,
/// session::{ConnectionId, SessionRegistry},
/// };
///
/// let registry = SessionRegistry::default();
/// let (_q1, h1) = PushQueues::<u8>::builder()
/// .unlimited()
/// .build()
/// .expect("failed to build PushQueues");
/// let (_q2, h2) = PushQueues::<u8>::builder()
/// .unlimited()
/// .build()
/// .expect("failed to build PushQueues");
/// let id1 = ConnectionId::new(7);
/// let id2 = ConnectionId::new(8);
/// assert!(registry.insert(id1, &h1));
/// assert!(registry.insert(id2, &h2));
/// drop(h1);
/// let ids = registry.active_ids();
/// assert_eq!(ids, vec![id2]);
/// ```
#[must_use]
pub fn active_ids(&self) -> Vec<ConnectionId> { self.retain_and_collect(|id, _| id) }
}
#[cfg(test)]
#[path = "session_tests.rs"]
mod tests;