dope-core 0.76.0

Owned native I/O and completion driver 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
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
484
485
486
use dope_sys::io::reactor::{
    complete::flags::Flow,
    event::{self, Reclaimed, kind},
};
use std::{marker, mem, pin, time};

use dope_sys::table::{self, Slots as _, reclaim::Queue as _};
use dope_sys::{
    engine::{self, Pending as _, admit, register},
    kernel::Fatal,
};
use finish::Finish;
use native::drain;
use o3::base::cell::{brand, region};

use crate::{
    Backend, Engine, Reported,
    driver::{
        self, Local, Native,
        result::poll,
        retained::flight,
        route::{self, lease::Registry},
        schedule::{clock, state},
        storage::{self, resident},
    },
    executor::{
        self, boot,
        drive::{self, block, turn::scope::Boot},
        session,
    },
    io::{event::net::accept, fd::access::Access, transfer},
    topology::lending,
};

pub mod creation;
pub mod domain;
pub mod finish;
pub mod native;

/// Application completions still require ordinary driver dispatch before startup.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Busy;

/// Generation-owned source and the policy responsible for its transitions.
pub struct Lifecycle<'d, Report> {
    pub(crate) local: Local<'d>,
    pub(crate) source: Option<register::Source<'d>>,
    pub(crate) pending: bool,
    pub(crate) report: &'d mut Report,
}

impl<'d, Report: event::Report<Event = Reported>> Lifecycle<'d, Report> {
    pub fn context(&mut self) -> &mut driver::Local<'d> {
        &mut self.local
    }

    pub fn driver_ref(&self) -> driver::Reference<'d> {
        self.local.driver
    }

    /// Reports one exact cancellation rejection to this scope's mandatory observer.
    pub fn rejected(
        &mut self,
        failure: &<Backend as admit::Native>::Error<(flight::Echo, admit::Cause<poll::Cause>)>,
    ) {
        self.report.report(failure.into());
    }

    /// Reports a consumed accept failure with its original driver-bound target.
    pub fn accept_error(
        &mut self,
        target: route::Erased<'d, kind::Accept>,
        cause: accept::Failure,
        flow: Flow,
    ) {
        self.report.report(Reclaimed::AcceptRoute {
            target: target.into_token(),
            cause,
            flow,
        });
    }

    /// Reports one already classified receive control or released data prefix.
    pub fn received(
        &mut self,
        target: route::Erased<'d, kind::Recv, impl route::Selection>,
        flow: Flow,
        result: Result<transfer::Len, crate::Errno>,
    ) {
        self.report.report(Reclaimed::RecvRoute {
            target: target.into_token(),
            result,
            flow,
        });
    }

    pub fn commit(&mut self, work: state::Reactor<'_, 'd>) -> Result<poll::Commit, poll::Error> {
        work.reclaim(self);
        let retry = self.local.retry;
        let pending =
            crate::Engine::commit(self, work.quota, retry).map_err(poll::Error::from_backend)?;
        self.local.retry = false;
        Ok(if pending {
            poll::Commit::Pending
        } else {
            poll::Commit::Drained
        })
    }

    pub fn wait(
        &mut self,
        work: state::Reactor<'_, 'd>,
        timeout: Option<time::Duration>,
    ) -> Result<(), poll::Error> {
        work.reclaim(self);
        let owner = self.driver_ref();
        let busy =
            self.local.retry || self.pending || owner.has_deferred() || owner.ready().has_ready();
        let mut native = native::Loan::new(&mut self.local);
        // SAFETY: The lifecycle retains this driver's registered storage and branded
        // flight owners throughout maintenance and native completion processing.
        unsafe { engine::raw::Poll::wait(native.as_mut(), work.quota, timeout, busy) }
            .map_err(poll::Error::from_backend)?;
        self.local.retry = false;
        Ok(())
    }

    pub fn release<T>(&mut self, owner: T) {
        drop(owner);
        self.retire();
    }

    pub(crate) fn retire(&mut self) {
        let view = self.local.driver.descriptors().retirement();
        table::Retire::drain(
            &mut *self.local.backend,
            view,
            view.pending(),
            &mut *self.report,
        );
    }

    fn finish<const STOP: bool, const RESUME: bool>(&mut self) {
        native::Loan::new(&mut self.local).reclaim(usize::MAX);
        drain::routes(&mut self.local);
        if let Err(cause) =
            crate::Engine::finish::<STOP, RESUME, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _>(self)
        {
            Fatal::Retirement(&cause).terminate();
        }
        if STOP || !RESUME {
            self.local.flights.finish();
        }
    }
}

// SAFETY: Root::enter lends the same engine, flight arena and descriptor domain.
unsafe impl<'d, R> engine::raw::Owner<'d, Engine, flight::Arena, Access<'d>> for Lifecycle<'d, R>
where
    R: event::Report<Event = Reported>,
{
    type Report = R;

    unsafe fn parts(
        &mut self,
    ) -> (
        &mut Engine,
        &'d flight::Arena,
        Access<'d>,
        &mut R,
        &mut Option<register::Source<'d>>,
        &mut bool,
    ) {
        (
            &mut *self.local.backend,
            self.local.flights,
            self.local.driver.descriptors(),
            &mut *self.report,
            &mut self.source,
            &mut self.pending,
        )
    }
}

/// Owns one native generation and every authority lent while it is running.
pub struct Core<'env: 'd, 'd, Q, Report> {
    pub(crate) lifecycle: Lifecycle<'d, Report>,
    pub(crate) work: state::Core<'d>,
    pub(crate) token: region::Token<brand::Identity<'d>>,
    pub(crate) pending: Option<event::raw::Completion<'d, flight::Complete<'d>>>,
    pub(crate) source: &'d Q,
    environment: marker::PhantomData<&'env mut &'env ()>,
}

impl<'env: 'd, 'd, Q, Report: event::Report<Event = Reported>> Core<'env, 'd, Q, Report> {
    pub(crate) fn install<'app, D>(
        &'app mut self,
        start: clock::Sample,
        backing: pin::Pin<&'app executor::raw::Backing<'d, D>>,
    ) -> session::App<'app, 'env, 'd, D, Report, Q>
    where
        'd: 'app,
        D: executor::raw::App<'d>,
    {
        let (token, driver, schedule) = self.split();
        schedule.sample(start);
        let stored = backing.pin();
        let mut install = Install::new(backing, driver.driver_ref());
        D::install(
            lending::raw::Project::exclusive(token.pin_mut(stored).project().app),
            install.reborrow(),
        );
        session::App {
            core: self,
            stored,
            install,
        }
    }

    /// # Safety
    /// Resume only the exact stopped head and plan returned by child native finish.
    /// Transfer final destruction of that head; its enclosing owner must not drop it again.
    pub(crate) unsafe fn resume<'app, D, S>(
        &'app mut self,
        backing: pin::Pin<&'app executor::raw::Backing<'d, D, S>>,
    ) -> session::App<'app, 'env, 'd, D, Report, Q, S>
    where
        'd: 'app,
        D: executor::raw::App<'d>,
        S: lending::raw::Project<App = D>,
    {
        let stored = backing.pin();
        // SAFETY: child native finish ended the loans of this exact stopped parent.
        unsafe {
            D::released(lending::raw::Project::exclusive(
                self.token.pin_mut(stored).project().app,
            ))
        };
        let install = Install::new(backing, self.driver_ref());
        session::App {
            core: self,
            stored,
            install,
        }
    }

    pub(crate) fn shutdown<'app, D>(
        app: &mut session::App<'app, 'env, 'd, D, Report, Q>,
        start: clock::Sample,
    ) where
        'd: 'app,
        D: executor::raw::App<'d>,
    {
        let (token, driver, schedule) = app.core.split();
        let turn = schedule.begin_at(start);
        let mut owner = lending::raw::Project::exclusive(token.pin_mut(app.stored).project().app);
        // SAFETY: the generative client body ended before shutdown of its owner.
        unsafe { D::released(owner.as_mut()) };
        D::shutdown(owner, turn.turn(), driver);
    }

    pub fn drive<R>(&mut self, root: R) -> Result<R::Output, drive::Error>
    where
        R: boot::Root<'d>,
        Q: executor::Startup,
    {
        let observer = self.source;
        let state = Boot::try_new(self).map_err(drive::Error::from);
        block::run_boot(state, root, observer)
    }

    pub fn driver(&mut self) -> &mut Local<'d> {
        &mut self.lifecycle.local
    }

    pub fn driver_ref(&self) -> driver::Reference<'d> {
        self.lifecycle.driver_ref()
    }

    pub fn source(&self) -> &'d Q {
        self.source
    }

    pub fn split(
        &mut self,
    ) -> (
        &mut region::Token<brand::Identity<'d>>,
        &mut Lifecycle<'d, Report>,
        &mut state::Core<'d>,
    ) {
        (&mut self.token, &mut self.lifecycle, &mut self.work)
    }

    pub fn try_boot(&self) -> Result<(), Busy> {
        use dope_sys::table::token::host::raw;

        if raw::Drain::is_pending(self.lifecycle.local.flights) {
            Err(Busy)
        } else {
            Ok(())
        }
    }

    pub fn quiesce(&mut self) {
        self.lifecycle.finish::<true, true>();
        self.lifecycle.finish::<false, true>();
    }

    pub(crate) fn finish<'app, H, T, C: Copy>(
        app: session::App<
            'app,
            'env,
            'd,
            H::Joined<T>,
            Report,
            Q,
            impl lending::raw::Project<App = H::Joined<T>>,
        >,
        forced: bool,
        source: C,
    ) -> (H::Retired, H::Time<C>, Option<dope_sys::Errno>)
    where
        'd: 'app,
        H: lending::raw::Head<'d>,
        T: executor::raw::App<'d>,
    {
        let session::App {
            core,
            stored,
            install,
        } = app;
        core.pending = None;
        let result = {
            let mut finish = Finish::new(&mut core.lifecycle, forced);
            let mut stored = core.token.pin_mut(stored).project();
            // SAFETY: the sole stopped App consumed its root and Install after native suspension.
            let (head, source) = unsafe {
                H::retire::<T, C>(
                    lending::raw::Project::exclusive(stored.app.as_mut()),
                    install,
                    &mut finish,
                    stored.park,
                    source,
                )
            };
            // SAFETY: final traversal ended every loan into this exact backing.
            unsafe { lending::raw::Project::release(stored.app) };
            (head, source, finish.disarm_error())
        };
        core.lifecycle.finish::<false, true>();
        result
    }

    fn run_storage<S, I, F, R, E, Reject>(
        &mut self,
        plan: S,
        input: I,
        body: F,
        rejected: Reject,
    ) -> (Result<R, E>, epochs::Closed)
    where
        S: storage::Build + 'd,
        Reject: FnOnce(&Q, S::Error, I, F) -> E,
        I: 'd,
        F: for<'life, 'p> FnOnce(I, storage::Loan<'life, 'p, 'd, S>, &mut Self) -> R,
    {
        let (mut backing, owned) = match plan.try_store() {
            Ok(storage) => storage,
            Err(cause) => {
                let error = rejected(self.source, cause, input, body);
                let proof = self.retire();
                return (Err(error), proof);
            }
        };
        match plan.try_build(
            owned,
            &mut backing,
            storage::Context::new(&mut self.lifecycle.local),
        ) {
            Ok(value) => {
                let store = pin::pin!(value);
                let output = body(input, storage::Loan::new(store.as_ref()), self);
                let proof = self.retire();
                (Ok(output), proof)
            }
            Err(cause) => {
                let error = rejected(self.source, cause, input, body);
                let proof = self.retire();
                (Err(error), proof)
            }
        }
    }

    fn retire(&mut self) -> epochs::Closed {
        self.pending = None;
        if mem::take(&mut self.lifecycle.pending) {
            self.lifecycle.report.report(Reclaimed::Shutdown);
        }
        self.lifecycle.finish::<true, false>();
        epochs::Closed { _seal: () }
    }
}

mod epochs;

struct Root<'native, 'env, Q, Report> {
    flights: &'native mut flight::Arena,
    resident: &'native mut resident::Arena,
    source: &'native domain::Source<Q>,
    report: &'env mut Report,
}

impl<'env, Q, Report: event::Report<Event = Reported>> Root<'_, 'env, Q, Report> {
    fn enter<'d>(
        &'d mut self,
        shared: driver::ReceiveRoot<'d>,
        token: region::Token<brand::Identity<'d>>,
        regions: (
            region::Token<region::Identity<'d>>,
            region::Token<region::Identity<'d, 1>>,
        ),
        backend: Native<'d>,
    ) -> Core<'env, 'd, Q, Report>
    where
        'env: 'd,
    {
        let alloc = self.resident.enter(&regions.0);
        let local = Local {
            driver: driver::Reference::new(shared, regions.0.proof()),
            backend,
            retry: false,
            flights: &*self.flights,
            resident: alloc,
            routes: Registry::new(),
            region: regions,
        };
        Core {
            work: state::Core::new(local.driver),
            lifecycle: Lifecycle {
                local,
                source: self.source.descriptor(),
                pending: false,
                report: &mut *self.report,
            },
            token,
            pending: None,
            source: &self.source.value,
            environment: marker::PhantomData,
        }
    }
}

/// Proof that nested resources are installed beneath their pinned owner.
#[must_use]
pub struct Install<'a, 'd> {
    owner: marker::PhantomData<&'a mut &'a ()>,
    _driver: driver::Invariant<'d>,
}

impl<'a, 'd> Install<'a, 'd> {
    fn new<D, S>(
        _: pin::Pin<&'a executor::raw::Backing<'d, D, S>>,
        driver: driver::Reference<'d>,
    ) -> Self
    where
        D: executor::raw::Layout<'d>,
        S: lending::raw::Project<App = D>,
    {
        Self {
            owner: marker::PhantomData,
            _driver: driver.brand,
        }
    }

    pub fn reborrow(&mut self) -> Install<'_, 'd> {
        Install {
            owner: marker::PhantomData,
            _driver: self._driver,
        }
    }
}

const _: () = {
    assert!(mem::size_of::<Install<'static, 'static>>() == 0);
    assert!(mem::align_of::<Install<'static, 'static>>() == 1);
};