dope-net 0.30.1

Owned network transports for dope
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
use std::{cell, mem};

use dope_core::driver::route::{
    Identity, KeyTag,
    table::{self, borrows, conn, entries::vacant},
};
use o3::{
    alloc,
    depot::{arena::slab, queue::indexed::shared, raw::Compact as _},
};
use pending::node::{Next, Node, State};

use crate::{
    link::{
        egress::reserve::demand,
        pool::{
            self, pending,
            recv::{input, storage::tail},
        },
        slot::types,
    },
    wire::{self, send},
};

mod node;
mod round;

pub use round::Round;

pub struct Pending<
    'a,
    'p,
    'w,
    'd,
    ID: Identity + 'w,
    T: crate::Transport,
    W: wire::Spec,
    S,
    M: input::Mode<W>,
    B,
    const IOV: usize,
    D: demand::Mode = demand::Fallible,
> where
    'd: 'w,
{
    pool: &'a pool::Connections<'p, 'w, 'd, ID, T, W, S, M, B, IOV, D>,
}

pub struct Mut<'a, 'd, ID: Identity, C> {
    slab: borrows::Access<'a, C, ID>,
    queue: &'a Queue<'d, ID>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Disposition {
    /// No scheduler-owned work remains. Any future progress has an external wake.
    Idle,
    /// The exact generation no longer exists and must be invalidated.
    Gone,
}

impl<'a, 'p, 'w, 'd, ID: Identity + 'w, T, W, S, M, B, const IOV: usize, D>
    Pending<'a, 'p, 'w, 'd, ID, T, W, S, M, B, IOV, D>
where
    'd: 'w,
    T: crate::Transport,
    W: wire::Spec,
    M: input::Mode<W>,
    D: demand::Mode,
{
    pub fn of(pool: &'a pool::Connections<'p, 'w, 'd, ID, T, W, S, M, B, IOV, D>) -> Self {
        Self { pool }
    }

    pub fn at(self, key: pool::Key<'d, ID>) -> Option<Handle<'a, 'd, ID>> {
        if !self.pool.prepared.slab.contains(key.parts()) {
            return None;
        }
        self.pool.prepared.pending.handle(key)
    }

    pub fn close(self, key: pool::Key<'d, ID>) {
        if let Some(conn) = self.pool.prepared.slab.get(key.parts())
            && let Some(handle) = self.pool.prepared.pending.handle(key)
        {
            conn.io().close();
            handle.wake();
        }
    }

    pub fn try_round(self) -> Result<Round<'p, 'd, ID>, Busy> {
        Round::try_new(
            self.pool.prepared.pending,
            *self.pool.keys,
            self.has_capacity(),
        )
    }

    pub fn is_empty(self) -> bool {
        self.pool.prepared.pending.is_empty() && !self.has_capacity()
    }

    fn has_capacity(&self) -> bool {
        self.pool.prepared.pending.has_waiting()
            && <W::Send as send::Policy<W>>::has_capacity(&self.pool.prepared.runtime)
    }
}

impl<'a, 'w, 'd, ID: Identity + 'w, W: wire::Spec, S>
    Mut<'a, 'd, ID, types::Connection<'w, 'd, ID, W, S>>
where
    'd: 'w,
{
    pub fn of<'p, T, M, B, const IOV: usize, D>(
        pool: &'a mut pool::Connections<'p, 'w, 'd, ID, T, W, S, M, B, IOV, D>,
    ) -> Self
    where
        T: crate::Transport,
        M: input::Mode<W>,
        D: demand::Mode,
    {
        Self {
            queue: pool.prepared.pending,
            slab: pool.prepared.slab.access(),
        }
    }
}

impl<'a, 'd, ID: Identity, C> Mut<'a, 'd, ID, C> {
    pub fn get(self, key: pool::Key<'d, ID>) -> Option<(&'a mut C, Handle<'a, 'd, ID>)> {
        let conn = self.slab.get(key.parts())?;
        let handle = self.queue.handle(key)?;
        Some((conn, handle))
    }
}

pub(super) struct Queue<'d, ID: Identity> {
    nodes: shared::Fifo<(), Node<'d, ID>>,
    topology: cell::Cell<Topology<'d, ID>>,
    status: cell::Cell<Status>,
    claimed: cell::Cell<Lock<'d, ID>>,
    capacity_claim: cell::Cell<Lock<'d, ID>>,
}

struct Detached<'a, 'd, ID: Identity> {
    index: pool::raw::Physical<'d, ID>,
    node: &'a Node<'d, ID>,
}

#[derive(Clone, Copy)]
struct Chain<'d, ID: Identity> {
    head: pool::raw::Physical<'d, ID>,
    tail: pool::raw::Physical<'d, ID>,
}

#[derive(Clone, Copy)]
enum Topology<'d, ID: Identity> {
    Empty,
    Occupied(Chain<'d, ID>),
}

#[derive(Clone, Copy)]
enum Lock<'d, ID: Identity> {
    Free,
    Held(pool::raw::Physical<'d, ID>),
}

#[derive(Clone, Copy)]
enum Status {
    Ready,
    Draining,
}

pub(in crate::link) struct Vacancy<'a, 'd, ID: Identity, T> {
    reservation: vacant::Entry<'a, T, ID>,
    key: pool::Key<'d, ID>,
}

pub(super) enum Admission<'q, 'a, 'd, ID: Identity, T> {
    Ready(Grant<'q, 'a, 'd, ID, T>),
    Busy,
    Full,
    Exhausted,
}

pub(super) struct Grant<'q, 'a, 'd, ID: Identity, T> {
    queue: &'q Queue<'d, ID>,
    keys: pool::Keyspace<'d, ID>,
    grant: borrows::Grant<'a, T, ID>,
}

#[derive(Debug)]
pub struct Busy;

#[derive(Clone, Copy)]
/// One generation-exact wake capability tied to its pool borrow and route.
pub struct Handle<'a, 'd, ID: Identity = KeyTag<0>> {
    queue: &'a Queue<'d, ID>,
    key: pool::Key<'d, ID>,
}

impl<'d, ID: Identity> Queue<'d, ID> {
    pub(in crate::link::pool) fn try_new(capacity: conn::Capacity) -> Result<Self, alloc::Error> {
        Ok(Self {
            nodes: shared::Fifo::try_new(capacity.entries().get())?,
            topology: cell::Cell::new(Topology::Empty),
            status: cell::Cell::new(Status::Ready),
            claimed: cell::Cell::new(Lock::Free),
            capacity_claim: cell::Cell::new(Lock::Free),
        })
    }

    pub(in crate::link::pool) fn handle(
        &self,
        key: pool::Key<'d, ID>,
    ) -> Option<Handle<'_, 'd, ID>> {
        let node = self.nodes.get(key.lane().index().get() as usize)?.state();
        (node.epoch.get() == key.epoch()).then_some(Handle { queue: self, key })
    }

    pub(in crate::link::pool) fn admit<'q, 'a, T, S, R>(
        &'q self,
        slab: &'a mut tail::Table<T, ID, S, R>,
        keys: pool::Keyspace<'d, ID>,
        capacity: conn::Capacity,
    ) -> Admission<'q, 'a, 'd, ID, T> {
        let slots = table::Capacity::from(capacity);
        let grant = match self.claimed.get() {
            Lock::Held(claimed) => {
                let claimed = claimed.lane();
                if !slots.contains(claimed) || slab.key_at(claimed).is_some() {
                    slab.access().try_head(capacity)
                } else {
                    match slab.access().try_except(capacity, claimed) {
                        Err(slab::Vacancy::Full) => return Admission::Busy,
                        grant => grant,
                    }
                }
            }
            Lock::Free => slab.access().try_head(capacity),
        };
        match grant {
            Ok(grant) => Admission::Ready(Grant {
                queue: self,
                keys,
                grant,
            }),
            Err(slab::Vacancy::Full) => Admission::Full,
            Err(slab::Vacancy::IdentityExhausted) => Admission::Exhausted,
        }
    }

    pub(in crate::link::pool) fn is_empty(&self) -> bool {
        matches!(self.topology.get(), Topology::Empty) && matches!(self.status.get(), Status::Ready)
    }

    pub(in crate::link::pool) fn has_waiting(&self) -> bool {
        !self.nodes.is_empty::<0>()
    }

    pub(in crate::link::pool) fn release_send(&self) {
        if matches!(self.capacity_claim.get(), Lock::Held(_)) {
            return;
        }
        let Some((index, node, ())) = self.nodes.pop_front::<0>() else {
            return;
        };
        // SAFETY: this slot belongs to this route and lies within its admitted capacity.
        let index = unsafe { pool::raw::Physical::from_raw(index as u32) };
        self.capacity_claim.set(Lock::Held(index));
        node.capacity.set(true);
        self.wake(index, node);
    }

    fn clear_wait(&self, index: pool::raw::Physical<'d, ID>) {
        let slot = self.slot(index);
        slot.clear::<0>();
        slot.state().capacity.set(false);
        self.end_capacity(index);
    }

    fn end_capacity(&self, index: pool::raw::Physical<'d, ID>) {
        if let Lock::Held(held) = self.capacity_claim.get()
            && held.lane() == index.lane()
        {
            self.capacity_claim.set(Lock::Free);
        }
    }

    fn wake(&self, index: pool::raw::Physical<'d, ID>, node: &Node<'d, ID>) {
        match node.state.get() {
            State::Idle => self.enqueue(Detached { index, node }),
            State::Queued | State::Awakened | State::Retired => {}
            State::Claimed => node.state.set(State::Awakened),
        }
    }

    fn enqueue(&self, detached: Detached<'_, 'd, ID>) {
        let Detached { index, node } = detached;
        node.next.set(Next::End);
        node.state.set(State::Queued);
        let chain = match self.topology.get() {
            Topology::Empty => Chain {
                head: index,
                tail: index,
            },
            Topology::Occupied(Chain { head, tail }) => {
                self.node(tail).next.set(Next::Slot(index));
                Chain { head, tail: index }
            }
        };
        self.topology.set(Topology::Occupied(chain));
    }
}

impl<'a, 'd, ID: Identity, T> Grant<'_, 'a, 'd, ID, T> {
    pub(in crate::link::pool) fn reserve(self) -> Vacancy<'a, 'd, ID, T> {
        let entry = self.grant.reserve();
        let key = self.keys.bind_table(entry.key());
        let node = self.queue.node(pool::raw::Physical::bind(key));
        self.queue.clear_wait(pool::raw::Physical::bind(key));
        node.epoch.set(key.epoch());
        Vacancy {
            reservation: entry,
            key,
        }
    }
}

impl<'a, 'd, ID: Identity, T> Vacancy<'a, 'd, ID, T> {
    pub(in crate::link::pool) fn key(&self) -> pool::Key<'d, ID> {
        self.key
    }

    pub(in crate::link::pool) fn commit_with<R>(
        self,
        build: impl FnOnce(pool::Key<'d, ID>) -> (T, R),
    ) -> R {
        let Self {
            reservation: entry,
            key,
        } = self;
        let (value, result) = build(key);
        entry.insert(value);
        result
    }
}

impl<'d, ID: Identity> Queue<'d, ID> {
    fn node(&self, index: pool::raw::Physical<'d, ID>) -> &Node<'d, ID> {
        self.slot(index).state()
    }

    fn slot(&self, index: pool::raw::Physical<'d, ID>) -> shared::Slot<'_, (), Node<'d, ID>> {
        use o3::depot::{index::Initialized, raw::Proof};

        // SAFETY: admission binds every link to this queue's route and capacity.
        unsafe {
            Proof::<_, Initialized<()>>::new((&self.nodes, index.lane().index().get() as usize))
        }
        .into()
    }
}

impl<'d, ID: Identity> Handle<'_, 'd, ID> {
    /// Synchronizes this exact generation's shared-send-capacity wait.
    pub fn wait_send(self, waiting: bool) {
        let index = pool::raw::Physical::bind(self.key);
        let slot = self.queue.slot(index);
        let node = slot.state();
        if node.epoch.get() != self.key.epoch() || matches!(node.state.get(), State::Retired) {
            return;
        }
        if waiting {
            node.capacity.set(false);
            if slot.get::<0>().is_none() {
                slot.push::<0>(());
            }
        } else {
            self.queue.clear_wait(index);
        }
    }

    /// Retains a resource wake until its send attempt runs, including across
    /// an unrelated receive barrier. Ordinary pending work does not imply it.
    pub fn has_capacity(self) -> bool {
        let node = self.queue.node(pool::raw::Physical::bind(self.key));
        node.epoch.get() == self.key.epoch() && node.capacity.get()
    }

    pub fn wake(self) {
        let Self { queue, key } = self;
        let index = pool::raw::Physical::bind(key);
        let node = queue.node(index);
        if node.epoch.get() != key.epoch() {
            return;
        }
        queue.wake(index, node);
    }
}

const _: () = {
    assert!(mem::size_of::<Queue<'static, KeyTag<0>>>() == 6 * mem::size_of::<u64>());
    assert!(mem::size_of::<Round<'static, 'static, KeyTag<0>>>() == 2 * mem::size_of::<usize>());
    assert!(
        mem::size_of::<Handle<'static, 'static, KeyTag<0>>>()
            == mem::size_of::<usize>() + mem::size_of::<pool::Key<'static, KeyTag<0>>>()
    );
};