1#![allow(missing_docs)]
12
13use std::collections::HashMap;
14use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15
16use super::error::{LifecycleError, RuntimeError};
17use super::process::FlowId;
18use super::sync_lock;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
27pub struct LinkId(pub(crate) u64);
28
29pub(super) const CONSUMED_LINK_ID: u64 = 0;
32
33const MAX_LINK_ID: u64 = i64::MAX as u64;
35
36static NEXT_LINK: AtomicU64 = AtomicU64::new(1);
37static LINK_IDS_EXHAUSTED: AtomicBool = AtomicBool::new(false);
38
39impl LinkId {
40 #[inline]
41 pub fn as_u64(self) -> u64 {
42 self.0
43 }
44
45 #[inline]
46 pub(crate) fn from_u64(raw: u64) -> Self {
47 Self(raw)
48 }
49}
50
51impl std::fmt::Display for LinkId {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 write!(f, "link#{}", self.0)
54 }
55}
56
57fn try_next_link_id() -> Result<LinkId, RuntimeError> {
58 if LINK_IDS_EXHAUSTED.load(Ordering::Relaxed) {
59 return Err(RuntimeError::LinkIdExhausted);
60 }
61 let id = NEXT_LINK.fetch_add(1, Ordering::Relaxed);
62 if id == 0 || id > MAX_LINK_ID {
63 LINK_IDS_EXHAUSTED.store(true, Ordering::Relaxed);
64 return Err(RuntimeError::LinkIdExhausted);
65 }
66 Ok(LinkId(id))
67}
68
69#[derive(Debug, Clone, Copy)]
70struct Link {
71 a: FlowId,
72 b: FlowId,
73}
74
75pub(super) struct LinkTable {
81 links: HashMap<LinkId, Link>,
82 pairs: HashMap<(FlowId, FlowId), LinkId>,
83 by_flow: HashMap<FlowId, Vec<LinkId>>,
84}
85
86impl LinkTable {
87 pub(super) fn new() -> Self {
88 Self {
89 links: HashMap::new(),
90 pairs: HashMap::new(),
91 by_flow: HashMap::new(),
92 }
93 }
94
95 #[inline]
96 pub(super) fn len(&self) -> usize {
97 self.links.len()
98 }
99
100 #[inline]
101 fn pair_key(a: FlowId, b: FlowId) -> (FlowId, FlowId) {
102 if a <= b {
103 (a, b)
104 } else {
105 (b, a)
106 }
107 }
108
109 #[inline]
110 pub(super) fn has_pair(&self, a: FlowId, b: FlowId) -> bool {
111 a != b && self.pairs.contains_key(&Self::pair_key(a, b))
112 }
113
114 fn drop_index(&mut self, flow: FlowId, id: LinkId) {
115 if let Some(ids) = self.by_flow.get_mut(&flow) {
116 ids.retain(|existing| *existing != id);
117 if ids.is_empty() {
118 self.by_flow.remove(&flow);
119 }
120 }
121 }
122
123 fn index_flow(&mut self, flow: FlowId, id: LinkId) {
124 self.by_flow.entry(flow).or_default().push(id);
125 }
126
127 fn insert(&mut self, id: LinkId, a: FlowId, b: FlowId) {
129 self.links.insert(id, Link { a, b });
130 self.pairs.insert(Self::pair_key(a, b), id);
131 self.index_flow(a, id);
132 self.index_flow(b, id);
133 }
134
135 fn unlink_id(&mut self, id: LinkId) -> Option<Link> {
137 let link = self.links.remove(&id)?;
138 self.pairs.remove(&Self::pair_key(link.a, link.b));
139 self.drop_index(link.a, id);
140 self.drop_index(link.b, id);
141 Some(link)
142 }
143
144 #[cfg(test)]
145 pub(crate) fn link(&mut self, a: FlowId, b: FlowId) -> Result<LinkId, LifecycleError> {
146 if a == b {
147 return Err(LifecycleError::SelfRelation);
148 }
149 if self.has_pair(a, b) {
150 return Err(LifecycleError::AlreadyLinked);
151 }
152 let id = match try_next_link_id() {
153 Ok(id) => id,
154 Err(_) => return Err(LifecycleError::Unavailable),
155 };
156 self.insert(id, a, b);
157 Ok(id)
158 }
159
160 pub(super) fn unlink_owned(&mut self, owner: FlowId, id: LinkId) -> Result<(), LifecycleError> {
161 match self.links.get(&id) {
162 Some(link) if link.a == owner || link.b == owner => {
163 let _ = self.unlink_id(id);
164 Ok(())
165 }
166 Some(_) => Err(LifecycleError::NotOwner),
167 None => Err(LifecycleError::InvalidLink),
168 }
169 }
170
171 pub(super) fn remove_links_of(&mut self, target: FlowId) -> Vec<(LinkId, FlowId)> {
176 let Some(ids) = self.by_flow.remove(&target) else {
177 return Vec::new();
178 };
179 let mut result = Vec::with_capacity(ids.len());
180 for id in ids {
181 let Some(link) = self.links.remove(&id) else {
182 continue;
183 };
184 self.pairs.remove(&Self::pair_key(link.a, link.b));
185 let peer = if link.a == target { link.b } else { link.a };
186 self.drop_index(peer, id);
187 result.push((id, peer));
188 }
189 result.sort_unstable_by_key(|(id, _)| id.0);
190 result
191 }
192}
193
194impl Default for LinkTable {
195 fn default() -> Self {
196 Self::new()
197 }
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub(crate) enum LinkOutcome {
203 Linked(LinkId),
205 Consumed { dead: FlowId },
208}
209
210pub(crate) struct LinkStore {
212 inner: std::sync::Mutex<LinkTable>,
213 max_links: u32,
214}
215
216impl LinkStore {
217 pub(crate) fn new(max_links: u32) -> Self {
219 Self {
220 inner: std::sync::Mutex::new(LinkTable::new()),
221 max_links,
222 }
223 }
224
225 #[cfg(test)]
227 pub(crate) fn link(
228 &self,
229 a: FlowId,
230 b: FlowId,
231 ) -> Result<Result<LinkId, LifecycleError>, RuntimeError> {
232 match self.link_if_live(a, b, |_| Ok(true))? {
233 Ok(LinkOutcome::Linked(id)) => Ok(Ok(id)),
234 Ok(LinkOutcome::Consumed { dead }) => Ok(Err(LifecycleError::NoSuchFlow(dead))),
235 Err(error) => Ok(Err(error)),
236 }
237 }
238
239 pub(crate) fn link_if_live<F>(
251 &self,
252 a: FlowId,
253 b: FlowId,
254 is_live: F,
255 ) -> Result<Result<LinkOutcome, LifecycleError>, RuntimeError>
256 where
257 F: Fn(FlowId) -> Result<bool, RuntimeError>,
258 {
259 let id = {
260 let mut table = sync_lock::lock(&self.inner, "LinkStore::link")?;
261 if a == b {
264 return Ok(Err(LifecycleError::SelfRelation));
265 }
266 if table.has_pair(a, b) {
267 return Ok(Err(LifecycleError::AlreadyLinked));
268 }
269 if self.max_links != 0 && table.len() >= self.max_links as usize {
270 return Ok(Err(LifecycleError::LinkLimitReached {
271 limit: self.max_links,
272 }));
273 }
274 let id = try_next_link_id()?;
275 table.insert(id, a, b);
276 id
277 };
278 self.confirm_live(id, a, b, is_live)
279 }
280
281 fn confirm_live<F>(
282 &self,
283 id: LinkId,
284 a: FlowId,
285 b: FlowId,
286 is_live: F,
287 ) -> Result<Result<LinkOutcome, LifecycleError>, RuntimeError>
288 where
289 F: Fn(FlowId) -> Result<bool, RuntimeError>,
290 {
291 let a_live = match is_live(a) {
292 Ok(v) => v,
293 Err(e) => {
294 let _ = self.force_remove(id);
295 return Err(e);
296 }
297 };
298 let b_live = match is_live(b) {
299 Ok(v) => v,
300 Err(e) => {
301 let _ = self.force_remove(id);
302 return Err(e);
303 }
304 };
305 if a_live && b_live {
306 return Ok(Ok(LinkOutcome::Linked(id)));
307 }
308 let dead = if a_live { b } else { a };
309 match self.force_remove(id) {
310 Ok(true) => Ok(Err(LifecycleError::NoSuchFlow(dead))),
311 Ok(false) => Ok(Ok(LinkOutcome::Consumed { dead })),
312 Err(e) => Err(e),
313 }
314 }
315
316 fn force_remove(&self, id: LinkId) -> Result<bool, RuntimeError> {
317 Ok(sync_lock::lock(&self.inner, "LinkStore::confirm_live")?
318 .unlink_id(id)
319 .is_some())
320 }
321
322 pub(crate) fn unlink_owned(
323 &self,
324 owner: FlowId,
325 id: LinkId,
326 ) -> Result<Result<(), LifecycleError>, RuntimeError> {
327 Ok(sync_lock::lock(&self.inner, "LinkStore::unlink_owned")?.unlink_owned(owner, id))
328 }
329
330 pub(crate) fn remove_links_of(
331 &self,
332 target: FlowId,
333 ) -> Result<Vec<(LinkId, FlowId)>, RuntimeError> {
334 Ok(sync_lock::lock(&self.inner, "LinkStore::remove_links_of")?.remove_links_of(target))
335 }
336}
337
338impl Default for LinkStore {
339 fn default() -> Self {
340 Self::new(0)
341 }
342}
343
344#[cfg(test)]
345mod tests {
346 use super::*;
347 use crate::scheduler::process::next_flow_id;
348
349 #[test]
350 fn remove_links_returns_both_directions() -> Result<(), String> {
351 let mut table = LinkTable::new();
352 let a = next_flow_id();
353 let b = next_flow_id();
354 let c = next_flow_id();
355 table.link(a, b).map_err(|e| e.to_string())?;
356 table.link(c, a).map_err(|e| e.to_string())?;
357 let removed = table.remove_links_of(a);
358 let peers: Vec<FlowId> = removed.iter().map(|(_, p)| *p).collect();
359 assert_eq!(peers.len(), 2);
360 assert!(peers.contains(&b));
361 assert!(peers.contains(&c));
362 assert!(removed[0].0 < removed[1].0);
363 assert!(table.remove_links_of(a).is_empty());
364 assert!(table.remove_links_of(b).is_empty());
365 assert!(table.remove_links_of(c).is_empty());
366 assert_eq!(table.len(), 0);
367 Ok(())
368 }
369
370 #[test]
371 fn rejects_self_and_duplicate() {
372 let mut table = LinkTable::new();
373 let a = next_flow_id();
374 let b = next_flow_id();
375 assert_eq!(table.link(a, a), Err(LifecycleError::SelfRelation));
376 assert!(table.link(a, b).is_ok());
377 assert_eq!(table.link(b, a), Err(LifecycleError::AlreadyLinked));
378 assert!(table.has_pair(a, b));
379 assert!(table.has_pair(b, a));
380 }
381
382 #[test]
383 fn unlink_owned_rejects_stranger_and_unknown() -> Result<(), String> {
384 let mut table = LinkTable::new();
385 let a = next_flow_id();
386 let b = next_flow_id();
387 let stranger = next_flow_id();
388 let id = table.link(a, b).map_err(|e| e.to_string())?;
389 assert_eq!(
390 table.unlink_owned(stranger, id),
391 Err(LifecycleError::NotOwner)
392 );
393 assert_eq!(
394 table.unlink_owned(a, LinkId::from_u64(0)),
395 Err(LifecycleError::InvalidLink)
396 );
397 table.unlink_owned(b, id).map_err(|e| e.to_string())?;
398 assert_eq!(table.unlink_owned(a, id), Err(LifecycleError::InvalidLink));
399 assert_eq!(table.len(), 0);
400 assert!(!table.has_pair(a, b));
401 Ok(())
402 }
403
404 #[test]
405 fn unlink_after_remove_is_invalid() -> Result<(), String> {
406 let mut table = LinkTable::new();
407 let a = next_flow_id();
408 let b = next_flow_id();
409 let id = table.link(a, b).map_err(|e| e.to_string())?;
410 assert_eq!(table.remove_links_of(a), vec![(id, b)]);
411 assert_eq!(table.unlink_owned(b, id), Err(LifecycleError::InvalidLink));
412 Ok(())
413 }
414
415 #[test]
416 fn link_limit_is_process_wide_and_released() -> Result<(), Box<dyn std::error::Error>> {
417 let store = LinkStore::new(1);
418 let a = next_flow_id();
419 let b = next_flow_id();
420 let c = next_flow_id();
421 let first = store.link(a, b)??;
422 let second = store.link(b, c)?;
423 assert!(matches!(
424 second,
425 Err(LifecycleError::LinkLimitReached { limit: 1 })
426 ));
427 store.unlink_owned(a, first)??;
428 store.link(b, c)??;
429 Ok(())
430 }
431
432 #[test]
433 fn link_limit_does_not_mask_self_or_duplicate() -> Result<(), Box<dyn std::error::Error>> {
434 let store = LinkStore::new(1);
435 let a = next_flow_id();
436 let b = next_flow_id();
437 store.link(a, b)??;
438 let self_err = store.link(a, a)?;
440 assert!(matches!(self_err, Err(LifecycleError::SelfRelation)));
441 let dup = store.link(b, a)?;
442 assert!(matches!(dup, Err(LifecycleError::AlreadyLinked)));
443 let other = store.link(a, next_flow_id())?;
444 assert!(matches!(
445 other,
446 Err(LifecycleError::LinkLimitReached { limit: 1 })
447 ));
448 Ok(())
449 }
450
451 #[test]
452 fn unlimited_store_accepts_many() -> Result<(), Box<dyn std::error::Error>> {
453 let store = LinkStore::new(0);
454 let a = next_flow_id();
455 store.link(a, next_flow_id())??;
456 store.link(a, next_flow_id())??;
457 store.link(a, next_flow_id())??;
458 Ok(())
459 }
460
461 #[test]
462 fn dead_peer_rolls_back_and_releases_quota() -> Result<(), Box<dyn std::error::Error>> {
463 let store = LinkStore::new(1);
464 let a = next_flow_id();
465 let b = next_flow_id();
466 let result = store.link_if_live(a, b, |id| Ok(id != b))?;
467 assert!(matches!(result, Err(LifecycleError::NoSuchFlow(dead)) if dead == b));
468 store.link_if_live(a, next_flow_id(), |_| Ok(true))??;
470 Ok(())
471 }
472
473 #[test]
474 fn finalize_already_removed_is_not_a_second_fault() -> Result<(), Box<dyn std::error::Error>> {
475 let store = LinkStore::new(0);
476 let a = next_flow_id();
477 let b = next_flow_id();
478 let id = {
481 let mut table = sync_lock::lock(&store.inner, "test")?;
482 if table.has_pair(a, b) {
483 return Err("pair should be free".into());
484 }
485 let id = try_next_link_id()?;
486 table.insert(id, a, b);
487 id
488 };
489 let _ = store.remove_links_of(b)?;
490 let confirmed = store.confirm_live(id, a, b, |id| Ok(id != b))?;
491 assert_eq!(confirmed, Ok(LinkOutcome::Consumed { dead: b }));
492 Ok(())
493 }
494}