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
487
488
489
490
use dope_sys::io::{Close as _, reactor::event};
use std::{cell::Cell, convert::Infallible, os::fd, pin::Pin};

use dope_sys::{
    engine::{self, register, shutdown},
    probe::Stopped,
};
use o3::{
    base::{cell::brand, num::Epoch},
    mem::slot::Occupied,
};

use crate::{
    Backend,
    driver::{
        self, Seed, life, life::native::host::Host, result, result::Refused, retained::flight,
        route, schedule, settings, storage,
    },
    executor,
};

/// The unstarted generation: one driver with the single source it retains.
pub struct Generation<'place, Q = ()>(Occupied<'place, raw::Parts<Q>>);

pub use raw::Place;

/// Exact descriptor receipt retained with its immutably exposed owner.
pub(super) struct Source<Q: ?Sized> {
    descriptor: Option<raw::Descriptor>,
    pub(super) value: Q,
}

impl<Q: ?Sized> Source<Q> {
    pub(in crate::driver::life) fn descriptor(&self) -> Option<register::Source<'_>> {
        self.descriptor.as_ref().map(raw::Descriptor::source)
    }
}

pub(in crate::driver) mod raw;

pub type Outcome<T, E, Q = ()> = Result<T, Error<E, T, Q>>;
pub type Observation<'a, R> = Result<R, (Unmap, &'a R)>;

impl<Q> Generation<'_, Q> {
    pub fn run<'env, S, I, F, R, Report>(
        self,
        plan: S,
        input: I,
        body: F,
        report: &'env mut Report,
    ) -> Outcome<R, Infallible, Q>
    where
        S: storage::Build<Error = Infallible> + 'env,
        Q: 'env,
        I: 'env,
        F: 'env
            + for<'life, 'p, 'd> FnOnce(
                I,
                storage::Loan<'life, 'p, 'd, S>,
                &mut life::Core<'env, 'd, Q, Report>,
            ) -> R,
        Report: event::Report<Event = crate::Reported>,
    {
        self.run_native(
            plan,
            input,
            body,
            report,
            |_, cause, _, _| match cause {},
            |_, result, closed| Closing::finish(result, closed),
        )
    }

    pub fn try_run<'env, S, I, F, R, Report>(
        self,
        plan: S,
        input: I,
        body: F,
        report: &'env mut Report,
    ) -> Outcome<R, Rejected<S::Error, (I, F)>, Q>
    where
        S: storage::Build + 'env,
        Q: executor::Startup + 'env,
        I: 'env,
        F: 'env
            + for<'life, 'p, 'd> FnOnce(
                I,
                storage::Loan<'life, 'p, 'd, S>,
                &mut life::Core<'env, 'd, Q, Report>,
            ) -> R,
        Report: event::Report<Event = crate::Reported>,
    {
        self.run_native(
            plan,
            input,
            body,
            report,
            Rejected::before_run,
            |_, result, closed| Closing::finish(result, closed),
        )
    }

    /// Finishes at the worker's report while a failed native shutdown still owns its result.
    pub fn observe<'env, S, I, F, R, Report, T>(
        self,
        plan: S,
        input: I,
        body: F,
        report: &'env mut Report,
        finish: impl FnOnce(&mut Report, Observation<'_, R>) -> T,
    ) -> T
    where
        S: storage::Build<Error = Infallible> + 'env,
        Q: 'env,
        I: 'env,
        F: 'env
            + for<'life, 'p, 'd> FnOnce(
                I,
                storage::Loan<'life, 'p, 'd, S>,
                &mut life::Core<'env, 'd, Q, Report>,
            ) -> R,
        Report: event::Report<Event = crate::Reported>,
    {
        self.run_native(
            plan,
            input,
            body,
            report,
            |_, never, _, _| match never {},
            |report, result, closed| {
                observed(result, closed, |result| match result {
                    Ok(Ok(value)) => finish(report, Ok(value)),
                    Err((failure, Ok(value))) => finish(report, Err((failure, value))),
                    Ok(Err(never)) => match never {},
                    Err((_, Err(never))) => match *never {},
                })
            },
        )
    }

    pub(crate) fn run_native<'env, S, I, F, R, E, Report, Reject, T>(
        self,
        plan: S,
        input: I,
        body: F,
        report: &'env mut Report,
        rejected: Reject,
        finish: impl FnOnce(&mut Report, Result<R, E>, Retired<Q>) -> T,
    ) -> T
    where
        S: storage::Build + 'env,
        Q: 'env,
        I: 'env,
        F: 'env
            + for<'life, 'p, 'd> FnOnce(
                I,
                storage::Loan<'life, 'p, 'd, S>,
                &mut life::Core<'env, 'd, Q, Report>,
            ) -> R,
        Report: event::Report<Event = crate::Reported>,
        Reject: 'env + FnOnce(&Q, S::Error, I, F) -> E,
    {
        use dope_sys::memory::Context as _;
        let (mut backend, remaining) = self.0.split();
        let (mut arenas, remaining) = remaining.split();
        let (mut shared, source) = remaining.split();
        let accounts = shared.context().buffer().layout().0.accounts();
        let (resident, flights) = arenas.get_mut();
        let root = life::Root {
            flights,
            resident,
            source: &source,
            report,
        };
        let mut parts = (root, shared.get_mut(), backend.get_mut());
        let (result, closed) =
            brand::Identity::scope_pinned(Pin::new(&mut parts), |token, regions, parts| {
                let (root, shared, backend) = parts.get_mut();
                // SAFETY: this generation exclusively owns the inactive mapping and backend.
                let shared = unsafe { shared.enter(accounts) };
                let mut core = root.enter(shared, token, regions, backend);
                core.run_storage(plan, input, body, rejected)
            });
        let report = parts.0.report;
        closed.reclaim(shared.get_mut());
        let closed = raw::close(backend, shared);
        drop(arenas);
        finish(
            report,
            result,
            Stopped::attach(source.into_inner().value, closed),
        )
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Register {
    Full(result::SubmitError),
    Register(crate::Errno),
}

impl Register {
    pub(crate) fn native(error: register::Error) -> Self {
        match error {
            register::Error::Full(full) => Self::Full(result::SubmitError::from(full)),
            register::Error::Register(error) => Self::Register(error),
        }
    }
}

/// Storage and generation-finalization failures preserved without erasure.
pub enum Error<E, T, Q = ()> {
    Storage(E),
    Close(Closing<E, T, Q>),
}

/// Exact preflight failure paired with the operation that has not run.
pub struct Rejected<E, O> {
    pub cause: E,
    pub operation: O,
}

impl<E, I, F> Rejected<E, (I, F)> {
    pub(crate) fn before_run<Q: executor::Startup>(
        source: &Q,
        cause: E,
        input: I,
        body: F,
    ) -> Self {
        executor::failed(source);
        Self {
            cause,
            operation: (input, body),
        }
    }
}

impl<E, T, Q> Error<E, T, Q> {
    /// Borrows all failures while retaining the application output and retry ownership.
    pub fn cause(&self) -> Cause<&E> {
        match self {
            Self::Storage(error) => Cause::Storage(error),
            Self::Close(state) => Cause::Close {
                storage: state.result.as_ref().err(),
                failure: state.failure(),
            },
        }
    }

    pub fn map_storage<F>(self, map: impl FnOnce(E) -> F) -> Error<F, T, Q> {
        match self {
            Self::Storage(error) => Error::Storage(map(error)),
            Self::Close(state) => Error::Close(state.map_storage(map)),
        }
    }
}

/// Generation result and source retained until backend teardown completes.
pub struct Closing<E, T, Q> {
    result: Result<T, E>,
    stopped: Stopped<Q, raw::Closing>,
}

#[derive(Clone, Copy, Debug)]
pub enum Unmap {
    Backend(storage::Mapping),
    Context(storage::Mapping),
}

impl Unmap {
    fn native<E>(error: shutdown::Failure<E>) -> Self
    where
        result::Kernel: From<E>,
    {
        match error {
            shutdown::Failure::Backend(error) => Self::Backend(storage::Mapping::from(error)),
            shutdown::Failure::Context(error) => Self::Context(storage::Mapping::from(error)),
        }
    }
}

fn seeded(config: &settings::Config) -> Result<(settings::Plan<'_>, Seed), Refused> {
    let plan = settings::Plan::try_new(config).map_err(Refused::Plan)?;
    let seed = Seed::acquire()
        .map_err(|error| Refused::kernel(result::IoOperation::Entropy, error.into()))?;
    Ok((plan, seed))
}

impl<'p> Generation<'p> {
    pub fn try_new(
        config: settings::Config,
        place: &'p mut Place,
    ) -> Result<Self, executor::Error<'p>> {
        let (plan, seed) = seeded(&config)?;
        Self::build(plan, seed, (), (), place)
    }

    pub fn try_seed(
        config: settings::Config,
        seed: Seed,
        place: &'p mut Place,
    ) -> Result<Self, executor::Error<'p>> {
        let plan = settings::Plan::try_new(&config).map_err(Refused::Plan)?;
        Self::build(plan, seed, (), (), place)
    }
}

impl<'p, Q: fd::AsFd> Generation<'p, Q> {
    pub fn try_registered(
        config: settings::Config,
        source: Q,
        interest: register::Interest,
        place: &'p mut Place<Q>,
    ) -> Result<Self, executor::Error<'p>> {
        let (plan, seed) = seeded(&config)?;
        Self::build(plan, seed, source, interest, place)
    }

    pub fn try_registered_seed(
        config: settings::Config,
        seed: Seed,
        source: Q,
        interest: register::Interest,
        place: &'p mut Place<Q>,
    ) -> Result<Self, executor::Error<'p>> {
        let plan = settings::Plan::try_new(&config).map_err(Refused::Plan)?;
        Self::build(plan, seed, source, interest, place)
    }
}

trait Registration<Q> {
    fn source(self, owner: &Q) -> Option<register::Source<'_>>;
}

impl Registration<()> for () {
    fn source(self, _: &()) -> Option<register::Source<'_>> {
        None
    }
}

impl<Q: fd::AsFd> Registration<Q> for register::Interest {
    fn source(self, owner: &Q) -> Option<register::Source<'_>> {
        Some(register::Source {
            fd: owner.as_fd(),
            interest: self,
        })
    }
}

impl<'p, Q> Generation<'p, Q> {
    fn build(
        plan: settings::Plan<'_>,
        seed: Seed,
        value: Q,
        interest: impl Registration<Q>,
        place: &'p mut Place<Q>,
    ) -> Result<Self, executor::Error<'p>> {
        let config = plan.config();
        let resident = storage::resident::Arena::try_new(config.domains().get() as usize)
            .map_err(Refused::from)?;
        let init =
            driver::ReceiveArena::try_allocate(config.receive().count()).map_err(Refused::from)?;
        let schedule = schedule::State::try_new(plan).map_err(Refused::from)?;
        let timer = schedule::clock::timer::heap::raw::Store::try_new(
            config.schedule().timers().count().get(),
        )
        .map_err(Refused::from)?;
        // SAFETY: all fallible host allocation precedes native creation.
        // The returned context stays beside its backend until native shutdown.
        let (backend, buffer, receive) =
            match unsafe { <Backend as engine::raw::Create<Host<Backend>, _>>::try_new(config) } {
                Ok(parts) => parts,
                Err(error) => return Err(place.refuse(error)),
            };
        let shared = init.initialize(driver::Shared {
            random_seed: seed,
            schedule,
            receive,
            buffer,
            retire: route::queues::Pending::new(),
            generations: [const { Cell::new(Some(Epoch::INITIAL)) }; route::CAPACITY],
            sequence: schedule::sequence::Owner::new(),
            timer,
        });
        // SAFETY: the receipt is installed with its owning value, which outlives backend destruction.
        let descriptor = interest
            .source(&value)
            .map(|source| unsafe { raw::Descriptor::new(source) });
        let mut ready = place.ready((
            backend,
            (
                (resident, flight::Arena::new()),
                (shared, Source { descriptor, value }),
            ),
        ));
        let (backend, (_, (_, source))) = ready.get_mut();
        if let Some(source) = source.descriptor() {
            // SAFETY: the owner remains in this place through quiescence. A failed registration
            // drops the backend first, including a registration published before failure.
            unsafe { engine::raw::Register::register(backend, source) }
                .map_err(|cause| Refused::Register(Register::native(cause)))?;
        }
        Ok(Self(ready))
    }
}

pub(crate) type Retired<Q> = Result<(Q, ()), Stopped<Q, raw::Closing>>;

pub(crate) fn observed<E, R, Q, T>(
    result: Result<R, E>,
    closed: Retired<Q>,
    finish: impl FnOnce(Observation<'_, Result<R, E>>) -> T,
) -> T {
    match closed {
        Ok((source, ())) => {
            drop(source);
            finish(Ok(result))
        }
        Err(stopped) => {
            let output = finish(Err((
                Unmap::native(shutdown::Cleanup::failure(&stopped.cause)),
                &result,
            )));
            drop(result);
            drop(stopped);
            output
        }
    }
}

impl<E, T, Q> Closing<E, T, Q> {
    fn finish(result: Result<T, E>, closed: Retired<Q>) -> Outcome<T, E, Q> {
        match closed {
            Ok(_) => result.map_err(Error::Storage),
            Err(stopped) => Err(Error::Close(Self { result, stopped })),
        }
    }

    pub fn map_storage<F>(self, map: impl FnOnce(E) -> F) -> Closing<F, T, Q> {
        Closing {
            result: self.result.map_err(map),
            stopped: self.stopped,
        }
    }

    pub fn result(&self) -> &Result<T, E> {
        &self.result
    }

    pub fn failure(&self) -> Unmap {
        Unmap::native(shutdown::Cleanup::failure(&self.stopped.cause))
    }

    /// Reports the previous failure before retrying its native owner.
    pub fn try_close(self, report: impl FnMut(Unmap)) -> Outcome<T, E, Q> {
        Self::finish(self.result, retry(self.stopped, report))
    }
}

fn retry<Q, C: shutdown::Cleanup>(
    stopped: Stopped<Q, C>,
    mut report: impl FnMut(Unmap),
) -> Result<(Q, ()), Stopped<Q, C>>
where
    result::Kernel: From<C::Error>,
{
    let (owner, error) = stopped.cause.recover().into_parts();
    report(Unmap::native(error.into()));
    Stopped::attach(stopped.state, owner.try_close())
}

/// Every native cause borrowed without taking the stored application output or source.
#[derive(Debug)]
pub enum Cause<E> {
    Storage(E),
    Close { storage: Option<E>, failure: Unmap },
}

impl<E> Cause<E> {
    /// Projects only the storage cause; generation output and retry owners stay borrowed.
    pub fn map_storage<F>(self, map: impl FnOnce(E) -> F) -> Cause<F> {
        match self {
            Self::Storage(error) => Cause::Storage(map(error)),
            Self::Close { storage, failure } => Cause::Close {
                storage: storage.map(map),
                failure,
            },
        }
    }
}