rig-ecs 0.44.0

rig inside a Bevy World: effects as entities, handlers as entities, the driver as a system.
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
//! Effect recording and cancellation observers for the world bus.
//!
//! ```
//! use rig_ecs::bus::record::DeliveryBatch;
//! let batch = DeliveryBatch::default();
//! assert_eq!(batch.0, 0);
//! ```

use std::sync::Arc;

use bevy_ecs::{
    lifecycle::{Insert, Remove},
    prelude::*,
};
use rig_core::{
    effect::{Delivery, DeliveryKind, EffectId, EffectKind, HandlerDescriptor, Outcome},
    error::ErrorReport,
    serve::{Recorder, cancelled},
    streaming::{Item, Relayed, StreamEvent},
};

use super::{
    effect::{EffectOutcome, InFlight, Issued},
    handlers::Bound,
};
use bevy_ecs::component::Component;

/// The world's recorder. `Dispatch` opens a record as it takes an effect,
/// `Collect` closes it as the outcome lands, a despawn in flight closes it
/// as cancelled, and every `Bound` insert describes its handler. Install
/// with [`Recording::install`] (which also describes the handlers bound so
/// far) or as a plain resource before any handler is bound. It derefs to
/// the [`Recorder`] it records into.
#[derive(Resource, Clone)]
pub struct Recording(Arc<dyn Recorder + Send + Sync>);

impl Recording {
    /// A recording into `recorder`.
    pub fn new(recorder: impl Recorder + Send + Sync) -> Self {
        Self(Arc::new(recorder))
    }

    /// Begin delivery tracking, describe currently bound handlers in key order,
    /// and install `recorder` as the world's recording resource.
    pub fn install(world: &mut World, recorder: impl Recorder + Send + Sync) {
        let recording = Self::new(recorder);
        recording.begin_delivery_tracking();
        let mut bound: Vec<HandlerDescriptor> = world
            .query::<&Bound>()
            .iter(world)
            .map(|bound| bound.descriptor.clone())
            .collect();
        bound.sort_by(|a, b| a.key.cmp(&b.key));
        recording.handlers(bound);
        world.insert_resource(recording);
    }
}

impl std::ops::Deref for Recording {
    type Target = dyn Recorder + Send + Sync;

    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

/// The current delivery batch. Advances once per schedule pass.
#[derive(Resource, Default)]
pub struct DeliveryBatch(pub u64);

/// Begin the next pass's observation group.
pub fn begin_delivery_pass(mut batch: ResMut<DeliveryBatch>) {
    batch.0 += 1;
}

/// Record visibility when the outcome is inserted, not later when a query
/// happens to visit it. This also captures answers from world-served handlers.
pub fn record_outcome(
    added: On<Add, EffectOutcome>,
    issued: Query<(&Issued, Has<super::collect::CollectedOutcome>), With<InFlight>>,
    recording: Option<Res<Recording>>,
    batch: Res<DeliveryBatch>,
) {
    if let Some(recording) = recording
        && let Ok((Issued(id), collected)) = issued.get(added.event().entity)
    {
        if !collected {
            recording.unsupported_delivery("an in-flight EffectOutcome bypassed Collect; submit world answers with WorldOutcome or typed Answer instead");
        }
        recording.delivery(Delivery {
            batch: batch.0,
            id: *id,
            kind: DeliveryKind::Outcome,
        });
    }
}

/// Shared in-flight observation state containing the original handler answer
/// and whether a layer discarded dispatch. Not serialized; layer verdicts do not
/// replace the recorded answer.
#[derive(Component, Clone, Default)]
pub struct Observed(pub Arc<ObservedState>);

/// The dispatch's replacement slot (`Dispatch::replaced_by`): the layer
/// whose verdict the consumer's answer is from, once one said so. Runtime-
/// only; removed with the in-flight markers at collection.
#[derive(Component)]
pub struct ReplacedBy(pub Arc<std::sync::Mutex<Option<String>>>);

impl ReplacedBy {
    /// The layer named, if any.
    pub fn layer(&self) -> Option<String> {
        self.0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
    }
}

/// The observer's slots.
#[derive(Default)]
pub struct ObservedState {
    state: std::sync::Mutex<Observation>,
}

#[derive(Default)]
struct Observation {
    outcome: Option<Result<Outcome, ErrorReport>>,
    discarded: bool,
    closed: bool,
}

impl ObservedState {
    fn lock(&self) -> std::sync::MutexGuard<'_, Observation> {
        self.state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Close observation and take the original answer. No later worker callback
    /// can modify recording after this boundary, even if its poll was in progress.
    pub fn take_outcome(&self) -> Option<Result<Outcome, ErrorReport>> {
        let mut state = self.lock();
        state.closed = true;
        state.outcome.take()
    }

    /// Whether the original handler answer has been observed.
    pub fn has_outcome(&self) -> bool {
        self.lock().outcome.is_some()
    }

    /// Whether a layer discarded the dispatch.
    pub fn is_discarded(&self) -> bool {
        self.lock().discarded
    }
}

/// Records original answers, stream items, and layer patches or discards for a
/// task-served dispatch. Once observation closes, worker callbacks cannot mutate
/// the recording.
pub struct WorldObserver {
    /// Explicit host operation, already bound to this dispatch's subject.
    pub adapter: Option<rig_core::observe::AdapterContext>,
    /// Tool output shared with the caller, read without consuming it.
    pub published: Option<Arc<rig_core::tool::PublishedContext>>,
    /// The dispatch.
    pub id: EffectId,
    /// The world's recorder, if any.
    pub recording: Option<Recording>,
    /// The shared slots.
    pub observed: Arc<ObservedState>,
    /// The world's witness with the current dispatch subject.
    pub witness: Option<(super::witness::Witnessing, rig_core::observe::Subject)>,
}

impl WorldObserver {
    fn record_answer(&self, state: &mut Observation, outcome: &Result<Outcome, ErrorReport>) {
        if let (Some(recording), Some(output)) = (
            &self.recording,
            self.published
                .as_ref()
                .and_then(|published| published.result_context()),
        ) {
            recording.tool_output(self.id, output);
        }
        state.outcome = Some(outcome.clone());
    }

    fn record_item(&self, item: &Result<Relayed, ErrorReport>) {
        if let Some(recording) = &self.recording
            && recording.keep_events()
        {
            match item {
                Ok(Relayed::Origin(origin)) => recording.origin(self.id, origin),
                Ok(Relayed::Item(item)) => recording.event(self.id, item),
                Ok(Relayed::Done(_)) => {}
                Err(error) => recording.stream_error(self.id, error),
            }
        }
    }
}

impl rig_core::serve::Observe for WorldObserver {
    fn adapter_context(&self) -> Option<rig_core::observe::AdapterContext> {
        if let Some(context) = &self.adapter {
            return Some(context.clone());
        }
        let (witness, subject) = self.witness.as_ref()?;
        let mut subject = subject.clone();
        subject.effect = Some(self.id);
        Some(rig_core::observe::AdapterContext::new(
            witness.sink().clone(),
            subject,
            format!("effect/{}", self.id),
        ))
    }

    fn outcome(&mut self, outcome: &Result<Outcome, ErrorReport>) {
        let mut state = self.observed.lock();
        if !state.closed {
            self.record_answer(&mut state, outcome);
        }
    }

    fn keep_events(&self) -> bool {
        self.recording
            .as_ref()
            .is_some_and(|recording| recording.keep_events())
    }

    fn stream_item(
        &mut self,
        item: &Result<Relayed, ErrorReport>,
        outcome: Option<&Result<Outcome, ErrorReport>>,
    ) {
        // Source polling and folding happen before this lock. Only observation
        // is atomic with cancellation, so arbitrary handler work cannot hold it.
        let mut state = self.observed.lock();
        if state.closed {
            return;
        }
        self.record_item(item);
        if let Some(outcome) = outcome {
            self.record_answer(&mut state, outcome);
        }
    }

    fn origin(&mut self, origin: &rig_core::message::Origin) {
        let state = self.observed.lock();
        if !state.closed
            && let Some(recording) = &self.recording
        {
            recording.origin(self.id, origin);
        }
    }

    fn event(&mut self, item: &Item<StreamEvent>) {
        let state = self.observed.lock();
        if !state.closed
            && let Some(recording) = &self.recording
        {
            recording.event(self.id, item);
        }
    }

    fn stream_error(&mut self, error: &ErrorReport) {
        let state = self.observed.lock();
        if !state.closed
            && let Some(recording) = &self.recording
        {
            recording.stream_error(self.id, error);
        }
    }

    fn discard(&mut self, layer: &str) {
        let mut state = self.observed.lock();
        if !state.closed {
            state.discarded = true;
            if let Some(recording) = &self.recording {
                recording.discard(self.id);
            }
            if let Some((witness, subject)) = &self.witness {
                let mut subject = subject.clone();
                subject.effect = Some(self.id);
                witness.emit(
                    subject,
                    rig_core::observe::Stage::Handler,
                    rig_core::observe::Emitter::named(layer),
                    rig_core::observe::Action::Denied {
                        reason: rig_core::observe::Reason::code("layer_discarded"),
                    },
                );
            }
        }
    }

    fn patch(&mut self, kind: &EffectKind) {
        let state = self.observed.lock();
        if !state.closed
            && let Some(recording) = &self.recording
        {
            recording.patch(self.id, kind.clone());
        }
    }
}

/// Close recording when an effect leaves flight before settlement.
/// Preserve any original handler answer and tool output; otherwise record
/// cancellation. An observed answer cancelled before delivery gets a cancellation
/// boundary, not an invented outcome delivery. Discarded dispatches stay unrecorded.
pub fn record_cancelled(
    removed: On<Remove, InFlight>,
    effects: Query<(
        &Issued,
        Option<&EffectOutcome>,
        Has<super::collect::CollectedOutcome>,
        Option<&super::effect::Publishing>,
        Option<&super::effect::ToolOutputs>,
        Option<&Observed>,
    )>,
    recording: Option<Res<Recording>>,
    batch: Res<DeliveryBatch>,
) {
    let Some(recording) = recording else {
        return;
    };
    let Ok((Issued(id), outcome, collected, publishing, outputs, observed)) =
        effects.get(removed.event().entity)
    else {
        return;
    };
    if observed.is_some_and(|observed| observed.0.is_discarded()) {
        return;
    }
    match outcome {
        // Landed but not settled: `settle` retires `CollectedOutcome` before
        // it retires `InFlight`, so its presence here means settlement never
        // ran (the entity is being despawned with its answer on it).
        Some(EffectOutcome(landed)) if collected => {
            let original = observed.and_then(|observed| observed.0.take_outcome());
            if observed.is_none()
                && let Some(outputs) = outputs
            {
                recording.tool_output(*id, outputs.0.result_context());
            }
            recording.resolve(*id, original.unwrap_or_else(|| landed.clone()));
        }
        Some(_) => {}
        None => {
            let original = observed.and_then(|observed| observed.0.take_outcome());
            let output = publishing
                .and_then(|published| published.0.result_context())
                .or_else(|| outputs.map(|outputs| outputs.0.result_context()));
            if let Some(output) = output {
                recording.tool_output(*id, output);
            }
            if original.as_ref().is_some_and(|answer| {
                !answer
                    .as_ref()
                    .is_err_and(|error| error.kind == rig_core::error::ErrorKind::Cancelled)
            }) {
                recording.delivery(Delivery {
                    batch: batch.0,
                    id: *id,
                    kind: DeliveryKind::Cancelled,
                });
            }
            recording.resolve(*id, original.unwrap_or_else(|| Err(cancelled())));
        }
    }
}

/// An in-flight effect losing `InFlight` without an outcome, seen by the
/// witness: a cancelled dispatch, whether or not a record is kept.
pub fn witness_cancelled(
    removed: On<Remove, InFlight>,
    effects: Query<(Has<EffectOutcome>, Option<&Observed>), With<Issued>>,
    subjects: super::witness::Subjects,
    witness: Option<Res<super::witness::Witnessing>>,
) {
    let entity = removed.event().entity;
    let Some(witness) = witness else {
        return;
    };
    let Ok((answered, observed)) = effects.get(entity) else {
        return;
    };
    if answered || observed.is_some_and(|observed| observed.0.is_discarded()) {
        return;
    }
    let observation = rig_core::observe::Observation::new(
        subjects.of(entity),
        rig_core::observe::Stage::Collect,
        super::witness::bus_emitter(),
        rig_core::observe::Action::Cancelled {
            reason: rig_core::observe::Reason::from_report(&cancelled()),
        },
    );
    witness.observe(observation);
}

/// Describe an inserted or replaced [`Bound`] component to the installed recorder.
pub fn record_bound(
    inserted: On<Insert, Bound>,
    bound: Query<&Bound>,
    recording: Option<Res<Recording>>,
) {
    let Some(recording) = recording else {
        return;
    };
    if let Ok(bound) = bound.get(inserted.event().entity) {
        recording.handlers(vec![bound.descriptor.clone()]);
    }
}

#[cfg(test)]
mod tests;