foundation_core 0.0.6

Central crate for all foundation crates for the ewe-platform project
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
//! Task-spawn builders, decomposed by `ExecutionEngine` verb.
//!
//! WHY: `ExecutionEngine` exposes four dispatch verbs — `schedule`, `lift`,
//! `sequenced`, `broadcast` — and each supports three delivery forms (spawn,
//! recv-iterator, stream-iterator). Their trait-bound needs diverge: only
//! `broadcast` (and the delivery iterators, which park on
//! `State::Depends(QueueVacancyReadiness)` and therefore need `Send` under
//! `multi`) require `Send`; the plain `spawn` form of `schedule`/`lift`/
//! `sequenced` never does. A single mux-everything builder cannot express that
//! without per-method `#[cfg]`.
//!
//! WHAT: a cfg-agnostic [`TaskSpawnConfig`] collects the task/parent/resolver,
//! then transitions (`as_scheduled`/`as_lifted`/`as_sequenced`/`as_broadcast`)
//! into one of four verb builders — [`ScheduleBuilder`], [`LiftBuilder`],
//! [`SequenceBuilder`], [`BroadcastBuilder`]. Each verb builder exposes the same
//! terminal surface: `spawn()`, `recv()`, `stream()`, `stream_with_config()`.
//!
//! HOW: the `Send`-free `spawn()` of the three local verbs lives here (ungated).
//! The `Send`-diverging terminals — every `recv`/`stream` (they build a
//! `*ConsumingIter`) plus `BroadcastBuilder::spawn` — live once in
//! [`sendable`] (`#![cfg(multi)]`, `Send`) and once in [`non_sendable`]
//! (`#![cfg(not multi)]`, no `Send`), re-exported below. The `#[cfg]` is at
//! module scope only: there is no per-function gating.

use std::{any::Any, marker::PhantomData};

use crate::synca::Entry;
use crate::valtron::AnyResult;
use crate::valtron::{
    BoxedExecutionEngine, BoxedPanicHandler, DoNext, ExecutorError, FnMutReady, FnReady, OnNext,
    SpawnInfo, TaskIterator, TaskReadyResolver, TaskStatus,
};

// The twins carry only inherent-impl terminals (no exported names), so they are
// `mod`-compiled but not re-exported — the methods attach to the verb-builder
// structs declared below.
#[cfg(feature = "multi")]
mod sendable;

#[cfg(not(feature = "multi"))]
mod non_sendable;

/// Which local verb a [`BroadcastBuilder`] falls back to when `multi` is off.
///
/// WHY: under `multi = off` there is no global queue, so `broadcast` degrades to
/// a local dispatch (`broadcast_or_lift` / `broadcast_or_sequence`). The chosen
/// fallback is captured at the `as_broadcast*` transition and consumed by
/// [`non_sendable`]'s `BroadcastBuilder` terminals.
#[derive(Debug, Clone, Copy)]
pub enum LocalFallback {
    /// `broadcast_or_lift`: lift onto the top of the local queue.
    Lift,
    /// `broadcast_or_sequence`: sequence with the parent on the local queue.
    Sequence,
}

/// The cfg-agnostic configuration stage of the task-spawn builders.
///
/// WHAT: holds the engine handle, the task, an optional parent, an optional
/// ready-`Resolver`, and an optional panic handler. It carries only setters and
/// the verb transitions — never a dispatch — so it needs no `Send` and lives in
/// one ungated impl.
pub struct TaskSpawnConfig<Done, Pending, Resolver, Task>
where
    Resolver: TaskReadyResolver<Done, Pending>,
    Task: TaskIterator<Pending = Pending, Ready = Done>,
{
    pub(crate) engine: BoxedExecutionEngine,
    pub(crate) task: Option<Task>,
    pub(crate) parent: Option<Entry>,
    pub(crate) resolver: Option<Resolver>,
    pub(crate) panic_handler: Option<BoxedPanicHandler>,
    pub(crate) _marker: PhantomData<(Done, Pending)>,
}

impl<Done, Pending, Resolver, Task> TaskSpawnConfig<Done, Pending, Resolver, Task>
where
    Done: 'static,
    Pending: 'static,
    Resolver: TaskReadyResolver<Done, Pending> + 'static,
    Task: TaskIterator<Pending = Pending, Ready = Done> + 'static,
{
    /// Create an empty config bound to `engine`.
    #[must_use]
    pub fn new(engine: BoxedExecutionEngine) -> Self {
        Self {
            engine,
            task: None,
            parent: None,
            resolver: None,
            panic_handler: None,
            _marker: PhantomData,
        }
    }

    /// Set the task to spawn.
    #[must_use]
    pub fn with_task(mut self, task: Task) -> Self {
        self.task = Some(task);
        self
    }

    /// Set the parent entry (used by `lift`/`sequence`/broadcast fallback).
    #[must_use]
    pub fn with_parent(mut self, parent: Entry) -> Self {
        self.parent = Some(parent);
        self
    }

    /// Set the parent entry from an `Option`.
    #[must_use]
    pub fn maybe_parent(mut self, parent: Option<Entry>) -> Self {
        self.parent = parent;
        self
    }

    /// Set the ready-`Resolver` (the `spawn`-form ready handler).
    #[must_use]
    pub fn with_resolver(mut self, resolver: Resolver) -> Self {
        self.resolver = Some(resolver);
        self
    }

    /// Attach a panic handler invoked if the task panics.
    #[must_use]
    pub fn with_panic_handler<T>(mut self, handler: T) -> Self
    where
        T: Fn(Box<dyn Any + Send>) + Send + Sync + 'static,
    {
        self.panic_handler = Some(Box::new(handler));
        self
    }

    /// Transition to a [`ScheduleBuilder`] (bottom of the local queue).
    #[must_use]
    pub fn as_scheduled(self) -> ScheduleBuilder<Done, Pending, Resolver, Task> {
        ScheduleBuilder { config: self }
    }

    /// Transition to a [`LiftBuilder`] (top of the local queue).
    #[must_use]
    pub fn as_lifted(self) -> LiftBuilder<Done, Pending, Resolver, Task> {
        LiftBuilder { config: self }
    }

    /// Transition to a [`SequenceBuilder`] linked to `parent`.
    #[must_use]
    pub fn as_sequenced(
        mut self,
        parent: Entry,
    ) -> SequenceBuilder<Done, Pending, Resolver, Task> {
        self.parent = Some(parent);
        SequenceBuilder { config: self }
    }

    /// Transition to a [`BroadcastBuilder`] (global queue under `multi`, else
    /// lift fallback).
    #[must_use]
    pub fn as_broadcast(self) -> BroadcastBuilder<Done, Pending, Resolver, Task> {
        BroadcastBuilder {
            config: self,
            fallback: LocalFallback::Lift,
        }
    }

    /// Transition to a [`BroadcastBuilder`] whose `multi = off` fallback is
    /// `lift` (optional parent honored).
    #[must_use]
    pub fn as_broadcast_or_lift(self) -> BroadcastBuilder<Done, Pending, Resolver, Task> {
        BroadcastBuilder {
            config: self,
            fallback: LocalFallback::Lift,
        }
    }

    /// Transition to a [`BroadcastBuilder`] whose `multi = off` fallback is
    /// `sequence` with `parent`.
    #[must_use]
    pub fn as_broadcast_or_sequenced(
        mut self,
        parent: Entry,
    ) -> BroadcastBuilder<Done, Pending, Resolver, Task> {
        self.parent = Some(parent);
        BroadcastBuilder {
            config: self,
            fallback: LocalFallback::Sequence,
        }
    }
}

// ---------------------------------------------------------------------------
// on_next / on_send_next resolver setters (Resolver is a concrete Fn wrapper)
// ---------------------------------------------------------------------------

impl<F, Done, Pending, Task> TaskSpawnConfig<Done, Pending, FnReady<F>, Task>
where
    Done: 'static,
    Pending: 'static,
    Task: TaskIterator<Pending = Pending, Ready = Done> + 'static,
    F: Fn(TaskStatus<Done, Pending>, BoxedExecutionEngine) + 'static,
{
    /// Install a `Fn` ready-handler as the resolver.
    #[must_use]
    pub fn on_next(self, action: F) -> Self {
        self.with_resolver(FnReady::new(action))
    }
}

impl<F, Done, Pending, Task> TaskSpawnConfig<Done, Pending, FnMutReady<F>, Task>
where
    Done: 'static,
    Pending: 'static,
    Task: TaskIterator<Pending = Pending, Ready = Done> + 'static,
    F: FnMut(TaskStatus<Done, Pending>, BoxedExecutionEngine) + 'static,
{
    /// Install a `FnMut` ready-handler as the resolver.
    #[must_use]
    pub fn on_next_mut(self, action: F) -> Self
    where
        F: Fn(TaskStatus<Done, Pending>, BoxedExecutionEngine) + 'static,
    {
        self.with_resolver(FnMutReady::new(action))
    }
}

impl<F, Done, Pending, Task> TaskSpawnConfig<Done, Pending, FnReady<F>, Task>
where
    Done: Send + 'static,
    Pending: Send + 'static,
    Task: TaskIterator<Pending = Pending, Ready = Done> + Send + 'static,
    F: Fn(TaskStatus<Done, Pending>, BoxedExecutionEngine) + Send + 'static,
{
    /// Install a `Send` `Fn` ready-handler as the resolver (broadcast path).
    #[must_use]
    pub fn on_send_next(self, action: F) -> Self {
        self.with_resolver(FnReady::new(action))
    }
}

impl<F, Done, Pending, Task> TaskSpawnConfig<Done, Pending, FnMutReady<F>, Task>
where
    Done: Send + 'static,
    Pending: Send + 'static,
    Task: TaskIterator<Pending = Pending, Ready = Done> + Send + 'static,
    F: FnMut(TaskStatus<Done, Pending>, BoxedExecutionEngine) + Send + 'static,
{
    /// Install a `Send` `FnMut` ready-handler as the resolver (broadcast path).
    #[must_use]
    pub fn on_send_next_mut(self, action: F) -> Self
    where
        F: Fn(TaskStatus<Done, Pending>, BoxedExecutionEngine) + 'static,
    {
        self.with_resolver(FnMutReady::new(action))
    }
}

// ---------------------------------------------------------------------------
// Verb builders (structs declared once, ungated)
// ---------------------------------------------------------------------------

/// Dispatches to the **bottom** of the local queue (`ExecutionEngine::schedule`).
pub struct ScheduleBuilder<Done, Pending, Resolver, Task>
where
    Resolver: TaskReadyResolver<Done, Pending>,
    Task: TaskIterator<Pending = Pending, Ready = Done>,
{
    pub(crate) config: TaskSpawnConfig<Done, Pending, Resolver, Task>,
}

/// Dispatches to the **top** of the local queue (`ExecutionEngine::lift`).
pub struct LiftBuilder<Done, Pending, Resolver, Task>
where
    Resolver: TaskReadyResolver<Done, Pending>,
    Task: TaskIterator<Pending = Pending, Ready = Done>,
{
    pub(crate) config: TaskSpawnConfig<Done, Pending, Resolver, Task>,
}

/// Sequences the task with a parent (`ExecutionEngine::sequenced`). Its delivery
/// queue is **bounded** (Feature 45 Part B), so the child parks on vacancy when
/// it outruns the draining parent.
pub struct SequenceBuilder<Done, Pending, Resolver, Task>
where
    Resolver: TaskReadyResolver<Done, Pending>,
    Task: TaskIterator<Pending = Pending, Ready = Done>,
{
    pub(crate) config: TaskSpawnConfig<Done, Pending, Resolver, Task>,
}

/// Broadcasts to the global queue under `multi`; falls back to a local verb when
/// `multi` is off (see [`LocalFallback`]).
pub struct BroadcastBuilder<Done, Pending, Resolver, Task>
where
    Resolver: TaskReadyResolver<Done, Pending>,
    Task: TaskIterator<Pending = Pending, Ready = Done>,
{
    pub(crate) config: TaskSpawnConfig<Done, Pending, Resolver, Task>,
    pub(crate) fallback: LocalFallback,
}

// ---------------------------------------------------------------------------
// Send-free spawn() for the three local verbs (no readiness, no Send).
// ---------------------------------------------------------------------------

/// Build the boxed local task (`OnNext` if a resolver is set, else `DoNext`).
///
/// WHY: the spawn form never touches a delivery queue or a readiness, so it boxes
/// into the non-`Send` `BoxedExecutionIterator` the local engine verbs already
/// accept — no `Send` bound is required, even under `multi`.
fn local_spawn_task<Done, Pending, Resolver, Task>(
    task: Task,
    resolver: Option<Resolver>,
) -> crate::valtron::BoxedExecutionIterator
where
    Done: 'static,
    Pending: 'static,
    Resolver: TaskReadyResolver<Done, Pending> + 'static,
    Task: TaskIterator<Pending = Pending, Ready = Done> + 'static,
{
    match resolver {
        Some(resolver) => OnNext::new(task, resolver).into(),
        None => Box::new(DoNext::new(task)),
    }
}

impl<Done, Pending, Resolver, Task> ScheduleBuilder<Done, Pending, Resolver, Task>
where
    Done: 'static,
    Pending: 'static,
    Resolver: TaskReadyResolver<Done, Pending> + 'static,
    Task: TaskIterator<Pending = Pending, Ready = Done> + 'static,
{
    /// Deliver the task to the bottom of the local queue.
    pub fn spawn(self) -> AnyResult<SpawnInfo, ExecutorError> {
        let c = self.config;
        let Some(task) = c.task else {
            return Err(ExecutorError::TaskRequired);
        };
        c.engine.schedule(local_spawn_task(task, c.resolver))
    }
}

impl<Done, Pending, Resolver, Task> LiftBuilder<Done, Pending, Resolver, Task>
where
    Done: 'static,
    Pending: 'static,
    Resolver: TaskReadyResolver<Done, Pending> + 'static,
    Task: TaskIterator<Pending = Pending, Ready = Done> + 'static,
{
    /// Deliver the task to the top of the local queue.
    pub fn spawn(self) -> AnyResult<SpawnInfo, ExecutorError> {
        let c = self.config;
        let parent = c.parent;
        let Some(task) = c.task else {
            return Err(ExecutorError::TaskRequired);
        };
        c.engine.lift(local_spawn_task(task, c.resolver), parent)
    }
}

impl<Done, Pending, Resolver, Task> SequenceBuilder<Done, Pending, Resolver, Task>
where
    Done: 'static,
    Pending: 'static,
    Resolver: TaskReadyResolver<Done, Pending> + 'static,
    Task: TaskIterator<Pending = Pending, Ready = Done> + 'static,
{
    /// Sequence the task with its parent on the local queue.
    pub fn spawn(self) -> AnyResult<SpawnInfo, ExecutorError> {
        let c = self.config;
        let Some(parent) = c.parent else {
            return Err(ExecutorError::ParentMustBeSupplied);
        };
        let Some(task) = c.task else {
            return Err(ExecutorError::TaskRequired);
        };
        c.engine
            .sequenced(local_spawn_task(task, c.resolver), parent)
    }
}

// ---------------------------------------------------------------------------
// Entry points
// ---------------------------------------------------------------------------

/// [`spawn_builder`] returns a [`TaskSpawnConfig`] whose resolver is a boxed
/// `dyn TaskReadyResolver`, for the common local-dispatch paths.
#[must_use]
#[allow(clippy::type_complexity)]
pub fn spawn_builder<Task>(
    engine: BoxedExecutionEngine,
) -> TaskSpawnConfig<
    Task::Ready,
    Task::Pending,
    Box<dyn TaskReadyResolver<Task::Ready, Task::Pending> + 'static>,
    Task,
>
where
    Task::Ready: 'static,
    Task::Pending: 'static,
    Task: TaskIterator + 'static,
{
    TaskSpawnConfig::new(engine)
}

/// [`spawn_broadcaster`] returns a [`TaskSpawnConfig`] whose resolver is a
/// `Send` boxed `dyn TaskReadyResolver`, for the broadcast path.
#[must_use]
#[allow(clippy::type_complexity)]
pub fn spawn_broadcaster<Task>(
    engine: BoxedExecutionEngine,
) -> TaskSpawnConfig<
    Task::Ready,
    Task::Pending,
    Box<dyn TaskReadyResolver<Task::Ready, Task::Pending> + Send + 'static>,
    Task,
>
where
    Task::Ready: Send + 'static,
    Task::Pending: Send + 'static,
    Task: TaskIterator + Send + 'static,
{
    TaskSpawnConfig::new(engine)
}