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