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