cordis-core 0.2.12

Typed lifecycle, services, events, effects, and observation for the Cordis v3 runtime
Documentation
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Private Registry residency and exact allocation claims.

use crate::fiber::{Fiber, LifecycleRecursion};
use parking_lot::Mutex;
use std::any::TypeId;
use std::collections::HashMap;
#[cfg(test)]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Weak};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(
    dead_code,
    reason = "anonymous allocation and bulk removal are exercised by internal lifecycle probes"
)]
pub(crate) enum PluginKey {
    Typed(TypeId),
    Anonymous(u64),
}

pub(crate) struct PluginGroup {
    id: PluginKey,
    fibers: Mutex<Vec<Arc<Fiber>>>,
}

impl PluginGroup {
    fn new(id: PluginKey) -> Arc<Self> {
        Arc::new(Self {
            id,
            fibers: Mutex::new(Vec::new()),
        })
    }
    fn fiber_count(&self) -> usize {
        self.fibers.lock().len()
    }
    fn take_fiber(&self, fiber: &Arc<Fiber>) -> (Option<Arc<Fiber>>, bool) {
        let mut fibers = self.fibers.lock();
        let removed = fibers
            .iter()
            .position(|candidate| Arc::ptr_eq(candidate, fiber))
            .map(|index| fibers.remove(index));
        (removed, fibers.is_empty())
    }
}

struct RegistryState {
    allocations: Mutex<HashMap<PluginKey, Arc<PluginGroup>>>,
    /// Flat strong residency authority. Current-allocation detach does not
    /// remove a Fiber; only its exact terminal residency release does.
    residents: Mutex<Vec<Arc<Fiber>>>,
    #[cfg(test)]
    admissions: AtomicUsize,
}

pub(crate) struct Registry {
    state: Arc<RegistryState>,
}

impl Registry {
    pub(crate) fn new() -> Self {
        Self {
            state: Arc::new(RegistryState {
                allocations: Mutex::new(HashMap::new()),
                residents: Mutex::new(Vec::new()),
                #[cfg(test)]
                admissions: AtomicUsize::new(0),
            }),
        }
    }
    pub(crate) fn snapshot_fibers(&self) -> Vec<Arc<Fiber>> {
        // Serialize flat observation with membership publication.
        let _guard = self.state.allocations.lock();
        self.state.residents.lock().clone()
    }
    #[cfg(test)]
    pub(crate) fn admission_count(&self) -> usize {
        self.state.admissions.load(Ordering::SeqCst)
    }
    #[cfg(test)]
    fn resident_fiber_count(&self) -> usize {
        let _guard = self.state.allocations.lock();
        self.state.residents.lock().len()
    }
    /// Atomically attach one Fiber and install its exact residency claim.
    ///
    /// Claim installation happens while the Registry mapping is locked and
    /// before membership becomes visible to detach. A remover therefore cannot
    /// freeze this Fiber until its ordinary terminal barrier can release the
    /// exact allocation occurrence. The claim itself is weak to avoid a cycle.
    pub(crate) fn attach_fiber(&self, key: PluginKey, fiber: Arc<Fiber>) {
        let mut allocations = self.state.allocations.lock();
        let allocation = allocations
            .entry(key)
            .or_insert_with(|| PluginGroup::new(key))
            .clone();
        let claim = ResidencyClaim {
            allocation: Arc::downgrade(&allocation),
            fiber: Arc::downgrade(&fiber),
            registry: Arc::downgrade(&self.state),
        };
        let previous = fiber.residency.lock().replace(claim);
        assert!(
            previous.is_none(),
            "a Fiber may have only one residency occurrence"
        );
        allocation.fibers.lock().push(fiber.clone());
        self.state.residents.lock().push(fiber);
        #[cfg(test)]
        self.state.admissions.fetch_add(1, Ordering::SeqCst);
    }
    /// Atomically detach one current allocation and freeze its completion set.
    ///
    /// Attach uses the same Registry → allocation lock order, so a Fiber is
    /// either already in `fibers` when the mapping is detached or it observes
    /// the missing mapping and attaches to a fresh allocation. Recursion is
    /// checked while both facts are fixed and therefore refuses before detach.
    fn detach_for_removal(
        &self,
        key: PluginKey,
    ) -> std::result::Result<Option<DetachedGroup>, LifecycleRecursion> {
        let mut allocations = self.state.allocations.lock();
        let Some(allocation) = allocations.get(&key).cloned() else {
            return Ok(None);
        };
        let fibers = allocation.fibers.lock();
        crate::fiber::refuse_group_removal_recursion(&fibers)?;
        let frozen = fibers.clone();
        let detached = allocations
            .remove(&key)
            .expect("current allocation remains mapped while Registry lock is held");
        drop(fibers);
        Ok(Some(DetachedGroup {
            allocation: detached,
            fibers: frozen,
        }))
    }
}

/// One committed bulk-removal allocation. Keeping the allocation strongly alive
/// lets every frozen Fiber release its exact weak residency claim while the old
/// mapping is detached and a same-key replacement may already exist.
struct DetachedGroup {
    allocation: Arc<PluginGroup>,
    fibers: Vec<Arc<Fiber>>,
}

impl DetachedGroup {
    async fn dispose_all(self) {
        let Self { allocation, fibers } = self;
        for fiber in fibers {
            fiber.dispose().await;
        }
        debug_assert_eq!(allocation.fiber_count(), 0);
    }
}

impl crate::Context {
    /// Remove the current allocation for typed Plugin `P`.
    ///
    /// Detach is the irreversible commit: members already attached are frozen
    /// into this removal, while later same-type spawns create or join a fresh
    /// allocation. After detach, disposal is framework-owned and reaches every
    /// member's ordinary terminal unlink barrier even if this caller is
    /// cancelled. An absent allocation is already removed.
    ///
    /// A call from the settle context of a Fiber in the current allocation is
    /// refused before detach so it cannot synchronously wait on its own teardown.
    pub async fn remove_plugins<P: crate::Plugin>(
        &self,
    ) -> std::result::Result<(), LifecycleRecursion> {
        let detached = self
            .root
            .registry
            .detach_for_removal(PluginKey::Typed(TypeId::of::<P>()))?;
        let Some(detached) = detached else {
            return Ok(());
        };

        let (tx, rx) = tokio::sync::oneshot::channel();
        crate::effect::detach(async move {
            detached.dispose_all().await;
            let _ = tx.send(());
        });
        rx.await
            .expect("framework-owned group removal always publishes completion");
        Ok(())
    }
}

pub(crate) struct ResidencyClaim {
    allocation: Weak<PluginGroup>,
    fiber: Weak<Fiber>,
    registry: Weak<RegistryState>,
}

impl ResidencyClaim {
    /// Release only the exact allocation represented by this claim.
    pub(crate) fn release(self) {
        let (Some(registry), Some(allocation), Some(fiber)) = (
            self.registry.upgrade(),
            self.allocation.upgrade(),
            self.fiber.upgrade(),
        ) else {
            return;
        };
        // Match attach's registry → allocation lock order. This is what
        // prevents release from deadlocking an attach racing terminal unlink.
        let (removed_group_fiber, removed_resident, removed_allocation) = {
            let mut allocations = registry.allocations.lock();
            let current = allocations
                .get(&allocation.id)
                .is_some_and(|candidate| Arc::ptr_eq(candidate, &allocation));
            let (removed_group_fiber, idle) = allocation.take_fiber(&fiber);
            let removed_allocation = if current && idle {
                allocations.remove(&allocation.id)
            } else {
                None
            };
            let removed_resident = {
                let mut residents = registry.residents.lock();
                residents
                    .iter()
                    .position(|candidate| Arc::ptr_eq(candidate, &fiber))
                    .map(|index| residents.remove(index))
            };
            (removed_group_fiber, removed_resident, removed_allocation)
        };
        // A resident Fiber can own plugin/config values with arbitrary Drop.
        // Move every potentially-last strong reference out of all framework
        // critical sections before destruction.
        drop(removed_group_fiber);
        drop(removed_resident);
        drop(removed_allocation);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fiber::Fiber;
    use crate::{Context, Plugin, PreparedPlugin};
    use std::convert::Infallible;
    use std::future::{Future, ready};
    use std::sync::atomic::{AtomicBool, Ordering};

    struct ReentrantDrop {
        registry: Weak<RegistryState>,
        observed_unlocked: Arc<AtomicBool>,
    }

    impl Drop for ReentrantDrop {
        fn drop(&mut self) {
            let unlocked = self.registry.upgrade().is_some_and(|state| {
                state.allocations.try_lock().is_some() && state.residents.try_lock().is_some()
            });
            self.observed_unlocked.store(unlocked, Ordering::SeqCst);
        }
    }

    impl Plugin for ReentrantDrop {
        type Config = ();
        type Input = ();
        type PrepareError = Infallible;
        type ApplyError = Infallible;

        fn prepare(&self, (): ()) -> Result<(), Infallible> {
            Ok(())
        }

        fn apply(
            &self,
            _ctx: Context,
            _prepared: &(),
        ) -> impl Future<Output = Result<(), Infallible>> + Send {
            ready(Ok(()))
        }
    }

    fn attach(registry: &Registry, key: PluginKey, fiber: &Arc<Fiber>) {
        registry.attach_fiber(key, fiber.clone());
    }

    #[test]
    fn registry_strongly_retains_an_admitted_fiber() {
        let registry = Registry::new();
        let fiber = Fiber::new("resident");
        let weak = Arc::downgrade(&fiber);
        attach(&registry, PluginKey::Anonymous(1), &fiber);

        drop(fiber);

        assert!(weak.upgrade().is_some());
        assert_eq!(registry.resident_fiber_count(), 1);
    }

    #[test]
    fn terminal_unlink_drops_the_last_fiber_outside_registry_locks() {
        let ctx = Context::new();
        let registry = &ctx.root.registry;
        let observed_unlocked = Arc::new(AtomicBool::new(false));
        let prepared = PreparedPlugin::from_input(
            ReentrantDrop {
                registry: Arc::downgrade(&registry.state),
                observed_unlocked: observed_unlocked.clone(),
            },
            (),
        );
        let PreparedPlugin {
            plugin,
            name,
            inject,
            contract,
        } = prepared;
        let fiber = Fiber::new(name.clone());
        fiber
            .spawn_state
            .install(
                plugin,
                name,
                inject,
                ctx.clone(),
                PluginKey::Typed(contract),
                ctx.clone(),
            )
            .unwrap();
        registry.attach_fiber(PluginKey::Typed(contract), fiber.clone());

        drop(fiber);
        let resident = registry
            .snapshot_fibers()
            .pop()
            .expect("Fiber remains resident");
        resident.release_residency();
        drop(resident);

        assert!(observed_unlocked.load(Ordering::SeqCst));
        assert_eq!(registry.resident_fiber_count(), 0);
    }

    #[tokio::test]
    async fn typed_and_anonymous_claims_release_and_prune_their_exact_allocation() {
        let registry = Registry::new();
        let cases = [
            PluginKey::Typed(TypeId::of::<u8>()),
            PluginKey::Anonymous(2),
        ];

        for key in cases {
            let fiber = Fiber::new("resident");
            attach(&registry, key, &fiber);
            assert_eq!(registry.resident_fiber_count(), 1);

            fiber.dispose().await;

            assert_eq!(registry.resident_fiber_count(), 0);
            assert!(!registry.state.allocations.lock().contains_key(&key));
        }
    }

    #[test]
    fn detached_members_remain_flat_residents_until_exact_terminal_release() {
        let registry = Registry::new();
        let key = PluginKey::Typed(TypeId::of::<u128>());
        let old = Fiber::new("old");
        attach(&registry, key, &old);

        let detached = registry
            .detach_for_removal(key)
            .unwrap()
            .expect("current typed allocation detaches");
        assert!(registry.state.allocations.lock().get(&key).is_none());
        assert!(
            registry
                .snapshot_fibers()
                .iter()
                .any(|fiber| Arc::ptr_eq(fiber, &old))
        );

        let replacement = Fiber::new("replacement");
        attach(&registry, key, &replacement);
        let residents = registry.snapshot_fibers();
        assert_eq!(residents.len(), 2);
        assert!(residents.iter().any(|fiber| Arc::ptr_eq(fiber, &old)));
        assert!(
            residents
                .iter()
                .any(|fiber| Arc::ptr_eq(fiber, &replacement))
        );

        old.release_residency();
        let residents = registry.snapshot_fibers();
        assert_eq!(residents.len(), 1);
        assert!(Arc::ptr_eq(&residents[0], &replacement));
        assert_eq!(detached.allocation.fiber_count(), 0);

        replacement.release_residency();
        assert!(registry.snapshot_fibers().is_empty());
    }

    #[test]
    fn attach_first_defeats_prune_for_typed_and_anonymous_allocations() {
        let registry = Registry::new();
        for key in [
            PluginKey::Typed(TypeId::of::<u16>()),
            PluginKey::Anonymous(7),
        ] {
            let first = Fiber::new("first");
            attach(&registry, key, &first);
            let allocation = registry.state.allocations.lock().get(&key).unwrap().clone();

            let second = Fiber::new("second");
            attach(&registry, key, &second);
            first.release_residency();

            assert_eq!(allocation.fiber_count(), 1);
            assert!(Arc::ptr_eq(
                registry.state.allocations.lock().get(&key).unwrap(),
                &allocation
            ));
            second.release_residency();
            assert!(!registry.state.allocations.lock().contains_key(&key));
        }
    }

    #[test]
    fn prune_first_forces_a_fresh_typed_or_anonymous_allocation() {
        let registry = Registry::new();
        for key in [
            PluginKey::Typed(TypeId::of::<u32>()),
            PluginKey::Anonymous(8),
        ] {
            let first = Fiber::new("first");
            attach(&registry, key, &first);
            let old = registry.state.allocations.lock().get(&key).unwrap().clone();
            first.release_residency();
            assert!(!registry.state.allocations.lock().contains_key(&key));

            let replacement = Fiber::new("replacement");
            attach(&registry, key, &replacement);
            let fresh = registry.state.allocations.lock().get(&key).unwrap().clone();
            assert!(!Arc::ptr_eq(&old, &fresh));
            replacement.release_residency();
        }
    }

    #[test]
    fn releasing_an_old_claim_cannot_prune_a_typed_or_anonymous_replacement() {
        let registry = Registry::new();
        for key in [
            PluginKey::Typed(TypeId::of::<u64>()),
            PluginKey::Anonymous(9),
        ] {
            let first = Fiber::new("first");
            attach(&registry, key, &first);

            // This is the committed-detach window of Registry removal: the old
            // allocation remains alive while its frozen Fibers are being disposed,
            // but the grouping key already selects a fresh allocation.
            let detached = registry.state.allocations.lock().remove(&key).unwrap();
            let replacement = Fiber::new("replacement");
            attach(&registry, key, &replacement);

            first.release_residency();

            assert_eq!(detached.fiber_count(), 0);
            assert_eq!(registry.resident_fiber_count(), 1);
            let replacement_allocation = replacement
                .residency
                .lock()
                .as_ref()
                .unwrap()
                .allocation
                .upgrade()
                .unwrap();
            assert!(Arc::ptr_eq(
                registry.state.allocations.lock().get(&key).unwrap(),
                &replacement_allocation
            ));
            replacement.release_residency();
            assert_eq!(registry.resident_fiber_count(), 0);
        }
    }
}