bevy_impulse 0.2.0

Reactive programming and workflow execution for bevy
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/*
 * Copyright (C) 2024 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

use bevy_ecs::{
    prelude::{Component, Entity, World},
    world::{EntityRef, EntityWorldMut},
};

use backtrace::Backtrace;

use std::{collections::HashMap, sync::Arc};

use smallvec::SmallVec;

use thiserror::Error as ThisError;

use crate::{
    operation::ScopeStorage, Cancel, Cancellation, DisposalFailure, ImpulseMarker, OperationResult,
    OperationRoster, OrBroken, UnhandledErrors,
};

#[derive(ThisError, Debug, Clone)]
#[error("The output of an operation in a workflow was disposed")]
pub struct Disposal {
    pub cause: Arc<DisposalCause>,
}

impl<T: Into<DisposalCause>> From<T> for Disposal {
    fn from(value: T) -> Self {
        Disposal {
            cause: Arc::new(value.into()),
        }
    }
}

impl Disposal {
    pub fn service_unavailable(service: Entity, for_node: Entity) -> Disposal {
        ServiceUnavailable { service, for_node }.into()
    }

    pub fn task_despawned(task: Entity, node: Entity) -> Disposal {
        TaskDespawned { task, node }.into()
    }

    pub fn branching(
        branched_at_node: Entity,
        disposed_for_target: Entity,
        reason: Option<anyhow::Error>,
    ) -> Disposal {
        DisposedBranch {
            branched_at_node,
            disposed_for_target,
            reason,
        }
        .into()
    }

    pub fn buffer_key(accessor_node: Entity, key_for_buffer: Entity) -> Disposal {
        DisposedBufferKey {
            accessor_node,
            key_for_buffer,
        }
        .into()
    }

    pub fn supplanted(
        supplanted_at_node: Entity,
        supplanted_by_node: Entity,
        supplanting_session: Entity,
    ) -> Disposal {
        Supplanted {
            supplanted_at_node,
            supplanted_by_node,
            supplanting_session,
        }
        .into()
    }

    pub fn filtered(filtered_at_node: Entity, reason: Option<anyhow::Error>) -> Self {
        Filtered {
            filtered_at_node,
            reason,
        }
        .into()
    }

    pub fn trimming(trimmer: Entity, nodes: SmallVec<[Entity; 16]>) -> Self {
        Trimming { trimmer, nodes }.into()
    }

    pub fn closed_gate(gate_node: Entity, closed_buffers: SmallVec<[Entity; 8]>) -> Self {
        ClosedGate {
            gate_node,
            closed_buffers,
        }
        .into()
    }

    pub fn empty_spread(spread_node: Entity) -> Self {
        EmptySpread { spread_node }.into()
    }

    pub fn deficient_collection(collect_node: Entity, min: usize, actual: usize) -> Self {
        DeficientCollection {
            collect_node,
            min,
            actual,
        }
        .into()
    }
}

#[derive(Debug)]
pub enum DisposalCause {
    /// Some services will queue up requests to deliver them one at a time.
    /// Depending on the label of the incoming requests, a new request might
    /// supplant an earlier one, causing the earlier request to be disposed.
    Supplanted(Supplanted),

    /// A node filtered out a response.
    Filtered(Filtered),

    /// A node disposed of one of its output branches.
    Branching(DisposedBranch),

    /// A buffer key was disposed, so a buffer will no longer be able to update.
    BufferKey(DisposedBufferKey),

    /// A [`Service`](crate::Service) provider needed by the chain was despawned
    /// or had a critical component removed. The entity provided in the variant
    /// is the unavailable service.
    ServiceUnavailable(ServiceUnavailable),

    /// An entity that was managing the execution of a task was despawned,
    /// causing the task to be cancelled and making it impossible to deliver a
    /// response.
    TaskDespawned(TaskDespawned),

    /// An output was disposed because a mutex was poisoned.
    PoisonedMutex(PoisonedMutexDisposal),

    /// A scope was cancelled so its output has been disposed.
    Scope(Cancellation),

    /// One or more streams from a node never emitted any signal. This can lead
    /// to unexpected
    UnusedStreams(UnusedStreams),

    /// Some nodes in the workflow were trimmed.
    Trimming(Trimming),

    /// A gate was closed, which cut off the ability of a workflow to proceed.
    ClosedGate(ClosedGate),

    /// A spread operation was given an empty collection so there was nothing to
    /// spread. As a result, no signal was sent out of the node after it
    /// received a signal.
    EmptySpread(EmptySpread),

    /// A collect operation has a minimum number of entries, and it appears the
    /// workflow will not be able to meet that minimum, so a disposal notice has
    /// been sent out to indicate that the workflow is blocked up on the
    /// collection.
    DeficientCollection(DeficientCollection),
}

/// A variant of [`DisposalCause`]
#[derive(Debug, Clone, Copy)]
pub struct Supplanted {
    /// ID of the node whose service request was supplanted
    pub supplanted_at_node: Entity,
    /// ID of the node that did the supplanting
    pub supplanted_by_node: Entity,
    /// ID of the session that did the supplanting
    pub supplanting_session: Entity,
}

impl Supplanted {
    pub fn new(
        cancelled_at_node: Entity,
        supplanting_node: Entity,
        supplanting_session: Entity,
    ) -> Self {
        Self {
            supplanted_at_node: cancelled_at_node,
            supplanted_by_node: supplanting_node,
            supplanting_session,
        }
    }
}

impl From<Supplanted> for DisposalCause {
    fn from(value: Supplanted) -> Self {
        DisposalCause::Supplanted(value)
    }
}

/// A variant of [`DisposalCause`]
#[derive(Debug)]
pub struct Filtered {
    /// ID of the node that did the filtering
    pub filtered_at_node: Entity,
    /// Optionally, a reason given for why the filtering happened.
    pub reason: Option<anyhow::Error>,
}

impl Filtered {
    pub fn new(filtered_at_node: Entity, reason: Option<anyhow::Error>) -> Self {
        Self {
            filtered_at_node,
            reason,
        }
    }
}

impl From<Filtered> for DisposalCause {
    fn from(value: Filtered) -> Self {
        Self::Filtered(value)
    }
}

/// A variant of [`DisposalCause`]
#[derive(Debug)]
pub struct DisposedBranch {
    /// The node where the branching happened
    pub branched_at_node: Entity,
    /// The target node whose input was disposed
    pub disposed_for_target: Entity,
    /// Optionally, a reason given for the branching
    pub reason: Option<anyhow::Error>,
}

impl From<DisposedBranch> for DisposalCause {
    fn from(value: DisposedBranch) -> Self {
        Self::Branching(value)
    }
}

/// A variant of [`DisposalCause`]
#[derive(Debug)]
pub struct DisposedBufferKey {
    pub accessor_node: Entity,
    pub key_for_buffer: Entity,
}

impl From<DisposedBufferKey> for DisposalCause {
    fn from(value: DisposedBufferKey) -> Self {
        Self::BufferKey(value)
    }
}

/// A variant of [`DisposalCause`]
#[derive(Debug)]
pub struct ServiceUnavailable {
    /// The service that is no longer available
    pub service: Entity,
    /// The node that intended to use the service
    pub for_node: Entity,
}

impl From<ServiceUnavailable> for DisposalCause {
    fn from(value: ServiceUnavailable) -> Self {
        Self::ServiceUnavailable(value)
    }
}

/// A variant of [`DisposalCause`]
#[derive(Debug)]
pub struct TaskDespawned {
    /// The entity that was managing the task
    pub task: Entity,
    /// The node that the task was spawned by
    pub node: Entity,
}

impl From<TaskDespawned> for DisposalCause {
    fn from(value: TaskDespawned) -> Self {
        Self::TaskDespawned(value)
    }
}
/// A variant of [`DisposalCause`]
#[derive(Debug)]
pub struct PoisonedMutexDisposal {
    /// The node containing the poisoned mutex
    pub for_node: Entity,
}

impl From<PoisonedMutexDisposal> for DisposalCause {
    fn from(value: PoisonedMutexDisposal) -> Self {
        Self::PoisonedMutex(value)
    }
}

/// A variant of [`DisposalCause`]
#[derive(Debug)]
pub struct UnusedStreams {
    /// The node which did not use all its streams
    pub node: Entity,
    /// The streams which went unused.
    pub streams: Vec<&'static str>,
}

impl UnusedStreams {
    pub fn new(node: Entity) -> Self {
        Self {
            node,
            streams: Default::default(),
        }
    }
}

impl From<UnusedStreams> for DisposalCause {
    fn from(value: UnusedStreams) -> Self {
        Self::UnusedStreams(value)
    }
}

/// A variant of [`DisposalCause`]
#[derive(Debug)]
pub struct Trimming {
    pub trimmer: Entity,
    pub nodes: SmallVec<[Entity; 16]>,
}

impl From<Trimming> for DisposalCause {
    fn from(value: Trimming) -> Self {
        Self::Trimming(value)
    }
}

/// A variant of [`DisposalCause`]
#[derive(Debug)]
pub struct ClosedGate {
    /// The gate node which triggered the closing
    pub gate_node: Entity,
    /// The buffers which were closed by the gate node
    pub closed_buffers: SmallVec<[Entity; 8]>,
}

impl From<ClosedGate> for DisposalCause {
    fn from(value: ClosedGate) -> Self {
        Self::ClosedGate(value)
    }
}

/// A variant of [`DisposalCause`]
#[derive(Debug)]
pub struct EmptySpread {
    /// The node that was doing the spreading
    pub spread_node: Entity,
}

impl From<EmptySpread> for DisposalCause {
    fn from(value: EmptySpread) -> Self {
        Self::EmptySpread(value)
    }
}

/// A variant of [`DisposalCause`]
#[derive(Debug)]
pub struct DeficientCollection {
    /// The node that is doing the collection
    pub collect_node: Entity,
    /// The minimum required size of the collection
    pub min: usize,
    /// The actual size of the collection when it became unreachable
    pub actual: usize,
}

impl From<DeficientCollection> for DisposalCause {
    fn from(value: DeficientCollection) -> Self {
        Self::DeficientCollection(value)
    }
}

pub trait ManageDisposal {
    fn emit_disposal(&mut self, session: Entity, disposal: Disposal, roster: &mut OperationRoster);

    fn clear_disposals(&mut self, session: Entity);

    /// Used to transfer the disposals gathered by a temporary operation (e.g.
    /// a task) over to a persistent node
    fn transfer_disposals(&mut self, to_node: Entity) -> OperationResult;
}

pub trait InspectDisposals {
    fn get_disposals(&self, session: Entity) -> Option<&Vec<Disposal>>;
}

impl<'w> ManageDisposal for EntityWorldMut<'w> {
    fn emit_disposal(&mut self, session: Entity, disposal: Disposal, roster: &mut OperationRoster) {
        let Some(scope) = self.get::<ScopeStorage>() else {
            if self.contains::<ImpulseMarker>() {
                // If an impulse has been supplanted, we trigger a cancellation
                // for it. Besides supplanting, we do not generally convert a
                // disposal into a cancellation because sometimes services will
                // emit disposals just to trigger a reachability check, e.g. for
                // unused streams, not because the actual result is undeliverable.
                if let DisposalCause::Supplanted(supplanted) = disposal.cause.as_ref() {
                    let cancellation: Cancellation = (*supplanted).into();
                    roster.cancel(Cancel {
                        origin: self.id(),
                        target: session,
                        session: Some(session),
                        cancellation,
                    });
                }
                // TODO(@mxgrey): Consider whether there is a more sound way to
                // decide whether a disposal should be converted into a
                // cancellation for impulses.
            } else {
                // If the emitting node does not have a scope as not part of an
                // impulse chain, then something is broken.
                let broken_node = self.id();
                self.world_scope(|world| {
                    world
                        .get_resource_or_insert_with(UnhandledErrors::default)
                        .disposals
                        .push(DisposalFailure {
                            disposal,
                            broken_node,
                            backtrace: Some(Backtrace::new()),
                        });
                });
            }
            return;
        };
        let scope = scope.get();

        if let Some(mut storage) = self.get_mut::<DisposalStorage>() {
            storage.disposals.entry(session).or_default().push(disposal);
        } else {
            let mut storage = DisposalStorage::default();
            storage.disposals.entry(session).or_default().push(disposal);
            self.insert(storage);
        }

        roster.disposed(scope, self.id(), session);
    }

    fn clear_disposals(&mut self, session: Entity) {
        if let Some(mut storage) = self.get_mut::<DisposalStorage>() {
            storage.disposals.remove(&session);
        }
    }

    fn transfer_disposals(&mut self, to: Entity) -> OperationResult {
        if let Some(from_storage) = self.take::<DisposalStorage>() {
            self.world_scope::<OperationResult>(|world| {
                let mut to_mut = world.get_entity_mut(to).or_broken()?;
                match to_mut.get_mut::<DisposalStorage>() {
                    Some(mut to_storage) => {
                        for (session, disposals) in from_storage.disposals {
                            to_storage
                                .disposals
                                .entry(session)
                                .or_default()
                                .extend(disposals);
                        }
                    }
                    None => {
                        to_mut.insert(from_storage);
                    }
                }
                Ok(())
            })?;
        }

        Ok(())
    }
}

impl<'w> InspectDisposals for EntityWorldMut<'w> {
    fn get_disposals(&self, session: Entity) -> Option<&Vec<Disposal>> {
        if let Some(storage) = self.get::<DisposalStorage>() {
            return storage.disposals.get(&session);
        }

        None
    }
}

impl<'w> InspectDisposals for EntityRef<'w> {
    fn get_disposals(&self, session: Entity) -> Option<&Vec<Disposal>> {
        if let Some(storage) = self.get::<DisposalStorage>() {
            return storage.disposals.get(&session);
        }

        None
    }
}

pub fn emit_disposal(
    source: Entity,
    session: Entity,
    disposal: Disposal,
    world: &mut World,
    roster: &mut OperationRoster,
) {
    if let Some(mut source_mut) = world.get_entity_mut(source) {
        source_mut.emit_disposal(session, disposal, roster);
    } else {
        world
            .get_resource_or_insert_with(UnhandledErrors::default)
            .disposals
            .push(DisposalFailure {
                disposal,
                broken_node: source,
                backtrace: Some(Backtrace::new()),
            });
    }
}

#[derive(Component, Default)]
struct DisposalStorage {
    /// A map from a session to all the disposals that occurred for the session
    disposals: HashMap<Entity, Vec<Disposal>>,
}